xref: /llvm-project/llvm/lib/Analysis/ScalarEvolution.cpp (revision 507dd40a4abadbfdaa4f49a4823ddae6c7dfec4f)
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 static int CompareValueComplexity(const LoopInfo *const LI, Value *LV,
452                                   Value *RV, unsigned DepthLeft = 2) {
453   if (DepthLeft == 0)
454     return 0;
455 
456   // Order pointer values after integer values. This helps SCEVExpander form
457   // GEPs.
458   bool LIsPointer = LV->getType()->isPointerTy(),
459        RIsPointer = RV->getType()->isPointerTy();
460   if (LIsPointer != RIsPointer)
461     return (int)LIsPointer - (int)RIsPointer;
462 
463   // Compare getValueID values.
464   unsigned LID = LV->getValueID(), RID = RV->getValueID();
465   if (LID != RID)
466     return (int)LID - (int)RID;
467 
468   // Sort arguments by their position.
469   if (const Argument *LA = dyn_cast<Argument>(LV)) {
470     const Argument *RA = cast<Argument>(RV);
471     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
472     return (int)LArgNo - (int)RArgNo;
473   }
474 
475   // For instructions, compare their loop depth, and their operand count.  This
476   // is pretty loose.
477   if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
478     const Instruction *RInst = cast<Instruction>(RV);
479 
480     // Compare loop depths.
481     const BasicBlock *LParent = LInst->getParent(),
482                      *RParent = RInst->getParent();
483     if (LParent != RParent) {
484       unsigned LDepth = LI->getLoopDepth(LParent),
485                RDepth = LI->getLoopDepth(RParent);
486       if (LDepth != RDepth)
487         return (int)LDepth - (int)RDepth;
488     }
489 
490     // Compare the number of operands.
491     unsigned LNumOps = LInst->getNumOperands(),
492              RNumOps = RInst->getNumOperands();
493     if (LNumOps != RNumOps || LNumOps != 1)
494       return (int)LNumOps - (int)RNumOps;
495 
496     // We only bother "recursing" if we have one operand to look at (so we don't
497     // really recurse as much as we iterate).  We can consider expanding this
498     // logic in the future.
499     return CompareValueComplexity(LI, LInst->getOperand(0),
500                                   RInst->getOperand(0), DepthLeft - 1);
501   }
502 
503   return 0;
504 }
505 
506 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
507 // than RHS, respectively. A three-way result allows recursive comparisons to be
508 // more efficient.
509 static int CompareSCEVComplexity(const LoopInfo *const LI, const SCEV *LHS,
510                                  const SCEV *RHS) {
511   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
512   if (LHS == RHS)
513     return 0;
514 
515   // Primarily, sort the SCEVs by their getSCEVType().
516   unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
517   if (LType != RType)
518     return (int)LType - (int)RType;
519 
520   // Aside from the getSCEVType() ordering, the particular ordering
521   // isn't very important except that it's beneficial to be consistent,
522   // so that (a + b) and (b + a) don't end up as different expressions.
523   switch (static_cast<SCEVTypes>(LType)) {
524   case scUnknown: {
525     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
526     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
527 
528     return CompareValueComplexity(LI, LU->getValue(), RU->getValue());
529   }
530 
531   case scConstant: {
532     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
533     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
534 
535     // Compare constant values.
536     const APInt &LA = LC->getAPInt();
537     const APInt &RA = RC->getAPInt();
538     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
539     if (LBitWidth != RBitWidth)
540       return (int)LBitWidth - (int)RBitWidth;
541     return LA.ult(RA) ? -1 : 1;
542   }
543 
544   case scAddRecExpr: {
545     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
546     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
547 
548     // Compare addrec loop depths.
549     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
550     if (LLoop != RLoop) {
551       unsigned LDepth = LLoop->getLoopDepth(), RDepth = RLoop->getLoopDepth();
552       if (LDepth != RDepth)
553         return (int)LDepth - (int)RDepth;
554     }
555 
556     // Addrec complexity grows with operand count.
557     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
558     if (LNumOps != RNumOps)
559       return (int)LNumOps - (int)RNumOps;
560 
561     // Lexicographically compare.
562     for (unsigned i = 0; i != LNumOps; ++i) {
563       long X = CompareSCEVComplexity(LI, LA->getOperand(i), RA->getOperand(i));
564       if (X != 0)
565         return X;
566     }
567 
568     return 0;
569   }
570 
571   case scAddExpr:
572   case scMulExpr:
573   case scSMaxExpr:
574   case scUMaxExpr: {
575     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
576     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
577 
578     // Lexicographically compare n-ary expressions.
579     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
580     if (LNumOps != RNumOps)
581       return (int)LNumOps - (int)RNumOps;
582 
583     for (unsigned i = 0; i != LNumOps; ++i) {
584       if (i >= RNumOps)
585         return 1;
586       long X = CompareSCEVComplexity(LI, LC->getOperand(i), RC->getOperand(i));
587       if (X != 0)
588         return X;
589     }
590     return (int)LNumOps - (int)RNumOps;
591   }
592 
593   case scUDivExpr: {
594     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
595     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
596 
597     // Lexicographically compare udiv expressions.
598     long X = CompareSCEVComplexity(LI, LC->getLHS(), RC->getLHS());
599     if (X != 0)
600       return X;
601     return CompareSCEVComplexity(LI, LC->getRHS(), RC->getRHS());
602   }
603 
604   case scTruncate:
605   case scZeroExtend:
606   case scSignExtend: {
607     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
608     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
609 
610     // Compare cast expressions by operand.
611     return CompareSCEVComplexity(LI, LC->getOperand(), RC->getOperand());
612   }
613 
614   case scCouldNotCompute:
615     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
616   }
617   llvm_unreachable("Unknown SCEV kind!");
618 }
619 
620 /// Given a list of SCEV objects, order them by their complexity, and group
621 /// objects of the same complexity together by value.  When this routine is
622 /// finished, we know that any duplicates in the vector are consecutive and that
623 /// complexity is monotonically increasing.
624 ///
625 /// Note that we go take special precautions to ensure that we get deterministic
626 /// results from this routine.  In other words, we don't want the results of
627 /// this to depend on where the addresses of various SCEV objects happened to
628 /// land in memory.
629 ///
630 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
631                               LoopInfo *LI) {
632   if (Ops.size() < 2) return;  // Noop
633   if (Ops.size() == 2) {
634     // This is the common case, which also happens to be trivially simple.
635     // Special case it.
636     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
637     if (CompareSCEVComplexity(LI, RHS, LHS) < 0)
638       std::swap(LHS, RHS);
639     return;
640   }
641 
642   // Do the rough sort by complexity.
643   std::stable_sort(Ops.begin(), Ops.end(),
644                    [LI](const SCEV *LHS, const SCEV *RHS) {
645                      return CompareSCEVComplexity(LI, LHS, RHS) < 0;
646                    });
647 
648   // Now that we are sorted by complexity, group elements of the same
649   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
650   // be extremely short in practice.  Note that we take this approach because we
651   // do not want to depend on the addresses of the objects we are grouping.
652   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
653     const SCEV *S = Ops[i];
654     unsigned Complexity = S->getSCEVType();
655 
656     // If there are any objects of the same complexity and same value as this
657     // one, group them.
658     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
659       if (Ops[j] == S) { // Found a duplicate.
660         // Move it to immediately after i'th element.
661         std::swap(Ops[i+1], Ops[j]);
662         ++i;   // no need to rescan it.
663         if (i == e-2) return;  // Done!
664       }
665     }
666   }
667 }
668 
669 // Returns the size of the SCEV S.
670 static inline int sizeOfSCEV(const SCEV *S) {
671   struct FindSCEVSize {
672     int Size;
673     FindSCEVSize() : Size(0) {}
674 
675     bool follow(const SCEV *S) {
676       ++Size;
677       // Keep looking at all operands of S.
678       return true;
679     }
680     bool isDone() const {
681       return false;
682     }
683   };
684 
685   FindSCEVSize F;
686   SCEVTraversal<FindSCEVSize> ST(F);
687   ST.visitAll(S);
688   return F.Size;
689 }
690 
691 namespace {
692 
693 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
694 public:
695   // Computes the Quotient and Remainder of the division of Numerator by
696   // Denominator.
697   static void divide(ScalarEvolution &SE, const SCEV *Numerator,
698                      const SCEV *Denominator, const SCEV **Quotient,
699                      const SCEV **Remainder) {
700     assert(Numerator && Denominator && "Uninitialized SCEV");
701 
702     SCEVDivision D(SE, Numerator, Denominator);
703 
704     // Check for the trivial case here to avoid having to check for it in the
705     // rest of the code.
706     if (Numerator == Denominator) {
707       *Quotient = D.One;
708       *Remainder = D.Zero;
709       return;
710     }
711 
712     if (Numerator->isZero()) {
713       *Quotient = D.Zero;
714       *Remainder = D.Zero;
715       return;
716     }
717 
718     // A simple case when N/1. The quotient is N.
719     if (Denominator->isOne()) {
720       *Quotient = Numerator;
721       *Remainder = D.Zero;
722       return;
723     }
724 
725     // Split the Denominator when it is a product.
726     if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
727       const SCEV *Q, *R;
728       *Quotient = Numerator;
729       for (const SCEV *Op : T->operands()) {
730         divide(SE, *Quotient, Op, &Q, &R);
731         *Quotient = Q;
732 
733         // Bail out when the Numerator is not divisible by one of the terms of
734         // the Denominator.
735         if (!R->isZero()) {
736           *Quotient = D.Zero;
737           *Remainder = Numerator;
738           return;
739         }
740       }
741       *Remainder = D.Zero;
742       return;
743     }
744 
745     D.visit(Numerator);
746     *Quotient = D.Quotient;
747     *Remainder = D.Remainder;
748   }
749 
750   // Except in the trivial case described above, we do not know how to divide
751   // Expr by Denominator for the following functions with empty implementation.
752   void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
753   void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
754   void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
755   void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
756   void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
757   void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
758   void visitUnknown(const SCEVUnknown *Numerator) {}
759   void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
760 
761   void visitConstant(const SCEVConstant *Numerator) {
762     if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
763       APInt NumeratorVal = Numerator->getAPInt();
764       APInt DenominatorVal = D->getAPInt();
765       uint32_t NumeratorBW = NumeratorVal.getBitWidth();
766       uint32_t DenominatorBW = DenominatorVal.getBitWidth();
767 
768       if (NumeratorBW > DenominatorBW)
769         DenominatorVal = DenominatorVal.sext(NumeratorBW);
770       else if (NumeratorBW < DenominatorBW)
771         NumeratorVal = NumeratorVal.sext(DenominatorBW);
772 
773       APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
774       APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
775       APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
776       Quotient = SE.getConstant(QuotientVal);
777       Remainder = SE.getConstant(RemainderVal);
778       return;
779     }
780   }
781 
782   void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
783     const SCEV *StartQ, *StartR, *StepQ, *StepR;
784     if (!Numerator->isAffine())
785       return cannotDivide(Numerator);
786     divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
787     divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
788     // Bail out if the types do not match.
789     Type *Ty = Denominator->getType();
790     if (Ty != StartQ->getType() || Ty != StartR->getType() ||
791         Ty != StepQ->getType() || Ty != StepR->getType())
792       return cannotDivide(Numerator);
793     Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
794                                 Numerator->getNoWrapFlags());
795     Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
796                                  Numerator->getNoWrapFlags());
797   }
798 
799   void visitAddExpr(const SCEVAddExpr *Numerator) {
800     SmallVector<const SCEV *, 2> Qs, Rs;
801     Type *Ty = Denominator->getType();
802 
803     for (const SCEV *Op : Numerator->operands()) {
804       const SCEV *Q, *R;
805       divide(SE, Op, Denominator, &Q, &R);
806 
807       // Bail out if types do not match.
808       if (Ty != Q->getType() || Ty != R->getType())
809         return cannotDivide(Numerator);
810 
811       Qs.push_back(Q);
812       Rs.push_back(R);
813     }
814 
815     if (Qs.size() == 1) {
816       Quotient = Qs[0];
817       Remainder = Rs[0];
818       return;
819     }
820 
821     Quotient = SE.getAddExpr(Qs);
822     Remainder = SE.getAddExpr(Rs);
823   }
824 
825   void visitMulExpr(const SCEVMulExpr *Numerator) {
826     SmallVector<const SCEV *, 2> Qs;
827     Type *Ty = Denominator->getType();
828 
829     bool FoundDenominatorTerm = false;
830     for (const SCEV *Op : Numerator->operands()) {
831       // Bail out if types do not match.
832       if (Ty != Op->getType())
833         return cannotDivide(Numerator);
834 
835       if (FoundDenominatorTerm) {
836         Qs.push_back(Op);
837         continue;
838       }
839 
840       // Check whether Denominator divides one of the product operands.
841       const SCEV *Q, *R;
842       divide(SE, Op, Denominator, &Q, &R);
843       if (!R->isZero()) {
844         Qs.push_back(Op);
845         continue;
846       }
847 
848       // Bail out if types do not match.
849       if (Ty != Q->getType())
850         return cannotDivide(Numerator);
851 
852       FoundDenominatorTerm = true;
853       Qs.push_back(Q);
854     }
855 
856     if (FoundDenominatorTerm) {
857       Remainder = Zero;
858       if (Qs.size() == 1)
859         Quotient = Qs[0];
860       else
861         Quotient = SE.getMulExpr(Qs);
862       return;
863     }
864 
865     if (!isa<SCEVUnknown>(Denominator))
866       return cannotDivide(Numerator);
867 
868     // The Remainder is obtained by replacing Denominator by 0 in Numerator.
869     ValueToValueMap RewriteMap;
870     RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
871         cast<SCEVConstant>(Zero)->getValue();
872     Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
873 
874     if (Remainder->isZero()) {
875       // The Quotient is obtained by replacing Denominator by 1 in Numerator.
876       RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
877           cast<SCEVConstant>(One)->getValue();
878       Quotient =
879           SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
880       return;
881     }
882 
883     // Quotient is (Numerator - Remainder) divided by Denominator.
884     const SCEV *Q, *R;
885     const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
886     // This SCEV does not seem to simplify: fail the division here.
887     if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
888       return cannotDivide(Numerator);
889     divide(SE, Diff, Denominator, &Q, &R);
890     if (R != Zero)
891       return cannotDivide(Numerator);
892     Quotient = Q;
893   }
894 
895 private:
896   SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
897                const SCEV *Denominator)
898       : SE(S), Denominator(Denominator) {
899     Zero = SE.getZero(Denominator->getType());
900     One = SE.getOne(Denominator->getType());
901 
902     // We generally do not know how to divide Expr by Denominator. We
903     // initialize the division to a "cannot divide" state to simplify the rest
904     // of the code.
905     cannotDivide(Numerator);
906   }
907 
908   // Convenience function for giving up on the division. We set the quotient to
909   // be equal to zero and the remainder to be equal to the numerator.
910   void cannotDivide(const SCEV *Numerator) {
911     Quotient = Zero;
912     Remainder = Numerator;
913   }
914 
915   ScalarEvolution &SE;
916   const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
917 };
918 
919 }
920 
921 //===----------------------------------------------------------------------===//
922 //                      Simple SCEV method implementations
923 //===----------------------------------------------------------------------===//
924 
925 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
926 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
927                                        ScalarEvolution &SE,
928                                        Type *ResultTy) {
929   // Handle the simplest case efficiently.
930   if (K == 1)
931     return SE.getTruncateOrZeroExtend(It, ResultTy);
932 
933   // We are using the following formula for BC(It, K):
934   //
935   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
936   //
937   // Suppose, W is the bitwidth of the return value.  We must be prepared for
938   // overflow.  Hence, we must assure that the result of our computation is
939   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
940   // safe in modular arithmetic.
941   //
942   // However, this code doesn't use exactly that formula; the formula it uses
943   // is something like the following, where T is the number of factors of 2 in
944   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
945   // exponentiation:
946   //
947   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
948   //
949   // This formula is trivially equivalent to the previous formula.  However,
950   // this formula can be implemented much more efficiently.  The trick is that
951   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
952   // arithmetic.  To do exact division in modular arithmetic, all we have
953   // to do is multiply by the inverse.  Therefore, this step can be done at
954   // width W.
955   //
956   // The next issue is how to safely do the division by 2^T.  The way this
957   // is done is by doing the multiplication step at a width of at least W + T
958   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
959   // when we perform the division by 2^T (which is equivalent to a right shift
960   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
961   // truncated out after the division by 2^T.
962   //
963   // In comparison to just directly using the first formula, this technique
964   // is much more efficient; using the first formula requires W * K bits,
965   // but this formula less than W + K bits. Also, the first formula requires
966   // a division step, whereas this formula only requires multiplies and shifts.
967   //
968   // It doesn't matter whether the subtraction step is done in the calculation
969   // width or the input iteration count's width; if the subtraction overflows,
970   // the result must be zero anyway.  We prefer here to do it in the width of
971   // the induction variable because it helps a lot for certain cases; CodeGen
972   // isn't smart enough to ignore the overflow, which leads to much less
973   // efficient code if the width of the subtraction is wider than the native
974   // register width.
975   //
976   // (It's possible to not widen at all by pulling out factors of 2 before
977   // the multiplication; for example, K=2 can be calculated as
978   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
979   // extra arithmetic, so it's not an obvious win, and it gets
980   // much more complicated for K > 3.)
981 
982   // Protection from insane SCEVs; this bound is conservative,
983   // but it probably doesn't matter.
984   if (K > 1000)
985     return SE.getCouldNotCompute();
986 
987   unsigned W = SE.getTypeSizeInBits(ResultTy);
988 
989   // Calculate K! / 2^T and T; we divide out the factors of two before
990   // multiplying for calculating K! / 2^T to avoid overflow.
991   // Other overflow doesn't matter because we only care about the bottom
992   // W bits of the result.
993   APInt OddFactorial(W, 1);
994   unsigned T = 1;
995   for (unsigned i = 3; i <= K; ++i) {
996     APInt Mult(W, i);
997     unsigned TwoFactors = Mult.countTrailingZeros();
998     T += TwoFactors;
999     Mult = Mult.lshr(TwoFactors);
1000     OddFactorial *= Mult;
1001   }
1002 
1003   // We need at least W + T bits for the multiplication step
1004   unsigned CalculationBits = W + T;
1005 
1006   // Calculate 2^T, at width T+W.
1007   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1008 
1009   // Calculate the multiplicative inverse of K! / 2^T;
1010   // this multiplication factor will perform the exact division by
1011   // K! / 2^T.
1012   APInt Mod = APInt::getSignedMinValue(W+1);
1013   APInt MultiplyFactor = OddFactorial.zext(W+1);
1014   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1015   MultiplyFactor = MultiplyFactor.trunc(W);
1016 
1017   // Calculate the product, at width T+W
1018   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1019                                                       CalculationBits);
1020   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1021   for (unsigned i = 1; i != K; ++i) {
1022     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1023     Dividend = SE.getMulExpr(Dividend,
1024                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1025   }
1026 
1027   // Divide by 2^T
1028   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1029 
1030   // Truncate the result, and divide by K! / 2^T.
1031 
1032   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1033                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1034 }
1035 
1036 /// Return the value of this chain of recurrences at the specified iteration
1037 /// number.  We can evaluate this recurrence by multiplying each element in the
1038 /// chain by the binomial coefficient corresponding to it.  In other words, we
1039 /// can evaluate {A,+,B,+,C,+,D} as:
1040 ///
1041 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1042 ///
1043 /// where BC(It, k) stands for binomial coefficient.
1044 ///
1045 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1046                                                 ScalarEvolution &SE) const {
1047   const SCEV *Result = getStart();
1048   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1049     // The computation is correct in the face of overflow provided that the
1050     // multiplication is performed _after_ the evaluation of the binomial
1051     // coefficient.
1052     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1053     if (isa<SCEVCouldNotCompute>(Coeff))
1054       return Coeff;
1055 
1056     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1057   }
1058   return Result;
1059 }
1060 
1061 //===----------------------------------------------------------------------===//
1062 //                    SCEV Expression folder implementations
1063 //===----------------------------------------------------------------------===//
1064 
1065 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
1066                                              Type *Ty) {
1067   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1068          "This is not a truncating conversion!");
1069   assert(isSCEVable(Ty) &&
1070          "This is not a conversion to a SCEVable type!");
1071   Ty = getEffectiveSCEVType(Ty);
1072 
1073   FoldingSetNodeID ID;
1074   ID.AddInteger(scTruncate);
1075   ID.AddPointer(Op);
1076   ID.AddPointer(Ty);
1077   void *IP = nullptr;
1078   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1079 
1080   // Fold if the operand is constant.
1081   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1082     return getConstant(
1083       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1084 
1085   // trunc(trunc(x)) --> trunc(x)
1086   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1087     return getTruncateExpr(ST->getOperand(), Ty);
1088 
1089   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1090   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1091     return getTruncateOrSignExtend(SS->getOperand(), Ty);
1092 
1093   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1094   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1095     return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1096 
1097   // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
1098   // eliminate all the truncates, or we replace other casts with truncates.
1099   if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1100     SmallVector<const SCEV *, 4> Operands;
1101     bool hasTrunc = false;
1102     for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1103       const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
1104       if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1105         hasTrunc = isa<SCEVTruncateExpr>(S);
1106       Operands.push_back(S);
1107     }
1108     if (!hasTrunc)
1109       return getAddExpr(Operands);
1110     UniqueSCEVs.FindNodeOrInsertPos(ID, IP);  // Mutates IP, returns NULL.
1111   }
1112 
1113   // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
1114   // eliminate all the truncates, or we replace other casts with truncates.
1115   if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1116     SmallVector<const SCEV *, 4> Operands;
1117     bool hasTrunc = false;
1118     for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1119       const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
1120       if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1121         hasTrunc = isa<SCEVTruncateExpr>(S);
1122       Operands.push_back(S);
1123     }
1124     if (!hasTrunc)
1125       return getMulExpr(Operands);
1126     UniqueSCEVs.FindNodeOrInsertPos(ID, IP);  // Mutates IP, returns NULL.
1127   }
1128 
1129   // If the input value is a chrec scev, truncate the chrec's operands.
1130   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1131     SmallVector<const SCEV *, 4> Operands;
1132     for (const SCEV *Op : AddRec->operands())
1133       Operands.push_back(getTruncateExpr(Op, Ty));
1134     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1135   }
1136 
1137   // The cast wasn't folded; create an explicit cast node. We can reuse
1138   // the existing insert position since if we get here, we won't have
1139   // made any changes which would invalidate it.
1140   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1141                                                  Op, Ty);
1142   UniqueSCEVs.InsertNode(S, IP);
1143   return S;
1144 }
1145 
1146 // Get the limit of a recurrence such that incrementing by Step cannot cause
1147 // signed overflow as long as the value of the recurrence within the
1148 // loop does not exceed this limit before incrementing.
1149 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1150                                                  ICmpInst::Predicate *Pred,
1151                                                  ScalarEvolution *SE) {
1152   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1153   if (SE->isKnownPositive(Step)) {
1154     *Pred = ICmpInst::ICMP_SLT;
1155     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1156                            SE->getSignedRange(Step).getSignedMax());
1157   }
1158   if (SE->isKnownNegative(Step)) {
1159     *Pred = ICmpInst::ICMP_SGT;
1160     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1161                            SE->getSignedRange(Step).getSignedMin());
1162   }
1163   return nullptr;
1164 }
1165 
1166 // Get the limit of a recurrence such that incrementing by Step cannot cause
1167 // unsigned overflow as long as the value of the recurrence within the loop does
1168 // not exceed this limit before incrementing.
1169 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1170                                                    ICmpInst::Predicate *Pred,
1171                                                    ScalarEvolution *SE) {
1172   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1173   *Pred = ICmpInst::ICMP_ULT;
1174 
1175   return SE->getConstant(APInt::getMinValue(BitWidth) -
1176                          SE->getUnsignedRange(Step).getUnsignedMax());
1177 }
1178 
1179 namespace {
1180 
1181 struct ExtendOpTraitsBase {
1182   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *);
1183 };
1184 
1185 // Used to make code generic over signed and unsigned overflow.
1186 template <typename ExtendOp> struct ExtendOpTraits {
1187   // Members present:
1188   //
1189   // static const SCEV::NoWrapFlags WrapType;
1190   //
1191   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1192   //
1193   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1194   //                                           ICmpInst::Predicate *Pred,
1195   //                                           ScalarEvolution *SE);
1196 };
1197 
1198 template <>
1199 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1200   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1201 
1202   static const GetExtendExprTy GetExtendExpr;
1203 
1204   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1205                                              ICmpInst::Predicate *Pred,
1206                                              ScalarEvolution *SE) {
1207     return getSignedOverflowLimitForStep(Step, Pred, SE);
1208   }
1209 };
1210 
1211 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1212     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1213 
1214 template <>
1215 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1216   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1217 
1218   static const GetExtendExprTy GetExtendExpr;
1219 
1220   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1221                                              ICmpInst::Predicate *Pred,
1222                                              ScalarEvolution *SE) {
1223     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1224   }
1225 };
1226 
1227 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1228     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1229 }
1230 
1231 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1232 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1233 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1234 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1235 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1236 // expression "Step + sext/zext(PreIncAR)" is congruent with
1237 // "sext/zext(PostIncAR)"
1238 template <typename ExtendOpTy>
1239 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1240                                         ScalarEvolution *SE) {
1241   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1242   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1243 
1244   const Loop *L = AR->getLoop();
1245   const SCEV *Start = AR->getStart();
1246   const SCEV *Step = AR->getStepRecurrence(*SE);
1247 
1248   // Check for a simple looking step prior to loop entry.
1249   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1250   if (!SA)
1251     return nullptr;
1252 
1253   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1254   // subtraction is expensive. For this purpose, perform a quick and dirty
1255   // difference, by checking for Step in the operand list.
1256   SmallVector<const SCEV *, 4> DiffOps;
1257   for (const SCEV *Op : SA->operands())
1258     if (Op != Step)
1259       DiffOps.push_back(Op);
1260 
1261   if (DiffOps.size() == SA->getNumOperands())
1262     return nullptr;
1263 
1264   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1265   // `Step`:
1266 
1267   // 1. NSW/NUW flags on the step increment.
1268   auto PreStartFlags =
1269     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1270   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1271   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1272       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1273 
1274   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1275   // "S+X does not sign/unsign-overflow".
1276   //
1277 
1278   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1279   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1280       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1281     return PreStart;
1282 
1283   // 2. Direct overflow check on the step operation's expression.
1284   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1285   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1286   const SCEV *OperandExtendedStart =
1287       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy),
1288                      (SE->*GetExtendExpr)(Step, WideTy));
1289   if ((SE->*GetExtendExpr)(Start, WideTy) == OperandExtendedStart) {
1290     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1291       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1292       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1293       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1294       const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1295     }
1296     return PreStart;
1297   }
1298 
1299   // 3. Loop precondition.
1300   ICmpInst::Predicate Pred;
1301   const SCEV *OverflowLimit =
1302       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1303 
1304   if (OverflowLimit &&
1305       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1306     return PreStart;
1307 
1308   return nullptr;
1309 }
1310 
1311 // Get the normalized zero or sign extended expression for this AddRec's Start.
1312 template <typename ExtendOpTy>
1313 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1314                                         ScalarEvolution *SE) {
1315   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1316 
1317   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE);
1318   if (!PreStart)
1319     return (SE->*GetExtendExpr)(AR->getStart(), Ty);
1320 
1321   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty),
1322                         (SE->*GetExtendExpr)(PreStart, Ty));
1323 }
1324 
1325 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1326 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1327 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1328 //
1329 // Formally:
1330 //
1331 //     {S,+,X} == {S-T,+,X} + T
1332 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1333 //
1334 // If ({S-T,+,X} + T) does not overflow  ... (1)
1335 //
1336 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1337 //
1338 // If {S-T,+,X} does not overflow  ... (2)
1339 //
1340 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1341 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1342 //
1343 // If (S-T)+T does not overflow  ... (3)
1344 //
1345 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1346 //      == {Ext(S),+,Ext(X)} == LHS
1347 //
1348 // Thus, if (1), (2) and (3) are true for some T, then
1349 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1350 //
1351 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1352 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1353 // to check for (1) and (2).
1354 //
1355 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1356 // is `Delta` (defined below).
1357 //
1358 template <typename ExtendOpTy>
1359 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1360                                                 const SCEV *Step,
1361                                                 const Loop *L) {
1362   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1363 
1364   // We restrict `Start` to a constant to prevent SCEV from spending too much
1365   // time here.  It is correct (but more expensive) to continue with a
1366   // non-constant `Start` and do a general SCEV subtraction to compute
1367   // `PreStart` below.
1368   //
1369   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1370   if (!StartC)
1371     return false;
1372 
1373   APInt StartAI = StartC->getAPInt();
1374 
1375   for (unsigned Delta : {-2, -1, 1, 2}) {
1376     const SCEV *PreStart = getConstant(StartAI - Delta);
1377 
1378     FoldingSetNodeID ID;
1379     ID.AddInteger(scAddRecExpr);
1380     ID.AddPointer(PreStart);
1381     ID.AddPointer(Step);
1382     ID.AddPointer(L);
1383     void *IP = nullptr;
1384     const auto *PreAR =
1385       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1386 
1387     // Give up if we don't already have the add recurrence we need because
1388     // actually constructing an add recurrence is relatively expensive.
1389     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1390       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1391       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1392       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1393           DeltaS, &Pred, this);
1394       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1395         return true;
1396     }
1397   }
1398 
1399   return false;
1400 }
1401 
1402 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
1403                                                Type *Ty) {
1404   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1405          "This is not an extending conversion!");
1406   assert(isSCEVable(Ty) &&
1407          "This is not a conversion to a SCEVable type!");
1408   Ty = getEffectiveSCEVType(Ty);
1409 
1410   // Fold if the operand is constant.
1411   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1412     return getConstant(
1413       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1414 
1415   // zext(zext(x)) --> zext(x)
1416   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1417     return getZeroExtendExpr(SZ->getOperand(), Ty);
1418 
1419   // Before doing any expensive analysis, check to see if we've already
1420   // computed a SCEV for this Op and Ty.
1421   FoldingSetNodeID ID;
1422   ID.AddInteger(scZeroExtend);
1423   ID.AddPointer(Op);
1424   ID.AddPointer(Ty);
1425   void *IP = nullptr;
1426   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1427 
1428   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1429   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1430     // It's possible the bits taken off by the truncate were all zero bits. If
1431     // so, we should be able to simplify this further.
1432     const SCEV *X = ST->getOperand();
1433     ConstantRange CR = getUnsignedRange(X);
1434     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1435     unsigned NewBits = getTypeSizeInBits(Ty);
1436     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1437             CR.zextOrTrunc(NewBits)))
1438       return getTruncateOrZeroExtend(X, Ty);
1439   }
1440 
1441   // If the input value is a chrec scev, and we can prove that the value
1442   // did not overflow the old, smaller, value, we can zero extend all of the
1443   // operands (often constants).  This allows analysis of something like
1444   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1445   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1446     if (AR->isAffine()) {
1447       const SCEV *Start = AR->getStart();
1448       const SCEV *Step = AR->getStepRecurrence(*this);
1449       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1450       const Loop *L = AR->getLoop();
1451 
1452       if (!AR->hasNoUnsignedWrap()) {
1453         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1454         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1455       }
1456 
1457       // If we have special knowledge that this addrec won't overflow,
1458       // we don't need to do any further analysis.
1459       if (AR->hasNoUnsignedWrap())
1460         return getAddRecExpr(
1461             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1462             getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1463 
1464       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1465       // Note that this serves two purposes: It filters out loops that are
1466       // simply not analyzable, and it covers the case where this code is
1467       // being called from within backedge-taken count analysis, such that
1468       // attempting to ask for the backedge-taken count would likely result
1469       // in infinite recursion. In the later case, the analysis code will
1470       // cope with a conservative value, and it will take care to purge
1471       // that value once it has finished.
1472       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1473       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1474         // Manually compute the final value for AR, checking for
1475         // overflow.
1476 
1477         // Check whether the backedge-taken count can be losslessly casted to
1478         // the addrec's type. The count is always unsigned.
1479         const SCEV *CastedMaxBECount =
1480           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1481         const SCEV *RecastedMaxBECount =
1482           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1483         if (MaxBECount == RecastedMaxBECount) {
1484           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1485           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1486           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
1487           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy);
1488           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy);
1489           const SCEV *WideMaxBECount =
1490             getZeroExtendExpr(CastedMaxBECount, WideTy);
1491           const SCEV *OperandExtendedAdd =
1492             getAddExpr(WideStart,
1493                        getMulExpr(WideMaxBECount,
1494                                   getZeroExtendExpr(Step, WideTy)));
1495           if (ZAdd == OperandExtendedAdd) {
1496             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1497             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1498             // Return the expression with the addrec on the outside.
1499             return getAddRecExpr(
1500                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1501                 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1502           }
1503           // Similar to above, only this time treat the step value as signed.
1504           // This covers loops that count down.
1505           OperandExtendedAdd =
1506             getAddExpr(WideStart,
1507                        getMulExpr(WideMaxBECount,
1508                                   getSignExtendExpr(Step, WideTy)));
1509           if (ZAdd == OperandExtendedAdd) {
1510             // Cache knowledge of AR NW, which is propagated to this AddRec.
1511             // Negative step causes unsigned wrap, but it still can't self-wrap.
1512             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1513             // Return the expression with the addrec on the outside.
1514             return getAddRecExpr(
1515                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1516                 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1517           }
1518         }
1519       }
1520 
1521       // Normally, in the cases we can prove no-overflow via a
1522       // backedge guarding condition, we can also compute a backedge
1523       // taken count for the loop.  The exceptions are assumptions and
1524       // guards present in the loop -- SCEV is not great at exploiting
1525       // these to compute max backedge taken counts, but can still use
1526       // these to prove lack of overflow.  Use this fact to avoid
1527       // doing extra work that may not pay off.
1528       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1529           !AC.assumptions().empty()) {
1530         // If the backedge is guarded by a comparison with the pre-inc
1531         // value the addrec is safe. Also, if the entry is guarded by
1532         // a comparison with the start value and the backedge is
1533         // guarded by a comparison with the post-inc value, the addrec
1534         // is safe.
1535         if (isKnownPositive(Step)) {
1536           const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1537                                       getUnsignedRange(Step).getUnsignedMax());
1538           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1539               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
1540                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
1541                                            AR->getPostIncExpr(*this), N))) {
1542             // Cache knowledge of AR NUW, which is propagated to this
1543             // AddRec.
1544             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1545             // Return the expression with the addrec on the outside.
1546             return getAddRecExpr(
1547                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1548                 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1549           }
1550         } else if (isKnownNegative(Step)) {
1551           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1552                                       getSignedRange(Step).getSignedMin());
1553           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1554               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
1555                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1556                                            AR->getPostIncExpr(*this), N))) {
1557             // Cache knowledge of AR NW, which is propagated to this
1558             // AddRec.  Negative step causes unsigned wrap, but it
1559             // still can't self-wrap.
1560             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1561             // Return the expression with the addrec on the outside.
1562             return getAddRecExpr(
1563                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1564                 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1565           }
1566         }
1567       }
1568 
1569       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1570         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1571         return getAddRecExpr(
1572             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1573             getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1574       }
1575     }
1576 
1577   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1578     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1579     if (SA->hasNoUnsignedWrap()) {
1580       // If the addition does not unsign overflow then we can, by definition,
1581       // commute the zero extension with the addition operation.
1582       SmallVector<const SCEV *, 4> Ops;
1583       for (const auto *Op : SA->operands())
1584         Ops.push_back(getZeroExtendExpr(Op, Ty));
1585       return getAddExpr(Ops, SCEV::FlagNUW);
1586     }
1587   }
1588 
1589   // The cast wasn't folded; create an explicit cast node.
1590   // Recompute the insert position, as it may have been invalidated.
1591   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1592   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1593                                                    Op, Ty);
1594   UniqueSCEVs.InsertNode(S, IP);
1595   return S;
1596 }
1597 
1598 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
1599                                                Type *Ty) {
1600   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1601          "This is not an extending conversion!");
1602   assert(isSCEVable(Ty) &&
1603          "This is not a conversion to a SCEVable type!");
1604   Ty = getEffectiveSCEVType(Ty);
1605 
1606   // Fold if the operand is constant.
1607   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1608     return getConstant(
1609       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1610 
1611   // sext(sext(x)) --> sext(x)
1612   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1613     return getSignExtendExpr(SS->getOperand(), Ty);
1614 
1615   // sext(zext(x)) --> zext(x)
1616   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1617     return getZeroExtendExpr(SZ->getOperand(), Ty);
1618 
1619   // Before doing any expensive analysis, check to see if we've already
1620   // computed a SCEV for this Op and Ty.
1621   FoldingSetNodeID ID;
1622   ID.AddInteger(scSignExtend);
1623   ID.AddPointer(Op);
1624   ID.AddPointer(Ty);
1625   void *IP = nullptr;
1626   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1627 
1628   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1629   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1630     // It's possible the bits taken off by the truncate were all sign bits. If
1631     // so, we should be able to simplify this further.
1632     const SCEV *X = ST->getOperand();
1633     ConstantRange CR = getSignedRange(X);
1634     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1635     unsigned NewBits = getTypeSizeInBits(Ty);
1636     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1637             CR.sextOrTrunc(NewBits)))
1638       return getTruncateOrSignExtend(X, Ty);
1639   }
1640 
1641   // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
1642   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1643     if (SA->getNumOperands() == 2) {
1644       auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1645       auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
1646       if (SMul && SC1) {
1647         if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
1648           const APInt &C1 = SC1->getAPInt();
1649           const APInt &C2 = SC2->getAPInt();
1650           if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
1651               C2.ugt(C1) && C2.isPowerOf2())
1652             return getAddExpr(getSignExtendExpr(SC1, Ty),
1653                               getSignExtendExpr(SMul, Ty));
1654         }
1655       }
1656     }
1657 
1658     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1659     if (SA->hasNoSignedWrap()) {
1660       // If the addition does not sign overflow then we can, by definition,
1661       // commute the sign extension with the addition operation.
1662       SmallVector<const SCEV *, 4> Ops;
1663       for (const auto *Op : SA->operands())
1664         Ops.push_back(getSignExtendExpr(Op, Ty));
1665       return getAddExpr(Ops, SCEV::FlagNSW);
1666     }
1667   }
1668   // If the input value is a chrec scev, and we can prove that the value
1669   // did not overflow the old, smaller, value, we can sign extend all of the
1670   // operands (often constants).  This allows analysis of something like
1671   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1672   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1673     if (AR->isAffine()) {
1674       const SCEV *Start = AR->getStart();
1675       const SCEV *Step = AR->getStepRecurrence(*this);
1676       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1677       const Loop *L = AR->getLoop();
1678 
1679       if (!AR->hasNoSignedWrap()) {
1680         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1681         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1682       }
1683 
1684       // If we have special knowledge that this addrec won't overflow,
1685       // we don't need to do any further analysis.
1686       if (AR->hasNoSignedWrap())
1687         return getAddRecExpr(
1688             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1689             getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW);
1690 
1691       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1692       // Note that this serves two purposes: It filters out loops that are
1693       // simply not analyzable, and it covers the case where this code is
1694       // being called from within backedge-taken count analysis, such that
1695       // attempting to ask for the backedge-taken count would likely result
1696       // in infinite recursion. In the later case, the analysis code will
1697       // cope with a conservative value, and it will take care to purge
1698       // that value once it has finished.
1699       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1700       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1701         // Manually compute the final value for AR, checking for
1702         // overflow.
1703 
1704         // Check whether the backedge-taken count can be losslessly casted to
1705         // the addrec's type. The count is always unsigned.
1706         const SCEV *CastedMaxBECount =
1707           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1708         const SCEV *RecastedMaxBECount =
1709           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1710         if (MaxBECount == RecastedMaxBECount) {
1711           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1712           // Check whether Start+Step*MaxBECount has no signed overflow.
1713           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
1714           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy);
1715           const SCEV *WideStart = getSignExtendExpr(Start, WideTy);
1716           const SCEV *WideMaxBECount =
1717             getZeroExtendExpr(CastedMaxBECount, WideTy);
1718           const SCEV *OperandExtendedAdd =
1719             getAddExpr(WideStart,
1720                        getMulExpr(WideMaxBECount,
1721                                   getSignExtendExpr(Step, WideTy)));
1722           if (SAdd == OperandExtendedAdd) {
1723             // Cache knowledge of AR NSW, which is propagated to this AddRec.
1724             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1725             // Return the expression with the addrec on the outside.
1726             return getAddRecExpr(
1727                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1728                 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1729           }
1730           // Similar to above, only this time treat the step value as unsigned.
1731           // This covers loops that count up with an unsigned step.
1732           OperandExtendedAdd =
1733             getAddExpr(WideStart,
1734                        getMulExpr(WideMaxBECount,
1735                                   getZeroExtendExpr(Step, WideTy)));
1736           if (SAdd == OperandExtendedAdd) {
1737             // If AR wraps around then
1738             //
1739             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
1740             // => SAdd != OperandExtendedAdd
1741             //
1742             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1743             // (SAdd == OperandExtendedAdd => AR is NW)
1744 
1745             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1746 
1747             // Return the expression with the addrec on the outside.
1748             return getAddRecExpr(
1749                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1750                 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1751           }
1752         }
1753       }
1754 
1755       // Normally, in the cases we can prove no-overflow via a
1756       // backedge guarding condition, we can also compute a backedge
1757       // taken count for the loop.  The exceptions are assumptions and
1758       // guards present in the loop -- SCEV is not great at exploiting
1759       // these to compute max backedge taken counts, but can still use
1760       // these to prove lack of overflow.  Use this fact to avoid
1761       // doing extra work that may not pay off.
1762 
1763       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1764           !AC.assumptions().empty()) {
1765         // If the backedge is guarded by a comparison with the pre-inc
1766         // value the addrec is safe. Also, if the entry is guarded by
1767         // a comparison with the start value and the backedge is
1768         // guarded by a comparison with the post-inc value, the addrec
1769         // is safe.
1770         ICmpInst::Predicate Pred;
1771         const SCEV *OverflowLimit =
1772             getSignedOverflowLimitForStep(Step, &Pred, this);
1773         if (OverflowLimit &&
1774             (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1775              (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1776               isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1777                                           OverflowLimit)))) {
1778           // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1779           const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1780           return getAddRecExpr(
1781               getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1782               getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1783         }
1784       }
1785 
1786       // If Start and Step are constants, check if we can apply this
1787       // transformation:
1788       // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
1789       auto *SC1 = dyn_cast<SCEVConstant>(Start);
1790       auto *SC2 = dyn_cast<SCEVConstant>(Step);
1791       if (SC1 && SC2) {
1792         const APInt &C1 = SC1->getAPInt();
1793         const APInt &C2 = SC2->getAPInt();
1794         if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1795             C2.isPowerOf2()) {
1796           Start = getSignExtendExpr(Start, Ty);
1797           const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
1798                                             AR->getNoWrapFlags());
1799           return getAddExpr(Start, getSignExtendExpr(NewAR, Ty));
1800         }
1801       }
1802 
1803       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
1804         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1805         return getAddRecExpr(
1806             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1807             getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1808       }
1809     }
1810 
1811   // If the input value is provably positive and we could not simplify
1812   // away the sext build a zext instead.
1813   if (isKnownNonNegative(Op))
1814     return getZeroExtendExpr(Op, Ty);
1815 
1816   // The cast wasn't folded; create an explicit cast node.
1817   // Recompute the insert position, as it may have been invalidated.
1818   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1819   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1820                                                    Op, Ty);
1821   UniqueSCEVs.InsertNode(S, IP);
1822   return S;
1823 }
1824 
1825 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1826 /// unspecified bits out to the given type.
1827 ///
1828 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1829                                               Type *Ty) {
1830   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1831          "This is not an extending conversion!");
1832   assert(isSCEVable(Ty) &&
1833          "This is not a conversion to a SCEVable type!");
1834   Ty = getEffectiveSCEVType(Ty);
1835 
1836   // Sign-extend negative constants.
1837   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1838     if (SC->getAPInt().isNegative())
1839       return getSignExtendExpr(Op, Ty);
1840 
1841   // Peel off a truncate cast.
1842   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
1843     const SCEV *NewOp = T->getOperand();
1844     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1845       return getAnyExtendExpr(NewOp, Ty);
1846     return getTruncateOrNoop(NewOp, Ty);
1847   }
1848 
1849   // Next try a zext cast. If the cast is folded, use it.
1850   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
1851   if (!isa<SCEVZeroExtendExpr>(ZExt))
1852     return ZExt;
1853 
1854   // Next try a sext cast. If the cast is folded, use it.
1855   const SCEV *SExt = getSignExtendExpr(Op, Ty);
1856   if (!isa<SCEVSignExtendExpr>(SExt))
1857     return SExt;
1858 
1859   // Force the cast to be folded into the operands of an addrec.
1860   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1861     SmallVector<const SCEV *, 4> Ops;
1862     for (const SCEV *Op : AR->operands())
1863       Ops.push_back(getAnyExtendExpr(Op, Ty));
1864     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
1865   }
1866 
1867   // If the expression is obviously signed, use the sext cast value.
1868   if (isa<SCEVSMaxExpr>(Op))
1869     return SExt;
1870 
1871   // Absent any other information, use the zext cast value.
1872   return ZExt;
1873 }
1874 
1875 /// Process the given Ops list, which is a list of operands to be added under
1876 /// the given scale, update the given map. This is a helper function for
1877 /// getAddRecExpr. As an example of what it does, given a sequence of operands
1878 /// that would form an add expression like this:
1879 ///
1880 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
1881 ///
1882 /// where A and B are constants, update the map with these values:
1883 ///
1884 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1885 ///
1886 /// and add 13 + A*B*29 to AccumulatedConstant.
1887 /// This will allow getAddRecExpr to produce this:
1888 ///
1889 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1890 ///
1891 /// This form often exposes folding opportunities that are hidden in
1892 /// the original operand list.
1893 ///
1894 /// Return true iff it appears that any interesting folding opportunities
1895 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
1896 /// the common case where no interesting opportunities are present, and
1897 /// is also used as a check to avoid infinite recursion.
1898 ///
1899 static bool
1900 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1901                              SmallVectorImpl<const SCEV *> &NewOps,
1902                              APInt &AccumulatedConstant,
1903                              const SCEV *const *Ops, size_t NumOperands,
1904                              const APInt &Scale,
1905                              ScalarEvolution &SE) {
1906   bool Interesting = false;
1907 
1908   // Iterate over the add operands. They are sorted, with constants first.
1909   unsigned i = 0;
1910   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1911     ++i;
1912     // Pull a buried constant out to the outside.
1913     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1914       Interesting = true;
1915     AccumulatedConstant += Scale * C->getAPInt();
1916   }
1917 
1918   // Next comes everything else. We're especially interested in multiplies
1919   // here, but they're in the middle, so just visit the rest with one loop.
1920   for (; i != NumOperands; ++i) {
1921     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1922     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1923       APInt NewScale =
1924           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
1925       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1926         // A multiplication of a constant with another add; recurse.
1927         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
1928         Interesting |=
1929           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1930                                        Add->op_begin(), Add->getNumOperands(),
1931                                        NewScale, SE);
1932       } else {
1933         // A multiplication of a constant with some other value. Update
1934         // the map.
1935         SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1936         const SCEV *Key = SE.getMulExpr(MulOps);
1937         auto Pair = M.insert({Key, NewScale});
1938         if (Pair.second) {
1939           NewOps.push_back(Pair.first->first);
1940         } else {
1941           Pair.first->second += NewScale;
1942           // The map already had an entry for this value, which may indicate
1943           // a folding opportunity.
1944           Interesting = true;
1945         }
1946       }
1947     } else {
1948       // An ordinary operand. Update the map.
1949       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1950           M.insert({Ops[i], Scale});
1951       if (Pair.second) {
1952         NewOps.push_back(Pair.first->first);
1953       } else {
1954         Pair.first->second += Scale;
1955         // The map already had an entry for this value, which may indicate
1956         // a folding opportunity.
1957         Interesting = true;
1958       }
1959     }
1960   }
1961 
1962   return Interesting;
1963 }
1964 
1965 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
1966 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
1967 // can't-overflow flags for the operation if possible.
1968 static SCEV::NoWrapFlags
1969 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
1970                       const SmallVectorImpl<const SCEV *> &Ops,
1971                       SCEV::NoWrapFlags Flags) {
1972   using namespace std::placeholders;
1973   typedef OverflowingBinaryOperator OBO;
1974 
1975   bool CanAnalyze =
1976       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
1977   (void)CanAnalyze;
1978   assert(CanAnalyze && "don't call from other places!");
1979 
1980   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
1981   SCEV::NoWrapFlags SignOrUnsignWrap =
1982       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
1983 
1984   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
1985   auto IsKnownNonNegative = [&](const SCEV *S) {
1986     return SE->isKnownNonNegative(S);
1987   };
1988 
1989   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
1990     Flags =
1991         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
1992 
1993   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
1994 
1995   if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
1996       Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
1997 
1998     // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
1999     // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
2000 
2001     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2002     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2003       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2004           Instruction::Add, C, OBO::NoSignedWrap);
2005       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2006         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2007     }
2008     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2009       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2010           Instruction::Add, C, OBO::NoUnsignedWrap);
2011       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2012         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2013     }
2014   }
2015 
2016   return Flags;
2017 }
2018 
2019 /// Get a canonical add expression, or something simpler if possible.
2020 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2021                                         SCEV::NoWrapFlags Flags) {
2022   assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2023          "only nuw or nsw allowed");
2024   assert(!Ops.empty() && "Cannot get empty add!");
2025   if (Ops.size() == 1) return Ops[0];
2026 #ifndef NDEBUG
2027   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2028   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2029     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2030            "SCEVAddExpr operand types don't match!");
2031 #endif
2032 
2033   // Sort by complexity, this groups all similar expression types together.
2034   GroupByComplexity(Ops, &LI);
2035 
2036   Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2037 
2038   // If there are any constants, fold them together.
2039   unsigned Idx = 0;
2040   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2041     ++Idx;
2042     assert(Idx < Ops.size());
2043     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2044       // We found two constants, fold them together!
2045       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2046       if (Ops.size() == 2) return Ops[0];
2047       Ops.erase(Ops.begin()+1);  // Erase the folded element
2048       LHSC = cast<SCEVConstant>(Ops[0]);
2049     }
2050 
2051     // If we are left with a constant zero being added, strip it off.
2052     if (LHSC->getValue()->isZero()) {
2053       Ops.erase(Ops.begin());
2054       --Idx;
2055     }
2056 
2057     if (Ops.size() == 1) return Ops[0];
2058   }
2059 
2060   // Okay, check to see if the same value occurs in the operand list more than
2061   // once.  If so, merge them together into an multiply expression.  Since we
2062   // sorted the list, these values are required to be adjacent.
2063   Type *Ty = Ops[0]->getType();
2064   bool FoundMatch = false;
2065   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2066     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2067       // Scan ahead to count how many equal operands there are.
2068       unsigned Count = 2;
2069       while (i+Count != e && Ops[i+Count] == Ops[i])
2070         ++Count;
2071       // Merge the values into a multiply.
2072       const SCEV *Scale = getConstant(Ty, Count);
2073       const SCEV *Mul = getMulExpr(Scale, Ops[i]);
2074       if (Ops.size() == Count)
2075         return Mul;
2076       Ops[i] = Mul;
2077       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2078       --i; e -= Count - 1;
2079       FoundMatch = true;
2080     }
2081   if (FoundMatch)
2082     return getAddExpr(Ops, Flags);
2083 
2084   // Check for truncates. If all the operands are truncated from the same
2085   // type, see if factoring out the truncate would permit the result to be
2086   // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
2087   // if the contents of the resulting outer trunc fold to something simple.
2088   for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
2089     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
2090     Type *DstType = Trunc->getType();
2091     Type *SrcType = Trunc->getOperand()->getType();
2092     SmallVector<const SCEV *, 8> LargeOps;
2093     bool Ok = true;
2094     // Check all the operands to see if they can be represented in the
2095     // source type of the truncate.
2096     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2097       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2098         if (T->getOperand()->getType() != SrcType) {
2099           Ok = false;
2100           break;
2101         }
2102         LargeOps.push_back(T->getOperand());
2103       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2104         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2105       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2106         SmallVector<const SCEV *, 8> LargeMulOps;
2107         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2108           if (const SCEVTruncateExpr *T =
2109                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2110             if (T->getOperand()->getType() != SrcType) {
2111               Ok = false;
2112               break;
2113             }
2114             LargeMulOps.push_back(T->getOperand());
2115           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2116             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2117           } else {
2118             Ok = false;
2119             break;
2120           }
2121         }
2122         if (Ok)
2123           LargeOps.push_back(getMulExpr(LargeMulOps));
2124       } else {
2125         Ok = false;
2126         break;
2127       }
2128     }
2129     if (Ok) {
2130       // Evaluate the expression in the larger type.
2131       const SCEV *Fold = getAddExpr(LargeOps, Flags);
2132       // If it folds to something simple, use it. Otherwise, don't.
2133       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2134         return getTruncateExpr(Fold, DstType);
2135     }
2136   }
2137 
2138   // Skip past any other cast SCEVs.
2139   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2140     ++Idx;
2141 
2142   // If there are add operands they would be next.
2143   if (Idx < Ops.size()) {
2144     bool DeletedAdd = false;
2145     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2146       // If we have an add, expand the add operands onto the end of the operands
2147       // list.
2148       Ops.erase(Ops.begin()+Idx);
2149       Ops.append(Add->op_begin(), Add->op_end());
2150       DeletedAdd = true;
2151     }
2152 
2153     // If we deleted at least one add, we added operands to the end of the list,
2154     // and they are not necessarily sorted.  Recurse to resort and resimplify
2155     // any operands we just acquired.
2156     if (DeletedAdd)
2157       return getAddExpr(Ops);
2158   }
2159 
2160   // Skip over the add expression until we get to a multiply.
2161   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2162     ++Idx;
2163 
2164   // Check to see if there are any folding opportunities present with
2165   // operands multiplied by constant values.
2166   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2167     uint64_t BitWidth = getTypeSizeInBits(Ty);
2168     DenseMap<const SCEV *, APInt> M;
2169     SmallVector<const SCEV *, 8> NewOps;
2170     APInt AccumulatedConstant(BitWidth, 0);
2171     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2172                                      Ops.data(), Ops.size(),
2173                                      APInt(BitWidth, 1), *this)) {
2174       struct APIntCompare {
2175         bool operator()(const APInt &LHS, const APInt &RHS) const {
2176           return LHS.ult(RHS);
2177         }
2178       };
2179 
2180       // Some interesting folding opportunity is present, so its worthwhile to
2181       // re-generate the operands list. Group the operands by constant scale,
2182       // to avoid multiplying by the same constant scale multiple times.
2183       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2184       for (const SCEV *NewOp : NewOps)
2185         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2186       // Re-generate the operands list.
2187       Ops.clear();
2188       if (AccumulatedConstant != 0)
2189         Ops.push_back(getConstant(AccumulatedConstant));
2190       for (auto &MulOp : MulOpLists)
2191         if (MulOp.first != 0)
2192           Ops.push_back(getMulExpr(getConstant(MulOp.first),
2193                                    getAddExpr(MulOp.second)));
2194       if (Ops.empty())
2195         return getZero(Ty);
2196       if (Ops.size() == 1)
2197         return Ops[0];
2198       return getAddExpr(Ops);
2199     }
2200   }
2201 
2202   // If we are adding something to a multiply expression, make sure the
2203   // something is not already an operand of the multiply.  If so, merge it into
2204   // the multiply.
2205   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2206     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2207     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2208       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2209       if (isa<SCEVConstant>(MulOpSCEV))
2210         continue;
2211       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2212         if (MulOpSCEV == Ops[AddOp]) {
2213           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2214           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2215           if (Mul->getNumOperands() != 2) {
2216             // If the multiply has more than two operands, we must get the
2217             // Y*Z term.
2218             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2219                                                 Mul->op_begin()+MulOp);
2220             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2221             InnerMul = getMulExpr(MulOps);
2222           }
2223           const SCEV *One = getOne(Ty);
2224           const SCEV *AddOne = getAddExpr(One, InnerMul);
2225           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
2226           if (Ops.size() == 2) return OuterMul;
2227           if (AddOp < Idx) {
2228             Ops.erase(Ops.begin()+AddOp);
2229             Ops.erase(Ops.begin()+Idx-1);
2230           } else {
2231             Ops.erase(Ops.begin()+Idx);
2232             Ops.erase(Ops.begin()+AddOp-1);
2233           }
2234           Ops.push_back(OuterMul);
2235           return getAddExpr(Ops);
2236         }
2237 
2238       // Check this multiply against other multiplies being added together.
2239       for (unsigned OtherMulIdx = Idx+1;
2240            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2241            ++OtherMulIdx) {
2242         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2243         // If MulOp occurs in OtherMul, we can fold the two multiplies
2244         // together.
2245         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2246              OMulOp != e; ++OMulOp)
2247           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2248             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2249             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2250             if (Mul->getNumOperands() != 2) {
2251               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2252                                                   Mul->op_begin()+MulOp);
2253               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2254               InnerMul1 = getMulExpr(MulOps);
2255             }
2256             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2257             if (OtherMul->getNumOperands() != 2) {
2258               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2259                                                   OtherMul->op_begin()+OMulOp);
2260               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2261               InnerMul2 = getMulExpr(MulOps);
2262             }
2263             const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
2264             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
2265             if (Ops.size() == 2) return OuterMul;
2266             Ops.erase(Ops.begin()+Idx);
2267             Ops.erase(Ops.begin()+OtherMulIdx-1);
2268             Ops.push_back(OuterMul);
2269             return getAddExpr(Ops);
2270           }
2271       }
2272     }
2273   }
2274 
2275   // If there are any add recurrences in the operands list, see if any other
2276   // added values are loop invariant.  If so, we can fold them into the
2277   // recurrence.
2278   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2279     ++Idx;
2280 
2281   // Scan over all recurrences, trying to fold loop invariants into them.
2282   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2283     // Scan all of the other operands to this add and add them to the vector if
2284     // they are loop invariant w.r.t. the recurrence.
2285     SmallVector<const SCEV *, 8> LIOps;
2286     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2287     const Loop *AddRecLoop = AddRec->getLoop();
2288     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2289       if (isLoopInvariant(Ops[i], AddRecLoop)) {
2290         LIOps.push_back(Ops[i]);
2291         Ops.erase(Ops.begin()+i);
2292         --i; --e;
2293       }
2294 
2295     // If we found some loop invariants, fold them into the recurrence.
2296     if (!LIOps.empty()) {
2297       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2298       LIOps.push_back(AddRec->getStart());
2299 
2300       SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2301                                              AddRec->op_end());
2302       // This follows from the fact that the no-wrap flags on the outer add
2303       // expression are applicable on the 0th iteration, when the add recurrence
2304       // will be equal to its start value.
2305       AddRecOps[0] = getAddExpr(LIOps, Flags);
2306 
2307       // Build the new addrec. Propagate the NUW and NSW flags if both the
2308       // outer add and the inner addrec are guaranteed to have no overflow.
2309       // Always propagate NW.
2310       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2311       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2312 
2313       // If all of the other operands were loop invariant, we are done.
2314       if (Ops.size() == 1) return NewRec;
2315 
2316       // Otherwise, add the folded AddRec by the non-invariant parts.
2317       for (unsigned i = 0;; ++i)
2318         if (Ops[i] == AddRec) {
2319           Ops[i] = NewRec;
2320           break;
2321         }
2322       return getAddExpr(Ops);
2323     }
2324 
2325     // Okay, if there weren't any loop invariants to be folded, check to see if
2326     // there are multiple AddRec's with the same loop induction variable being
2327     // added together.  If so, we can fold them.
2328     for (unsigned OtherIdx = Idx+1;
2329          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2330          ++OtherIdx)
2331       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2332         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2333         SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2334                                                AddRec->op_end());
2335         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2336              ++OtherIdx)
2337           if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
2338             if (OtherAddRec->getLoop() == AddRecLoop) {
2339               for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2340                    i != e; ++i) {
2341                 if (i >= AddRecOps.size()) {
2342                   AddRecOps.append(OtherAddRec->op_begin()+i,
2343                                    OtherAddRec->op_end());
2344                   break;
2345                 }
2346                 AddRecOps[i] = getAddExpr(AddRecOps[i],
2347                                           OtherAddRec->getOperand(i));
2348               }
2349               Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2350             }
2351         // Step size has changed, so we cannot guarantee no self-wraparound.
2352         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2353         return getAddExpr(Ops);
2354       }
2355 
2356     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2357     // next one.
2358   }
2359 
2360   // Okay, it looks like we really DO need an add expr.  Check to see if we
2361   // already have one, otherwise create a new one.
2362   FoldingSetNodeID ID;
2363   ID.AddInteger(scAddExpr);
2364   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2365     ID.AddPointer(Ops[i]);
2366   void *IP = nullptr;
2367   SCEVAddExpr *S =
2368     static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2369   if (!S) {
2370     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2371     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2372     S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
2373                                         O, Ops.size());
2374     UniqueSCEVs.InsertNode(S, IP);
2375   }
2376   S->setNoWrapFlags(Flags);
2377   return S;
2378 }
2379 
2380 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2381   uint64_t k = i*j;
2382   if (j > 1 && k / j != i) Overflow = true;
2383   return k;
2384 }
2385 
2386 /// Compute the result of "n choose k", the binomial coefficient.  If an
2387 /// intermediate computation overflows, Overflow will be set and the return will
2388 /// be garbage. Overflow is not cleared on absence of overflow.
2389 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2390   // We use the multiplicative formula:
2391   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2392   // At each iteration, we take the n-th term of the numeral and divide by the
2393   // (k-n)th term of the denominator.  This division will always produce an
2394   // integral result, and helps reduce the chance of overflow in the
2395   // intermediate computations. However, we can still overflow even when the
2396   // final result would fit.
2397 
2398   if (n == 0 || n == k) return 1;
2399   if (k > n) return 0;
2400 
2401   if (k > n/2)
2402     k = n-k;
2403 
2404   uint64_t r = 1;
2405   for (uint64_t i = 1; i <= k; ++i) {
2406     r = umul_ov(r, n-(i-1), Overflow);
2407     r /= i;
2408   }
2409   return r;
2410 }
2411 
2412 /// Determine if any of the operands in this SCEV are a constant or if
2413 /// any of the add or multiply expressions in this SCEV contain a constant.
2414 static bool containsConstantSomewhere(const SCEV *StartExpr) {
2415   SmallVector<const SCEV *, 4> Ops;
2416   Ops.push_back(StartExpr);
2417   while (!Ops.empty()) {
2418     const SCEV *CurrentExpr = Ops.pop_back_val();
2419     if (isa<SCEVConstant>(*CurrentExpr))
2420       return true;
2421 
2422     if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) {
2423       const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr);
2424       Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end());
2425     }
2426   }
2427   return false;
2428 }
2429 
2430 /// Get a canonical multiply expression, or something simpler if possible.
2431 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2432                                         SCEV::NoWrapFlags Flags) {
2433   assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2434          "only nuw or nsw allowed");
2435   assert(!Ops.empty() && "Cannot get empty mul!");
2436   if (Ops.size() == 1) return Ops[0];
2437 #ifndef NDEBUG
2438   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2439   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2440     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2441            "SCEVMulExpr operand types don't match!");
2442 #endif
2443 
2444   // Sort by complexity, this groups all similar expression types together.
2445   GroupByComplexity(Ops, &LI);
2446 
2447   Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2448 
2449   // If there are any constants, fold them together.
2450   unsigned Idx = 0;
2451   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2452 
2453     // C1*(C2+V) -> C1*C2 + C1*V
2454     if (Ops.size() == 2)
2455         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2456           // If any of Add's ops are Adds or Muls with a constant,
2457           // apply this transformation as well.
2458           if (Add->getNumOperands() == 2)
2459             if (containsConstantSomewhere(Add))
2460               return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
2461                                 getMulExpr(LHSC, Add->getOperand(1)));
2462 
2463     ++Idx;
2464     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2465       // We found two constants, fold them together!
2466       ConstantInt *Fold =
2467           ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2468       Ops[0] = getConstant(Fold);
2469       Ops.erase(Ops.begin()+1);  // Erase the folded element
2470       if (Ops.size() == 1) return Ops[0];
2471       LHSC = cast<SCEVConstant>(Ops[0]);
2472     }
2473 
2474     // If we are left with a constant one being multiplied, strip it off.
2475     if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
2476       Ops.erase(Ops.begin());
2477       --Idx;
2478     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2479       // If we have a multiply of zero, it will always be zero.
2480       return Ops[0];
2481     } else if (Ops[0]->isAllOnesValue()) {
2482       // If we have a mul by -1 of an add, try distributing the -1 among the
2483       // add operands.
2484       if (Ops.size() == 2) {
2485         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2486           SmallVector<const SCEV *, 4> NewOps;
2487           bool AnyFolded = false;
2488           for (const SCEV *AddOp : Add->operands()) {
2489             const SCEV *Mul = getMulExpr(Ops[0], AddOp);
2490             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2491             NewOps.push_back(Mul);
2492           }
2493           if (AnyFolded)
2494             return getAddExpr(NewOps);
2495         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2496           // Negation preserves a recurrence's no self-wrap property.
2497           SmallVector<const SCEV *, 4> Operands;
2498           for (const SCEV *AddRecOp : AddRec->operands())
2499             Operands.push_back(getMulExpr(Ops[0], AddRecOp));
2500 
2501           return getAddRecExpr(Operands, AddRec->getLoop(),
2502                                AddRec->getNoWrapFlags(SCEV::FlagNW));
2503         }
2504       }
2505     }
2506 
2507     if (Ops.size() == 1)
2508       return Ops[0];
2509   }
2510 
2511   // Skip over the add expression until we get to a multiply.
2512   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2513     ++Idx;
2514 
2515   // If there are mul operands inline them all into this expression.
2516   if (Idx < Ops.size()) {
2517     bool DeletedMul = false;
2518     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2519       // If we have an mul, expand the mul operands onto the end of the operands
2520       // list.
2521       Ops.erase(Ops.begin()+Idx);
2522       Ops.append(Mul->op_begin(), Mul->op_end());
2523       DeletedMul = true;
2524     }
2525 
2526     // If we deleted at least one mul, we added operands to the end of the list,
2527     // and they are not necessarily sorted.  Recurse to resort and resimplify
2528     // any operands we just acquired.
2529     if (DeletedMul)
2530       return getMulExpr(Ops);
2531   }
2532 
2533   // If there are any add recurrences in the operands list, see if any other
2534   // added values are loop invariant.  If so, we can fold them into the
2535   // recurrence.
2536   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2537     ++Idx;
2538 
2539   // Scan over all recurrences, trying to fold loop invariants into them.
2540   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2541     // Scan all of the other operands to this mul and add them to the vector if
2542     // they are loop invariant w.r.t. the recurrence.
2543     SmallVector<const SCEV *, 8> LIOps;
2544     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2545     const Loop *AddRecLoop = AddRec->getLoop();
2546     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2547       if (isLoopInvariant(Ops[i], AddRecLoop)) {
2548         LIOps.push_back(Ops[i]);
2549         Ops.erase(Ops.begin()+i);
2550         --i; --e;
2551       }
2552 
2553     // If we found some loop invariants, fold them into the recurrence.
2554     if (!LIOps.empty()) {
2555       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
2556       SmallVector<const SCEV *, 4> NewOps;
2557       NewOps.reserve(AddRec->getNumOperands());
2558       const SCEV *Scale = getMulExpr(LIOps);
2559       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2560         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
2561 
2562       // Build the new addrec. Propagate the NUW and NSW flags if both the
2563       // outer mul and the inner addrec are guaranteed to have no overflow.
2564       //
2565       // No self-wrap cannot be guaranteed after changing the step size, but
2566       // will be inferred if either NUW or NSW is true.
2567       Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2568       const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
2569 
2570       // If all of the other operands were loop invariant, we are done.
2571       if (Ops.size() == 1) return NewRec;
2572 
2573       // Otherwise, multiply the folded AddRec by the non-invariant parts.
2574       for (unsigned i = 0;; ++i)
2575         if (Ops[i] == AddRec) {
2576           Ops[i] = NewRec;
2577           break;
2578         }
2579       return getMulExpr(Ops);
2580     }
2581 
2582     // Okay, if there weren't any loop invariants to be folded, check to see if
2583     // there are multiple AddRec's with the same loop induction variable being
2584     // multiplied together.  If so, we can fold them.
2585 
2586     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2587     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2588     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2589     //   ]]],+,...up to x=2n}.
2590     // Note that the arguments to choose() are always integers with values
2591     // known at compile time, never SCEV objects.
2592     //
2593     // The implementation avoids pointless extra computations when the two
2594     // addrec's are of different length (mathematically, it's equivalent to
2595     // an infinite stream of zeros on the right).
2596     bool OpsModified = false;
2597     for (unsigned OtherIdx = Idx+1;
2598          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2599          ++OtherIdx) {
2600       const SCEVAddRecExpr *OtherAddRec =
2601         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2602       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
2603         continue;
2604 
2605       bool Overflow = false;
2606       Type *Ty = AddRec->getType();
2607       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2608       SmallVector<const SCEV*, 7> AddRecOps;
2609       for (int x = 0, xe = AddRec->getNumOperands() +
2610              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
2611         const SCEV *Term = getZero(Ty);
2612         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2613           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2614           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2615                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2616                z < ze && !Overflow; ++z) {
2617             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2618             uint64_t Coeff;
2619             if (LargerThan64Bits)
2620               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2621             else
2622               Coeff = Coeff1*Coeff2;
2623             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2624             const SCEV *Term1 = AddRec->getOperand(y-z);
2625             const SCEV *Term2 = OtherAddRec->getOperand(z);
2626             Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
2627           }
2628         }
2629         AddRecOps.push_back(Term);
2630       }
2631       if (!Overflow) {
2632         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2633                                               SCEV::FlagAnyWrap);
2634         if (Ops.size() == 2) return NewAddRec;
2635         Ops[Idx] = NewAddRec;
2636         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2637         OpsModified = true;
2638         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2639         if (!AddRec)
2640           break;
2641       }
2642     }
2643     if (OpsModified)
2644       return getMulExpr(Ops);
2645 
2646     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2647     // next one.
2648   }
2649 
2650   // Okay, it looks like we really DO need an mul expr.  Check to see if we
2651   // already have one, otherwise create a new one.
2652   FoldingSetNodeID ID;
2653   ID.AddInteger(scMulExpr);
2654   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2655     ID.AddPointer(Ops[i]);
2656   void *IP = nullptr;
2657   SCEVMulExpr *S =
2658     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2659   if (!S) {
2660     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2661     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2662     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2663                                         O, Ops.size());
2664     UniqueSCEVs.InsertNode(S, IP);
2665   }
2666   S->setNoWrapFlags(Flags);
2667   return S;
2668 }
2669 
2670 /// Get a canonical unsigned division expression, or something simpler if
2671 /// possible.
2672 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2673                                          const SCEV *RHS) {
2674   assert(getEffectiveSCEVType(LHS->getType()) ==
2675          getEffectiveSCEVType(RHS->getType()) &&
2676          "SCEVUDivExpr operand types don't match!");
2677 
2678   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
2679     if (RHSC->getValue()->equalsInt(1))
2680       return LHS;                               // X udiv 1 --> x
2681     // If the denominator is zero, the result of the udiv is undefined. Don't
2682     // try to analyze it, because the resolution chosen here may differ from
2683     // the resolution chosen in other parts of the compiler.
2684     if (!RHSC->getValue()->isZero()) {
2685       // Determine if the division can be folded into the operands of
2686       // its operands.
2687       // TODO: Generalize this to non-constants by using known-bits information.
2688       Type *Ty = LHS->getType();
2689       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
2690       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
2691       // For non-power-of-two values, effectively round the value up to the
2692       // nearest power of two.
2693       if (!RHSC->getAPInt().isPowerOf2())
2694         ++MaxShiftAmt;
2695       IntegerType *ExtTy =
2696         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
2697       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2698         if (const SCEVConstant *Step =
2699             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2700           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
2701           const APInt &StepInt = Step->getAPInt();
2702           const APInt &DivInt = RHSC->getAPInt();
2703           if (!StepInt.urem(DivInt) &&
2704               getZeroExtendExpr(AR, ExtTy) ==
2705               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2706                             getZeroExtendExpr(Step, ExtTy),
2707                             AR->getLoop(), SCEV::FlagAnyWrap)) {
2708             SmallVector<const SCEV *, 4> Operands;
2709             for (const SCEV *Op : AR->operands())
2710               Operands.push_back(getUDivExpr(Op, RHS));
2711             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
2712           }
2713           /// Get a canonical UDivExpr for a recurrence.
2714           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2715           // We can currently only fold X%N if X is constant.
2716           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2717           if (StartC && !DivInt.urem(StepInt) &&
2718               getZeroExtendExpr(AR, ExtTy) ==
2719               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2720                             getZeroExtendExpr(Step, ExtTy),
2721                             AR->getLoop(), SCEV::FlagAnyWrap)) {
2722             const APInt &StartInt = StartC->getAPInt();
2723             const APInt &StartRem = StartInt.urem(StepInt);
2724             if (StartRem != 0)
2725               LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2726                                   AR->getLoop(), SCEV::FlagNW);
2727           }
2728         }
2729       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2730       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2731         SmallVector<const SCEV *, 4> Operands;
2732         for (const SCEV *Op : M->operands())
2733           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
2734         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2735           // Find an operand that's safely divisible.
2736           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2737             const SCEV *Op = M->getOperand(i);
2738             const SCEV *Div = getUDivExpr(Op, RHSC);
2739             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2740               Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2741                                                       M->op_end());
2742               Operands[i] = Div;
2743               return getMulExpr(Operands);
2744             }
2745           }
2746       }
2747       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
2748       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
2749         SmallVector<const SCEV *, 4> Operands;
2750         for (const SCEV *Op : A->operands())
2751           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
2752         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2753           Operands.clear();
2754           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2755             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2756             if (isa<SCEVUDivExpr>(Op) ||
2757                 getMulExpr(Op, RHS) != A->getOperand(i))
2758               break;
2759             Operands.push_back(Op);
2760           }
2761           if (Operands.size() == A->getNumOperands())
2762             return getAddExpr(Operands);
2763         }
2764       }
2765 
2766       // Fold if both operands are constant.
2767       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2768         Constant *LHSCV = LHSC->getValue();
2769         Constant *RHSCV = RHSC->getValue();
2770         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2771                                                                    RHSCV)));
2772       }
2773     }
2774   }
2775 
2776   FoldingSetNodeID ID;
2777   ID.AddInteger(scUDivExpr);
2778   ID.AddPointer(LHS);
2779   ID.AddPointer(RHS);
2780   void *IP = nullptr;
2781   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2782   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2783                                              LHS, RHS);
2784   UniqueSCEVs.InsertNode(S, IP);
2785   return S;
2786 }
2787 
2788 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
2789   APInt A = C1->getAPInt().abs();
2790   APInt B = C2->getAPInt().abs();
2791   uint32_t ABW = A.getBitWidth();
2792   uint32_t BBW = B.getBitWidth();
2793 
2794   if (ABW > BBW)
2795     B = B.zext(ABW);
2796   else if (ABW < BBW)
2797     A = A.zext(BBW);
2798 
2799   return APIntOps::GreatestCommonDivisor(A, B);
2800 }
2801 
2802 /// Get a canonical unsigned division expression, or something simpler if
2803 /// possible. There is no representation for an exact udiv in SCEV IR, but we
2804 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
2805 /// it's not exact because the udiv may be clearing bits.
2806 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
2807                                               const SCEV *RHS) {
2808   // TODO: we could try to find factors in all sorts of things, but for now we
2809   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
2810   // end of this file for inspiration.
2811 
2812   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
2813   if (!Mul)
2814     return getUDivExpr(LHS, RHS);
2815 
2816   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
2817     // If the mulexpr multiplies by a constant, then that constant must be the
2818     // first element of the mulexpr.
2819     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
2820       if (LHSCst == RHSCst) {
2821         SmallVector<const SCEV *, 2> Operands;
2822         Operands.append(Mul->op_begin() + 1, Mul->op_end());
2823         return getMulExpr(Operands);
2824       }
2825 
2826       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
2827       // that there's a factor provided by one of the other terms. We need to
2828       // check.
2829       APInt Factor = gcd(LHSCst, RHSCst);
2830       if (!Factor.isIntN(1)) {
2831         LHSCst =
2832             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
2833         RHSCst =
2834             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
2835         SmallVector<const SCEV *, 2> Operands;
2836         Operands.push_back(LHSCst);
2837         Operands.append(Mul->op_begin() + 1, Mul->op_end());
2838         LHS = getMulExpr(Operands);
2839         RHS = RHSCst;
2840         Mul = dyn_cast<SCEVMulExpr>(LHS);
2841         if (!Mul)
2842           return getUDivExactExpr(LHS, RHS);
2843       }
2844     }
2845   }
2846 
2847   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
2848     if (Mul->getOperand(i) == RHS) {
2849       SmallVector<const SCEV *, 2> Operands;
2850       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
2851       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
2852       return getMulExpr(Operands);
2853     }
2854   }
2855 
2856   return getUDivExpr(LHS, RHS);
2857 }
2858 
2859 /// Get an add recurrence expression for the specified loop.  Simplify the
2860 /// expression as much as possible.
2861 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
2862                                            const Loop *L,
2863                                            SCEV::NoWrapFlags Flags) {
2864   SmallVector<const SCEV *, 4> Operands;
2865   Operands.push_back(Start);
2866   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
2867     if (StepChrec->getLoop() == L) {
2868       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
2869       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
2870     }
2871 
2872   Operands.push_back(Step);
2873   return getAddRecExpr(Operands, L, Flags);
2874 }
2875 
2876 /// Get an add recurrence expression for the specified loop.  Simplify the
2877 /// expression as much as possible.
2878 const SCEV *
2879 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
2880                                const Loop *L, SCEV::NoWrapFlags Flags) {
2881   if (Operands.size() == 1) return Operands[0];
2882 #ifndef NDEBUG
2883   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
2884   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
2885     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
2886            "SCEVAddRecExpr operand types don't match!");
2887   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2888     assert(isLoopInvariant(Operands[i], L) &&
2889            "SCEVAddRecExpr operand is not loop-invariant!");
2890 #endif
2891 
2892   if (Operands.back()->isZero()) {
2893     Operands.pop_back();
2894     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
2895   }
2896 
2897   // It's tempting to want to call getMaxBackedgeTakenCount count here and
2898   // use that information to infer NUW and NSW flags. However, computing a
2899   // BE count requires calling getAddRecExpr, so we may not yet have a
2900   // meaningful BE count at this point (and if we don't, we'd be stuck
2901   // with a SCEVCouldNotCompute as the cached BE count).
2902 
2903   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
2904 
2905   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
2906   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
2907     const Loop *NestedLoop = NestedAR->getLoop();
2908     if (L->contains(NestedLoop)
2909             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
2910             : (!NestedLoop->contains(L) &&
2911                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
2912       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
2913                                                   NestedAR->op_end());
2914       Operands[0] = NestedAR->getStart();
2915       // AddRecs require their operands be loop-invariant with respect to their
2916       // loops. Don't perform this transformation if it would break this
2917       // requirement.
2918       bool AllInvariant = all_of(
2919           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
2920 
2921       if (AllInvariant) {
2922         // Create a recurrence for the outer loop with the same step size.
2923         //
2924         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
2925         // inner recurrence has the same property.
2926         SCEV::NoWrapFlags OuterFlags =
2927           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
2928 
2929         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
2930         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
2931           return isLoopInvariant(Op, NestedLoop);
2932         });
2933 
2934         if (AllInvariant) {
2935           // Ok, both add recurrences are valid after the transformation.
2936           //
2937           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
2938           // the outer recurrence has the same property.
2939           SCEV::NoWrapFlags InnerFlags =
2940             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
2941           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
2942         }
2943       }
2944       // Reset Operands to its original state.
2945       Operands[0] = NestedAR;
2946     }
2947   }
2948 
2949   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
2950   // already have one, otherwise create a new one.
2951   FoldingSetNodeID ID;
2952   ID.AddInteger(scAddRecExpr);
2953   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2954     ID.AddPointer(Operands[i]);
2955   ID.AddPointer(L);
2956   void *IP = nullptr;
2957   SCEVAddRecExpr *S =
2958     static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2959   if (!S) {
2960     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2961     std::uninitialized_copy(Operands.begin(), Operands.end(), O);
2962     S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2963                                            O, Operands.size(), L);
2964     UniqueSCEVs.InsertNode(S, IP);
2965   }
2966   S->setNoWrapFlags(Flags);
2967   return S;
2968 }
2969 
2970 const SCEV *
2971 ScalarEvolution::getGEPExpr(Type *PointeeType, const SCEV *BaseExpr,
2972                             const SmallVectorImpl<const SCEV *> &IndexExprs,
2973                             bool InBounds) {
2974   // getSCEV(Base)->getType() has the same address space as Base->getType()
2975   // because SCEV::getType() preserves the address space.
2976   Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
2977   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
2978   // instruction to its SCEV, because the Instruction may be guarded by control
2979   // flow and the no-overflow bits may not be valid for the expression in any
2980   // context. This can be fixed similarly to how these flags are handled for
2981   // adds.
2982   SCEV::NoWrapFlags Wrap = InBounds ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
2983 
2984   const SCEV *TotalOffset = getZero(IntPtrTy);
2985   // The address space is unimportant. The first thing we do on CurTy is getting
2986   // its element type.
2987   Type *CurTy = PointerType::getUnqual(PointeeType);
2988   for (const SCEV *IndexExpr : IndexExprs) {
2989     // Compute the (potentially symbolic) offset in bytes for this index.
2990     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2991       // For a struct, add the member offset.
2992       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
2993       unsigned FieldNo = Index->getZExtValue();
2994       const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
2995 
2996       // Add the field offset to the running total offset.
2997       TotalOffset = getAddExpr(TotalOffset, FieldOffset);
2998 
2999       // Update CurTy to the type of the field at Index.
3000       CurTy = STy->getTypeAtIndex(Index);
3001     } else {
3002       // Update CurTy to its element type.
3003       CurTy = cast<SequentialType>(CurTy)->getElementType();
3004       // For an array, add the element offset, explicitly scaled.
3005       const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3006       // Getelementptr indices are signed.
3007       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3008 
3009       // Multiply the index by the element size to compute the element offset.
3010       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3011 
3012       // Add the element offset to the running total offset.
3013       TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3014     }
3015   }
3016 
3017   // Add the total offset from all the GEP indices to the base.
3018   return getAddExpr(BaseExpr, TotalOffset, Wrap);
3019 }
3020 
3021 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3022                                          const SCEV *RHS) {
3023   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3024   return getSMaxExpr(Ops);
3025 }
3026 
3027 const SCEV *
3028 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3029   assert(!Ops.empty() && "Cannot get empty smax!");
3030   if (Ops.size() == 1) return Ops[0];
3031 #ifndef NDEBUG
3032   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3033   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3034     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3035            "SCEVSMaxExpr operand types don't match!");
3036 #endif
3037 
3038   // Sort by complexity, this groups all similar expression types together.
3039   GroupByComplexity(Ops, &LI);
3040 
3041   // If there are any constants, fold them together.
3042   unsigned Idx = 0;
3043   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3044     ++Idx;
3045     assert(Idx < Ops.size());
3046     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3047       // We found two constants, fold them together!
3048       ConstantInt *Fold = ConstantInt::get(
3049           getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
3050       Ops[0] = getConstant(Fold);
3051       Ops.erase(Ops.begin()+1);  // Erase the folded element
3052       if (Ops.size() == 1) return Ops[0];
3053       LHSC = cast<SCEVConstant>(Ops[0]);
3054     }
3055 
3056     // If we are left with a constant minimum-int, strip it off.
3057     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3058       Ops.erase(Ops.begin());
3059       --Idx;
3060     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3061       // If we have an smax with a constant maximum-int, it will always be
3062       // maximum-int.
3063       return Ops[0];
3064     }
3065 
3066     if (Ops.size() == 1) return Ops[0];
3067   }
3068 
3069   // Find the first SMax
3070   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3071     ++Idx;
3072 
3073   // Check to see if one of the operands is an SMax. If so, expand its operands
3074   // onto our operand list, and recurse to simplify.
3075   if (Idx < Ops.size()) {
3076     bool DeletedSMax = false;
3077     while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
3078       Ops.erase(Ops.begin()+Idx);
3079       Ops.append(SMax->op_begin(), SMax->op_end());
3080       DeletedSMax = true;
3081     }
3082 
3083     if (DeletedSMax)
3084       return getSMaxExpr(Ops);
3085   }
3086 
3087   // Okay, check to see if the same value occurs in the operand list twice.  If
3088   // so, delete one.  Since we sorted the list, these values are required to
3089   // be adjacent.
3090   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3091     //  X smax Y smax Y  -->  X smax Y
3092     //  X smax Y         -->  X, if X is always greater than Y
3093     if (Ops[i] == Ops[i+1] ||
3094         isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3095       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3096       --i; --e;
3097     } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
3098       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3099       --i; --e;
3100     }
3101 
3102   if (Ops.size() == 1) return Ops[0];
3103 
3104   assert(!Ops.empty() && "Reduced smax down to nothing!");
3105 
3106   // Okay, it looks like we really DO need an smax expr.  Check to see if we
3107   // already have one, otherwise create a new one.
3108   FoldingSetNodeID ID;
3109   ID.AddInteger(scSMaxExpr);
3110   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3111     ID.AddPointer(Ops[i]);
3112   void *IP = nullptr;
3113   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3114   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3115   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3116   SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3117                                              O, Ops.size());
3118   UniqueSCEVs.InsertNode(S, IP);
3119   return S;
3120 }
3121 
3122 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3123                                          const SCEV *RHS) {
3124   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3125   return getUMaxExpr(Ops);
3126 }
3127 
3128 const SCEV *
3129 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3130   assert(!Ops.empty() && "Cannot get empty umax!");
3131   if (Ops.size() == 1) return Ops[0];
3132 #ifndef NDEBUG
3133   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3134   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3135     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3136            "SCEVUMaxExpr operand types don't match!");
3137 #endif
3138 
3139   // Sort by complexity, this groups all similar expression types together.
3140   GroupByComplexity(Ops, &LI);
3141 
3142   // If there are any constants, fold them together.
3143   unsigned Idx = 0;
3144   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3145     ++Idx;
3146     assert(Idx < Ops.size());
3147     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3148       // We found two constants, fold them together!
3149       ConstantInt *Fold = ConstantInt::get(
3150           getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
3151       Ops[0] = getConstant(Fold);
3152       Ops.erase(Ops.begin()+1);  // Erase the folded element
3153       if (Ops.size() == 1) return Ops[0];
3154       LHSC = cast<SCEVConstant>(Ops[0]);
3155     }
3156 
3157     // If we are left with a constant minimum-int, strip it off.
3158     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3159       Ops.erase(Ops.begin());
3160       --Idx;
3161     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3162       // If we have an umax with a constant maximum-int, it will always be
3163       // maximum-int.
3164       return Ops[0];
3165     }
3166 
3167     if (Ops.size() == 1) return Ops[0];
3168   }
3169 
3170   // Find the first UMax
3171   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3172     ++Idx;
3173 
3174   // Check to see if one of the operands is a UMax. If so, expand its operands
3175   // onto our operand list, and recurse to simplify.
3176   if (Idx < Ops.size()) {
3177     bool DeletedUMax = false;
3178     while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
3179       Ops.erase(Ops.begin()+Idx);
3180       Ops.append(UMax->op_begin(), UMax->op_end());
3181       DeletedUMax = true;
3182     }
3183 
3184     if (DeletedUMax)
3185       return getUMaxExpr(Ops);
3186   }
3187 
3188   // Okay, check to see if the same value occurs in the operand list twice.  If
3189   // so, delete one.  Since we sorted the list, these values are required to
3190   // be adjacent.
3191   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3192     //  X umax Y umax Y  -->  X umax Y
3193     //  X umax Y         -->  X, if X is always greater than Y
3194     if (Ops[i] == Ops[i+1] ||
3195         isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3196       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3197       --i; --e;
3198     } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
3199       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3200       --i; --e;
3201     }
3202 
3203   if (Ops.size() == 1) return Ops[0];
3204 
3205   assert(!Ops.empty() && "Reduced umax down to nothing!");
3206 
3207   // Okay, it looks like we really DO need a umax expr.  Check to see if we
3208   // already have one, otherwise create a new one.
3209   FoldingSetNodeID ID;
3210   ID.AddInteger(scUMaxExpr);
3211   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3212     ID.AddPointer(Ops[i]);
3213   void *IP = nullptr;
3214   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3215   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3216   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3217   SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3218                                              O, Ops.size());
3219   UniqueSCEVs.InsertNode(S, IP);
3220   return S;
3221 }
3222 
3223 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3224                                          const SCEV *RHS) {
3225   // ~smax(~x, ~y) == smin(x, y).
3226   return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3227 }
3228 
3229 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3230                                          const SCEV *RHS) {
3231   // ~umax(~x, ~y) == umin(x, y)
3232   return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3233 }
3234 
3235 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3236   // We can bypass creating a target-independent
3237   // constant expression and then folding it back into a ConstantInt.
3238   // This is just a compile-time optimization.
3239   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3240 }
3241 
3242 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3243                                              StructType *STy,
3244                                              unsigned FieldNo) {
3245   // We can bypass creating a target-independent
3246   // constant expression and then folding it back into a ConstantInt.
3247   // This is just a compile-time optimization.
3248   return getConstant(
3249       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3250 }
3251 
3252 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3253   // Don't attempt to do anything other than create a SCEVUnknown object
3254   // here.  createSCEV only calls getUnknown after checking for all other
3255   // interesting possibilities, and any other code that calls getUnknown
3256   // is doing so in order to hide a value from SCEV canonicalization.
3257 
3258   FoldingSetNodeID ID;
3259   ID.AddInteger(scUnknown);
3260   ID.AddPointer(V);
3261   void *IP = nullptr;
3262   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3263     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3264            "Stale SCEVUnknown in uniquing map!");
3265     return S;
3266   }
3267   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3268                                             FirstUnknown);
3269   FirstUnknown = cast<SCEVUnknown>(S);
3270   UniqueSCEVs.InsertNode(S, IP);
3271   return S;
3272 }
3273 
3274 //===----------------------------------------------------------------------===//
3275 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3276 //
3277 
3278 /// Test if values of the given type are analyzable within the SCEV
3279 /// framework. This primarily includes integer types, and it can optionally
3280 /// include pointer types if the ScalarEvolution class has access to
3281 /// target-specific information.
3282 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3283   // Integers and pointers are always SCEVable.
3284   return Ty->isIntegerTy() || Ty->isPointerTy();
3285 }
3286 
3287 /// Return the size in bits of the specified type, for which isSCEVable must
3288 /// return true.
3289 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3290   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3291   return getDataLayout().getTypeSizeInBits(Ty);
3292 }
3293 
3294 /// Return a type with the same bitwidth as the given type and which represents
3295 /// how SCEV will treat the given type, for which isSCEVable must return
3296 /// true. For pointer types, this is the pointer-sized integer type.
3297 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3298   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3299 
3300   if (Ty->isIntegerTy())
3301     return Ty;
3302 
3303   // The only other support type is pointer.
3304   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3305   return getDataLayout().getIntPtrType(Ty);
3306 }
3307 
3308 const SCEV *ScalarEvolution::getCouldNotCompute() {
3309   return CouldNotCompute.get();
3310 }
3311 
3312 
3313 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3314   // Helper class working with SCEVTraversal to figure out if a SCEV contains
3315   // a SCEVUnknown with null value-pointer. FindInvalidSCEVUnknown::FindOne
3316   // is set iff if find such SCEVUnknown.
3317   //
3318   struct FindInvalidSCEVUnknown {
3319     bool FindOne;
3320     FindInvalidSCEVUnknown() { FindOne = false; }
3321     bool follow(const SCEV *S) {
3322       switch (static_cast<SCEVTypes>(S->getSCEVType())) {
3323       case scConstant:
3324         return false;
3325       case scUnknown:
3326         if (!cast<SCEVUnknown>(S)->getValue())
3327           FindOne = true;
3328         return false;
3329       default:
3330         return true;
3331       }
3332     }
3333     bool isDone() const { return FindOne; }
3334   };
3335 
3336   FindInvalidSCEVUnknown F;
3337   SCEVTraversal<FindInvalidSCEVUnknown> ST(F);
3338   ST.visitAll(S);
3339 
3340   return !F.FindOne;
3341 }
3342 
3343 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3344   // Helper class working with SCEVTraversal to figure out if a SCEV contains a
3345   // sub SCEV of scAddRecExpr type.  FindInvalidSCEVUnknown::FoundOne is set iff
3346   // if such sub scAddRecExpr type SCEV is found.
3347   struct FindAddRecurrence {
3348     bool FoundOne;
3349     FindAddRecurrence() : FoundOne(false) {}
3350 
3351     bool follow(const SCEV *S) {
3352       switch (static_cast<SCEVTypes>(S->getSCEVType())) {
3353       case scAddRecExpr:
3354         FoundOne = true;
3355       case scConstant:
3356       case scUnknown:
3357       case scCouldNotCompute:
3358         return false;
3359       default:
3360         return true;
3361       }
3362     }
3363     bool isDone() const { return FoundOne; }
3364   };
3365 
3366   HasRecMapType::iterator I = HasRecMap.find(S);
3367   if (I != HasRecMap.end())
3368     return I->second;
3369 
3370   FindAddRecurrence F;
3371   SCEVTraversal<FindAddRecurrence> ST(F);
3372   ST.visitAll(S);
3373   HasRecMap.insert({S, F.FoundOne});
3374   return F.FoundOne;
3375 }
3376 
3377 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3378 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3379 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3380 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3381   const auto *Add = dyn_cast<SCEVAddExpr>(S);
3382   if (!Add)
3383     return {S, nullptr};
3384 
3385   if (Add->getNumOperands() != 2)
3386     return {S, nullptr};
3387 
3388   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3389   if (!ConstOp)
3390     return {S, nullptr};
3391 
3392   return {Add->getOperand(1), ConstOp->getValue()};
3393 }
3394 
3395 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3396 /// by the value and offset from any ValueOffsetPair in the set.
3397 SetVector<ScalarEvolution::ValueOffsetPair> *
3398 ScalarEvolution::getSCEVValues(const SCEV *S) {
3399   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3400   if (SI == ExprValueMap.end())
3401     return nullptr;
3402 #ifndef NDEBUG
3403   if (VerifySCEVMap) {
3404     // Check there is no dangling Value in the set returned.
3405     for (const auto &VE : SI->second)
3406       assert(ValueExprMap.count(VE.first));
3407   }
3408 #endif
3409   return &SI->second;
3410 }
3411 
3412 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3413 /// cannot be used separately. eraseValueFromMap should be used to remove
3414 /// V from ValueExprMap and ExprValueMap at the same time.
3415 void ScalarEvolution::eraseValueFromMap(Value *V) {
3416   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3417   if (I != ValueExprMap.end()) {
3418     const SCEV *S = I->second;
3419     // Remove {V, 0} from the set of ExprValueMap[S]
3420     if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3421       SV->remove({V, nullptr});
3422 
3423     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3424     const SCEV *Stripped;
3425     ConstantInt *Offset;
3426     std::tie(Stripped, Offset) = splitAddExpr(S);
3427     if (Offset != nullptr) {
3428       if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3429         SV->remove({V, Offset});
3430     }
3431     ValueExprMap.erase(V);
3432   }
3433 }
3434 
3435 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3436 /// create a new one.
3437 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3438   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3439 
3440   const SCEV *S = getExistingSCEV(V);
3441   if (S == nullptr) {
3442     S = createSCEV(V);
3443     // During PHI resolution, it is possible to create two SCEVs for the same
3444     // V, so it is needed to double check whether V->S is inserted into
3445     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3446     std::pair<ValueExprMapType::iterator, bool> Pair =
3447         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3448     if (Pair.second) {
3449       ExprValueMap[S].insert({V, nullptr});
3450 
3451       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3452       // ExprValueMap.
3453       const SCEV *Stripped = S;
3454       ConstantInt *Offset = nullptr;
3455       std::tie(Stripped, Offset) = splitAddExpr(S);
3456       // If stripped is SCEVUnknown, don't bother to save
3457       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3458       // increase the complexity of the expansion code.
3459       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3460       // because it may generate add/sub instead of GEP in SCEV expansion.
3461       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3462           !isa<GetElementPtrInst>(V))
3463         ExprValueMap[Stripped].insert({V, Offset});
3464     }
3465   }
3466   return S;
3467 }
3468 
3469 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3470   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3471 
3472   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3473   if (I != ValueExprMap.end()) {
3474     const SCEV *S = I->second;
3475     if (checkValidity(S))
3476       return S;
3477     eraseValueFromMap(V);
3478     forgetMemoizedResults(S);
3479   }
3480   return nullptr;
3481 }
3482 
3483 /// Return a SCEV corresponding to -V = -1*V
3484 ///
3485 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3486                                              SCEV::NoWrapFlags Flags) {
3487   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3488     return getConstant(
3489                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3490 
3491   Type *Ty = V->getType();
3492   Ty = getEffectiveSCEVType(Ty);
3493   return getMulExpr(
3494       V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3495 }
3496 
3497 /// Return a SCEV corresponding to ~V = -1-V
3498 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3499   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3500     return getConstant(
3501                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3502 
3503   Type *Ty = V->getType();
3504   Ty = getEffectiveSCEVType(Ty);
3505   const SCEV *AllOnes =
3506                    getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3507   return getMinusSCEV(AllOnes, V);
3508 }
3509 
3510 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3511                                           SCEV::NoWrapFlags Flags) {
3512   // Fast path: X - X --> 0.
3513   if (LHS == RHS)
3514     return getZero(LHS->getType());
3515 
3516   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3517   // makes it so that we cannot make much use of NUW.
3518   auto AddFlags = SCEV::FlagAnyWrap;
3519   const bool RHSIsNotMinSigned =
3520       !getSignedRange(RHS).getSignedMin().isMinSignedValue();
3521   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3522     // Let M be the minimum representable signed value. Then (-1)*RHS
3523     // signed-wraps if and only if RHS is M. That can happen even for
3524     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3525     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3526     // (-1)*RHS, we need to prove that RHS != M.
3527     //
3528     // If LHS is non-negative and we know that LHS - RHS does not
3529     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3530     // either by proving that RHS > M or that LHS >= 0.
3531     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3532       AddFlags = SCEV::FlagNSW;
3533     }
3534   }
3535 
3536   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3537   // RHS is NSW and LHS >= 0.
3538   //
3539   // The difficulty here is that the NSW flag may have been proven
3540   // relative to a loop that is to be found in a recurrence in LHS and
3541   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3542   // larger scope than intended.
3543   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3544 
3545   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags);
3546 }
3547 
3548 const SCEV *
3549 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3550   Type *SrcTy = V->getType();
3551   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3552          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3553          "Cannot truncate or zero extend with non-integer arguments!");
3554   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3555     return V;  // No conversion
3556   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3557     return getTruncateExpr(V, Ty);
3558   return getZeroExtendExpr(V, Ty);
3559 }
3560 
3561 const SCEV *
3562 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
3563                                          Type *Ty) {
3564   Type *SrcTy = V->getType();
3565   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3566          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3567          "Cannot truncate or zero extend with non-integer arguments!");
3568   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3569     return V;  // No conversion
3570   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3571     return getTruncateExpr(V, Ty);
3572   return getSignExtendExpr(V, Ty);
3573 }
3574 
3575 const SCEV *
3576 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3577   Type *SrcTy = V->getType();
3578   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3579          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3580          "Cannot noop or zero extend with non-integer arguments!");
3581   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3582          "getNoopOrZeroExtend cannot truncate!");
3583   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3584     return V;  // No conversion
3585   return getZeroExtendExpr(V, Ty);
3586 }
3587 
3588 const SCEV *
3589 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3590   Type *SrcTy = V->getType();
3591   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3592          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3593          "Cannot noop or sign extend with non-integer arguments!");
3594   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3595          "getNoopOrSignExtend cannot truncate!");
3596   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3597     return V;  // No conversion
3598   return getSignExtendExpr(V, Ty);
3599 }
3600 
3601 const SCEV *
3602 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3603   Type *SrcTy = V->getType();
3604   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3605          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3606          "Cannot noop or any extend with non-integer arguments!");
3607   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3608          "getNoopOrAnyExtend cannot truncate!");
3609   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3610     return V;  // No conversion
3611   return getAnyExtendExpr(V, Ty);
3612 }
3613 
3614 const SCEV *
3615 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3616   Type *SrcTy = V->getType();
3617   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3618          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3619          "Cannot truncate or noop with non-integer arguments!");
3620   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3621          "getTruncateOrNoop cannot extend!");
3622   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3623     return V;  // No conversion
3624   return getTruncateExpr(V, Ty);
3625 }
3626 
3627 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3628                                                         const SCEV *RHS) {
3629   const SCEV *PromotedLHS = LHS;
3630   const SCEV *PromotedRHS = RHS;
3631 
3632   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3633     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3634   else
3635     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3636 
3637   return getUMaxExpr(PromotedLHS, PromotedRHS);
3638 }
3639 
3640 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3641                                                         const SCEV *RHS) {
3642   const SCEV *PromotedLHS = LHS;
3643   const SCEV *PromotedRHS = RHS;
3644 
3645   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3646     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3647   else
3648     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3649 
3650   return getUMinExpr(PromotedLHS, PromotedRHS);
3651 }
3652 
3653 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3654   // A pointer operand may evaluate to a nonpointer expression, such as null.
3655   if (!V->getType()->isPointerTy())
3656     return V;
3657 
3658   if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3659     return getPointerBase(Cast->getOperand());
3660   } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
3661     const SCEV *PtrOp = nullptr;
3662     for (const SCEV *NAryOp : NAry->operands()) {
3663       if (NAryOp->getType()->isPointerTy()) {
3664         // Cannot find the base of an expression with multiple pointer operands.
3665         if (PtrOp)
3666           return V;
3667         PtrOp = NAryOp;
3668       }
3669     }
3670     if (!PtrOp)
3671       return V;
3672     return getPointerBase(PtrOp);
3673   }
3674   return V;
3675 }
3676 
3677 /// Push users of the given Instruction onto the given Worklist.
3678 static void
3679 PushDefUseChildren(Instruction *I,
3680                    SmallVectorImpl<Instruction *> &Worklist) {
3681   // Push the def-use children onto the Worklist stack.
3682   for (User *U : I->users())
3683     Worklist.push_back(cast<Instruction>(U));
3684 }
3685 
3686 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
3687   SmallVector<Instruction *, 16> Worklist;
3688   PushDefUseChildren(PN, Worklist);
3689 
3690   SmallPtrSet<Instruction *, 8> Visited;
3691   Visited.insert(PN);
3692   while (!Worklist.empty()) {
3693     Instruction *I = Worklist.pop_back_val();
3694     if (!Visited.insert(I).second)
3695       continue;
3696 
3697     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
3698     if (It != ValueExprMap.end()) {
3699       const SCEV *Old = It->second;
3700 
3701       // Short-circuit the def-use traversal if the symbolic name
3702       // ceases to appear in expressions.
3703       if (Old != SymName && !hasOperand(Old, SymName))
3704         continue;
3705 
3706       // SCEVUnknown for a PHI either means that it has an unrecognized
3707       // structure, it's a PHI that's in the progress of being computed
3708       // by createNodeForPHI, or it's a single-value PHI. In the first case,
3709       // additional loop trip count information isn't going to change anything.
3710       // In the second case, createNodeForPHI will perform the necessary
3711       // updates on its own when it gets to that point. In the third, we do
3712       // want to forget the SCEVUnknown.
3713       if (!isa<PHINode>(I) ||
3714           !isa<SCEVUnknown>(Old) ||
3715           (I != PN && Old == SymName)) {
3716         eraseValueFromMap(It->first);
3717         forgetMemoizedResults(Old);
3718       }
3719     }
3720 
3721     PushDefUseChildren(I, Worklist);
3722   }
3723 }
3724 
3725 namespace {
3726 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
3727 public:
3728   static const SCEV *rewrite(const SCEV *S, const Loop *L,
3729                              ScalarEvolution &SE) {
3730     SCEVInitRewriter Rewriter(L, SE);
3731     const SCEV *Result = Rewriter.visit(S);
3732     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3733   }
3734 
3735   SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
3736       : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3737 
3738   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3739     if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3740       Valid = false;
3741     return Expr;
3742   }
3743 
3744   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3745     // Only allow AddRecExprs for this loop.
3746     if (Expr->getLoop() == L)
3747       return Expr->getStart();
3748     Valid = false;
3749     return Expr;
3750   }
3751 
3752   bool isValid() { return Valid; }
3753 
3754 private:
3755   const Loop *L;
3756   bool Valid;
3757 };
3758 
3759 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
3760 public:
3761   static const SCEV *rewrite(const SCEV *S, const Loop *L,
3762                              ScalarEvolution &SE) {
3763     SCEVShiftRewriter Rewriter(L, SE);
3764     const SCEV *Result = Rewriter.visit(S);
3765     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3766   }
3767 
3768   SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
3769       : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3770 
3771   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3772     // Only allow AddRecExprs for this loop.
3773     if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3774       Valid = false;
3775     return Expr;
3776   }
3777 
3778   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3779     if (Expr->getLoop() == L && Expr->isAffine())
3780       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
3781     Valid = false;
3782     return Expr;
3783   }
3784   bool isValid() { return Valid; }
3785 
3786 private:
3787   const Loop *L;
3788   bool Valid;
3789 };
3790 } // end anonymous namespace
3791 
3792 SCEV::NoWrapFlags
3793 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
3794   if (!AR->isAffine())
3795     return SCEV::FlagAnyWrap;
3796 
3797   typedef OverflowingBinaryOperator OBO;
3798   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
3799 
3800   if (!AR->hasNoSignedWrap()) {
3801     ConstantRange AddRecRange = getSignedRange(AR);
3802     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
3803 
3804     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3805         Instruction::Add, IncRange, OBO::NoSignedWrap);
3806     if (NSWRegion.contains(AddRecRange))
3807       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
3808   }
3809 
3810   if (!AR->hasNoUnsignedWrap()) {
3811     ConstantRange AddRecRange = getUnsignedRange(AR);
3812     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
3813 
3814     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3815         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
3816     if (NUWRegion.contains(AddRecRange))
3817       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
3818   }
3819 
3820   return Result;
3821 }
3822 
3823 namespace {
3824 /// Represents an abstract binary operation.  This may exist as a
3825 /// normal instruction or constant expression, or may have been
3826 /// derived from an expression tree.
3827 struct BinaryOp {
3828   unsigned Opcode;
3829   Value *LHS;
3830   Value *RHS;
3831   bool IsNSW;
3832   bool IsNUW;
3833 
3834   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
3835   /// constant expression.
3836   Operator *Op;
3837 
3838   explicit BinaryOp(Operator *Op)
3839       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
3840         IsNSW(false), IsNUW(false), Op(Op) {
3841     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
3842       IsNSW = OBO->hasNoSignedWrap();
3843       IsNUW = OBO->hasNoUnsignedWrap();
3844     }
3845   }
3846 
3847   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
3848                     bool IsNUW = false)
3849       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW),
3850         Op(nullptr) {}
3851 };
3852 }
3853 
3854 
3855 /// Try to map \p V into a BinaryOp, and return \c None on failure.
3856 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
3857   auto *Op = dyn_cast<Operator>(V);
3858   if (!Op)
3859     return None;
3860 
3861   // Implementation detail: all the cleverness here should happen without
3862   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
3863   // SCEV expressions when possible, and we should not break that.
3864 
3865   switch (Op->getOpcode()) {
3866   case Instruction::Add:
3867   case Instruction::Sub:
3868   case Instruction::Mul:
3869   case Instruction::UDiv:
3870   case Instruction::And:
3871   case Instruction::Or:
3872   case Instruction::AShr:
3873   case Instruction::Shl:
3874     return BinaryOp(Op);
3875 
3876   case Instruction::Xor:
3877     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
3878       // If the RHS of the xor is a signbit, then this is just an add.
3879       // Instcombine turns add of signbit into xor as a strength reduction step.
3880       if (RHSC->getValue().isSignBit())
3881         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
3882     return BinaryOp(Op);
3883 
3884   case Instruction::LShr:
3885     // Turn logical shift right of a constant into a unsigned divide.
3886     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
3887       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
3888 
3889       // If the shift count is not less than the bitwidth, the result of
3890       // the shift is undefined. Don't try to analyze it, because the
3891       // resolution chosen here may differ from the resolution chosen in
3892       // other parts of the compiler.
3893       if (SA->getValue().ult(BitWidth)) {
3894         Constant *X =
3895             ConstantInt::get(SA->getContext(),
3896                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
3897         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
3898       }
3899     }
3900     return BinaryOp(Op);
3901 
3902   case Instruction::ExtractValue: {
3903     auto *EVI = cast<ExtractValueInst>(Op);
3904     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
3905       break;
3906 
3907     auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
3908     if (!CI)
3909       break;
3910 
3911     if (auto *F = CI->getCalledFunction())
3912       switch (F->getIntrinsicID()) {
3913       case Intrinsic::sadd_with_overflow:
3914       case Intrinsic::uadd_with_overflow: {
3915         if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
3916           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3917                           CI->getArgOperand(1));
3918 
3919         // Now that we know that all uses of the arithmetic-result component of
3920         // CI are guarded by the overflow check, we can go ahead and pretend
3921         // that the arithmetic is non-overflowing.
3922         if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
3923           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3924                           CI->getArgOperand(1), /* IsNSW = */ true,
3925                           /* IsNUW = */ false);
3926         else
3927           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3928                           CI->getArgOperand(1), /* IsNSW = */ false,
3929                           /* IsNUW*/ true);
3930       }
3931 
3932       case Intrinsic::ssub_with_overflow:
3933       case Intrinsic::usub_with_overflow:
3934         return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
3935                         CI->getArgOperand(1));
3936 
3937       case Intrinsic::smul_with_overflow:
3938       case Intrinsic::umul_with_overflow:
3939         return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
3940                         CI->getArgOperand(1));
3941       default:
3942         break;
3943       }
3944   }
3945 
3946   default:
3947     break;
3948   }
3949 
3950   return None;
3951 }
3952 
3953 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
3954   const Loop *L = LI.getLoopFor(PN->getParent());
3955   if (!L || L->getHeader() != PN->getParent())
3956     return nullptr;
3957 
3958   // The loop may have multiple entrances or multiple exits; we can analyze
3959   // this phi as an addrec if it has a unique entry value and a unique
3960   // backedge value.
3961   Value *BEValueV = nullptr, *StartValueV = nullptr;
3962   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3963     Value *V = PN->getIncomingValue(i);
3964     if (L->contains(PN->getIncomingBlock(i))) {
3965       if (!BEValueV) {
3966         BEValueV = V;
3967       } else if (BEValueV != V) {
3968         BEValueV = nullptr;
3969         break;
3970       }
3971     } else if (!StartValueV) {
3972       StartValueV = V;
3973     } else if (StartValueV != V) {
3974       StartValueV = nullptr;
3975       break;
3976     }
3977   }
3978   if (BEValueV && StartValueV) {
3979     // While we are analyzing this PHI node, handle its value symbolically.
3980     const SCEV *SymbolicName = getUnknown(PN);
3981     assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
3982            "PHI node already processed?");
3983     ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
3984 
3985     // Using this symbolic name for the PHI, analyze the value coming around
3986     // the back-edge.
3987     const SCEV *BEValue = getSCEV(BEValueV);
3988 
3989     // NOTE: If BEValue is loop invariant, we know that the PHI node just
3990     // has a special value for the first iteration of the loop.
3991 
3992     // If the value coming around the backedge is an add with the symbolic
3993     // value we just inserted, then we found a simple induction variable!
3994     if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
3995       // If there is a single occurrence of the symbolic value, replace it
3996       // with a recurrence.
3997       unsigned FoundIndex = Add->getNumOperands();
3998       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
3999         if (Add->getOperand(i) == SymbolicName)
4000           if (FoundIndex == e) {
4001             FoundIndex = i;
4002             break;
4003           }
4004 
4005       if (FoundIndex != Add->getNumOperands()) {
4006         // Create an add with everything but the specified operand.
4007         SmallVector<const SCEV *, 8> Ops;
4008         for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4009           if (i != FoundIndex)
4010             Ops.push_back(Add->getOperand(i));
4011         const SCEV *Accum = getAddExpr(Ops);
4012 
4013         // This is not a valid addrec if the step amount is varying each
4014         // loop iteration, but is not itself an addrec in this loop.
4015         if (isLoopInvariant(Accum, L) ||
4016             (isa<SCEVAddRecExpr>(Accum) &&
4017              cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4018           SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4019 
4020           if (auto BO = MatchBinaryOp(BEValueV, DT)) {
4021             if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4022               if (BO->IsNUW)
4023                 Flags = setFlags(Flags, SCEV::FlagNUW);
4024               if (BO->IsNSW)
4025                 Flags = setFlags(Flags, SCEV::FlagNSW);
4026             }
4027           } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4028             // If the increment is an inbounds GEP, then we know the address
4029             // space cannot be wrapped around. We cannot make any guarantee
4030             // about signed or unsigned overflow because pointers are
4031             // unsigned but we may have a negative index from the base
4032             // pointer. We can guarantee that no unsigned wrap occurs if the
4033             // indices form a positive value.
4034             if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4035               Flags = setFlags(Flags, SCEV::FlagNW);
4036 
4037               const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4038               if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4039                 Flags = setFlags(Flags, SCEV::FlagNUW);
4040             }
4041 
4042             // We cannot transfer nuw and nsw flags from subtraction
4043             // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4044             // for instance.
4045           }
4046 
4047           const SCEV *StartVal = getSCEV(StartValueV);
4048           const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4049 
4050           // Okay, for the entire analysis of this edge we assumed the PHI
4051           // to be symbolic.  We now need to go back and purge all of the
4052           // entries for the scalars that use the symbolic expression.
4053           forgetSymbolicName(PN, SymbolicName);
4054           ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4055 
4056           // We can add Flags to the post-inc expression only if we
4057           // know that it us *undefined behavior* for BEValueV to
4058           // overflow.
4059           if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4060             if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4061               (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4062 
4063           return PHISCEV;
4064         }
4065       }
4066     } else {
4067       // Otherwise, this could be a loop like this:
4068       //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
4069       // In this case, j = {1,+,1}  and BEValue is j.
4070       // Because the other in-value of i (0) fits the evolution of BEValue
4071       // i really is an addrec evolution.
4072       //
4073       // We can generalize this saying that i is the shifted value of BEValue
4074       // by one iteration:
4075       //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
4076       const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
4077       const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this);
4078       if (Shifted != getCouldNotCompute() &&
4079           Start != getCouldNotCompute()) {
4080         const SCEV *StartVal = getSCEV(StartValueV);
4081         if (Start == StartVal) {
4082           // Okay, for the entire analysis of this edge we assumed the PHI
4083           // to be symbolic.  We now need to go back and purge all of the
4084           // entries for the scalars that use the symbolic expression.
4085           forgetSymbolicName(PN, SymbolicName);
4086           ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
4087           return Shifted;
4088         }
4089       }
4090     }
4091 
4092     // Remove the temporary PHI node SCEV that has been inserted while intending
4093     // to create an AddRecExpr for this PHI node. We can not keep this temporary
4094     // as it will prevent later (possibly simpler) SCEV expressions to be added
4095     // to the ValueExprMap.
4096     eraseValueFromMap(PN);
4097   }
4098 
4099   return nullptr;
4100 }
4101 
4102 // Checks if the SCEV S is available at BB.  S is considered available at BB
4103 // if S can be materialized at BB without introducing a fault.
4104 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
4105                                BasicBlock *BB) {
4106   struct CheckAvailable {
4107     bool TraversalDone = false;
4108     bool Available = true;
4109 
4110     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
4111     BasicBlock *BB = nullptr;
4112     DominatorTree &DT;
4113 
4114     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
4115       : L(L), BB(BB), DT(DT) {}
4116 
4117     bool setUnavailable() {
4118       TraversalDone = true;
4119       Available = false;
4120       return false;
4121     }
4122 
4123     bool follow(const SCEV *S) {
4124       switch (S->getSCEVType()) {
4125       case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
4126       case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
4127         // These expressions are available if their operand(s) is/are.
4128         return true;
4129 
4130       case scAddRecExpr: {
4131         // We allow add recurrences that are on the loop BB is in, or some
4132         // outer loop.  This guarantees availability because the value of the
4133         // add recurrence at BB is simply the "current" value of the induction
4134         // variable.  We can relax this in the future; for instance an add
4135         // recurrence on a sibling dominating loop is also available at BB.
4136         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
4137         if (L && (ARLoop == L || ARLoop->contains(L)))
4138           return true;
4139 
4140         return setUnavailable();
4141       }
4142 
4143       case scUnknown: {
4144         // For SCEVUnknown, we check for simple dominance.
4145         const auto *SU = cast<SCEVUnknown>(S);
4146         Value *V = SU->getValue();
4147 
4148         if (isa<Argument>(V))
4149           return false;
4150 
4151         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
4152           return false;
4153 
4154         return setUnavailable();
4155       }
4156 
4157       case scUDivExpr:
4158       case scCouldNotCompute:
4159         // We do not try to smart about these at all.
4160         return setUnavailable();
4161       }
4162       llvm_unreachable("switch should be fully covered!");
4163     }
4164 
4165     bool isDone() { return TraversalDone; }
4166   };
4167 
4168   CheckAvailable CA(L, BB, DT);
4169   SCEVTraversal<CheckAvailable> ST(CA);
4170 
4171   ST.visitAll(S);
4172   return CA.Available;
4173 }
4174 
4175 // Try to match a control flow sequence that branches out at BI and merges back
4176 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
4177 // match.
4178 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
4179                           Value *&C, Value *&LHS, Value *&RHS) {
4180   C = BI->getCondition();
4181 
4182   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
4183   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
4184 
4185   if (!LeftEdge.isSingleEdge())
4186     return false;
4187 
4188   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
4189 
4190   Use &LeftUse = Merge->getOperandUse(0);
4191   Use &RightUse = Merge->getOperandUse(1);
4192 
4193   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
4194     LHS = LeftUse;
4195     RHS = RightUse;
4196     return true;
4197   }
4198 
4199   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
4200     LHS = RightUse;
4201     RHS = LeftUse;
4202     return true;
4203   }
4204 
4205   return false;
4206 }
4207 
4208 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
4209   auto IsReachable =
4210       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
4211   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
4212     const Loop *L = LI.getLoopFor(PN->getParent());
4213 
4214     // We don't want to break LCSSA, even in a SCEV expression tree.
4215     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4216       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
4217         return nullptr;
4218 
4219     // Try to match
4220     //
4221     //  br %cond, label %left, label %right
4222     // left:
4223     //  br label %merge
4224     // right:
4225     //  br label %merge
4226     // merge:
4227     //  V = phi [ %x, %left ], [ %y, %right ]
4228     //
4229     // as "select %cond, %x, %y"
4230 
4231     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
4232     assert(IDom && "At least the entry block should dominate PN");
4233 
4234     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
4235     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
4236 
4237     if (BI && BI->isConditional() &&
4238         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
4239         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
4240         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
4241       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
4242   }
4243 
4244   return nullptr;
4245 }
4246 
4247 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
4248   if (const SCEV *S = createAddRecFromPHI(PN))
4249     return S;
4250 
4251   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
4252     return S;
4253 
4254   // If the PHI has a single incoming value, follow that value, unless the
4255   // PHI's incoming blocks are in a different loop, in which case doing so
4256   // risks breaking LCSSA form. Instcombine would normally zap these, but
4257   // it doesn't have DominatorTree information, so it may miss cases.
4258   if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC))
4259     if (LI.replacementPreservesLCSSAForm(PN, V))
4260       return getSCEV(V);
4261 
4262   // If it's not a loop phi, we can't handle it yet.
4263   return getUnknown(PN);
4264 }
4265 
4266 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
4267                                                       Value *Cond,
4268                                                       Value *TrueVal,
4269                                                       Value *FalseVal) {
4270   // Handle "constant" branch or select. This can occur for instance when a
4271   // loop pass transforms an inner loop and moves on to process the outer loop.
4272   if (auto *CI = dyn_cast<ConstantInt>(Cond))
4273     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
4274 
4275   // Try to match some simple smax or umax patterns.
4276   auto *ICI = dyn_cast<ICmpInst>(Cond);
4277   if (!ICI)
4278     return getUnknown(I);
4279 
4280   Value *LHS = ICI->getOperand(0);
4281   Value *RHS = ICI->getOperand(1);
4282 
4283   switch (ICI->getPredicate()) {
4284   case ICmpInst::ICMP_SLT:
4285   case ICmpInst::ICMP_SLE:
4286     std::swap(LHS, RHS);
4287     LLVM_FALLTHROUGH;
4288   case ICmpInst::ICMP_SGT:
4289   case ICmpInst::ICMP_SGE:
4290     // a >s b ? a+x : b+x  ->  smax(a, b)+x
4291     // a >s b ? b+x : a+x  ->  smin(a, b)+x
4292     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4293       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
4294       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
4295       const SCEV *LA = getSCEV(TrueVal);
4296       const SCEV *RA = getSCEV(FalseVal);
4297       const SCEV *LDiff = getMinusSCEV(LA, LS);
4298       const SCEV *RDiff = getMinusSCEV(RA, RS);
4299       if (LDiff == RDiff)
4300         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
4301       LDiff = getMinusSCEV(LA, RS);
4302       RDiff = getMinusSCEV(RA, LS);
4303       if (LDiff == RDiff)
4304         return getAddExpr(getSMinExpr(LS, RS), LDiff);
4305     }
4306     break;
4307   case ICmpInst::ICMP_ULT:
4308   case ICmpInst::ICMP_ULE:
4309     std::swap(LHS, RHS);
4310     LLVM_FALLTHROUGH;
4311   case ICmpInst::ICMP_UGT:
4312   case ICmpInst::ICMP_UGE:
4313     // a >u b ? a+x : b+x  ->  umax(a, b)+x
4314     // a >u b ? b+x : a+x  ->  umin(a, b)+x
4315     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4316       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4317       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
4318       const SCEV *LA = getSCEV(TrueVal);
4319       const SCEV *RA = getSCEV(FalseVal);
4320       const SCEV *LDiff = getMinusSCEV(LA, LS);
4321       const SCEV *RDiff = getMinusSCEV(RA, RS);
4322       if (LDiff == RDiff)
4323         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4324       LDiff = getMinusSCEV(LA, RS);
4325       RDiff = getMinusSCEV(RA, LS);
4326       if (LDiff == RDiff)
4327         return getAddExpr(getUMinExpr(LS, RS), LDiff);
4328     }
4329     break;
4330   case ICmpInst::ICMP_NE:
4331     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
4332     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4333         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4334       const SCEV *One = getOne(I->getType());
4335       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4336       const SCEV *LA = getSCEV(TrueVal);
4337       const SCEV *RA = getSCEV(FalseVal);
4338       const SCEV *LDiff = getMinusSCEV(LA, LS);
4339       const SCEV *RDiff = getMinusSCEV(RA, One);
4340       if (LDiff == RDiff)
4341         return getAddExpr(getUMaxExpr(One, LS), LDiff);
4342     }
4343     break;
4344   case ICmpInst::ICMP_EQ:
4345     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
4346     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4347         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4348       const SCEV *One = getOne(I->getType());
4349       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4350       const SCEV *LA = getSCEV(TrueVal);
4351       const SCEV *RA = getSCEV(FalseVal);
4352       const SCEV *LDiff = getMinusSCEV(LA, One);
4353       const SCEV *RDiff = getMinusSCEV(RA, LS);
4354       if (LDiff == RDiff)
4355         return getAddExpr(getUMaxExpr(One, LS), LDiff);
4356     }
4357     break;
4358   default:
4359     break;
4360   }
4361 
4362   return getUnknown(I);
4363 }
4364 
4365 /// Expand GEP instructions into add and multiply operations. This allows them
4366 /// to be analyzed by regular SCEV code.
4367 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
4368   // Don't attempt to analyze GEPs over unsized objects.
4369   if (!GEP->getSourceElementType()->isSized())
4370     return getUnknown(GEP);
4371 
4372   SmallVector<const SCEV *, 4> IndexExprs;
4373   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
4374     IndexExprs.push_back(getSCEV(*Index));
4375   return getGEPExpr(GEP->getSourceElementType(),
4376                     getSCEV(GEP->getPointerOperand()),
4377                     IndexExprs, GEP->isInBounds());
4378 }
4379 
4380 uint32_t
4381 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
4382   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
4383     return C->getAPInt().countTrailingZeros();
4384 
4385   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
4386     return std::min(GetMinTrailingZeros(T->getOperand()),
4387                     (uint32_t)getTypeSizeInBits(T->getType()));
4388 
4389   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
4390     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4391     return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
4392              getTypeSizeInBits(E->getType()) : OpRes;
4393   }
4394 
4395   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
4396     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4397     return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
4398              getTypeSizeInBits(E->getType()) : OpRes;
4399   }
4400 
4401   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
4402     // The result is the min of all operands results.
4403     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
4404     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
4405       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
4406     return MinOpRes;
4407   }
4408 
4409   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
4410     // The result is the sum of all operands results.
4411     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
4412     uint32_t BitWidth = getTypeSizeInBits(M->getType());
4413     for (unsigned i = 1, e = M->getNumOperands();
4414          SumOpRes != BitWidth && i != e; ++i)
4415       SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
4416                           BitWidth);
4417     return SumOpRes;
4418   }
4419 
4420   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
4421     // The result is the min of all operands results.
4422     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
4423     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
4424       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
4425     return MinOpRes;
4426   }
4427 
4428   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
4429     // The result is the min of all operands results.
4430     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
4431     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
4432       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
4433     return MinOpRes;
4434   }
4435 
4436   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
4437     // The result is the min of all operands results.
4438     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
4439     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
4440       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
4441     return MinOpRes;
4442   }
4443 
4444   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4445     // For a SCEVUnknown, ask ValueTracking.
4446     unsigned BitWidth = getTypeSizeInBits(U->getType());
4447     APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
4448     computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC,
4449                      nullptr, &DT);
4450     return Zeros.countTrailingOnes();
4451   }
4452 
4453   // SCEVUDivExpr
4454   return 0;
4455 }
4456 
4457 /// Helper method to assign a range to V from metadata present in the IR.
4458 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
4459   if (Instruction *I = dyn_cast<Instruction>(V))
4460     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
4461       return getConstantRangeFromMetadata(*MD);
4462 
4463   return None;
4464 }
4465 
4466 /// Determine the range for a particular SCEV.  If SignHint is
4467 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
4468 /// with a "cleaner" unsigned (resp. signed) representation.
4469 ConstantRange
4470 ScalarEvolution::getRange(const SCEV *S,
4471                           ScalarEvolution::RangeSignHint SignHint) {
4472   DenseMap<const SCEV *, ConstantRange> &Cache =
4473       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
4474                                                        : SignedRanges;
4475 
4476   // See if we've computed this range already.
4477   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
4478   if (I != Cache.end())
4479     return I->second;
4480 
4481   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
4482     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
4483 
4484   unsigned BitWidth = getTypeSizeInBits(S->getType());
4485   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
4486 
4487   // If the value has known zeros, the maximum value will have those known zeros
4488   // as well.
4489   uint32_t TZ = GetMinTrailingZeros(S);
4490   if (TZ != 0) {
4491     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
4492       ConservativeResult =
4493           ConstantRange(APInt::getMinValue(BitWidth),
4494                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
4495     else
4496       ConservativeResult = ConstantRange(
4497           APInt::getSignedMinValue(BitWidth),
4498           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
4499   }
4500 
4501   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
4502     ConstantRange X = getRange(Add->getOperand(0), SignHint);
4503     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
4504       X = X.add(getRange(Add->getOperand(i), SignHint));
4505     return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
4506   }
4507 
4508   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
4509     ConstantRange X = getRange(Mul->getOperand(0), SignHint);
4510     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
4511       X = X.multiply(getRange(Mul->getOperand(i), SignHint));
4512     return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
4513   }
4514 
4515   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
4516     ConstantRange X = getRange(SMax->getOperand(0), SignHint);
4517     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
4518       X = X.smax(getRange(SMax->getOperand(i), SignHint));
4519     return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
4520   }
4521 
4522   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
4523     ConstantRange X = getRange(UMax->getOperand(0), SignHint);
4524     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
4525       X = X.umax(getRange(UMax->getOperand(i), SignHint));
4526     return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
4527   }
4528 
4529   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
4530     ConstantRange X = getRange(UDiv->getLHS(), SignHint);
4531     ConstantRange Y = getRange(UDiv->getRHS(), SignHint);
4532     return setRange(UDiv, SignHint,
4533                     ConservativeResult.intersectWith(X.udiv(Y)));
4534   }
4535 
4536   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
4537     ConstantRange X = getRange(ZExt->getOperand(), SignHint);
4538     return setRange(ZExt, SignHint,
4539                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
4540   }
4541 
4542   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
4543     ConstantRange X = getRange(SExt->getOperand(), SignHint);
4544     return setRange(SExt, SignHint,
4545                     ConservativeResult.intersectWith(X.signExtend(BitWidth)));
4546   }
4547 
4548   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
4549     ConstantRange X = getRange(Trunc->getOperand(), SignHint);
4550     return setRange(Trunc, SignHint,
4551                     ConservativeResult.intersectWith(X.truncate(BitWidth)));
4552   }
4553 
4554   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
4555     // If there's no unsigned wrap, the value will never be less than its
4556     // initial value.
4557     if (AddRec->hasNoUnsignedWrap())
4558       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
4559         if (!C->getValue()->isZero())
4560           ConservativeResult = ConservativeResult.intersectWith(
4561               ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
4562 
4563     // If there's no signed wrap, and all the operands have the same sign or
4564     // zero, the value won't ever change sign.
4565     if (AddRec->hasNoSignedWrap()) {
4566       bool AllNonNeg = true;
4567       bool AllNonPos = true;
4568       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4569         if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
4570         if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
4571       }
4572       if (AllNonNeg)
4573         ConservativeResult = ConservativeResult.intersectWith(
4574           ConstantRange(APInt(BitWidth, 0),
4575                         APInt::getSignedMinValue(BitWidth)));
4576       else if (AllNonPos)
4577         ConservativeResult = ConservativeResult.intersectWith(
4578           ConstantRange(APInt::getSignedMinValue(BitWidth),
4579                         APInt(BitWidth, 1)));
4580     }
4581 
4582     // TODO: non-affine addrec
4583     if (AddRec->isAffine()) {
4584       const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
4585       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
4586           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
4587         auto RangeFromAffine = getRangeForAffineAR(
4588             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4589             BitWidth);
4590         if (!RangeFromAffine.isFullSet())
4591           ConservativeResult =
4592               ConservativeResult.intersectWith(RangeFromAffine);
4593 
4594         auto RangeFromFactoring = getRangeViaFactoring(
4595             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4596             BitWidth);
4597         if (!RangeFromFactoring.isFullSet())
4598           ConservativeResult =
4599               ConservativeResult.intersectWith(RangeFromFactoring);
4600       }
4601     }
4602 
4603     return setRange(AddRec, SignHint, ConservativeResult);
4604   }
4605 
4606   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4607     // Check if the IR explicitly contains !range metadata.
4608     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
4609     if (MDRange.hasValue())
4610       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
4611 
4612     // Split here to avoid paying the compile-time cost of calling both
4613     // computeKnownBits and ComputeNumSignBits.  This restriction can be lifted
4614     // if needed.
4615     const DataLayout &DL = getDataLayout();
4616     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
4617       // For a SCEVUnknown, ask ValueTracking.
4618       APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
4619       computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT);
4620       if (Ones != ~Zeros + 1)
4621         ConservativeResult =
4622             ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
4623     } else {
4624       assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
4625              "generalize as needed!");
4626       unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
4627       if (NS > 1)
4628         ConservativeResult = ConservativeResult.intersectWith(
4629             ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
4630                           APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
4631     }
4632 
4633     return setRange(U, SignHint, ConservativeResult);
4634   }
4635 
4636   return setRange(S, SignHint, ConservativeResult);
4637 }
4638 
4639 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
4640                                                    const SCEV *Step,
4641                                                    const SCEV *MaxBECount,
4642                                                    unsigned BitWidth) {
4643   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
4644          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
4645          "Precondition!");
4646 
4647   ConstantRange Result(BitWidth, /* isFullSet = */ true);
4648 
4649   // Check for overflow.  This must be done with ConstantRange arithmetic
4650   // because we could be called from within the ScalarEvolution overflow
4651   // checking code.
4652 
4653   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
4654   ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
4655   ConstantRange ZExtMaxBECountRange =
4656       MaxBECountRange.zextOrTrunc(BitWidth * 2 + 1);
4657 
4658   ConstantRange StepSRange = getSignedRange(Step);
4659   ConstantRange SExtStepSRange = StepSRange.sextOrTrunc(BitWidth * 2 + 1);
4660 
4661   ConstantRange StartURange = getUnsignedRange(Start);
4662   ConstantRange EndURange =
4663       StartURange.add(MaxBECountRange.multiply(StepSRange));
4664 
4665   // Check for unsigned overflow.
4666   ConstantRange ZExtStartURange = StartURange.zextOrTrunc(BitWidth * 2 + 1);
4667   ConstantRange ZExtEndURange = EndURange.zextOrTrunc(BitWidth * 2 + 1);
4668   if (ZExtStartURange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) ==
4669       ZExtEndURange) {
4670     APInt Min = APIntOps::umin(StartURange.getUnsignedMin(),
4671                                EndURange.getUnsignedMin());
4672     APInt Max = APIntOps::umax(StartURange.getUnsignedMax(),
4673                                EndURange.getUnsignedMax());
4674     bool IsFullRange = Min.isMinValue() && Max.isMaxValue();
4675     if (!IsFullRange)
4676       Result =
4677           Result.intersectWith(ConstantRange(Min, Max + 1));
4678   }
4679 
4680   ConstantRange StartSRange = getSignedRange(Start);
4681   ConstantRange EndSRange =
4682       StartSRange.add(MaxBECountRange.multiply(StepSRange));
4683 
4684   // Check for signed overflow. This must be done with ConstantRange
4685   // arithmetic because we could be called from within the ScalarEvolution
4686   // overflow checking code.
4687   ConstantRange SExtStartSRange = StartSRange.sextOrTrunc(BitWidth * 2 + 1);
4688   ConstantRange SExtEndSRange = EndSRange.sextOrTrunc(BitWidth * 2 + 1);
4689   if (SExtStartSRange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) ==
4690       SExtEndSRange) {
4691     APInt Min =
4692         APIntOps::smin(StartSRange.getSignedMin(), EndSRange.getSignedMin());
4693     APInt Max =
4694         APIntOps::smax(StartSRange.getSignedMax(), EndSRange.getSignedMax());
4695     bool IsFullRange = Min.isMinSignedValue() && Max.isMaxSignedValue();
4696     if (!IsFullRange)
4697       Result =
4698           Result.intersectWith(ConstantRange(Min, Max + 1));
4699   }
4700 
4701   return Result;
4702 }
4703 
4704 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
4705                                                     const SCEV *Step,
4706                                                     const SCEV *MaxBECount,
4707                                                     unsigned BitWidth) {
4708   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
4709   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
4710 
4711   struct SelectPattern {
4712     Value *Condition = nullptr;
4713     APInt TrueValue;
4714     APInt FalseValue;
4715 
4716     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
4717                            const SCEV *S) {
4718       Optional<unsigned> CastOp;
4719       APInt Offset(BitWidth, 0);
4720 
4721       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
4722              "Should be!");
4723 
4724       // Peel off a constant offset:
4725       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
4726         // In the future we could consider being smarter here and handle
4727         // {Start+Step,+,Step} too.
4728         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
4729           return;
4730 
4731         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
4732         S = SA->getOperand(1);
4733       }
4734 
4735       // Peel off a cast operation
4736       if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
4737         CastOp = SCast->getSCEVType();
4738         S = SCast->getOperand();
4739       }
4740 
4741       using namespace llvm::PatternMatch;
4742 
4743       auto *SU = dyn_cast<SCEVUnknown>(S);
4744       const APInt *TrueVal, *FalseVal;
4745       if (!SU ||
4746           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
4747                                           m_APInt(FalseVal)))) {
4748         Condition = nullptr;
4749         return;
4750       }
4751 
4752       TrueValue = *TrueVal;
4753       FalseValue = *FalseVal;
4754 
4755       // Re-apply the cast we peeled off earlier
4756       if (CastOp.hasValue())
4757         switch (*CastOp) {
4758         default:
4759           llvm_unreachable("Unknown SCEV cast type!");
4760 
4761         case scTruncate:
4762           TrueValue = TrueValue.trunc(BitWidth);
4763           FalseValue = FalseValue.trunc(BitWidth);
4764           break;
4765         case scZeroExtend:
4766           TrueValue = TrueValue.zext(BitWidth);
4767           FalseValue = FalseValue.zext(BitWidth);
4768           break;
4769         case scSignExtend:
4770           TrueValue = TrueValue.sext(BitWidth);
4771           FalseValue = FalseValue.sext(BitWidth);
4772           break;
4773         }
4774 
4775       // Re-apply the constant offset we peeled off earlier
4776       TrueValue += Offset;
4777       FalseValue += Offset;
4778     }
4779 
4780     bool isRecognized() { return Condition != nullptr; }
4781   };
4782 
4783   SelectPattern StartPattern(*this, BitWidth, Start);
4784   if (!StartPattern.isRecognized())
4785     return ConstantRange(BitWidth, /* isFullSet = */ true);
4786 
4787   SelectPattern StepPattern(*this, BitWidth, Step);
4788   if (!StepPattern.isRecognized())
4789     return ConstantRange(BitWidth, /* isFullSet = */ true);
4790 
4791   if (StartPattern.Condition != StepPattern.Condition) {
4792     // We don't handle this case today; but we could, by considering four
4793     // possibilities below instead of two. I'm not sure if there are cases where
4794     // that will help over what getRange already does, though.
4795     return ConstantRange(BitWidth, /* isFullSet = */ true);
4796   }
4797 
4798   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
4799   // construct arbitrary general SCEV expressions here.  This function is called
4800   // from deep in the call stack, and calling getSCEV (on a sext instruction,
4801   // say) can end up caching a suboptimal value.
4802 
4803   // FIXME: without the explicit `this` receiver below, MSVC errors out with
4804   // C2352 and C2512 (otherwise it isn't needed).
4805 
4806   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
4807   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
4808   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
4809   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
4810 
4811   ConstantRange TrueRange =
4812       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
4813   ConstantRange FalseRange =
4814       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
4815 
4816   return TrueRange.unionWith(FalseRange);
4817 }
4818 
4819 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
4820   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
4821   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
4822 
4823   // Return early if there are no flags to propagate to the SCEV.
4824   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4825   if (BinOp->hasNoUnsignedWrap())
4826     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
4827   if (BinOp->hasNoSignedWrap())
4828     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
4829   if (Flags == SCEV::FlagAnyWrap)
4830     return SCEV::FlagAnyWrap;
4831 
4832   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
4833 }
4834 
4835 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
4836   // Here we check that I is in the header of the innermost loop containing I,
4837   // since we only deal with instructions in the loop header. The actual loop we
4838   // need to check later will come from an add recurrence, but getting that
4839   // requires computing the SCEV of the operands, which can be expensive. This
4840   // check we can do cheaply to rule out some cases early.
4841   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
4842   if (InnermostContainingLoop == nullptr ||
4843       InnermostContainingLoop->getHeader() != I->getParent())
4844     return false;
4845 
4846   // Only proceed if we can prove that I does not yield poison.
4847   if (!isKnownNotFullPoison(I)) return false;
4848 
4849   // At this point we know that if I is executed, then it does not wrap
4850   // according to at least one of NSW or NUW. If I is not executed, then we do
4851   // not know if the calculation that I represents would wrap. Multiple
4852   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
4853   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
4854   // derived from other instructions that map to the same SCEV. We cannot make
4855   // that guarantee for cases where I is not executed. So we need to find the
4856   // loop that I is considered in relation to and prove that I is executed for
4857   // every iteration of that loop. That implies that the value that I
4858   // calculates does not wrap anywhere in the loop, so then we can apply the
4859   // flags to the SCEV.
4860   //
4861   // We check isLoopInvariant to disambiguate in case we are adding recurrences
4862   // from different loops, so that we know which loop to prove that I is
4863   // executed in.
4864   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
4865     // I could be an extractvalue from a call to an overflow intrinsic.
4866     // TODO: We can do better here in some cases.
4867     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
4868       return false;
4869     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
4870     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
4871       bool AllOtherOpsLoopInvariant = true;
4872       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
4873            ++OtherOpIndex) {
4874         if (OtherOpIndex != OpIndex) {
4875           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
4876           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
4877             AllOtherOpsLoopInvariant = false;
4878             break;
4879           }
4880         }
4881       }
4882       if (AllOtherOpsLoopInvariant &&
4883           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
4884         return true;
4885     }
4886   }
4887   return false;
4888 }
4889 
4890 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
4891   // If we know that \c I can never be poison period, then that's enough.
4892   if (isSCEVExprNeverPoison(I))
4893     return true;
4894 
4895   // For an add recurrence specifically, we assume that infinite loops without
4896   // side effects are undefined behavior, and then reason as follows:
4897   //
4898   // If the add recurrence is poison in any iteration, it is poison on all
4899   // future iterations (since incrementing poison yields poison). If the result
4900   // of the add recurrence is fed into the loop latch condition and the loop
4901   // does not contain any throws or exiting blocks other than the latch, we now
4902   // have the ability to "choose" whether the backedge is taken or not (by
4903   // choosing a sufficiently evil value for the poison feeding into the branch)
4904   // for every iteration including and after the one in which \p I first became
4905   // poison.  There are two possibilities (let's call the iteration in which \p
4906   // I first became poison as K):
4907   //
4908   //  1. In the set of iterations including and after K, the loop body executes
4909   //     no side effects.  In this case executing the backege an infinte number
4910   //     of times will yield undefined behavior.
4911   //
4912   //  2. In the set of iterations including and after K, the loop body executes
4913   //     at least one side effect.  In this case, that specific instance of side
4914   //     effect is control dependent on poison, which also yields undefined
4915   //     behavior.
4916 
4917   auto *ExitingBB = L->getExitingBlock();
4918   auto *LatchBB = L->getLoopLatch();
4919   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
4920     return false;
4921 
4922   SmallPtrSet<const Instruction *, 16> Pushed;
4923   SmallVector<const Instruction *, 8> PoisonStack;
4924 
4925   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
4926   // things that are known to be fully poison under that assumption go on the
4927   // PoisonStack.
4928   Pushed.insert(I);
4929   PoisonStack.push_back(I);
4930 
4931   bool LatchControlDependentOnPoison = false;
4932   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
4933     const Instruction *Poison = PoisonStack.pop_back_val();
4934 
4935     for (auto *PoisonUser : Poison->users()) {
4936       if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
4937         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
4938           PoisonStack.push_back(cast<Instruction>(PoisonUser));
4939       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
4940         assert(BI->isConditional() && "Only possibility!");
4941         if (BI->getParent() == LatchBB) {
4942           LatchControlDependentOnPoison = true;
4943           break;
4944         }
4945       }
4946     }
4947   }
4948 
4949   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
4950 }
4951 
4952 ScalarEvolution::LoopProperties
4953 ScalarEvolution::getLoopProperties(const Loop *L) {
4954   typedef ScalarEvolution::LoopProperties LoopProperties;
4955 
4956   auto Itr = LoopPropertiesCache.find(L);
4957   if (Itr == LoopPropertiesCache.end()) {
4958     auto HasSideEffects = [](Instruction *I) {
4959       if (auto *SI = dyn_cast<StoreInst>(I))
4960         return !SI->isSimple();
4961 
4962       return I->mayHaveSideEffects();
4963     };
4964 
4965     LoopProperties LP = {/* HasNoAbnormalExits */ true,
4966                          /*HasNoSideEffects*/ true};
4967 
4968     for (auto *BB : L->getBlocks())
4969       for (auto &I : *BB) {
4970         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
4971           LP.HasNoAbnormalExits = false;
4972         if (HasSideEffects(&I))
4973           LP.HasNoSideEffects = false;
4974         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
4975           break; // We're already as pessimistic as we can get.
4976       }
4977 
4978     auto InsertPair = LoopPropertiesCache.insert({L, LP});
4979     assert(InsertPair.second && "We just checked!");
4980     Itr = InsertPair.first;
4981   }
4982 
4983   return Itr->second;
4984 }
4985 
4986 const SCEV *ScalarEvolution::createSCEV(Value *V) {
4987   if (!isSCEVable(V->getType()))
4988     return getUnknown(V);
4989 
4990   if (Instruction *I = dyn_cast<Instruction>(V)) {
4991     // Don't attempt to analyze instructions in blocks that aren't
4992     // reachable. Such instructions don't matter, and they aren't required
4993     // to obey basic rules for definitions dominating uses which this
4994     // analysis depends on.
4995     if (!DT.isReachableFromEntry(I->getParent()))
4996       return getUnknown(V);
4997   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
4998     return getConstant(CI);
4999   else if (isa<ConstantPointerNull>(V))
5000     return getZero(V->getType());
5001   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
5002     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
5003   else if (!isa<ConstantExpr>(V))
5004     return getUnknown(V);
5005 
5006   Operator *U = cast<Operator>(V);
5007   if (auto BO = MatchBinaryOp(U, DT)) {
5008     switch (BO->Opcode) {
5009     case Instruction::Add: {
5010       // The simple thing to do would be to just call getSCEV on both operands
5011       // and call getAddExpr with the result. However if we're looking at a
5012       // bunch of things all added together, this can be quite inefficient,
5013       // because it leads to N-1 getAddExpr calls for N ultimate operands.
5014       // Instead, gather up all the operands and make a single getAddExpr call.
5015       // LLVM IR canonical form means we need only traverse the left operands.
5016       SmallVector<const SCEV *, 4> AddOps;
5017       do {
5018         if (BO->Op) {
5019           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5020             AddOps.push_back(OpSCEV);
5021             break;
5022           }
5023 
5024           // If a NUW or NSW flag can be applied to the SCEV for this
5025           // addition, then compute the SCEV for this addition by itself
5026           // with a separate call to getAddExpr. We need to do that
5027           // instead of pushing the operands of the addition onto AddOps,
5028           // since the flags are only known to apply to this particular
5029           // addition - they may not apply to other additions that can be
5030           // formed with operands from AddOps.
5031           const SCEV *RHS = getSCEV(BO->RHS);
5032           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5033           if (Flags != SCEV::FlagAnyWrap) {
5034             const SCEV *LHS = getSCEV(BO->LHS);
5035             if (BO->Opcode == Instruction::Sub)
5036               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
5037             else
5038               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
5039             break;
5040           }
5041         }
5042 
5043         if (BO->Opcode == Instruction::Sub)
5044           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
5045         else
5046           AddOps.push_back(getSCEV(BO->RHS));
5047 
5048         auto NewBO = MatchBinaryOp(BO->LHS, DT);
5049         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
5050                        NewBO->Opcode != Instruction::Sub)) {
5051           AddOps.push_back(getSCEV(BO->LHS));
5052           break;
5053         }
5054         BO = NewBO;
5055       } while (true);
5056 
5057       return getAddExpr(AddOps);
5058     }
5059 
5060     case Instruction::Mul: {
5061       SmallVector<const SCEV *, 4> MulOps;
5062       do {
5063         if (BO->Op) {
5064           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5065             MulOps.push_back(OpSCEV);
5066             break;
5067           }
5068 
5069           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5070           if (Flags != SCEV::FlagAnyWrap) {
5071             MulOps.push_back(
5072                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
5073             break;
5074           }
5075         }
5076 
5077         MulOps.push_back(getSCEV(BO->RHS));
5078         auto NewBO = MatchBinaryOp(BO->LHS, DT);
5079         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
5080           MulOps.push_back(getSCEV(BO->LHS));
5081           break;
5082         }
5083         BO = NewBO;
5084       } while (true);
5085 
5086       return getMulExpr(MulOps);
5087     }
5088     case Instruction::UDiv:
5089       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
5090     case Instruction::Sub: {
5091       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5092       if (BO->Op)
5093         Flags = getNoWrapFlagsFromUB(BO->Op);
5094       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
5095     }
5096     case Instruction::And:
5097       // For an expression like x&255 that merely masks off the high bits,
5098       // use zext(trunc(x)) as the SCEV expression.
5099       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5100         if (CI->isNullValue())
5101           return getSCEV(BO->RHS);
5102         if (CI->isAllOnesValue())
5103           return getSCEV(BO->LHS);
5104         const APInt &A = CI->getValue();
5105 
5106         // Instcombine's ShrinkDemandedConstant may strip bits out of
5107         // constants, obscuring what would otherwise be a low-bits mask.
5108         // Use computeKnownBits to compute what ShrinkDemandedConstant
5109         // knew about to reconstruct a low-bits mask value.
5110         unsigned LZ = A.countLeadingZeros();
5111         unsigned TZ = A.countTrailingZeros();
5112         unsigned BitWidth = A.getBitWidth();
5113         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5114         computeKnownBits(BO->LHS, KnownZero, KnownOne, getDataLayout(),
5115                          0, &AC, nullptr, &DT);
5116 
5117         APInt EffectiveMask =
5118             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
5119         if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) {
5120           const SCEV *MulCount = getConstant(ConstantInt::get(
5121               getContext(), APInt::getOneBitSet(BitWidth, TZ)));
5122           return getMulExpr(
5123               getZeroExtendExpr(
5124                   getTruncateExpr(
5125                       getUDivExactExpr(getSCEV(BO->LHS), MulCount),
5126                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
5127                   BO->LHS->getType()),
5128               MulCount);
5129         }
5130       }
5131       break;
5132 
5133     case Instruction::Or:
5134       // If the RHS of the Or is a constant, we may have something like:
5135       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
5136       // optimizations will transparently handle this case.
5137       //
5138       // In order for this transformation to be safe, the LHS must be of the
5139       // form X*(2^n) and the Or constant must be less than 2^n.
5140       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5141         const SCEV *LHS = getSCEV(BO->LHS);
5142         const APInt &CIVal = CI->getValue();
5143         if (GetMinTrailingZeros(LHS) >=
5144             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
5145           // Build a plain add SCEV.
5146           const SCEV *S = getAddExpr(LHS, getSCEV(CI));
5147           // If the LHS of the add was an addrec and it has no-wrap flags,
5148           // transfer the no-wrap flags, since an or won't introduce a wrap.
5149           if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
5150             const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
5151             const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
5152                 OldAR->getNoWrapFlags());
5153           }
5154           return S;
5155         }
5156       }
5157       break;
5158 
5159     case Instruction::Xor:
5160       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5161         // If the RHS of xor is -1, then this is a not operation.
5162         if (CI->isAllOnesValue())
5163           return getNotSCEV(getSCEV(BO->LHS));
5164 
5165         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
5166         // This is a variant of the check for xor with -1, and it handles
5167         // the case where instcombine has trimmed non-demanded bits out
5168         // of an xor with -1.
5169         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
5170           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
5171             if (LBO->getOpcode() == Instruction::And &&
5172                 LCI->getValue() == CI->getValue())
5173               if (const SCEVZeroExtendExpr *Z =
5174                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
5175                 Type *UTy = BO->LHS->getType();
5176                 const SCEV *Z0 = Z->getOperand();
5177                 Type *Z0Ty = Z0->getType();
5178                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
5179 
5180                 // If C is a low-bits mask, the zero extend is serving to
5181                 // mask off the high bits. Complement the operand and
5182                 // re-apply the zext.
5183                 if (APIntOps::isMask(Z0TySize, CI->getValue()))
5184                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
5185 
5186                 // If C is a single bit, it may be in the sign-bit position
5187                 // before the zero-extend. In this case, represent the xor
5188                 // using an add, which is equivalent, and re-apply the zext.
5189                 APInt Trunc = CI->getValue().trunc(Z0TySize);
5190                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
5191                     Trunc.isSignBit())
5192                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
5193                                            UTy);
5194               }
5195       }
5196       break;
5197 
5198   case Instruction::Shl:
5199     // Turn shift left of a constant amount into a multiply.
5200     if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
5201       uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
5202 
5203       // If the shift count is not less than the bitwidth, the result of
5204       // the shift is undefined. Don't try to analyze it, because the
5205       // resolution chosen here may differ from the resolution chosen in
5206       // other parts of the compiler.
5207       if (SA->getValue().uge(BitWidth))
5208         break;
5209 
5210       // It is currently not resolved how to interpret NSW for left
5211       // shift by BitWidth - 1, so we avoid applying flags in that
5212       // case. Remove this check (or this comment) once the situation
5213       // is resolved. See
5214       // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
5215       // and http://reviews.llvm.org/D8890 .
5216       auto Flags = SCEV::FlagAnyWrap;
5217       if (BO->Op && SA->getValue().ult(BitWidth - 1))
5218         Flags = getNoWrapFlagsFromUB(BO->Op);
5219 
5220       Constant *X = ConstantInt::get(getContext(),
5221         APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5222       return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
5223     }
5224     break;
5225 
5226     case Instruction::AShr:
5227       // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
5228       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS))
5229         if (Operator *L = dyn_cast<Operator>(BO->LHS))
5230           if (L->getOpcode() == Instruction::Shl &&
5231               L->getOperand(1) == BO->RHS) {
5232             uint64_t BitWidth = getTypeSizeInBits(BO->LHS->getType());
5233 
5234             // If the shift count is not less than the bitwidth, the result of
5235             // the shift is undefined. Don't try to analyze it, because the
5236             // resolution chosen here may differ from the resolution chosen in
5237             // other parts of the compiler.
5238             if (CI->getValue().uge(BitWidth))
5239               break;
5240 
5241             uint64_t Amt = BitWidth - CI->getZExtValue();
5242             if (Amt == BitWidth)
5243               return getSCEV(L->getOperand(0)); // shift by zero --> noop
5244             return getSignExtendExpr(
5245                 getTruncateExpr(getSCEV(L->getOperand(0)),
5246                                 IntegerType::get(getContext(), Amt)),
5247                 BO->LHS->getType());
5248           }
5249       break;
5250     }
5251   }
5252 
5253   switch (U->getOpcode()) {
5254   case Instruction::Trunc:
5255     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
5256 
5257   case Instruction::ZExt:
5258     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
5259 
5260   case Instruction::SExt:
5261     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
5262 
5263   case Instruction::BitCast:
5264     // BitCasts are no-op casts so we just eliminate the cast.
5265     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
5266       return getSCEV(U->getOperand(0));
5267     break;
5268 
5269   // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
5270   // lead to pointer expressions which cannot safely be expanded to GEPs,
5271   // because ScalarEvolution doesn't respect the GEP aliasing rules when
5272   // simplifying integer expressions.
5273 
5274   case Instruction::GetElementPtr:
5275     return createNodeForGEP(cast<GEPOperator>(U));
5276 
5277   case Instruction::PHI:
5278     return createNodeForPHI(cast<PHINode>(U));
5279 
5280   case Instruction::Select:
5281     // U can also be a select constant expr, which let fall through.  Since
5282     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
5283     // constant expressions cannot have instructions as operands, we'd have
5284     // returned getUnknown for a select constant expressions anyway.
5285     if (isa<Instruction>(U))
5286       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
5287                                       U->getOperand(1), U->getOperand(2));
5288     break;
5289 
5290   case Instruction::Call:
5291   case Instruction::Invoke:
5292     if (Value *RV = CallSite(U).getReturnedArgOperand())
5293       return getSCEV(RV);
5294     break;
5295   }
5296 
5297   return getUnknown(V);
5298 }
5299 
5300 
5301 
5302 //===----------------------------------------------------------------------===//
5303 //                   Iteration Count Computation Code
5304 //
5305 
5306 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
5307   if (!ExitCount)
5308     return 0;
5309 
5310   ConstantInt *ExitConst = ExitCount->getValue();
5311 
5312   // Guard against huge trip counts.
5313   if (ExitConst->getValue().getActiveBits() > 32)
5314     return 0;
5315 
5316   // In case of integer overflow, this returns 0, which is correct.
5317   return ((unsigned)ExitConst->getZExtValue()) + 1;
5318 }
5319 
5320 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) {
5321   if (BasicBlock *ExitingBB = L->getExitingBlock())
5322     return getSmallConstantTripCount(L, ExitingBB);
5323 
5324   // No trip count information for multiple exits.
5325   return 0;
5326 }
5327 
5328 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L,
5329                                                     BasicBlock *ExitingBlock) {
5330   assert(ExitingBlock && "Must pass a non-null exiting block!");
5331   assert(L->isLoopExiting(ExitingBlock) &&
5332          "Exiting block must actually branch out of the loop!");
5333   const SCEVConstant *ExitCount =
5334       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
5335   return getConstantTripCount(ExitCount);
5336 }
5337 
5338 unsigned ScalarEvolution::getSmallConstantMaxTripCount(Loop *L) {
5339   const auto *MaxExitCount =
5340       dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L));
5341   return getConstantTripCount(MaxExitCount);
5342 }
5343 
5344 unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) {
5345   if (BasicBlock *ExitingBB = L->getExitingBlock())
5346     return getSmallConstantTripMultiple(L, ExitingBB);
5347 
5348   // No trip multiple information for multiple exits.
5349   return 0;
5350 }
5351 
5352 /// Returns the largest constant divisor of the trip count of this loop as a
5353 /// normal unsigned value, if possible. This means that the actual trip count is
5354 /// always a multiple of the returned value (don't forget the trip count could
5355 /// very well be zero as well!).
5356 ///
5357 /// Returns 1 if the trip count is unknown or not guaranteed to be the
5358 /// multiple of a constant (which is also the case if the trip count is simply
5359 /// constant, use getSmallConstantTripCount for that case), Will also return 1
5360 /// if the trip count is very large (>= 2^32).
5361 ///
5362 /// As explained in the comments for getSmallConstantTripCount, this assumes
5363 /// that control exits the loop via ExitingBlock.
5364 unsigned
5365 ScalarEvolution::getSmallConstantTripMultiple(Loop *L,
5366                                               BasicBlock *ExitingBlock) {
5367   assert(ExitingBlock && "Must pass a non-null exiting block!");
5368   assert(L->isLoopExiting(ExitingBlock) &&
5369          "Exiting block must actually branch out of the loop!");
5370   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
5371   if (ExitCount == getCouldNotCompute())
5372     return 1;
5373 
5374   // Get the trip count from the BE count by adding 1.
5375   const SCEV *TCMul = getAddExpr(ExitCount, getOne(ExitCount->getType()));
5376   // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt
5377   // to factor simple cases.
5378   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul))
5379     TCMul = Mul->getOperand(0);
5380 
5381   const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul);
5382   if (!MulC)
5383     return 1;
5384 
5385   ConstantInt *Result = MulC->getValue();
5386 
5387   // Guard against huge trip counts (this requires checking
5388   // for zero to handle the case where the trip count == -1 and the
5389   // addition wraps).
5390   if (!Result || Result->getValue().getActiveBits() > 32 ||
5391       Result->getValue().getActiveBits() == 0)
5392     return 1;
5393 
5394   return (unsigned)Result->getZExtValue();
5395 }
5396 
5397 /// Get the expression for the number of loop iterations for which this loop is
5398 /// guaranteed not to exit via ExitingBlock. Otherwise return
5399 /// SCEVCouldNotCompute.
5400 const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) {
5401   return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
5402 }
5403 
5404 const SCEV *
5405 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
5406                                                  SCEVUnionPredicate &Preds) {
5407   return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds);
5408 }
5409 
5410 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
5411   return getBackedgeTakenInfo(L).getExact(this);
5412 }
5413 
5414 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is
5415 /// known never to be less than the actual backedge taken count.
5416 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
5417   return getBackedgeTakenInfo(L).getMax(this);
5418 }
5419 
5420 /// Push PHI nodes in the header of the given loop onto the given Worklist.
5421 static void
5422 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
5423   BasicBlock *Header = L->getHeader();
5424 
5425   // Push all Loop-header PHIs onto the Worklist stack.
5426   for (BasicBlock::iterator I = Header->begin();
5427        PHINode *PN = dyn_cast<PHINode>(I); ++I)
5428     Worklist.push_back(PN);
5429 }
5430 
5431 const ScalarEvolution::BackedgeTakenInfo &
5432 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
5433   auto &BTI = getBackedgeTakenInfo(L);
5434   if (BTI.hasFullInfo())
5435     return BTI;
5436 
5437   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5438 
5439   if (!Pair.second)
5440     return Pair.first->second;
5441 
5442   BackedgeTakenInfo Result =
5443       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
5444 
5445   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
5446 }
5447 
5448 const ScalarEvolution::BackedgeTakenInfo &
5449 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
5450   // Initially insert an invalid entry for this loop. If the insertion
5451   // succeeds, proceed to actually compute a backedge-taken count and
5452   // update the value. The temporary CouldNotCompute value tells SCEV
5453   // code elsewhere that it shouldn't attempt to request a new
5454   // backedge-taken count, which could result in infinite recursion.
5455   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
5456       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5457   if (!Pair.second)
5458     return Pair.first->second;
5459 
5460   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
5461   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
5462   // must be cleared in this scope.
5463   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
5464 
5465   if (Result.getExact(this) != getCouldNotCompute()) {
5466     assert(isLoopInvariant(Result.getExact(this), L) &&
5467            isLoopInvariant(Result.getMax(this), L) &&
5468            "Computed backedge-taken count isn't loop invariant for loop!");
5469     ++NumTripCountsComputed;
5470   }
5471   else if (Result.getMax(this) == getCouldNotCompute() &&
5472            isa<PHINode>(L->getHeader()->begin())) {
5473     // Only count loops that have phi nodes as not being computable.
5474     ++NumTripCountsNotComputed;
5475   }
5476 
5477   // Now that we know more about the trip count for this loop, forget any
5478   // existing SCEV values for PHI nodes in this loop since they are only
5479   // conservative estimates made without the benefit of trip count
5480   // information. This is similar to the code in forgetLoop, except that
5481   // it handles SCEVUnknown PHI nodes specially.
5482   if (Result.hasAnyInfo()) {
5483     SmallVector<Instruction *, 16> Worklist;
5484     PushLoopPHIs(L, Worklist);
5485 
5486     SmallPtrSet<Instruction *, 8> Visited;
5487     while (!Worklist.empty()) {
5488       Instruction *I = Worklist.pop_back_val();
5489       if (!Visited.insert(I).second)
5490         continue;
5491 
5492       ValueExprMapType::iterator It =
5493         ValueExprMap.find_as(static_cast<Value *>(I));
5494       if (It != ValueExprMap.end()) {
5495         const SCEV *Old = It->second;
5496 
5497         // SCEVUnknown for a PHI either means that it has an unrecognized
5498         // structure, or it's a PHI that's in the progress of being computed
5499         // by createNodeForPHI.  In the former case, additional loop trip
5500         // count information isn't going to change anything. In the later
5501         // case, createNodeForPHI will perform the necessary updates on its
5502         // own when it gets to that point.
5503         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
5504           eraseValueFromMap(It->first);
5505           forgetMemoizedResults(Old);
5506         }
5507         if (PHINode *PN = dyn_cast<PHINode>(I))
5508           ConstantEvolutionLoopExitValue.erase(PN);
5509       }
5510 
5511       PushDefUseChildren(I, Worklist);
5512     }
5513   }
5514 
5515   // Re-lookup the insert position, since the call to
5516   // computeBackedgeTakenCount above could result in a
5517   // recusive call to getBackedgeTakenInfo (on a different
5518   // loop), which would invalidate the iterator computed
5519   // earlier.
5520   return BackedgeTakenCounts.find(L)->second = std::move(Result);
5521 }
5522 
5523 void ScalarEvolution::forgetLoop(const Loop *L) {
5524   // Drop any stored trip count value.
5525   auto RemoveLoopFromBackedgeMap =
5526       [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
5527         auto BTCPos = Map.find(L);
5528         if (BTCPos != Map.end()) {
5529           BTCPos->second.clear();
5530           Map.erase(BTCPos);
5531         }
5532       };
5533 
5534   RemoveLoopFromBackedgeMap(BackedgeTakenCounts);
5535   RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts);
5536 
5537   // Drop information about expressions based on loop-header PHIs.
5538   SmallVector<Instruction *, 16> Worklist;
5539   PushLoopPHIs(L, Worklist);
5540 
5541   SmallPtrSet<Instruction *, 8> Visited;
5542   while (!Worklist.empty()) {
5543     Instruction *I = Worklist.pop_back_val();
5544     if (!Visited.insert(I).second)
5545       continue;
5546 
5547     ValueExprMapType::iterator It =
5548       ValueExprMap.find_as(static_cast<Value *>(I));
5549     if (It != ValueExprMap.end()) {
5550       eraseValueFromMap(It->first);
5551       forgetMemoizedResults(It->second);
5552       if (PHINode *PN = dyn_cast<PHINode>(I))
5553         ConstantEvolutionLoopExitValue.erase(PN);
5554     }
5555 
5556     PushDefUseChildren(I, Worklist);
5557   }
5558 
5559   // Forget all contained loops too, to avoid dangling entries in the
5560   // ValuesAtScopes map.
5561   for (Loop *I : *L)
5562     forgetLoop(I);
5563 
5564   LoopPropertiesCache.erase(L);
5565 }
5566 
5567 void ScalarEvolution::forgetValue(Value *V) {
5568   Instruction *I = dyn_cast<Instruction>(V);
5569   if (!I) return;
5570 
5571   // Drop information about expressions based on loop-header PHIs.
5572   SmallVector<Instruction *, 16> Worklist;
5573   Worklist.push_back(I);
5574 
5575   SmallPtrSet<Instruction *, 8> Visited;
5576   while (!Worklist.empty()) {
5577     I = Worklist.pop_back_val();
5578     if (!Visited.insert(I).second)
5579       continue;
5580 
5581     ValueExprMapType::iterator It =
5582       ValueExprMap.find_as(static_cast<Value *>(I));
5583     if (It != ValueExprMap.end()) {
5584       eraseValueFromMap(It->first);
5585       forgetMemoizedResults(It->second);
5586       if (PHINode *PN = dyn_cast<PHINode>(I))
5587         ConstantEvolutionLoopExitValue.erase(PN);
5588     }
5589 
5590     PushDefUseChildren(I, Worklist);
5591   }
5592 }
5593 
5594 /// Get the exact loop backedge taken count considering all loop exits. A
5595 /// computable result can only be returned for loops with a single exit.
5596 /// Returning the minimum taken count among all exits is incorrect because one
5597 /// of the loop's exit limit's may have been skipped. howFarToZero assumes that
5598 /// the limit of each loop test is never skipped. This is a valid assumption as
5599 /// long as the loop exits via that test. For precise results, it is the
5600 /// caller's responsibility to specify the relevant loop exit using
5601 /// getExact(ExitingBlock, SE).
5602 const SCEV *
5603 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE,
5604                                              SCEVUnionPredicate *Preds) const {
5605   // If any exits were not computable, the loop is not computable.
5606   if (!isComplete() || ExitNotTaken.empty())
5607     return SE->getCouldNotCompute();
5608 
5609   const SCEV *BECount = nullptr;
5610   for (auto &ENT : ExitNotTaken) {
5611     assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
5612 
5613     if (!BECount)
5614       BECount = ENT.ExactNotTaken;
5615     else if (BECount != ENT.ExactNotTaken)
5616       return SE->getCouldNotCompute();
5617     if (Preds && !ENT.hasAlwaysTruePredicate())
5618       Preds->add(ENT.Predicate.get());
5619 
5620     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
5621            "Predicate should be always true!");
5622   }
5623 
5624   assert(BECount && "Invalid not taken count for loop exit");
5625   return BECount;
5626 }
5627 
5628 /// Get the exact not taken count for this loop exit.
5629 const SCEV *
5630 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
5631                                              ScalarEvolution *SE) const {
5632   for (auto &ENT : ExitNotTaken)
5633     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
5634       return ENT.ExactNotTaken;
5635 
5636   return SE->getCouldNotCompute();
5637 }
5638 
5639 /// getMax - Get the max backedge taken count for the loop.
5640 const SCEV *
5641 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
5642   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
5643     return !ENT.hasAlwaysTruePredicate();
5644   };
5645 
5646   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
5647     return SE->getCouldNotCompute();
5648 
5649   return getMax();
5650 }
5651 
5652 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
5653                                                     ScalarEvolution *SE) const {
5654   if (getMax() && getMax() != SE->getCouldNotCompute() &&
5655       SE->hasOperand(getMax(), S))
5656     return true;
5657 
5658   for (auto &ENT : ExitNotTaken)
5659     if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
5660         SE->hasOperand(ENT.ExactNotTaken, S))
5661       return true;
5662 
5663   return false;
5664 }
5665 
5666 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
5667 /// computable exit into a persistent ExitNotTakenInfo array.
5668 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
5669     SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
5670         &&ExitCounts,
5671     bool Complete, const SCEV *MaxCount)
5672     : MaxAndComplete(MaxCount, Complete) {
5673   typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
5674   ExitNotTaken.reserve(ExitCounts.size());
5675   std::transform(
5676       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
5677       [&](const EdgeExitInfo &EEI) {
5678         BasicBlock *ExitBB = EEI.first;
5679         const ExitLimit &EL = EEI.second;
5680         if (EL.Predicates.empty())
5681           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
5682 
5683         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
5684         for (auto *Pred : EL.Predicates)
5685           Predicate->add(Pred);
5686 
5687         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
5688       });
5689 }
5690 
5691 /// Invalidate this result and free the ExitNotTakenInfo array.
5692 void ScalarEvolution::BackedgeTakenInfo::clear() {
5693   ExitNotTaken.clear();
5694 }
5695 
5696 /// Compute the number of times the backedge of the specified loop will execute.
5697 ScalarEvolution::BackedgeTakenInfo
5698 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
5699                                            bool AllowPredicates) {
5700   SmallVector<BasicBlock *, 8> ExitingBlocks;
5701   L->getExitingBlocks(ExitingBlocks);
5702 
5703   typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
5704 
5705   SmallVector<EdgeExitInfo, 4> ExitCounts;
5706   bool CouldComputeBECount = true;
5707   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
5708   const SCEV *MustExitMaxBECount = nullptr;
5709   const SCEV *MayExitMaxBECount = nullptr;
5710 
5711   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
5712   // and compute maxBECount.
5713   // Do a union of all the predicates here.
5714   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
5715     BasicBlock *ExitBB = ExitingBlocks[i];
5716     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
5717 
5718     assert((AllowPredicates || EL.Predicates.empty()) &&
5719            "Predicated exit limit when predicates are not allowed!");
5720 
5721     // 1. For each exit that can be computed, add an entry to ExitCounts.
5722     // CouldComputeBECount is true only if all exits can be computed.
5723     if (EL.ExactNotTaken == getCouldNotCompute())
5724       // We couldn't compute an exact value for this exit, so
5725       // we won't be able to compute an exact value for the loop.
5726       CouldComputeBECount = false;
5727     else
5728       ExitCounts.emplace_back(ExitBB, EL);
5729 
5730     // 2. Derive the loop's MaxBECount from each exit's max number of
5731     // non-exiting iterations. Partition the loop exits into two kinds:
5732     // LoopMustExits and LoopMayExits.
5733     //
5734     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
5735     // is a LoopMayExit.  If any computable LoopMustExit is found, then
5736     // MaxBECount is the minimum EL.MaxNotTaken of computable
5737     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
5738     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
5739     // computable EL.MaxNotTaken.
5740     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
5741         DT.dominates(ExitBB, Latch)) {
5742       if (!MustExitMaxBECount)
5743         MustExitMaxBECount = EL.MaxNotTaken;
5744       else {
5745         MustExitMaxBECount =
5746             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
5747       }
5748     } else if (MayExitMaxBECount != getCouldNotCompute()) {
5749       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
5750         MayExitMaxBECount = EL.MaxNotTaken;
5751       else {
5752         MayExitMaxBECount =
5753             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
5754       }
5755     }
5756   }
5757   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
5758     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
5759   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
5760                            MaxBECount);
5761 }
5762 
5763 ScalarEvolution::ExitLimit
5764 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
5765                                   bool AllowPredicates) {
5766 
5767   // Okay, we've chosen an exiting block.  See what condition causes us to exit
5768   // at this block and remember the exit block and whether all other targets
5769   // lead to the loop header.
5770   bool MustExecuteLoopHeader = true;
5771   BasicBlock *Exit = nullptr;
5772   for (auto *SBB : successors(ExitingBlock))
5773     if (!L->contains(SBB)) {
5774       if (Exit) // Multiple exit successors.
5775         return getCouldNotCompute();
5776       Exit = SBB;
5777     } else if (SBB != L->getHeader()) {
5778       MustExecuteLoopHeader = false;
5779     }
5780 
5781   // At this point, we know we have a conditional branch that determines whether
5782   // the loop is exited.  However, we don't know if the branch is executed each
5783   // time through the loop.  If not, then the execution count of the branch will
5784   // not be equal to the trip count of the loop.
5785   //
5786   // Currently we check for this by checking to see if the Exit branch goes to
5787   // the loop header.  If so, we know it will always execute the same number of
5788   // times as the loop.  We also handle the case where the exit block *is* the
5789   // loop header.  This is common for un-rotated loops.
5790   //
5791   // If both of those tests fail, walk up the unique predecessor chain to the
5792   // header, stopping if there is an edge that doesn't exit the loop. If the
5793   // header is reached, the execution count of the branch will be equal to the
5794   // trip count of the loop.
5795   //
5796   //  More extensive analysis could be done to handle more cases here.
5797   //
5798   if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
5799     // The simple checks failed, try climbing the unique predecessor chain
5800     // up to the header.
5801     bool Ok = false;
5802     for (BasicBlock *BB = ExitingBlock; BB; ) {
5803       BasicBlock *Pred = BB->getUniquePredecessor();
5804       if (!Pred)
5805         return getCouldNotCompute();
5806       TerminatorInst *PredTerm = Pred->getTerminator();
5807       for (const BasicBlock *PredSucc : PredTerm->successors()) {
5808         if (PredSucc == BB)
5809           continue;
5810         // If the predecessor has a successor that isn't BB and isn't
5811         // outside the loop, assume the worst.
5812         if (L->contains(PredSucc))
5813           return getCouldNotCompute();
5814       }
5815       if (Pred == L->getHeader()) {
5816         Ok = true;
5817         break;
5818       }
5819       BB = Pred;
5820     }
5821     if (!Ok)
5822       return getCouldNotCompute();
5823   }
5824 
5825   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
5826   TerminatorInst *Term = ExitingBlock->getTerminator();
5827   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
5828     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
5829     // Proceed to the next level to examine the exit condition expression.
5830     return computeExitLimitFromCond(
5831         L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1),
5832         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
5833   }
5834 
5835   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
5836     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
5837                                                 /*ControlsExit=*/IsOnlyExit);
5838 
5839   return getCouldNotCompute();
5840 }
5841 
5842 ScalarEvolution::ExitLimit
5843 ScalarEvolution::computeExitLimitFromCond(const Loop *L,
5844                                           Value *ExitCond,
5845                                           BasicBlock *TBB,
5846                                           BasicBlock *FBB,
5847                                           bool ControlsExit,
5848                                           bool AllowPredicates) {
5849   // Check if the controlling expression for this loop is an And or Or.
5850   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
5851     if (BO->getOpcode() == Instruction::And) {
5852       // Recurse on the operands of the and.
5853       bool EitherMayExit = L->contains(TBB);
5854       ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
5855                                                ControlsExit && !EitherMayExit,
5856                                                AllowPredicates);
5857       ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
5858                                                ControlsExit && !EitherMayExit,
5859                                                AllowPredicates);
5860       const SCEV *BECount = getCouldNotCompute();
5861       const SCEV *MaxBECount = getCouldNotCompute();
5862       if (EitherMayExit) {
5863         // Both conditions must be true for the loop to continue executing.
5864         // Choose the less conservative count.
5865         if (EL0.ExactNotTaken == getCouldNotCompute() ||
5866             EL1.ExactNotTaken == getCouldNotCompute())
5867           BECount = getCouldNotCompute();
5868         else
5869           BECount =
5870               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
5871         if (EL0.MaxNotTaken == getCouldNotCompute())
5872           MaxBECount = EL1.MaxNotTaken;
5873         else if (EL1.MaxNotTaken == getCouldNotCompute())
5874           MaxBECount = EL0.MaxNotTaken;
5875         else
5876           MaxBECount =
5877               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
5878       } else {
5879         // Both conditions must be true at the same time for the loop to exit.
5880         // For now, be conservative.
5881         assert(L->contains(FBB) && "Loop block has no successor in loop!");
5882         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
5883           MaxBECount = EL0.MaxNotTaken;
5884         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
5885           BECount = EL0.ExactNotTaken;
5886       }
5887 
5888       // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
5889       // to be more aggressive when computing BECount than when computing
5890       // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
5891       // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
5892       // to not.
5893       if (isa<SCEVCouldNotCompute>(MaxBECount) &&
5894           !isa<SCEVCouldNotCompute>(BECount))
5895         MaxBECount = BECount;
5896 
5897       return ExitLimit(BECount, MaxBECount, {&EL0.Predicates, &EL1.Predicates});
5898     }
5899     if (BO->getOpcode() == Instruction::Or) {
5900       // Recurse on the operands of the or.
5901       bool EitherMayExit = L->contains(FBB);
5902       ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
5903                                                ControlsExit && !EitherMayExit,
5904                                                AllowPredicates);
5905       ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
5906                                                ControlsExit && !EitherMayExit,
5907                                                AllowPredicates);
5908       const SCEV *BECount = getCouldNotCompute();
5909       const SCEV *MaxBECount = getCouldNotCompute();
5910       if (EitherMayExit) {
5911         // Both conditions must be false for the loop to continue executing.
5912         // Choose the less conservative count.
5913         if (EL0.ExactNotTaken == getCouldNotCompute() ||
5914             EL1.ExactNotTaken == getCouldNotCompute())
5915           BECount = getCouldNotCompute();
5916         else
5917           BECount =
5918               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
5919         if (EL0.MaxNotTaken == getCouldNotCompute())
5920           MaxBECount = EL1.MaxNotTaken;
5921         else if (EL1.MaxNotTaken == getCouldNotCompute())
5922           MaxBECount = EL0.MaxNotTaken;
5923         else
5924           MaxBECount =
5925               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
5926       } else {
5927         // Both conditions must be false at the same time for the loop to exit.
5928         // For now, be conservative.
5929         assert(L->contains(TBB) && "Loop block has no successor in loop!");
5930         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
5931           MaxBECount = EL0.MaxNotTaken;
5932         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
5933           BECount = EL0.ExactNotTaken;
5934       }
5935 
5936       return ExitLimit(BECount, MaxBECount, {&EL0.Predicates, &EL1.Predicates});
5937     }
5938   }
5939 
5940   // With an icmp, it may be feasible to compute an exact backedge-taken count.
5941   // Proceed to the next level to examine the icmp.
5942   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
5943     ExitLimit EL =
5944         computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
5945     if (EL.hasFullInfo() || !AllowPredicates)
5946       return EL;
5947 
5948     // Try again, but use SCEV predicates this time.
5949     return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit,
5950                                     /*AllowPredicates=*/true);
5951   }
5952 
5953   // Check for a constant condition. These are normally stripped out by
5954   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
5955   // preserve the CFG and is temporarily leaving constant conditions
5956   // in place.
5957   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
5958     if (L->contains(FBB) == !CI->getZExtValue())
5959       // The backedge is always taken.
5960       return getCouldNotCompute();
5961     else
5962       // The backedge is never taken.
5963       return getZero(CI->getType());
5964   }
5965 
5966   // If it's not an integer or pointer comparison then compute it the hard way.
5967   return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
5968 }
5969 
5970 ScalarEvolution::ExitLimit
5971 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
5972                                           ICmpInst *ExitCond,
5973                                           BasicBlock *TBB,
5974                                           BasicBlock *FBB,
5975                                           bool ControlsExit,
5976                                           bool AllowPredicates) {
5977 
5978   // If the condition was exit on true, convert the condition to exit on false
5979   ICmpInst::Predicate Cond;
5980   if (!L->contains(FBB))
5981     Cond = ExitCond->getPredicate();
5982   else
5983     Cond = ExitCond->getInversePredicate();
5984 
5985   // Handle common loops like: for (X = "string"; *X; ++X)
5986   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
5987     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
5988       ExitLimit ItCnt =
5989         computeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
5990       if (ItCnt.hasAnyInfo())
5991         return ItCnt;
5992     }
5993 
5994   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
5995   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
5996 
5997   // Try to evaluate any dependencies out of the loop.
5998   LHS = getSCEVAtScope(LHS, L);
5999   RHS = getSCEVAtScope(RHS, L);
6000 
6001   // At this point, we would like to compute how many iterations of the
6002   // loop the predicate will return true for these inputs.
6003   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
6004     // If there is a loop-invariant, force it into the RHS.
6005     std::swap(LHS, RHS);
6006     Cond = ICmpInst::getSwappedPredicate(Cond);
6007   }
6008 
6009   // Simplify the operands before analyzing them.
6010   (void)SimplifyICmpOperands(Cond, LHS, RHS);
6011 
6012   // If we have a comparison of a chrec against a constant, try to use value
6013   // ranges to answer this query.
6014   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
6015     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
6016       if (AddRec->getLoop() == L) {
6017         // Form the constant range.
6018         ConstantRange CompRange =
6019             ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt());
6020 
6021         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
6022         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
6023       }
6024 
6025   switch (Cond) {
6026   case ICmpInst::ICMP_NE: {                     // while (X != Y)
6027     // Convert to: while (X-Y != 0)
6028     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
6029                                 AllowPredicates);
6030     if (EL.hasAnyInfo()) return EL;
6031     break;
6032   }
6033   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
6034     // Convert to: while (X-Y == 0)
6035     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
6036     if (EL.hasAnyInfo()) return EL;
6037     break;
6038   }
6039   case ICmpInst::ICMP_SLT:
6040   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
6041     bool IsSigned = Cond == ICmpInst::ICMP_SLT;
6042     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
6043                                     AllowPredicates);
6044     if (EL.hasAnyInfo()) return EL;
6045     break;
6046   }
6047   case ICmpInst::ICMP_SGT:
6048   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
6049     bool IsSigned = Cond == ICmpInst::ICMP_SGT;
6050     ExitLimit EL =
6051         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
6052                             AllowPredicates);
6053     if (EL.hasAnyInfo()) return EL;
6054     break;
6055   }
6056   default:
6057     break;
6058   }
6059 
6060   auto *ExhaustiveCount =
6061       computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
6062 
6063   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
6064     return ExhaustiveCount;
6065 
6066   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
6067                                       ExitCond->getOperand(1), L, Cond);
6068 }
6069 
6070 ScalarEvolution::ExitLimit
6071 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
6072                                                       SwitchInst *Switch,
6073                                                       BasicBlock *ExitingBlock,
6074                                                       bool ControlsExit) {
6075   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
6076 
6077   // Give up if the exit is the default dest of a switch.
6078   if (Switch->getDefaultDest() == ExitingBlock)
6079     return getCouldNotCompute();
6080 
6081   assert(L->contains(Switch->getDefaultDest()) &&
6082          "Default case must not exit the loop!");
6083   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
6084   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
6085 
6086   // while (X != Y) --> while (X-Y != 0)
6087   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
6088   if (EL.hasAnyInfo())
6089     return EL;
6090 
6091   return getCouldNotCompute();
6092 }
6093 
6094 static ConstantInt *
6095 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
6096                                 ScalarEvolution &SE) {
6097   const SCEV *InVal = SE.getConstant(C);
6098   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
6099   assert(isa<SCEVConstant>(Val) &&
6100          "Evaluation of SCEV at constant didn't fold correctly?");
6101   return cast<SCEVConstant>(Val)->getValue();
6102 }
6103 
6104 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
6105 /// compute the backedge execution count.
6106 ScalarEvolution::ExitLimit
6107 ScalarEvolution::computeLoadConstantCompareExitLimit(
6108   LoadInst *LI,
6109   Constant *RHS,
6110   const Loop *L,
6111   ICmpInst::Predicate predicate) {
6112 
6113   if (LI->isVolatile()) return getCouldNotCompute();
6114 
6115   // Check to see if the loaded pointer is a getelementptr of a global.
6116   // TODO: Use SCEV instead of manually grubbing with GEPs.
6117   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
6118   if (!GEP) return getCouldNotCompute();
6119 
6120   // Make sure that it is really a constant global we are gepping, with an
6121   // initializer, and make sure the first IDX is really 0.
6122   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
6123   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
6124       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
6125       !cast<Constant>(GEP->getOperand(1))->isNullValue())
6126     return getCouldNotCompute();
6127 
6128   // Okay, we allow one non-constant index into the GEP instruction.
6129   Value *VarIdx = nullptr;
6130   std::vector<Constant*> Indexes;
6131   unsigned VarIdxNum = 0;
6132   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
6133     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
6134       Indexes.push_back(CI);
6135     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
6136       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
6137       VarIdx = GEP->getOperand(i);
6138       VarIdxNum = i-2;
6139       Indexes.push_back(nullptr);
6140     }
6141 
6142   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
6143   if (!VarIdx)
6144     return getCouldNotCompute();
6145 
6146   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
6147   // Check to see if X is a loop variant variable value now.
6148   const SCEV *Idx = getSCEV(VarIdx);
6149   Idx = getSCEVAtScope(Idx, L);
6150 
6151   // We can only recognize very limited forms of loop index expressions, in
6152   // particular, only affine AddRec's like {C1,+,C2}.
6153   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
6154   if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
6155       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
6156       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
6157     return getCouldNotCompute();
6158 
6159   unsigned MaxSteps = MaxBruteForceIterations;
6160   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
6161     ConstantInt *ItCst = ConstantInt::get(
6162                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
6163     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
6164 
6165     // Form the GEP offset.
6166     Indexes[VarIdxNum] = Val;
6167 
6168     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
6169                                                          Indexes);
6170     if (!Result) break;  // Cannot compute!
6171 
6172     // Evaluate the condition for this iteration.
6173     Result = ConstantExpr::getICmp(predicate, Result, RHS);
6174     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
6175     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
6176       ++NumArrayLenItCounts;
6177       return getConstant(ItCst);   // Found terminating iteration!
6178     }
6179   }
6180   return getCouldNotCompute();
6181 }
6182 
6183 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
6184     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
6185   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
6186   if (!RHS)
6187     return getCouldNotCompute();
6188 
6189   const BasicBlock *Latch = L->getLoopLatch();
6190   if (!Latch)
6191     return getCouldNotCompute();
6192 
6193   const BasicBlock *Predecessor = L->getLoopPredecessor();
6194   if (!Predecessor)
6195     return getCouldNotCompute();
6196 
6197   // Return true if V is of the form "LHS `shift_op` <positive constant>".
6198   // Return LHS in OutLHS and shift_opt in OutOpCode.
6199   auto MatchPositiveShift =
6200       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
6201 
6202     using namespace PatternMatch;
6203 
6204     ConstantInt *ShiftAmt;
6205     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6206       OutOpCode = Instruction::LShr;
6207     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6208       OutOpCode = Instruction::AShr;
6209     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6210       OutOpCode = Instruction::Shl;
6211     else
6212       return false;
6213 
6214     return ShiftAmt->getValue().isStrictlyPositive();
6215   };
6216 
6217   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
6218   //
6219   // loop:
6220   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
6221   //   %iv.shifted = lshr i32 %iv, <positive constant>
6222   //
6223   // Return true on a succesful match.  Return the corresponding PHI node (%iv
6224   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
6225   auto MatchShiftRecurrence =
6226       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
6227     Optional<Instruction::BinaryOps> PostShiftOpCode;
6228 
6229     {
6230       Instruction::BinaryOps OpC;
6231       Value *V;
6232 
6233       // If we encounter a shift instruction, "peel off" the shift operation,
6234       // and remember that we did so.  Later when we inspect %iv's backedge
6235       // value, we will make sure that the backedge value uses the same
6236       // operation.
6237       //
6238       // Note: the peeled shift operation does not have to be the same
6239       // instruction as the one feeding into the PHI's backedge value.  We only
6240       // really care about it being the same *kind* of shift instruction --
6241       // that's all that is required for our later inferences to hold.
6242       if (MatchPositiveShift(LHS, V, OpC)) {
6243         PostShiftOpCode = OpC;
6244         LHS = V;
6245       }
6246     }
6247 
6248     PNOut = dyn_cast<PHINode>(LHS);
6249     if (!PNOut || PNOut->getParent() != L->getHeader())
6250       return false;
6251 
6252     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
6253     Value *OpLHS;
6254 
6255     return
6256         // The backedge value for the PHI node must be a shift by a positive
6257         // amount
6258         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
6259 
6260         // of the PHI node itself
6261         OpLHS == PNOut &&
6262 
6263         // and the kind of shift should be match the kind of shift we peeled
6264         // off, if any.
6265         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
6266   };
6267 
6268   PHINode *PN;
6269   Instruction::BinaryOps OpCode;
6270   if (!MatchShiftRecurrence(LHS, PN, OpCode))
6271     return getCouldNotCompute();
6272 
6273   const DataLayout &DL = getDataLayout();
6274 
6275   // The key rationale for this optimization is that for some kinds of shift
6276   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
6277   // within a finite number of iterations.  If the condition guarding the
6278   // backedge (in the sense that the backedge is taken if the condition is true)
6279   // is false for the value the shift recurrence stabilizes to, then we know
6280   // that the backedge is taken only a finite number of times.
6281 
6282   ConstantInt *StableValue = nullptr;
6283   switch (OpCode) {
6284   default:
6285     llvm_unreachable("Impossible case!");
6286 
6287   case Instruction::AShr: {
6288     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
6289     // bitwidth(K) iterations.
6290     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
6291     bool KnownZero, KnownOne;
6292     ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr,
6293                    Predecessor->getTerminator(), &DT);
6294     auto *Ty = cast<IntegerType>(RHS->getType());
6295     if (KnownZero)
6296       StableValue = ConstantInt::get(Ty, 0);
6297     else if (KnownOne)
6298       StableValue = ConstantInt::get(Ty, -1, true);
6299     else
6300       return getCouldNotCompute();
6301 
6302     break;
6303   }
6304   case Instruction::LShr:
6305   case Instruction::Shl:
6306     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
6307     // stabilize to 0 in at most bitwidth(K) iterations.
6308     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
6309     break;
6310   }
6311 
6312   auto *Result =
6313       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
6314   assert(Result->getType()->isIntegerTy(1) &&
6315          "Otherwise cannot be an operand to a branch instruction");
6316 
6317   if (Result->isZeroValue()) {
6318     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
6319     const SCEV *UpperBound =
6320         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
6321     return ExitLimit(getCouldNotCompute(), UpperBound);
6322   }
6323 
6324   return getCouldNotCompute();
6325 }
6326 
6327 /// Return true if we can constant fold an instruction of the specified type,
6328 /// assuming that all operands were constants.
6329 static bool CanConstantFold(const Instruction *I) {
6330   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
6331       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
6332       isa<LoadInst>(I))
6333     return true;
6334 
6335   if (const CallInst *CI = dyn_cast<CallInst>(I))
6336     if (const Function *F = CI->getCalledFunction())
6337       return canConstantFoldCallTo(F);
6338   return false;
6339 }
6340 
6341 /// Determine whether this instruction can constant evolve within this loop
6342 /// assuming its operands can all constant evolve.
6343 static bool canConstantEvolve(Instruction *I, const Loop *L) {
6344   // An instruction outside of the loop can't be derived from a loop PHI.
6345   if (!L->contains(I)) return false;
6346 
6347   if (isa<PHINode>(I)) {
6348     // We don't currently keep track of the control flow needed to evaluate
6349     // PHIs, so we cannot handle PHIs inside of loops.
6350     return L->getHeader() == I->getParent();
6351   }
6352 
6353   // If we won't be able to constant fold this expression even if the operands
6354   // are constants, bail early.
6355   return CanConstantFold(I);
6356 }
6357 
6358 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
6359 /// recursing through each instruction operand until reaching a loop header phi.
6360 static PHINode *
6361 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
6362                                DenseMap<Instruction *, PHINode *> &PHIMap) {
6363 
6364   // Otherwise, we can evaluate this instruction if all of its operands are
6365   // constant or derived from a PHI node themselves.
6366   PHINode *PHI = nullptr;
6367   for (Value *Op : UseInst->operands()) {
6368     if (isa<Constant>(Op)) continue;
6369 
6370     Instruction *OpInst = dyn_cast<Instruction>(Op);
6371     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
6372 
6373     PHINode *P = dyn_cast<PHINode>(OpInst);
6374     if (!P)
6375       // If this operand is already visited, reuse the prior result.
6376       // We may have P != PHI if this is the deepest point at which the
6377       // inconsistent paths meet.
6378       P = PHIMap.lookup(OpInst);
6379     if (!P) {
6380       // Recurse and memoize the results, whether a phi is found or not.
6381       // This recursive call invalidates pointers into PHIMap.
6382       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap);
6383       PHIMap[OpInst] = P;
6384     }
6385     if (!P)
6386       return nullptr;  // Not evolving from PHI
6387     if (PHI && PHI != P)
6388       return nullptr;  // Evolving from multiple different PHIs.
6389     PHI = P;
6390   }
6391   // This is a expression evolving from a constant PHI!
6392   return PHI;
6393 }
6394 
6395 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
6396 /// in the loop that V is derived from.  We allow arbitrary operations along the
6397 /// way, but the operands of an operation must either be constants or a value
6398 /// derived from a constant PHI.  If this expression does not fit with these
6399 /// constraints, return null.
6400 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
6401   Instruction *I = dyn_cast<Instruction>(V);
6402   if (!I || !canConstantEvolve(I, L)) return nullptr;
6403 
6404   if (PHINode *PN = dyn_cast<PHINode>(I))
6405     return PN;
6406 
6407   // Record non-constant instructions contained by the loop.
6408   DenseMap<Instruction *, PHINode *> PHIMap;
6409   return getConstantEvolvingPHIOperands(I, L, PHIMap);
6410 }
6411 
6412 /// EvaluateExpression - Given an expression that passes the
6413 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
6414 /// in the loop has the value PHIVal.  If we can't fold this expression for some
6415 /// reason, return null.
6416 static Constant *EvaluateExpression(Value *V, const Loop *L,
6417                                     DenseMap<Instruction *, Constant *> &Vals,
6418                                     const DataLayout &DL,
6419                                     const TargetLibraryInfo *TLI) {
6420   // Convenient constant check, but redundant for recursive calls.
6421   if (Constant *C = dyn_cast<Constant>(V)) return C;
6422   Instruction *I = dyn_cast<Instruction>(V);
6423   if (!I) return nullptr;
6424 
6425   if (Constant *C = Vals.lookup(I)) return C;
6426 
6427   // An instruction inside the loop depends on a value outside the loop that we
6428   // weren't given a mapping for, or a value such as a call inside the loop.
6429   if (!canConstantEvolve(I, L)) return nullptr;
6430 
6431   // An unmapped PHI can be due to a branch or another loop inside this loop,
6432   // or due to this not being the initial iteration through a loop where we
6433   // couldn't compute the evolution of this particular PHI last time.
6434   if (isa<PHINode>(I)) return nullptr;
6435 
6436   std::vector<Constant*> Operands(I->getNumOperands());
6437 
6438   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
6439     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
6440     if (!Operand) {
6441       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
6442       if (!Operands[i]) return nullptr;
6443       continue;
6444     }
6445     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
6446     Vals[Operand] = C;
6447     if (!C) return nullptr;
6448     Operands[i] = C;
6449   }
6450 
6451   if (CmpInst *CI = dyn_cast<CmpInst>(I))
6452     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
6453                                            Operands[1], DL, TLI);
6454   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6455     if (!LI->isVolatile())
6456       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
6457   }
6458   return ConstantFoldInstOperands(I, Operands, DL, TLI);
6459 }
6460 
6461 
6462 // If every incoming value to PN except the one for BB is a specific Constant,
6463 // return that, else return nullptr.
6464 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
6465   Constant *IncomingVal = nullptr;
6466 
6467   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6468     if (PN->getIncomingBlock(i) == BB)
6469       continue;
6470 
6471     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
6472     if (!CurrentVal)
6473       return nullptr;
6474 
6475     if (IncomingVal != CurrentVal) {
6476       if (IncomingVal)
6477         return nullptr;
6478       IncomingVal = CurrentVal;
6479     }
6480   }
6481 
6482   return IncomingVal;
6483 }
6484 
6485 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
6486 /// in the header of its containing loop, we know the loop executes a
6487 /// constant number of times, and the PHI node is just a recurrence
6488 /// involving constants, fold it.
6489 Constant *
6490 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
6491                                                    const APInt &BEs,
6492                                                    const Loop *L) {
6493   auto I = ConstantEvolutionLoopExitValue.find(PN);
6494   if (I != ConstantEvolutionLoopExitValue.end())
6495     return I->second;
6496 
6497   if (BEs.ugt(MaxBruteForceIterations))
6498     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
6499 
6500   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
6501 
6502   DenseMap<Instruction *, Constant *> CurrentIterVals;
6503   BasicBlock *Header = L->getHeader();
6504   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6505 
6506   BasicBlock *Latch = L->getLoopLatch();
6507   if (!Latch)
6508     return nullptr;
6509 
6510   for (auto &I : *Header) {
6511     PHINode *PHI = dyn_cast<PHINode>(&I);
6512     if (!PHI) break;
6513     auto *StartCST = getOtherIncomingValue(PHI, Latch);
6514     if (!StartCST) continue;
6515     CurrentIterVals[PHI] = StartCST;
6516   }
6517   if (!CurrentIterVals.count(PN))
6518     return RetVal = nullptr;
6519 
6520   Value *BEValue = PN->getIncomingValueForBlock(Latch);
6521 
6522   // Execute the loop symbolically to determine the exit value.
6523   if (BEs.getActiveBits() >= 32)
6524     return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
6525 
6526   unsigned NumIterations = BEs.getZExtValue(); // must be in range
6527   unsigned IterationNum = 0;
6528   const DataLayout &DL = getDataLayout();
6529   for (; ; ++IterationNum) {
6530     if (IterationNum == NumIterations)
6531       return RetVal = CurrentIterVals[PN];  // Got exit value!
6532 
6533     // Compute the value of the PHIs for the next iteration.
6534     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
6535     DenseMap<Instruction *, Constant *> NextIterVals;
6536     Constant *NextPHI =
6537         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6538     if (!NextPHI)
6539       return nullptr;        // Couldn't evaluate!
6540     NextIterVals[PN] = NextPHI;
6541 
6542     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
6543 
6544     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
6545     // cease to be able to evaluate one of them or if they stop evolving,
6546     // because that doesn't necessarily prevent us from computing PN.
6547     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
6548     for (const auto &I : CurrentIterVals) {
6549       PHINode *PHI = dyn_cast<PHINode>(I.first);
6550       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
6551       PHIsToCompute.emplace_back(PHI, I.second);
6552     }
6553     // We use two distinct loops because EvaluateExpression may invalidate any
6554     // iterators into CurrentIterVals.
6555     for (const auto &I : PHIsToCompute) {
6556       PHINode *PHI = I.first;
6557       Constant *&NextPHI = NextIterVals[PHI];
6558       if (!NextPHI) {   // Not already computed.
6559         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
6560         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6561       }
6562       if (NextPHI != I.second)
6563         StoppedEvolving = false;
6564     }
6565 
6566     // If all entries in CurrentIterVals == NextIterVals then we can stop
6567     // iterating, the loop can't continue to change.
6568     if (StoppedEvolving)
6569       return RetVal = CurrentIterVals[PN];
6570 
6571     CurrentIterVals.swap(NextIterVals);
6572   }
6573 }
6574 
6575 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
6576                                                           Value *Cond,
6577                                                           bool ExitWhen) {
6578   PHINode *PN = getConstantEvolvingPHI(Cond, L);
6579   if (!PN) return getCouldNotCompute();
6580 
6581   // If the loop is canonicalized, the PHI will have exactly two entries.
6582   // That's the only form we support here.
6583   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
6584 
6585   DenseMap<Instruction *, Constant *> CurrentIterVals;
6586   BasicBlock *Header = L->getHeader();
6587   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6588 
6589   BasicBlock *Latch = L->getLoopLatch();
6590   assert(Latch && "Should follow from NumIncomingValues == 2!");
6591 
6592   for (auto &I : *Header) {
6593     PHINode *PHI = dyn_cast<PHINode>(&I);
6594     if (!PHI)
6595       break;
6596     auto *StartCST = getOtherIncomingValue(PHI, Latch);
6597     if (!StartCST) continue;
6598     CurrentIterVals[PHI] = StartCST;
6599   }
6600   if (!CurrentIterVals.count(PN))
6601     return getCouldNotCompute();
6602 
6603   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
6604   // the loop symbolically to determine when the condition gets a value of
6605   // "ExitWhen".
6606   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
6607   const DataLayout &DL = getDataLayout();
6608   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
6609     auto *CondVal = dyn_cast_or_null<ConstantInt>(
6610         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
6611 
6612     // Couldn't symbolically evaluate.
6613     if (!CondVal) return getCouldNotCompute();
6614 
6615     if (CondVal->getValue() == uint64_t(ExitWhen)) {
6616       ++NumBruteForceTripCountsComputed;
6617       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
6618     }
6619 
6620     // Update all the PHI nodes for the next iteration.
6621     DenseMap<Instruction *, Constant *> NextIterVals;
6622 
6623     // Create a list of which PHIs we need to compute. We want to do this before
6624     // calling EvaluateExpression on them because that may invalidate iterators
6625     // into CurrentIterVals.
6626     SmallVector<PHINode *, 8> PHIsToCompute;
6627     for (const auto &I : CurrentIterVals) {
6628       PHINode *PHI = dyn_cast<PHINode>(I.first);
6629       if (!PHI || PHI->getParent() != Header) continue;
6630       PHIsToCompute.push_back(PHI);
6631     }
6632     for (PHINode *PHI : PHIsToCompute) {
6633       Constant *&NextPHI = NextIterVals[PHI];
6634       if (NextPHI) continue;    // Already computed!
6635 
6636       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
6637       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6638     }
6639     CurrentIterVals.swap(NextIterVals);
6640   }
6641 
6642   // Too many iterations were needed to evaluate.
6643   return getCouldNotCompute();
6644 }
6645 
6646 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
6647   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
6648       ValuesAtScopes[V];
6649   // Check to see if we've folded this expression at this loop before.
6650   for (auto &LS : Values)
6651     if (LS.first == L)
6652       return LS.second ? LS.second : V;
6653 
6654   Values.emplace_back(L, nullptr);
6655 
6656   // Otherwise compute it.
6657   const SCEV *C = computeSCEVAtScope(V, L);
6658   for (auto &LS : reverse(ValuesAtScopes[V]))
6659     if (LS.first == L) {
6660       LS.second = C;
6661       break;
6662     }
6663   return C;
6664 }
6665 
6666 /// This builds up a Constant using the ConstantExpr interface.  That way, we
6667 /// will return Constants for objects which aren't represented by a
6668 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
6669 /// Returns NULL if the SCEV isn't representable as a Constant.
6670 static Constant *BuildConstantFromSCEV(const SCEV *V) {
6671   switch (static_cast<SCEVTypes>(V->getSCEVType())) {
6672     case scCouldNotCompute:
6673     case scAddRecExpr:
6674       break;
6675     case scConstant:
6676       return cast<SCEVConstant>(V)->getValue();
6677     case scUnknown:
6678       return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
6679     case scSignExtend: {
6680       const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
6681       if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
6682         return ConstantExpr::getSExt(CastOp, SS->getType());
6683       break;
6684     }
6685     case scZeroExtend: {
6686       const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
6687       if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
6688         return ConstantExpr::getZExt(CastOp, SZ->getType());
6689       break;
6690     }
6691     case scTruncate: {
6692       const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
6693       if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
6694         return ConstantExpr::getTrunc(CastOp, ST->getType());
6695       break;
6696     }
6697     case scAddExpr: {
6698       const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
6699       if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
6700         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6701           unsigned AS = PTy->getAddressSpace();
6702           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
6703           C = ConstantExpr::getBitCast(C, DestPtrTy);
6704         }
6705         for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
6706           Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
6707           if (!C2) return nullptr;
6708 
6709           // First pointer!
6710           if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
6711             unsigned AS = C2->getType()->getPointerAddressSpace();
6712             std::swap(C, C2);
6713             Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
6714             // The offsets have been converted to bytes.  We can add bytes to an
6715             // i8* by GEP with the byte count in the first index.
6716             C = ConstantExpr::getBitCast(C, DestPtrTy);
6717           }
6718 
6719           // Don't bother trying to sum two pointers. We probably can't
6720           // statically compute a load that results from it anyway.
6721           if (C2->getType()->isPointerTy())
6722             return nullptr;
6723 
6724           if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6725             if (PTy->getElementType()->isStructTy())
6726               C2 = ConstantExpr::getIntegerCast(
6727                   C2, Type::getInt32Ty(C->getContext()), true);
6728             C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
6729           } else
6730             C = ConstantExpr::getAdd(C, C2);
6731         }
6732         return C;
6733       }
6734       break;
6735     }
6736     case scMulExpr: {
6737       const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
6738       if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
6739         // Don't bother with pointers at all.
6740         if (C->getType()->isPointerTy()) return nullptr;
6741         for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
6742           Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
6743           if (!C2 || C2->getType()->isPointerTy()) return nullptr;
6744           C = ConstantExpr::getMul(C, C2);
6745         }
6746         return C;
6747       }
6748       break;
6749     }
6750     case scUDivExpr: {
6751       const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
6752       if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
6753         if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
6754           if (LHS->getType() == RHS->getType())
6755             return ConstantExpr::getUDiv(LHS, RHS);
6756       break;
6757     }
6758     case scSMaxExpr:
6759     case scUMaxExpr:
6760       break; // TODO: smax, umax.
6761   }
6762   return nullptr;
6763 }
6764 
6765 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
6766   if (isa<SCEVConstant>(V)) return V;
6767 
6768   // If this instruction is evolved from a constant-evolving PHI, compute the
6769   // exit value from the loop without using SCEVs.
6770   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
6771     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
6772       const Loop *LI = this->LI[I->getParent()];
6773       if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
6774         if (PHINode *PN = dyn_cast<PHINode>(I))
6775           if (PN->getParent() == LI->getHeader()) {
6776             // Okay, there is no closed form solution for the PHI node.  Check
6777             // to see if the loop that contains it has a known backedge-taken
6778             // count.  If so, we may be able to force computation of the exit
6779             // value.
6780             const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
6781             if (const SCEVConstant *BTCC =
6782                   dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
6783               // Okay, we know how many times the containing loop executes.  If
6784               // this is a constant evolving PHI node, get the final value at
6785               // the specified iteration number.
6786               Constant *RV =
6787                   getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
6788               if (RV) return getSCEV(RV);
6789             }
6790           }
6791 
6792       // Okay, this is an expression that we cannot symbolically evaluate
6793       // into a SCEV.  Check to see if it's possible to symbolically evaluate
6794       // the arguments into constants, and if so, try to constant propagate the
6795       // result.  This is particularly useful for computing loop exit values.
6796       if (CanConstantFold(I)) {
6797         SmallVector<Constant *, 4> Operands;
6798         bool MadeImprovement = false;
6799         for (Value *Op : I->operands()) {
6800           if (Constant *C = dyn_cast<Constant>(Op)) {
6801             Operands.push_back(C);
6802             continue;
6803           }
6804 
6805           // If any of the operands is non-constant and if they are
6806           // non-integer and non-pointer, don't even try to analyze them
6807           // with scev techniques.
6808           if (!isSCEVable(Op->getType()))
6809             return V;
6810 
6811           const SCEV *OrigV = getSCEV(Op);
6812           const SCEV *OpV = getSCEVAtScope(OrigV, L);
6813           MadeImprovement |= OrigV != OpV;
6814 
6815           Constant *C = BuildConstantFromSCEV(OpV);
6816           if (!C) return V;
6817           if (C->getType() != Op->getType())
6818             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
6819                                                               Op->getType(),
6820                                                               false),
6821                                       C, Op->getType());
6822           Operands.push_back(C);
6823         }
6824 
6825         // Check to see if getSCEVAtScope actually made an improvement.
6826         if (MadeImprovement) {
6827           Constant *C = nullptr;
6828           const DataLayout &DL = getDataLayout();
6829           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
6830             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
6831                                                 Operands[1], DL, &TLI);
6832           else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
6833             if (!LI->isVolatile())
6834               C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
6835           } else
6836             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
6837           if (!C) return V;
6838           return getSCEV(C);
6839         }
6840       }
6841     }
6842 
6843     // This is some other type of SCEVUnknown, just return it.
6844     return V;
6845   }
6846 
6847   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
6848     // Avoid performing the look-up in the common case where the specified
6849     // expression has no loop-variant portions.
6850     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
6851       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
6852       if (OpAtScope != Comm->getOperand(i)) {
6853         // Okay, at least one of these operands is loop variant but might be
6854         // foldable.  Build a new instance of the folded commutative expression.
6855         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
6856                                             Comm->op_begin()+i);
6857         NewOps.push_back(OpAtScope);
6858 
6859         for (++i; i != e; ++i) {
6860           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
6861           NewOps.push_back(OpAtScope);
6862         }
6863         if (isa<SCEVAddExpr>(Comm))
6864           return getAddExpr(NewOps);
6865         if (isa<SCEVMulExpr>(Comm))
6866           return getMulExpr(NewOps);
6867         if (isa<SCEVSMaxExpr>(Comm))
6868           return getSMaxExpr(NewOps);
6869         if (isa<SCEVUMaxExpr>(Comm))
6870           return getUMaxExpr(NewOps);
6871         llvm_unreachable("Unknown commutative SCEV type!");
6872       }
6873     }
6874     // If we got here, all operands are loop invariant.
6875     return Comm;
6876   }
6877 
6878   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
6879     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
6880     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
6881     if (LHS == Div->getLHS() && RHS == Div->getRHS())
6882       return Div;   // must be loop invariant
6883     return getUDivExpr(LHS, RHS);
6884   }
6885 
6886   // If this is a loop recurrence for a loop that does not contain L, then we
6887   // are dealing with the final value computed by the loop.
6888   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
6889     // First, attempt to evaluate each operand.
6890     // Avoid performing the look-up in the common case where the specified
6891     // expression has no loop-variant portions.
6892     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
6893       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
6894       if (OpAtScope == AddRec->getOperand(i))
6895         continue;
6896 
6897       // Okay, at least one of these operands is loop variant but might be
6898       // foldable.  Build a new instance of the folded commutative expression.
6899       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
6900                                           AddRec->op_begin()+i);
6901       NewOps.push_back(OpAtScope);
6902       for (++i; i != e; ++i)
6903         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
6904 
6905       const SCEV *FoldedRec =
6906         getAddRecExpr(NewOps, AddRec->getLoop(),
6907                       AddRec->getNoWrapFlags(SCEV::FlagNW));
6908       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
6909       // The addrec may be folded to a nonrecurrence, for example, if the
6910       // induction variable is multiplied by zero after constant folding. Go
6911       // ahead and return the folded value.
6912       if (!AddRec)
6913         return FoldedRec;
6914       break;
6915     }
6916 
6917     // If the scope is outside the addrec's loop, evaluate it by using the
6918     // loop exit value of the addrec.
6919     if (!AddRec->getLoop()->contains(L)) {
6920       // To evaluate this recurrence, we need to know how many times the AddRec
6921       // loop iterates.  Compute this now.
6922       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
6923       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
6924 
6925       // Then, evaluate the AddRec.
6926       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
6927     }
6928 
6929     return AddRec;
6930   }
6931 
6932   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
6933     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
6934     if (Op == Cast->getOperand())
6935       return Cast;  // must be loop invariant
6936     return getZeroExtendExpr(Op, Cast->getType());
6937   }
6938 
6939   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
6940     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
6941     if (Op == Cast->getOperand())
6942       return Cast;  // must be loop invariant
6943     return getSignExtendExpr(Op, Cast->getType());
6944   }
6945 
6946   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
6947     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
6948     if (Op == Cast->getOperand())
6949       return Cast;  // must be loop invariant
6950     return getTruncateExpr(Op, Cast->getType());
6951   }
6952 
6953   llvm_unreachable("Unknown SCEV type!");
6954 }
6955 
6956 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
6957   return getSCEVAtScope(getSCEV(V), L);
6958 }
6959 
6960 /// Finds the minimum unsigned root of the following equation:
6961 ///
6962 ///     A * X = B (mod N)
6963 ///
6964 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
6965 /// A and B isn't important.
6966 ///
6967 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
6968 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
6969                                                ScalarEvolution &SE) {
6970   uint32_t BW = A.getBitWidth();
6971   assert(BW == B.getBitWidth() && "Bit widths must be the same.");
6972   assert(A != 0 && "A must be non-zero.");
6973 
6974   // 1. D = gcd(A, N)
6975   //
6976   // The gcd of A and N may have only one prime factor: 2. The number of
6977   // trailing zeros in A is its multiplicity
6978   uint32_t Mult2 = A.countTrailingZeros();
6979   // D = 2^Mult2
6980 
6981   // 2. Check if B is divisible by D.
6982   //
6983   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
6984   // is not less than multiplicity of this prime factor for D.
6985   if (B.countTrailingZeros() < Mult2)
6986     return SE.getCouldNotCompute();
6987 
6988   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
6989   // modulo (N / D).
6990   //
6991   // (N / D) may need BW+1 bits in its representation.  Hence, we'll use this
6992   // bit width during computations.
6993   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
6994   APInt Mod(BW + 1, 0);
6995   Mod.setBit(BW - Mult2);  // Mod = N / D
6996   APInt I = AD.multiplicativeInverse(Mod);
6997 
6998   // 4. Compute the minimum unsigned root of the equation:
6999   // I * (B / D) mod (N / D)
7000   APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
7001 
7002   // The result is guaranteed to be less than 2^BW so we may truncate it to BW
7003   // bits.
7004   return SE.getConstant(Result.trunc(BW));
7005 }
7006 
7007 /// Find the roots of the quadratic equation for the given quadratic chrec
7008 /// {L,+,M,+,N}.  This returns either the two roots (which might be the same) or
7009 /// two SCEVCouldNotCompute objects.
7010 ///
7011 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
7012 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
7013   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
7014   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
7015   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
7016   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
7017 
7018   // We currently can only solve this if the coefficients are constants.
7019   if (!LC || !MC || !NC)
7020     return None;
7021 
7022   uint32_t BitWidth = LC->getAPInt().getBitWidth();
7023   const APInt &L = LC->getAPInt();
7024   const APInt &M = MC->getAPInt();
7025   const APInt &N = NC->getAPInt();
7026   APInt Two(BitWidth, 2);
7027   APInt Four(BitWidth, 4);
7028 
7029   {
7030     using namespace APIntOps;
7031     const APInt& C = L;
7032     // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
7033     // The B coefficient is M-N/2
7034     APInt B(M);
7035     B -= sdiv(N,Two);
7036 
7037     // The A coefficient is N/2
7038     APInt A(N.sdiv(Two));
7039 
7040     // Compute the B^2-4ac term.
7041     APInt SqrtTerm(B);
7042     SqrtTerm *= B;
7043     SqrtTerm -= Four * (A * C);
7044 
7045     if (SqrtTerm.isNegative()) {
7046       // The loop is provably infinite.
7047       return None;
7048     }
7049 
7050     // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
7051     // integer value or else APInt::sqrt() will assert.
7052     APInt SqrtVal(SqrtTerm.sqrt());
7053 
7054     // Compute the two solutions for the quadratic formula.
7055     // The divisions must be performed as signed divisions.
7056     APInt NegB(-B);
7057     APInt TwoA(A << 1);
7058     if (TwoA.isMinValue())
7059       return None;
7060 
7061     LLVMContext &Context = SE.getContext();
7062 
7063     ConstantInt *Solution1 =
7064       ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
7065     ConstantInt *Solution2 =
7066       ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
7067 
7068     return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
7069                           cast<SCEVConstant>(SE.getConstant(Solution2)));
7070   } // end APIntOps namespace
7071 }
7072 
7073 ScalarEvolution::ExitLimit
7074 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
7075                               bool AllowPredicates) {
7076 
7077   // This is only used for loops with a "x != y" exit test. The exit condition
7078   // is now expressed as a single expression, V = x-y. So the exit test is
7079   // effectively V != 0.  We know and take advantage of the fact that this
7080   // expression only being used in a comparison by zero context.
7081 
7082   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
7083   // If the value is a constant
7084   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
7085     // If the value is already zero, the branch will execute zero times.
7086     if (C->getValue()->isZero()) return C;
7087     return getCouldNotCompute();  // Otherwise it will loop infinitely.
7088   }
7089 
7090   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
7091   if (!AddRec && AllowPredicates)
7092     // Try to make this an AddRec using runtime tests, in the first X
7093     // iterations of this loop, where X is the SCEV expression found by the
7094     // algorithm below.
7095     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
7096 
7097   if (!AddRec || AddRec->getLoop() != L)
7098     return getCouldNotCompute();
7099 
7100   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
7101   // the quadratic equation to solve it.
7102   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
7103     if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
7104       const SCEVConstant *R1 = Roots->first;
7105       const SCEVConstant *R2 = Roots->second;
7106       // Pick the smallest positive root value.
7107       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
7108               CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
7109         if (!CB->getZExtValue())
7110           std::swap(R1, R2); // R1 is the minimum root now.
7111 
7112         // We can only use this value if the chrec ends up with an exact zero
7113         // value at this index.  When solving for "X*X != 5", for example, we
7114         // should not accept a root of 2.
7115         const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
7116         if (Val->isZero())
7117           return ExitLimit(R1, R1, Predicates); // We found a quadratic root!
7118       }
7119     }
7120     return getCouldNotCompute();
7121   }
7122 
7123   // Otherwise we can only handle this if it is affine.
7124   if (!AddRec->isAffine())
7125     return getCouldNotCompute();
7126 
7127   // If this is an affine expression, the execution count of this branch is
7128   // the minimum unsigned root of the following equation:
7129   //
7130   //     Start + Step*N = 0 (mod 2^BW)
7131   //
7132   // equivalent to:
7133   //
7134   //             Step*N = -Start (mod 2^BW)
7135   //
7136   // where BW is the common bit width of Start and Step.
7137 
7138   // Get the initial value for the loop.
7139   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
7140   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
7141 
7142   // For now we handle only constant steps.
7143   //
7144   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
7145   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
7146   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
7147   // We have not yet seen any such cases.
7148   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
7149   if (!StepC || StepC->getValue()->equalsInt(0))
7150     return getCouldNotCompute();
7151 
7152   // For positive steps (counting up until unsigned overflow):
7153   //   N = -Start/Step (as unsigned)
7154   // For negative steps (counting down to zero):
7155   //   N = Start/-Step
7156   // First compute the unsigned distance from zero in the direction of Step.
7157   bool CountDown = StepC->getAPInt().isNegative();
7158   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
7159 
7160   // Handle unitary steps, which cannot wraparound.
7161   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
7162   //   N = Distance (as unsigned)
7163   if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
7164     ConstantRange CR = getUnsignedRange(Start);
7165     const SCEV *MaxBECount;
7166     if (!CountDown && CR.getUnsignedMin().isMinValue())
7167       // When counting up, the worst starting value is 1, not 0.
7168       MaxBECount = CR.getUnsignedMax().isMinValue()
7169         ? getConstant(APInt::getMinValue(CR.getBitWidth()))
7170         : getConstant(APInt::getMaxValue(CR.getBitWidth()));
7171     else
7172       MaxBECount = getConstant(CountDown ? CR.getUnsignedMax()
7173                                          : -CR.getUnsignedMin());
7174     return ExitLimit(Distance, MaxBECount, Predicates);
7175   }
7176 
7177   // As a special case, handle the instance where Step is a positive power of
7178   // two. In this case, determining whether Step divides Distance evenly can be
7179   // done by counting and comparing the number of trailing zeros of Step and
7180   // Distance.
7181   if (!CountDown) {
7182     const APInt &StepV = StepC->getAPInt();
7183     // StepV.isPowerOf2() returns true if StepV is an positive power of two.  It
7184     // also returns true if StepV is maximally negative (eg, INT_MIN), but that
7185     // case is not handled as this code is guarded by !CountDown.
7186     if (StepV.isPowerOf2() &&
7187         GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros()) {
7188       // Here we've constrained the equation to be of the form
7189       //
7190       //   2^(N + k) * Distance' = (StepV == 2^N) * X (mod 2^W)  ... (0)
7191       //
7192       // where we're operating on a W bit wide integer domain and k is
7193       // non-negative.  The smallest unsigned solution for X is the trip count.
7194       //
7195       // (0) is equivalent to:
7196       //
7197       //      2^(N + k) * Distance' - 2^N * X = L * 2^W
7198       // <=>  2^N(2^k * Distance' - X) = L * 2^(W - N) * 2^N
7199       // <=>  2^k * Distance' - X = L * 2^(W - N)
7200       // <=>  2^k * Distance'     = L * 2^(W - N) + X    ... (1)
7201       //
7202       // The smallest X satisfying (1) is unsigned remainder of dividing the LHS
7203       // by 2^(W - N).
7204       //
7205       // <=>  X = 2^k * Distance' URem 2^(W - N)   ... (2)
7206       //
7207       // E.g. say we're solving
7208       //
7209       //   2 * Val = 2 * X  (in i8)   ... (3)
7210       //
7211       // then from (2), we get X = Val URem i8 128 (k = 0 in this case).
7212       //
7213       // Note: It is tempting to solve (3) by setting X = Val, but Val is not
7214       // necessarily the smallest unsigned value of X that satisfies (3).
7215       // E.g. if Val is i8 -127 then the smallest value of X that satisfies (3)
7216       // is i8 1, not i8 -127
7217 
7218       const auto *ModuloResult = getUDivExactExpr(Distance, Step);
7219 
7220       // Since SCEV does not have a URem node, we construct one using a truncate
7221       // and a zero extend.
7222 
7223       unsigned NarrowWidth = StepV.getBitWidth() - StepV.countTrailingZeros();
7224       auto *NarrowTy = IntegerType::get(getContext(), NarrowWidth);
7225       auto *WideTy = Distance->getType();
7226 
7227       const SCEV *Limit =
7228           getZeroExtendExpr(getTruncateExpr(ModuloResult, NarrowTy), WideTy);
7229       return ExitLimit(Limit, Limit, Predicates);
7230     }
7231   }
7232 
7233   // If the condition controls loop exit (the loop exits only if the expression
7234   // is true) and the addition is no-wrap we can use unsigned divide to
7235   // compute the backedge count.  In this case, the step may not divide the
7236   // distance, but we don't care because if the condition is "missed" the loop
7237   // will have undefined behavior due to wrapping.
7238   if (ControlsExit && AddRec->hasNoSelfWrap() &&
7239       loopHasNoAbnormalExits(AddRec->getLoop())) {
7240     const SCEV *Exact =
7241         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
7242     return ExitLimit(Exact, Exact, Predicates);
7243   }
7244 
7245   // Then, try to solve the above equation provided that Start is constant.
7246   if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
7247     const SCEV *E = SolveLinEquationWithOverflow(
7248         StepC->getValue()->getValue(), -StartC->getValue()->getValue(), *this);
7249     return ExitLimit(E, E, Predicates);
7250   }
7251   return getCouldNotCompute();
7252 }
7253 
7254 ScalarEvolution::ExitLimit
7255 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
7256   // Loops that look like: while (X == 0) are very strange indeed.  We don't
7257   // handle them yet except for the trivial case.  This could be expanded in the
7258   // future as needed.
7259 
7260   // If the value is a constant, check to see if it is known to be non-zero
7261   // already.  If so, the backedge will execute zero times.
7262   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
7263     if (!C->getValue()->isNullValue())
7264       return getZero(C->getType());
7265     return getCouldNotCompute();  // Otherwise it will loop infinitely.
7266   }
7267 
7268   // We could implement others, but I really doubt anyone writes loops like
7269   // this, and if they did, they would already be constant folded.
7270   return getCouldNotCompute();
7271 }
7272 
7273 std::pair<BasicBlock *, BasicBlock *>
7274 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
7275   // If the block has a unique predecessor, then there is no path from the
7276   // predecessor to the block that does not go through the direct edge
7277   // from the predecessor to the block.
7278   if (BasicBlock *Pred = BB->getSinglePredecessor())
7279     return {Pred, BB};
7280 
7281   // A loop's header is defined to be a block that dominates the loop.
7282   // If the header has a unique predecessor outside the loop, it must be
7283   // a block that has exactly one successor that can reach the loop.
7284   if (Loop *L = LI.getLoopFor(BB))
7285     return {L->getLoopPredecessor(), L->getHeader()};
7286 
7287   return {nullptr, nullptr};
7288 }
7289 
7290 /// SCEV structural equivalence is usually sufficient for testing whether two
7291 /// expressions are equal, however for the purposes of looking for a condition
7292 /// guarding a loop, it can be useful to be a little more general, since a
7293 /// front-end may have replicated the controlling expression.
7294 ///
7295 static bool HasSameValue(const SCEV *A, const SCEV *B) {
7296   // Quick check to see if they are the same SCEV.
7297   if (A == B) return true;
7298 
7299   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
7300     // Not all instructions that are "identical" compute the same value.  For
7301     // instance, two distinct alloca instructions allocating the same type are
7302     // identical and do not read memory; but compute distinct values.
7303     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
7304   };
7305 
7306   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
7307   // two different instructions with the same value. Check for this case.
7308   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
7309     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
7310       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
7311         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
7312           if (ComputesEqualValues(AI, BI))
7313             return true;
7314 
7315   // Otherwise assume they may have a different value.
7316   return false;
7317 }
7318 
7319 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
7320                                            const SCEV *&LHS, const SCEV *&RHS,
7321                                            unsigned Depth) {
7322   bool Changed = false;
7323 
7324   // If we hit the max recursion limit bail out.
7325   if (Depth >= 3)
7326     return false;
7327 
7328   // Canonicalize a constant to the right side.
7329   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
7330     // Check for both operands constant.
7331     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
7332       if (ConstantExpr::getICmp(Pred,
7333                                 LHSC->getValue(),
7334                                 RHSC->getValue())->isNullValue())
7335         goto trivially_false;
7336       else
7337         goto trivially_true;
7338     }
7339     // Otherwise swap the operands to put the constant on the right.
7340     std::swap(LHS, RHS);
7341     Pred = ICmpInst::getSwappedPredicate(Pred);
7342     Changed = true;
7343   }
7344 
7345   // If we're comparing an addrec with a value which is loop-invariant in the
7346   // addrec's loop, put the addrec on the left. Also make a dominance check,
7347   // as both operands could be addrecs loop-invariant in each other's loop.
7348   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
7349     const Loop *L = AR->getLoop();
7350     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
7351       std::swap(LHS, RHS);
7352       Pred = ICmpInst::getSwappedPredicate(Pred);
7353       Changed = true;
7354     }
7355   }
7356 
7357   // If there's a constant operand, canonicalize comparisons with boundary
7358   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
7359   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
7360     const APInt &RA = RC->getAPInt();
7361 
7362     bool SimplifiedByConstantRange = false;
7363 
7364     if (!ICmpInst::isEquality(Pred)) {
7365       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
7366       if (ExactCR.isFullSet())
7367         goto trivially_true;
7368       else if (ExactCR.isEmptySet())
7369         goto trivially_false;
7370 
7371       APInt NewRHS;
7372       CmpInst::Predicate NewPred;
7373       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
7374           ICmpInst::isEquality(NewPred)) {
7375         // We were able to convert an inequality to an equality.
7376         Pred = NewPred;
7377         RHS = getConstant(NewRHS);
7378         Changed = SimplifiedByConstantRange = true;
7379       }
7380     }
7381 
7382     if (!SimplifiedByConstantRange) {
7383       switch (Pred) {
7384       default:
7385         break;
7386       case ICmpInst::ICMP_EQ:
7387       case ICmpInst::ICMP_NE:
7388         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
7389         if (!RA)
7390           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
7391             if (const SCEVMulExpr *ME =
7392                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
7393               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
7394                   ME->getOperand(0)->isAllOnesValue()) {
7395                 RHS = AE->getOperand(1);
7396                 LHS = ME->getOperand(1);
7397                 Changed = true;
7398               }
7399         break;
7400 
7401 
7402         // The "Should have been caught earlier!" messages refer to the fact
7403         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
7404         // should have fired on the corresponding cases, and canonicalized the
7405         // check to trivially_true or trivially_false.
7406 
7407       case ICmpInst::ICMP_UGE:
7408         assert(!RA.isMinValue() && "Should have been caught earlier!");
7409         Pred = ICmpInst::ICMP_UGT;
7410         RHS = getConstant(RA - 1);
7411         Changed = true;
7412         break;
7413       case ICmpInst::ICMP_ULE:
7414         assert(!RA.isMaxValue() && "Should have been caught earlier!");
7415         Pred = ICmpInst::ICMP_ULT;
7416         RHS = getConstant(RA + 1);
7417         Changed = true;
7418         break;
7419       case ICmpInst::ICMP_SGE:
7420         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
7421         Pred = ICmpInst::ICMP_SGT;
7422         RHS = getConstant(RA - 1);
7423         Changed = true;
7424         break;
7425       case ICmpInst::ICMP_SLE:
7426         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
7427         Pred = ICmpInst::ICMP_SLT;
7428         RHS = getConstant(RA + 1);
7429         Changed = true;
7430         break;
7431       }
7432     }
7433   }
7434 
7435   // Check for obvious equality.
7436   if (HasSameValue(LHS, RHS)) {
7437     if (ICmpInst::isTrueWhenEqual(Pred))
7438       goto trivially_true;
7439     if (ICmpInst::isFalseWhenEqual(Pred))
7440       goto trivially_false;
7441   }
7442 
7443   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
7444   // adding or subtracting 1 from one of the operands.
7445   switch (Pred) {
7446   case ICmpInst::ICMP_SLE:
7447     if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
7448       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
7449                        SCEV::FlagNSW);
7450       Pred = ICmpInst::ICMP_SLT;
7451       Changed = true;
7452     } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
7453       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
7454                        SCEV::FlagNSW);
7455       Pred = ICmpInst::ICMP_SLT;
7456       Changed = true;
7457     }
7458     break;
7459   case ICmpInst::ICMP_SGE:
7460     if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
7461       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
7462                        SCEV::FlagNSW);
7463       Pred = ICmpInst::ICMP_SGT;
7464       Changed = true;
7465     } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
7466       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
7467                        SCEV::FlagNSW);
7468       Pred = ICmpInst::ICMP_SGT;
7469       Changed = true;
7470     }
7471     break;
7472   case ICmpInst::ICMP_ULE:
7473     if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
7474       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
7475                        SCEV::FlagNUW);
7476       Pred = ICmpInst::ICMP_ULT;
7477       Changed = true;
7478     } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
7479       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
7480       Pred = ICmpInst::ICMP_ULT;
7481       Changed = true;
7482     }
7483     break;
7484   case ICmpInst::ICMP_UGE:
7485     if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
7486       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
7487       Pred = ICmpInst::ICMP_UGT;
7488       Changed = true;
7489     } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
7490       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
7491                        SCEV::FlagNUW);
7492       Pred = ICmpInst::ICMP_UGT;
7493       Changed = true;
7494     }
7495     break;
7496   default:
7497     break;
7498   }
7499 
7500   // TODO: More simplifications are possible here.
7501 
7502   // Recursively simplify until we either hit a recursion limit or nothing
7503   // changes.
7504   if (Changed)
7505     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
7506 
7507   return Changed;
7508 
7509 trivially_true:
7510   // Return 0 == 0.
7511   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
7512   Pred = ICmpInst::ICMP_EQ;
7513   return true;
7514 
7515 trivially_false:
7516   // Return 0 != 0.
7517   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
7518   Pred = ICmpInst::ICMP_NE;
7519   return true;
7520 }
7521 
7522 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
7523   return getSignedRange(S).getSignedMax().isNegative();
7524 }
7525 
7526 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
7527   return getSignedRange(S).getSignedMin().isStrictlyPositive();
7528 }
7529 
7530 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
7531   return !getSignedRange(S).getSignedMin().isNegative();
7532 }
7533 
7534 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
7535   return !getSignedRange(S).getSignedMax().isStrictlyPositive();
7536 }
7537 
7538 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
7539   return isKnownNegative(S) || isKnownPositive(S);
7540 }
7541 
7542 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
7543                                        const SCEV *LHS, const SCEV *RHS) {
7544   // Canonicalize the inputs first.
7545   (void)SimplifyICmpOperands(Pred, LHS, RHS);
7546 
7547   // If LHS or RHS is an addrec, check to see if the condition is true in
7548   // every iteration of the loop.
7549   // If LHS and RHS are both addrec, both conditions must be true in
7550   // every iteration of the loop.
7551   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
7552   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
7553   bool LeftGuarded = false;
7554   bool RightGuarded = false;
7555   if (LAR) {
7556     const Loop *L = LAR->getLoop();
7557     if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
7558         isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
7559       if (!RAR) return true;
7560       LeftGuarded = true;
7561     }
7562   }
7563   if (RAR) {
7564     const Loop *L = RAR->getLoop();
7565     if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
7566         isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
7567       if (!LAR) return true;
7568       RightGuarded = true;
7569     }
7570   }
7571   if (LeftGuarded && RightGuarded)
7572     return true;
7573 
7574   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
7575     return true;
7576 
7577   // Otherwise see what can be done with known constant ranges.
7578   return isKnownPredicateViaConstantRanges(Pred, LHS, RHS);
7579 }
7580 
7581 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
7582                                            ICmpInst::Predicate Pred,
7583                                            bool &Increasing) {
7584   bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
7585 
7586 #ifndef NDEBUG
7587   // Verify an invariant: inverting the predicate should turn a monotonically
7588   // increasing change to a monotonically decreasing one, and vice versa.
7589   bool IncreasingSwapped;
7590   bool ResultSwapped = isMonotonicPredicateImpl(
7591       LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
7592 
7593   assert(Result == ResultSwapped && "should be able to analyze both!");
7594   if (ResultSwapped)
7595     assert(Increasing == !IncreasingSwapped &&
7596            "monotonicity should flip as we flip the predicate");
7597 #endif
7598 
7599   return Result;
7600 }
7601 
7602 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
7603                                                ICmpInst::Predicate Pred,
7604                                                bool &Increasing) {
7605 
7606   // A zero step value for LHS means the induction variable is essentially a
7607   // loop invariant value. We don't really depend on the predicate actually
7608   // flipping from false to true (for increasing predicates, and the other way
7609   // around for decreasing predicates), all we care about is that *if* the
7610   // predicate changes then it only changes from false to true.
7611   //
7612   // A zero step value in itself is not very useful, but there may be places
7613   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
7614   // as general as possible.
7615 
7616   switch (Pred) {
7617   default:
7618     return false; // Conservative answer
7619 
7620   case ICmpInst::ICMP_UGT:
7621   case ICmpInst::ICMP_UGE:
7622   case ICmpInst::ICMP_ULT:
7623   case ICmpInst::ICMP_ULE:
7624     if (!LHS->hasNoUnsignedWrap())
7625       return false;
7626 
7627     Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
7628     return true;
7629 
7630   case ICmpInst::ICMP_SGT:
7631   case ICmpInst::ICMP_SGE:
7632   case ICmpInst::ICMP_SLT:
7633   case ICmpInst::ICMP_SLE: {
7634     if (!LHS->hasNoSignedWrap())
7635       return false;
7636 
7637     const SCEV *Step = LHS->getStepRecurrence(*this);
7638 
7639     if (isKnownNonNegative(Step)) {
7640       Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
7641       return true;
7642     }
7643 
7644     if (isKnownNonPositive(Step)) {
7645       Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
7646       return true;
7647     }
7648 
7649     return false;
7650   }
7651 
7652   }
7653 
7654   llvm_unreachable("switch has default clause!");
7655 }
7656 
7657 bool ScalarEvolution::isLoopInvariantPredicate(
7658     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
7659     ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
7660     const SCEV *&InvariantRHS) {
7661 
7662   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
7663   if (!isLoopInvariant(RHS, L)) {
7664     if (!isLoopInvariant(LHS, L))
7665       return false;
7666 
7667     std::swap(LHS, RHS);
7668     Pred = ICmpInst::getSwappedPredicate(Pred);
7669   }
7670 
7671   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
7672   if (!ArLHS || ArLHS->getLoop() != L)
7673     return false;
7674 
7675   bool Increasing;
7676   if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
7677     return false;
7678 
7679   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
7680   // true as the loop iterates, and the backedge is control dependent on
7681   // "ArLHS `Pred` RHS" == true then we can reason as follows:
7682   //
7683   //   * if the predicate was false in the first iteration then the predicate
7684   //     is never evaluated again, since the loop exits without taking the
7685   //     backedge.
7686   //   * if the predicate was true in the first iteration then it will
7687   //     continue to be true for all future iterations since it is
7688   //     monotonically increasing.
7689   //
7690   // For both the above possibilities, we can replace the loop varying
7691   // predicate with its value on the first iteration of the loop (which is
7692   // loop invariant).
7693   //
7694   // A similar reasoning applies for a monotonically decreasing predicate, by
7695   // replacing true with false and false with true in the above two bullets.
7696 
7697   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
7698 
7699   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
7700     return false;
7701 
7702   InvariantPred = Pred;
7703   InvariantLHS = ArLHS->getStart();
7704   InvariantRHS = RHS;
7705   return true;
7706 }
7707 
7708 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
7709     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
7710   if (HasSameValue(LHS, RHS))
7711     return ICmpInst::isTrueWhenEqual(Pred);
7712 
7713   // This code is split out from isKnownPredicate because it is called from
7714   // within isLoopEntryGuardedByCond.
7715 
7716   auto CheckRanges =
7717       [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
7718     return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
7719         .contains(RangeLHS);
7720   };
7721 
7722   // The check at the top of the function catches the case where the values are
7723   // known to be equal.
7724   if (Pred == CmpInst::ICMP_EQ)
7725     return false;
7726 
7727   if (Pred == CmpInst::ICMP_NE)
7728     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
7729            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
7730            isKnownNonZero(getMinusSCEV(LHS, RHS));
7731 
7732   if (CmpInst::isSigned(Pred))
7733     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
7734 
7735   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
7736 }
7737 
7738 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
7739                                                     const SCEV *LHS,
7740                                                     const SCEV *RHS) {
7741 
7742   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
7743   // Return Y via OutY.
7744   auto MatchBinaryAddToConst =
7745       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
7746              SCEV::NoWrapFlags ExpectedFlags) {
7747     const SCEV *NonConstOp, *ConstOp;
7748     SCEV::NoWrapFlags FlagsPresent;
7749 
7750     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
7751         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
7752       return false;
7753 
7754     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
7755     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
7756   };
7757 
7758   APInt C;
7759 
7760   switch (Pred) {
7761   default:
7762     break;
7763 
7764   case ICmpInst::ICMP_SGE:
7765     std::swap(LHS, RHS);
7766   case ICmpInst::ICMP_SLE:
7767     // X s<= (X + C)<nsw> if C >= 0
7768     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
7769       return true;
7770 
7771     // (X + C)<nsw> s<= X if C <= 0
7772     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
7773         !C.isStrictlyPositive())
7774       return true;
7775     break;
7776 
7777   case ICmpInst::ICMP_SGT:
7778     std::swap(LHS, RHS);
7779   case ICmpInst::ICMP_SLT:
7780     // X s< (X + C)<nsw> if C > 0
7781     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
7782         C.isStrictlyPositive())
7783       return true;
7784 
7785     // (X + C)<nsw> s< X if C < 0
7786     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
7787       return true;
7788     break;
7789   }
7790 
7791   return false;
7792 }
7793 
7794 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
7795                                                    const SCEV *LHS,
7796                                                    const SCEV *RHS) {
7797   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
7798     return false;
7799 
7800   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
7801   // the stack can result in exponential time complexity.
7802   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
7803 
7804   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
7805   //
7806   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
7807   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
7808   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
7809   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
7810   // use isKnownPredicate later if needed.
7811   return isKnownNonNegative(RHS) &&
7812          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
7813          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
7814 }
7815 
7816 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
7817                                         ICmpInst::Predicate Pred,
7818                                         const SCEV *LHS, const SCEV *RHS) {
7819   // No need to even try if we know the module has no guards.
7820   if (!HasGuards)
7821     return false;
7822 
7823   return any_of(*BB, [&](Instruction &I) {
7824     using namespace llvm::PatternMatch;
7825 
7826     Value *Condition;
7827     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
7828                          m_Value(Condition))) &&
7829            isImpliedCond(Pred, LHS, RHS, Condition, false);
7830   });
7831 }
7832 
7833 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
7834 /// protected by a conditional between LHS and RHS.  This is used to
7835 /// to eliminate casts.
7836 bool
7837 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
7838                                              ICmpInst::Predicate Pred,
7839                                              const SCEV *LHS, const SCEV *RHS) {
7840   // Interpret a null as meaning no loop, where there is obviously no guard
7841   // (interprocedural conditions notwithstanding).
7842   if (!L) return true;
7843 
7844   if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
7845     return true;
7846 
7847   BasicBlock *Latch = L->getLoopLatch();
7848   if (!Latch)
7849     return false;
7850 
7851   BranchInst *LoopContinuePredicate =
7852     dyn_cast<BranchInst>(Latch->getTerminator());
7853   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
7854       isImpliedCond(Pred, LHS, RHS,
7855                     LoopContinuePredicate->getCondition(),
7856                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
7857     return true;
7858 
7859   // We don't want more than one activation of the following loops on the stack
7860   // -- that can lead to O(n!) time complexity.
7861   if (WalkingBEDominatingConds)
7862     return false;
7863 
7864   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
7865 
7866   // See if we can exploit a trip count to prove the predicate.
7867   const auto &BETakenInfo = getBackedgeTakenInfo(L);
7868   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
7869   if (LatchBECount != getCouldNotCompute()) {
7870     // We know that Latch branches back to the loop header exactly
7871     // LatchBECount times.  This means the backdege condition at Latch is
7872     // equivalent to  "{0,+,1} u< LatchBECount".
7873     Type *Ty = LatchBECount->getType();
7874     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
7875     const SCEV *LoopCounter =
7876       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
7877     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
7878                       LatchBECount))
7879       return true;
7880   }
7881 
7882   // Check conditions due to any @llvm.assume intrinsics.
7883   for (auto &AssumeVH : AC.assumptions()) {
7884     if (!AssumeVH)
7885       continue;
7886     auto *CI = cast<CallInst>(AssumeVH);
7887     if (!DT.dominates(CI, Latch->getTerminator()))
7888       continue;
7889 
7890     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
7891       return true;
7892   }
7893 
7894   // If the loop is not reachable from the entry block, we risk running into an
7895   // infinite loop as we walk up into the dom tree.  These loops do not matter
7896   // anyway, so we just return a conservative answer when we see them.
7897   if (!DT.isReachableFromEntry(L->getHeader()))
7898     return false;
7899 
7900   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
7901     return true;
7902 
7903   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
7904        DTN != HeaderDTN; DTN = DTN->getIDom()) {
7905 
7906     assert(DTN && "should reach the loop header before reaching the root!");
7907 
7908     BasicBlock *BB = DTN->getBlock();
7909     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
7910       return true;
7911 
7912     BasicBlock *PBB = BB->getSinglePredecessor();
7913     if (!PBB)
7914       continue;
7915 
7916     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
7917     if (!ContinuePredicate || !ContinuePredicate->isConditional())
7918       continue;
7919 
7920     Value *Condition = ContinuePredicate->getCondition();
7921 
7922     // If we have an edge `E` within the loop body that dominates the only
7923     // latch, the condition guarding `E` also guards the backedge.  This
7924     // reasoning works only for loops with a single latch.
7925 
7926     BasicBlockEdge DominatingEdge(PBB, BB);
7927     if (DominatingEdge.isSingleEdge()) {
7928       // We're constructively (and conservatively) enumerating edges within the
7929       // loop body that dominate the latch.  The dominator tree better agree
7930       // with us on this:
7931       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
7932 
7933       if (isImpliedCond(Pred, LHS, RHS, Condition,
7934                         BB != ContinuePredicate->getSuccessor(0)))
7935         return true;
7936     }
7937   }
7938 
7939   return false;
7940 }
7941 
7942 bool
7943 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
7944                                           ICmpInst::Predicate Pred,
7945                                           const SCEV *LHS, const SCEV *RHS) {
7946   // Interpret a null as meaning no loop, where there is obviously no guard
7947   // (interprocedural conditions notwithstanding).
7948   if (!L) return false;
7949 
7950   if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
7951     return true;
7952 
7953   // Starting at the loop predecessor, climb up the predecessor chain, as long
7954   // as there are predecessors that can be found that have unique successors
7955   // leading to the original header.
7956   for (std::pair<BasicBlock *, BasicBlock *>
7957          Pair(L->getLoopPredecessor(), L->getHeader());
7958        Pair.first;
7959        Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
7960 
7961     if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS))
7962       return true;
7963 
7964     BranchInst *LoopEntryPredicate =
7965       dyn_cast<BranchInst>(Pair.first->getTerminator());
7966     if (!LoopEntryPredicate ||
7967         LoopEntryPredicate->isUnconditional())
7968       continue;
7969 
7970     if (isImpliedCond(Pred, LHS, RHS,
7971                       LoopEntryPredicate->getCondition(),
7972                       LoopEntryPredicate->getSuccessor(0) != Pair.second))
7973       return true;
7974   }
7975 
7976   // Check conditions due to any @llvm.assume intrinsics.
7977   for (auto &AssumeVH : AC.assumptions()) {
7978     if (!AssumeVH)
7979       continue;
7980     auto *CI = cast<CallInst>(AssumeVH);
7981     if (!DT.dominates(CI, L->getHeader()))
7982       continue;
7983 
7984     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
7985       return true;
7986   }
7987 
7988   return false;
7989 }
7990 
7991 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
7992                                     const SCEV *LHS, const SCEV *RHS,
7993                                     Value *FoundCondValue,
7994                                     bool Inverse) {
7995   if (!PendingLoopPredicates.insert(FoundCondValue).second)
7996     return false;
7997 
7998   auto ClearOnExit =
7999       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
8000 
8001   // Recursively handle And and Or conditions.
8002   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
8003     if (BO->getOpcode() == Instruction::And) {
8004       if (!Inverse)
8005         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8006                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
8007     } else if (BO->getOpcode() == Instruction::Or) {
8008       if (Inverse)
8009         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8010                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
8011     }
8012   }
8013 
8014   ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
8015   if (!ICI) return false;
8016 
8017   // Now that we found a conditional branch that dominates the loop or controls
8018   // the loop latch. Check to see if it is the comparison we are looking for.
8019   ICmpInst::Predicate FoundPred;
8020   if (Inverse)
8021     FoundPred = ICI->getInversePredicate();
8022   else
8023     FoundPred = ICI->getPredicate();
8024 
8025   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
8026   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
8027 
8028   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
8029 }
8030 
8031 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
8032                                     const SCEV *RHS,
8033                                     ICmpInst::Predicate FoundPred,
8034                                     const SCEV *FoundLHS,
8035                                     const SCEV *FoundRHS) {
8036   // Balance the types.
8037   if (getTypeSizeInBits(LHS->getType()) <
8038       getTypeSizeInBits(FoundLHS->getType())) {
8039     if (CmpInst::isSigned(Pred)) {
8040       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
8041       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
8042     } else {
8043       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
8044       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
8045     }
8046   } else if (getTypeSizeInBits(LHS->getType()) >
8047       getTypeSizeInBits(FoundLHS->getType())) {
8048     if (CmpInst::isSigned(FoundPred)) {
8049       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
8050       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
8051     } else {
8052       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
8053       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
8054     }
8055   }
8056 
8057   // Canonicalize the query to match the way instcombine will have
8058   // canonicalized the comparison.
8059   if (SimplifyICmpOperands(Pred, LHS, RHS))
8060     if (LHS == RHS)
8061       return CmpInst::isTrueWhenEqual(Pred);
8062   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
8063     if (FoundLHS == FoundRHS)
8064       return CmpInst::isFalseWhenEqual(FoundPred);
8065 
8066   // Check to see if we can make the LHS or RHS match.
8067   if (LHS == FoundRHS || RHS == FoundLHS) {
8068     if (isa<SCEVConstant>(RHS)) {
8069       std::swap(FoundLHS, FoundRHS);
8070       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
8071     } else {
8072       std::swap(LHS, RHS);
8073       Pred = ICmpInst::getSwappedPredicate(Pred);
8074     }
8075   }
8076 
8077   // Check whether the found predicate is the same as the desired predicate.
8078   if (FoundPred == Pred)
8079     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8080 
8081   // Check whether swapping the found predicate makes it the same as the
8082   // desired predicate.
8083   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
8084     if (isa<SCEVConstant>(RHS))
8085       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
8086     else
8087       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
8088                                    RHS, LHS, FoundLHS, FoundRHS);
8089   }
8090 
8091   // Unsigned comparison is the same as signed comparison when both the operands
8092   // are non-negative.
8093   if (CmpInst::isUnsigned(FoundPred) &&
8094       CmpInst::getSignedPredicate(FoundPred) == Pred &&
8095       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
8096     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8097 
8098   // Check if we can make progress by sharpening ranges.
8099   if (FoundPred == ICmpInst::ICMP_NE &&
8100       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
8101 
8102     const SCEVConstant *C = nullptr;
8103     const SCEV *V = nullptr;
8104 
8105     if (isa<SCEVConstant>(FoundLHS)) {
8106       C = cast<SCEVConstant>(FoundLHS);
8107       V = FoundRHS;
8108     } else {
8109       C = cast<SCEVConstant>(FoundRHS);
8110       V = FoundLHS;
8111     }
8112 
8113     // The guarding predicate tells us that C != V. If the known range
8114     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
8115     // range we consider has to correspond to same signedness as the
8116     // predicate we're interested in folding.
8117 
8118     APInt Min = ICmpInst::isSigned(Pred) ?
8119         getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin();
8120 
8121     if (Min == C->getAPInt()) {
8122       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
8123       // This is true even if (Min + 1) wraps around -- in case of
8124       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
8125 
8126       APInt SharperMin = Min + 1;
8127 
8128       switch (Pred) {
8129         case ICmpInst::ICMP_SGE:
8130         case ICmpInst::ICMP_UGE:
8131           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
8132           // RHS, we're done.
8133           if (isImpliedCondOperands(Pred, LHS, RHS, V,
8134                                     getConstant(SharperMin)))
8135             return true;
8136 
8137         case ICmpInst::ICMP_SGT:
8138         case ICmpInst::ICMP_UGT:
8139           // We know from the range information that (V `Pred` Min ||
8140           // V == Min).  We know from the guarding condition that !(V
8141           // == Min).  This gives us
8142           //
8143           //       V `Pred` Min || V == Min && !(V == Min)
8144           //   =>  V `Pred` Min
8145           //
8146           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
8147 
8148           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
8149             return true;
8150 
8151         default:
8152           // No change
8153           break;
8154       }
8155     }
8156   }
8157 
8158   // Check whether the actual condition is beyond sufficient.
8159   if (FoundPred == ICmpInst::ICMP_EQ)
8160     if (ICmpInst::isTrueWhenEqual(Pred))
8161       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
8162         return true;
8163   if (Pred == ICmpInst::ICMP_NE)
8164     if (!ICmpInst::isTrueWhenEqual(FoundPred))
8165       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
8166         return true;
8167 
8168   // Otherwise assume the worst.
8169   return false;
8170 }
8171 
8172 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
8173                                      const SCEV *&L, const SCEV *&R,
8174                                      SCEV::NoWrapFlags &Flags) {
8175   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
8176   if (!AE || AE->getNumOperands() != 2)
8177     return false;
8178 
8179   L = AE->getOperand(0);
8180   R = AE->getOperand(1);
8181   Flags = AE->getNoWrapFlags();
8182   return true;
8183 }
8184 
8185 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
8186                                                            const SCEV *Less) {
8187   // We avoid subtracting expressions here because this function is usually
8188   // fairly deep in the call stack (i.e. is called many times).
8189 
8190   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
8191     const auto *LAR = cast<SCEVAddRecExpr>(Less);
8192     const auto *MAR = cast<SCEVAddRecExpr>(More);
8193 
8194     if (LAR->getLoop() != MAR->getLoop())
8195       return None;
8196 
8197     // We look at affine expressions only; not for correctness but to keep
8198     // getStepRecurrence cheap.
8199     if (!LAR->isAffine() || !MAR->isAffine())
8200       return None;
8201 
8202     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
8203       return None;
8204 
8205     Less = LAR->getStart();
8206     More = MAR->getStart();
8207 
8208     // fall through
8209   }
8210 
8211   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
8212     const auto &M = cast<SCEVConstant>(More)->getAPInt();
8213     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
8214     return M - L;
8215   }
8216 
8217   const SCEV *L, *R;
8218   SCEV::NoWrapFlags Flags;
8219   if (splitBinaryAdd(Less, L, R, Flags))
8220     if (const auto *LC = dyn_cast<SCEVConstant>(L))
8221       if (R == More)
8222         return -(LC->getAPInt());
8223 
8224   if (splitBinaryAdd(More, L, R, Flags))
8225     if (const auto *LC = dyn_cast<SCEVConstant>(L))
8226       if (R == Less)
8227         return LC->getAPInt();
8228 
8229   return None;
8230 }
8231 
8232 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
8233     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
8234     const SCEV *FoundLHS, const SCEV *FoundRHS) {
8235   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
8236     return false;
8237 
8238   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8239   if (!AddRecLHS)
8240     return false;
8241 
8242   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
8243   if (!AddRecFoundLHS)
8244     return false;
8245 
8246   // We'd like to let SCEV reason about control dependencies, so we constrain
8247   // both the inequalities to be about add recurrences on the same loop.  This
8248   // way we can use isLoopEntryGuardedByCond later.
8249 
8250   const Loop *L = AddRecFoundLHS->getLoop();
8251   if (L != AddRecLHS->getLoop())
8252     return false;
8253 
8254   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
8255   //
8256   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
8257   //                                                                  ... (2)
8258   //
8259   // Informal proof for (2), assuming (1) [*]:
8260   //
8261   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
8262   //
8263   // Then
8264   //
8265   //       FoundLHS s< FoundRHS s< INT_MIN - C
8266   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
8267   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
8268   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
8269   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
8270   // <=>  FoundLHS + C s< FoundRHS + C
8271   //
8272   // [*]: (1) can be proved by ruling out overflow.
8273   //
8274   // [**]: This can be proved by analyzing all the four possibilities:
8275   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
8276   //    (A s>= 0, B s>= 0).
8277   //
8278   // Note:
8279   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
8280   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
8281   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
8282   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
8283   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
8284   // C)".
8285 
8286   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
8287   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
8288   if (!LDiff || !RDiff || *LDiff != *RDiff)
8289     return false;
8290 
8291   if (LDiff->isMinValue())
8292     return true;
8293 
8294   APInt FoundRHSLimit;
8295 
8296   if (Pred == CmpInst::ICMP_ULT) {
8297     FoundRHSLimit = -(*RDiff);
8298   } else {
8299     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
8300     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
8301   }
8302 
8303   // Try to prove (1) or (2), as needed.
8304   return isLoopEntryGuardedByCond(L, Pred, FoundRHS,
8305                                   getConstant(FoundRHSLimit));
8306 }
8307 
8308 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
8309                                             const SCEV *LHS, const SCEV *RHS,
8310                                             const SCEV *FoundLHS,
8311                                             const SCEV *FoundRHS) {
8312   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
8313     return true;
8314 
8315   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
8316     return true;
8317 
8318   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
8319                                      FoundLHS, FoundRHS) ||
8320          // ~x < ~y --> x > y
8321          isImpliedCondOperandsHelper(Pred, LHS, RHS,
8322                                      getNotSCEV(FoundRHS),
8323                                      getNotSCEV(FoundLHS));
8324 }
8325 
8326 
8327 /// If Expr computes ~A, return A else return nullptr
8328 static const SCEV *MatchNotExpr(const SCEV *Expr) {
8329   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
8330   if (!Add || Add->getNumOperands() != 2 ||
8331       !Add->getOperand(0)->isAllOnesValue())
8332     return nullptr;
8333 
8334   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
8335   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
8336       !AddRHS->getOperand(0)->isAllOnesValue())
8337     return nullptr;
8338 
8339   return AddRHS->getOperand(1);
8340 }
8341 
8342 
8343 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
8344 template<typename MaxExprType>
8345 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
8346                               const SCEV *Candidate) {
8347   const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
8348   if (!MaxExpr) return false;
8349 
8350   return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
8351 }
8352 
8353 
8354 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
8355 template<typename MaxExprType>
8356 static bool IsMinConsistingOf(ScalarEvolution &SE,
8357                               const SCEV *MaybeMinExpr,
8358                               const SCEV *Candidate) {
8359   const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
8360   if (!MaybeMaxExpr)
8361     return false;
8362 
8363   return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
8364 }
8365 
8366 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
8367                                            ICmpInst::Predicate Pred,
8368                                            const SCEV *LHS, const SCEV *RHS) {
8369 
8370   // If both sides are affine addrecs for the same loop, with equal
8371   // steps, and we know the recurrences don't wrap, then we only
8372   // need to check the predicate on the starting values.
8373 
8374   if (!ICmpInst::isRelational(Pred))
8375     return false;
8376 
8377   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
8378   if (!LAR)
8379     return false;
8380   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
8381   if (!RAR)
8382     return false;
8383   if (LAR->getLoop() != RAR->getLoop())
8384     return false;
8385   if (!LAR->isAffine() || !RAR->isAffine())
8386     return false;
8387 
8388   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
8389     return false;
8390 
8391   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
8392                          SCEV::FlagNSW : SCEV::FlagNUW;
8393   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
8394     return false;
8395 
8396   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
8397 }
8398 
8399 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
8400 /// expression?
8401 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
8402                                         ICmpInst::Predicate Pred,
8403                                         const SCEV *LHS, const SCEV *RHS) {
8404   switch (Pred) {
8405   default:
8406     return false;
8407 
8408   case ICmpInst::ICMP_SGE:
8409     std::swap(LHS, RHS);
8410     LLVM_FALLTHROUGH;
8411   case ICmpInst::ICMP_SLE:
8412     return
8413       // min(A, ...) <= A
8414       IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
8415       // A <= max(A, ...)
8416       IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
8417 
8418   case ICmpInst::ICMP_UGE:
8419     std::swap(LHS, RHS);
8420     LLVM_FALLTHROUGH;
8421   case ICmpInst::ICMP_ULE:
8422     return
8423       // min(A, ...) <= A
8424       IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
8425       // A <= max(A, ...)
8426       IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
8427   }
8428 
8429   llvm_unreachable("covered switch fell through?!");
8430 }
8431 
8432 bool
8433 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
8434                                              const SCEV *LHS, const SCEV *RHS,
8435                                              const SCEV *FoundLHS,
8436                                              const SCEV *FoundRHS) {
8437   auto IsKnownPredicateFull =
8438       [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
8439     return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
8440            IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
8441            IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
8442            isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
8443   };
8444 
8445   switch (Pred) {
8446   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
8447   case ICmpInst::ICMP_EQ:
8448   case ICmpInst::ICMP_NE:
8449     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
8450       return true;
8451     break;
8452   case ICmpInst::ICMP_SLT:
8453   case ICmpInst::ICMP_SLE:
8454     if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
8455         IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS))
8456       return true;
8457     break;
8458   case ICmpInst::ICMP_SGT:
8459   case ICmpInst::ICMP_SGE:
8460     if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
8461         IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS))
8462       return true;
8463     break;
8464   case ICmpInst::ICMP_ULT:
8465   case ICmpInst::ICMP_ULE:
8466     if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
8467         IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS))
8468       return true;
8469     break;
8470   case ICmpInst::ICMP_UGT:
8471   case ICmpInst::ICMP_UGE:
8472     if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
8473         IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS))
8474       return true;
8475     break;
8476   }
8477 
8478   return false;
8479 }
8480 
8481 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
8482                                                      const SCEV *LHS,
8483                                                      const SCEV *RHS,
8484                                                      const SCEV *FoundLHS,
8485                                                      const SCEV *FoundRHS) {
8486   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
8487     // The restriction on `FoundRHS` be lifted easily -- it exists only to
8488     // reduce the compile time impact of this optimization.
8489     return false;
8490 
8491   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
8492   if (!Addend)
8493     return false;
8494 
8495   APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
8496 
8497   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
8498   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
8499   ConstantRange FoundLHSRange =
8500       ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
8501 
8502   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
8503   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
8504 
8505   // We can also compute the range of values for `LHS` that satisfy the
8506   // consequent, "`LHS` `Pred` `RHS`":
8507   APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
8508   ConstantRange SatisfyingLHSRange =
8509       ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
8510 
8511   // The antecedent implies the consequent if every value of `LHS` that
8512   // satisfies the antecedent also satisfies the consequent.
8513   return SatisfyingLHSRange.contains(LHSRange);
8514 }
8515 
8516 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
8517                                          bool IsSigned, bool NoWrap) {
8518   assert(isKnownPositive(Stride) && "Positive stride expected!");
8519 
8520   if (NoWrap) return false;
8521 
8522   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8523   const SCEV *One = getOne(Stride->getType());
8524 
8525   if (IsSigned) {
8526     APInt MaxRHS = getSignedRange(RHS).getSignedMax();
8527     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
8528     APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8529                                 .getSignedMax();
8530 
8531     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
8532     return (MaxValue - MaxStrideMinusOne).slt(MaxRHS);
8533   }
8534 
8535   APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
8536   APInt MaxValue = APInt::getMaxValue(BitWidth);
8537   APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8538                               .getUnsignedMax();
8539 
8540   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
8541   return (MaxValue - MaxStrideMinusOne).ult(MaxRHS);
8542 }
8543 
8544 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
8545                                          bool IsSigned, bool NoWrap) {
8546   if (NoWrap) return false;
8547 
8548   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8549   const SCEV *One = getOne(Stride->getType());
8550 
8551   if (IsSigned) {
8552     APInt MinRHS = getSignedRange(RHS).getSignedMin();
8553     APInt MinValue = APInt::getSignedMinValue(BitWidth);
8554     APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8555                                .getSignedMax();
8556 
8557     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
8558     return (MinValue + MaxStrideMinusOne).sgt(MinRHS);
8559   }
8560 
8561   APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
8562   APInt MinValue = APInt::getMinValue(BitWidth);
8563   APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8564                             .getUnsignedMax();
8565 
8566   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
8567   return (MinValue + MaxStrideMinusOne).ugt(MinRHS);
8568 }
8569 
8570 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
8571                                             bool Equality) {
8572   const SCEV *One = getOne(Step->getType());
8573   Delta = Equality ? getAddExpr(Delta, Step)
8574                    : getAddExpr(Delta, getMinusSCEV(Step, One));
8575   return getUDivExpr(Delta, Step);
8576 }
8577 
8578 ScalarEvolution::ExitLimit
8579 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
8580                                   const Loop *L, bool IsSigned,
8581                                   bool ControlsExit, bool AllowPredicates) {
8582   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
8583   // We handle only IV < Invariant
8584   if (!isLoopInvariant(RHS, L))
8585     return getCouldNotCompute();
8586 
8587   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
8588   bool PredicatedIV = false;
8589 
8590   if (!IV && AllowPredicates) {
8591     // Try to make this an AddRec using runtime tests, in the first X
8592     // iterations of this loop, where X is the SCEV expression found by the
8593     // algorithm below.
8594     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
8595     PredicatedIV = true;
8596   }
8597 
8598   // Avoid weird loops
8599   if (!IV || IV->getLoop() != L || !IV->isAffine())
8600     return getCouldNotCompute();
8601 
8602   bool NoWrap = ControlsExit &&
8603                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
8604 
8605   const SCEV *Stride = IV->getStepRecurrence(*this);
8606 
8607   bool PositiveStride = isKnownPositive(Stride);
8608 
8609   // Avoid negative or zero stride values.
8610   if (!PositiveStride) {
8611     // We can compute the correct backedge taken count for loops with unknown
8612     // strides if we can prove that the loop is not an infinite loop with side
8613     // effects. Here's the loop structure we are trying to handle -
8614     //
8615     // i = start
8616     // do {
8617     //   A[i] = i;
8618     //   i += s;
8619     // } while (i < end);
8620     //
8621     // The backedge taken count for such loops is evaluated as -
8622     // (max(end, start + stride) - start - 1) /u stride
8623     //
8624     // The additional preconditions that we need to check to prove correctness
8625     // of the above formula is as follows -
8626     //
8627     // a) IV is either nuw or nsw depending upon signedness (indicated by the
8628     //    NoWrap flag).
8629     // b) loop is single exit with no side effects.
8630     //
8631     //
8632     // Precondition a) implies that if the stride is negative, this is a single
8633     // trip loop. The backedge taken count formula reduces to zero in this case.
8634     //
8635     // Precondition b) implies that the unknown stride cannot be zero otherwise
8636     // we have UB.
8637     //
8638     // The positive stride case is the same as isKnownPositive(Stride) returning
8639     // true (original behavior of the function).
8640     //
8641     // We want to make sure that the stride is truly unknown as there are edge
8642     // cases where ScalarEvolution propagates no wrap flags to the
8643     // post-increment/decrement IV even though the increment/decrement operation
8644     // itself is wrapping. The computed backedge taken count may be wrong in
8645     // such cases. This is prevented by checking that the stride is not known to
8646     // be either positive or non-positive. For example, no wrap flags are
8647     // propagated to the post-increment IV of this loop with a trip count of 2 -
8648     //
8649     // unsigned char i;
8650     // for(i=127; i<128; i+=129)
8651     //   A[i] = i;
8652     //
8653     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
8654         !loopHasNoSideEffects(L))
8655       return getCouldNotCompute();
8656 
8657   } else if (!Stride->isOne() &&
8658              doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
8659     // Avoid proven overflow cases: this will ensure that the backedge taken
8660     // count will not generate any unsigned overflow. Relaxed no-overflow
8661     // conditions exploit NoWrapFlags, allowing to optimize in presence of
8662     // undefined behaviors like the case of C language.
8663     return getCouldNotCompute();
8664 
8665   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
8666                                       : ICmpInst::ICMP_ULT;
8667   const SCEV *Start = IV->getStart();
8668   const SCEV *End = RHS;
8669   // If the backedge is taken at least once, then it will be taken
8670   // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
8671   // is the LHS value of the less-than comparison the first time it is evaluated
8672   // and End is the RHS.
8673   const SCEV *BECountIfBackedgeTaken =
8674     computeBECount(getMinusSCEV(End, Start), Stride, false);
8675   // If the loop entry is guarded by the result of the backedge test of the
8676   // first loop iteration, then we know the backedge will be taken at least
8677   // once and so the backedge taken count is as above. If not then we use the
8678   // expression (max(End,Start)-Start)/Stride to describe the backedge count,
8679   // as if the backedge is taken at least once max(End,Start) is End and so the
8680   // result is as above, and if not max(End,Start) is Start so we get a backedge
8681   // count of zero.
8682   const SCEV *BECount;
8683   if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
8684     BECount = BECountIfBackedgeTaken;
8685   else {
8686     End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
8687     BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
8688   }
8689 
8690   const SCEV *MaxBECount;
8691   if (isa<SCEVConstant>(BECount))
8692     MaxBECount = BECount;
8693   else if (isa<SCEVConstant>(BECountIfBackedgeTaken))
8694     // If we know exactly how many times the backedge will be taken if it's
8695     // taken at least once, then the backedge count will either be that or
8696     // zero.
8697     MaxBECount = BECountIfBackedgeTaken;
8698   else {
8699     // Calculate the maximum backedge count based on the range of values
8700     // permitted by Start, End, and Stride.
8701     APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
8702                               : getUnsignedRange(Start).getUnsignedMin();
8703 
8704     unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8705 
8706     APInt StrideForMaxBECount;
8707 
8708     if (PositiveStride)
8709       StrideForMaxBECount =
8710         IsSigned ? getSignedRange(Stride).getSignedMin()
8711                  : getUnsignedRange(Stride).getUnsignedMin();
8712     else
8713       // Using a stride of 1 is safe when computing max backedge taken count for
8714       // a loop with unknown stride.
8715       StrideForMaxBECount = APInt(BitWidth, 1, IsSigned);
8716 
8717     APInt Limit =
8718       IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1)
8719                : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1);
8720 
8721     // Although End can be a MAX expression we estimate MaxEnd considering only
8722     // the case End = RHS. This is safe because in the other case (End - Start)
8723     // is zero, leading to a zero maximum backedge taken count.
8724     APInt MaxEnd =
8725       IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
8726                : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
8727 
8728     MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
8729                                 getConstant(StrideForMaxBECount), false);
8730   }
8731 
8732   if (isa<SCEVCouldNotCompute>(MaxBECount))
8733     MaxBECount = BECount;
8734 
8735   return ExitLimit(BECount, MaxBECount, Predicates);
8736 }
8737 
8738 ScalarEvolution::ExitLimit
8739 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
8740                                      const Loop *L, bool IsSigned,
8741                                      bool ControlsExit, bool AllowPredicates) {
8742   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
8743   // We handle only IV > Invariant
8744   if (!isLoopInvariant(RHS, L))
8745     return getCouldNotCompute();
8746 
8747   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
8748   if (!IV && AllowPredicates)
8749     // Try to make this an AddRec using runtime tests, in the first X
8750     // iterations of this loop, where X is the SCEV expression found by the
8751     // algorithm below.
8752     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
8753 
8754   // Avoid weird loops
8755   if (!IV || IV->getLoop() != L || !IV->isAffine())
8756     return getCouldNotCompute();
8757 
8758   bool NoWrap = ControlsExit &&
8759                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
8760 
8761   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
8762 
8763   // Avoid negative or zero stride values
8764   if (!isKnownPositive(Stride))
8765     return getCouldNotCompute();
8766 
8767   // Avoid proven overflow cases: this will ensure that the backedge taken count
8768   // will not generate any unsigned overflow. Relaxed no-overflow conditions
8769   // exploit NoWrapFlags, allowing to optimize in presence of undefined
8770   // behaviors like the case of C language.
8771   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
8772     return getCouldNotCompute();
8773 
8774   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
8775                                       : ICmpInst::ICMP_UGT;
8776 
8777   const SCEV *Start = IV->getStart();
8778   const SCEV *End = RHS;
8779   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
8780     End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
8781 
8782   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
8783 
8784   APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
8785                             : getUnsignedRange(Start).getUnsignedMax();
8786 
8787   APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
8788                              : getUnsignedRange(Stride).getUnsignedMin();
8789 
8790   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8791   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
8792                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
8793 
8794   // Although End can be a MIN expression we estimate MinEnd considering only
8795   // the case End = RHS. This is safe because in the other case (Start - End)
8796   // is zero, leading to a zero maximum backedge taken count.
8797   APInt MinEnd =
8798     IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
8799              : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
8800 
8801 
8802   const SCEV *MaxBECount = getCouldNotCompute();
8803   if (isa<SCEVConstant>(BECount))
8804     MaxBECount = BECount;
8805   else
8806     MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
8807                                 getConstant(MinStride), false);
8808 
8809   if (isa<SCEVCouldNotCompute>(MaxBECount))
8810     MaxBECount = BECount;
8811 
8812   return ExitLimit(BECount, MaxBECount, Predicates);
8813 }
8814 
8815 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
8816                                                     ScalarEvolution &SE) const {
8817   if (Range.isFullSet())  // Infinite loop.
8818     return SE.getCouldNotCompute();
8819 
8820   // If the start is a non-zero constant, shift the range to simplify things.
8821   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
8822     if (!SC->getValue()->isZero()) {
8823       SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
8824       Operands[0] = SE.getZero(SC->getType());
8825       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
8826                                              getNoWrapFlags(FlagNW));
8827       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
8828         return ShiftedAddRec->getNumIterationsInRange(
8829             Range.subtract(SC->getAPInt()), SE);
8830       // This is strange and shouldn't happen.
8831       return SE.getCouldNotCompute();
8832     }
8833 
8834   // The only time we can solve this is when we have all constant indices.
8835   // Otherwise, we cannot determine the overflow conditions.
8836   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
8837     return SE.getCouldNotCompute();
8838 
8839   // Okay at this point we know that all elements of the chrec are constants and
8840   // that the start element is zero.
8841 
8842   // First check to see if the range contains zero.  If not, the first
8843   // iteration exits.
8844   unsigned BitWidth = SE.getTypeSizeInBits(getType());
8845   if (!Range.contains(APInt(BitWidth, 0)))
8846     return SE.getZero(getType());
8847 
8848   if (isAffine()) {
8849     // If this is an affine expression then we have this situation:
8850     //   Solve {0,+,A} in Range  ===  Ax in Range
8851 
8852     // We know that zero is in the range.  If A is positive then we know that
8853     // the upper value of the range must be the first possible exit value.
8854     // If A is negative then the lower of the range is the last possible loop
8855     // value.  Also note that we already checked for a full range.
8856     APInt One(BitWidth,1);
8857     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
8858     APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
8859 
8860     // The exit value should be (End+A)/A.
8861     APInt ExitVal = (End + A).udiv(A);
8862     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
8863 
8864     // Evaluate at the exit value.  If we really did fall out of the valid
8865     // range, then we computed our trip count, otherwise wrap around or other
8866     // things must have happened.
8867     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
8868     if (Range.contains(Val->getValue()))
8869       return SE.getCouldNotCompute();  // Something strange happened
8870 
8871     // Ensure that the previous value is in the range.  This is a sanity check.
8872     assert(Range.contains(
8873            EvaluateConstantChrecAtConstant(this,
8874            ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
8875            "Linear scev computation is off in a bad way!");
8876     return SE.getConstant(ExitValue);
8877   } else if (isQuadratic()) {
8878     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
8879     // quadratic equation to solve it.  To do this, we must frame our problem in
8880     // terms of figuring out when zero is crossed, instead of when
8881     // Range.getUpper() is crossed.
8882     SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
8883     NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
8884     const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap);
8885 
8886     // Next, solve the constructed addrec
8887     if (auto Roots =
8888             SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) {
8889       const SCEVConstant *R1 = Roots->first;
8890       const SCEVConstant *R2 = Roots->second;
8891       // Pick the smallest positive root value.
8892       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
8893               ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
8894         if (!CB->getZExtValue())
8895           std::swap(R1, R2); // R1 is the minimum root now.
8896 
8897         // Make sure the root is not off by one.  The returned iteration should
8898         // not be in the range, but the previous one should be.  When solving
8899         // for "X*X < 5", for example, we should not return a root of 2.
8900         ConstantInt *R1Val =
8901             EvaluateConstantChrecAtConstant(this, R1->getValue(), SE);
8902         if (Range.contains(R1Val->getValue())) {
8903           // The next iteration must be out of the range...
8904           ConstantInt *NextVal =
8905               ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
8906 
8907           R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
8908           if (!Range.contains(R1Val->getValue()))
8909             return SE.getConstant(NextVal);
8910           return SE.getCouldNotCompute(); // Something strange happened
8911         }
8912 
8913         // If R1 was not in the range, then it is a good return value.  Make
8914         // sure that R1-1 WAS in the range though, just in case.
8915         ConstantInt *NextVal =
8916             ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
8917         R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
8918         if (Range.contains(R1Val->getValue()))
8919           return R1;
8920         return SE.getCouldNotCompute(); // Something strange happened
8921       }
8922     }
8923   }
8924 
8925   return SE.getCouldNotCompute();
8926 }
8927 
8928 namespace {
8929 struct FindUndefs {
8930   bool Found;
8931   FindUndefs() : Found(false) {}
8932 
8933   bool follow(const SCEV *S) {
8934     if (const SCEVUnknown *C = dyn_cast<SCEVUnknown>(S)) {
8935       if (isa<UndefValue>(C->getValue()))
8936         Found = true;
8937     } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
8938       if (isa<UndefValue>(C->getValue()))
8939         Found = true;
8940     }
8941 
8942     // Keep looking if we haven't found it yet.
8943     return !Found;
8944   }
8945   bool isDone() const {
8946     // Stop recursion if we have found an undef.
8947     return Found;
8948   }
8949 };
8950 }
8951 
8952 // Return true when S contains at least an undef value.
8953 static inline bool
8954 containsUndefs(const SCEV *S) {
8955   FindUndefs F;
8956   SCEVTraversal<FindUndefs> ST(F);
8957   ST.visitAll(S);
8958 
8959   return F.Found;
8960 }
8961 
8962 namespace {
8963 // Collect all steps of SCEV expressions.
8964 struct SCEVCollectStrides {
8965   ScalarEvolution &SE;
8966   SmallVectorImpl<const SCEV *> &Strides;
8967 
8968   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
8969       : SE(SE), Strides(S) {}
8970 
8971   bool follow(const SCEV *S) {
8972     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
8973       Strides.push_back(AR->getStepRecurrence(SE));
8974     return true;
8975   }
8976   bool isDone() const { return false; }
8977 };
8978 
8979 // Collect all SCEVUnknown and SCEVMulExpr expressions.
8980 struct SCEVCollectTerms {
8981   SmallVectorImpl<const SCEV *> &Terms;
8982 
8983   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
8984       : Terms(T) {}
8985 
8986   bool follow(const SCEV *S) {
8987     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
8988         isa<SCEVSignExtendExpr>(S)) {
8989       if (!containsUndefs(S))
8990         Terms.push_back(S);
8991 
8992       // Stop recursion: once we collected a term, do not walk its operands.
8993       return false;
8994     }
8995 
8996     // Keep looking.
8997     return true;
8998   }
8999   bool isDone() const { return false; }
9000 };
9001 
9002 // Check if a SCEV contains an AddRecExpr.
9003 struct SCEVHasAddRec {
9004   bool &ContainsAddRec;
9005 
9006   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
9007    ContainsAddRec = false;
9008   }
9009 
9010   bool follow(const SCEV *S) {
9011     if (isa<SCEVAddRecExpr>(S)) {
9012       ContainsAddRec = true;
9013 
9014       // Stop recursion: once we collected a term, do not walk its operands.
9015       return false;
9016     }
9017 
9018     // Keep looking.
9019     return true;
9020   }
9021   bool isDone() const { return false; }
9022 };
9023 
9024 // Find factors that are multiplied with an expression that (possibly as a
9025 // subexpression) contains an AddRecExpr. In the expression:
9026 //
9027 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
9028 //
9029 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
9030 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
9031 // parameters as they form a product with an induction variable.
9032 //
9033 // This collector expects all array size parameters to be in the same MulExpr.
9034 // It might be necessary to later add support for collecting parameters that are
9035 // spread over different nested MulExpr.
9036 struct SCEVCollectAddRecMultiplies {
9037   SmallVectorImpl<const SCEV *> &Terms;
9038   ScalarEvolution &SE;
9039 
9040   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
9041       : Terms(T), SE(SE) {}
9042 
9043   bool follow(const SCEV *S) {
9044     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
9045       bool HasAddRec = false;
9046       SmallVector<const SCEV *, 0> Operands;
9047       for (auto Op : Mul->operands()) {
9048         if (isa<SCEVUnknown>(Op)) {
9049           Operands.push_back(Op);
9050         } else {
9051           bool ContainsAddRec;
9052           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
9053           visitAll(Op, ContiansAddRec);
9054           HasAddRec |= ContainsAddRec;
9055         }
9056       }
9057       if (Operands.size() == 0)
9058         return true;
9059 
9060       if (!HasAddRec)
9061         return false;
9062 
9063       Terms.push_back(SE.getMulExpr(Operands));
9064       // Stop recursion: once we collected a term, do not walk its operands.
9065       return false;
9066     }
9067 
9068     // Keep looking.
9069     return true;
9070   }
9071   bool isDone() const { return false; }
9072 };
9073 }
9074 
9075 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
9076 /// two places:
9077 ///   1) The strides of AddRec expressions.
9078 ///   2) Unknowns that are multiplied with AddRec expressions.
9079 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
9080     SmallVectorImpl<const SCEV *> &Terms) {
9081   SmallVector<const SCEV *, 4> Strides;
9082   SCEVCollectStrides StrideCollector(*this, Strides);
9083   visitAll(Expr, StrideCollector);
9084 
9085   DEBUG({
9086       dbgs() << "Strides:\n";
9087       for (const SCEV *S : Strides)
9088         dbgs() << *S << "\n";
9089     });
9090 
9091   for (const SCEV *S : Strides) {
9092     SCEVCollectTerms TermCollector(Terms);
9093     visitAll(S, TermCollector);
9094   }
9095 
9096   DEBUG({
9097       dbgs() << "Terms:\n";
9098       for (const SCEV *T : Terms)
9099         dbgs() << *T << "\n";
9100     });
9101 
9102   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
9103   visitAll(Expr, MulCollector);
9104 }
9105 
9106 static bool findArrayDimensionsRec(ScalarEvolution &SE,
9107                                    SmallVectorImpl<const SCEV *> &Terms,
9108                                    SmallVectorImpl<const SCEV *> &Sizes) {
9109   int Last = Terms.size() - 1;
9110   const SCEV *Step = Terms[Last];
9111 
9112   // End of recursion.
9113   if (Last == 0) {
9114     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
9115       SmallVector<const SCEV *, 2> Qs;
9116       for (const SCEV *Op : M->operands())
9117         if (!isa<SCEVConstant>(Op))
9118           Qs.push_back(Op);
9119 
9120       Step = SE.getMulExpr(Qs);
9121     }
9122 
9123     Sizes.push_back(Step);
9124     return true;
9125   }
9126 
9127   for (const SCEV *&Term : Terms) {
9128     // Normalize the terms before the next call to findArrayDimensionsRec.
9129     const SCEV *Q, *R;
9130     SCEVDivision::divide(SE, Term, Step, &Q, &R);
9131 
9132     // Bail out when GCD does not evenly divide one of the terms.
9133     if (!R->isZero())
9134       return false;
9135 
9136     Term = Q;
9137   }
9138 
9139   // Remove all SCEVConstants.
9140   Terms.erase(
9141       remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
9142       Terms.end());
9143 
9144   if (Terms.size() > 0)
9145     if (!findArrayDimensionsRec(SE, Terms, Sizes))
9146       return false;
9147 
9148   Sizes.push_back(Step);
9149   return true;
9150 }
9151 
9152 // Returns true when S contains at least a SCEVUnknown parameter.
9153 static inline bool
9154 containsParameters(const SCEV *S) {
9155   struct FindParameter {
9156     bool FoundParameter;
9157     FindParameter() : FoundParameter(false) {}
9158 
9159     bool follow(const SCEV *S) {
9160       if (isa<SCEVUnknown>(S)) {
9161         FoundParameter = true;
9162         // Stop recursion: we found a parameter.
9163         return false;
9164       }
9165       // Keep looking.
9166       return true;
9167     }
9168     bool isDone() const {
9169       // Stop recursion if we have found a parameter.
9170       return FoundParameter;
9171     }
9172   };
9173 
9174   FindParameter F;
9175   SCEVTraversal<FindParameter> ST(F);
9176   ST.visitAll(S);
9177 
9178   return F.FoundParameter;
9179 }
9180 
9181 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
9182 static inline bool
9183 containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
9184   for (const SCEV *T : Terms)
9185     if (containsParameters(T))
9186       return true;
9187   return false;
9188 }
9189 
9190 // Return the number of product terms in S.
9191 static inline int numberOfTerms(const SCEV *S) {
9192   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
9193     return Expr->getNumOperands();
9194   return 1;
9195 }
9196 
9197 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
9198   if (isa<SCEVConstant>(T))
9199     return nullptr;
9200 
9201   if (isa<SCEVUnknown>(T))
9202     return T;
9203 
9204   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
9205     SmallVector<const SCEV *, 2> Factors;
9206     for (const SCEV *Op : M->operands())
9207       if (!isa<SCEVConstant>(Op))
9208         Factors.push_back(Op);
9209 
9210     return SE.getMulExpr(Factors);
9211   }
9212 
9213   return T;
9214 }
9215 
9216 /// Return the size of an element read or written by Inst.
9217 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
9218   Type *Ty;
9219   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
9220     Ty = Store->getValueOperand()->getType();
9221   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
9222     Ty = Load->getType();
9223   else
9224     return nullptr;
9225 
9226   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
9227   return getSizeOfExpr(ETy, Ty);
9228 }
9229 
9230 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
9231                                           SmallVectorImpl<const SCEV *> &Sizes,
9232                                           const SCEV *ElementSize) const {
9233   if (Terms.size() < 1 || !ElementSize)
9234     return;
9235 
9236   // Early return when Terms do not contain parameters: we do not delinearize
9237   // non parametric SCEVs.
9238   if (!containsParameters(Terms))
9239     return;
9240 
9241   DEBUG({
9242       dbgs() << "Terms:\n";
9243       for (const SCEV *T : Terms)
9244         dbgs() << *T << "\n";
9245     });
9246 
9247   // Remove duplicates.
9248   std::sort(Terms.begin(), Terms.end());
9249   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
9250 
9251   // Put larger terms first.
9252   std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
9253     return numberOfTerms(LHS) > numberOfTerms(RHS);
9254   });
9255 
9256   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9257 
9258   // Try to divide all terms by the element size. If term is not divisible by
9259   // element size, proceed with the original term.
9260   for (const SCEV *&Term : Terms) {
9261     const SCEV *Q, *R;
9262     SCEVDivision::divide(SE, Term, ElementSize, &Q, &R);
9263     if (!Q->isZero())
9264       Term = Q;
9265   }
9266 
9267   SmallVector<const SCEV *, 4> NewTerms;
9268 
9269   // Remove constant factors.
9270   for (const SCEV *T : Terms)
9271     if (const SCEV *NewT = removeConstantFactors(SE, T))
9272       NewTerms.push_back(NewT);
9273 
9274   DEBUG({
9275       dbgs() << "Terms after sorting:\n";
9276       for (const SCEV *T : NewTerms)
9277         dbgs() << *T << "\n";
9278     });
9279 
9280   if (NewTerms.empty() ||
9281       !findArrayDimensionsRec(SE, NewTerms, Sizes)) {
9282     Sizes.clear();
9283     return;
9284   }
9285 
9286   // The last element to be pushed into Sizes is the size of an element.
9287   Sizes.push_back(ElementSize);
9288 
9289   DEBUG({
9290       dbgs() << "Sizes:\n";
9291       for (const SCEV *S : Sizes)
9292         dbgs() << *S << "\n";
9293     });
9294 }
9295 
9296 void ScalarEvolution::computeAccessFunctions(
9297     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
9298     SmallVectorImpl<const SCEV *> &Sizes) {
9299 
9300   // Early exit in case this SCEV is not an affine multivariate function.
9301   if (Sizes.empty())
9302     return;
9303 
9304   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
9305     if (!AR->isAffine())
9306       return;
9307 
9308   const SCEV *Res = Expr;
9309   int Last = Sizes.size() - 1;
9310   for (int i = Last; i >= 0; i--) {
9311     const SCEV *Q, *R;
9312     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
9313 
9314     DEBUG({
9315         dbgs() << "Res: " << *Res << "\n";
9316         dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
9317         dbgs() << "Res divided by Sizes[i]:\n";
9318         dbgs() << "Quotient: " << *Q << "\n";
9319         dbgs() << "Remainder: " << *R << "\n";
9320       });
9321 
9322     Res = Q;
9323 
9324     // Do not record the last subscript corresponding to the size of elements in
9325     // the array.
9326     if (i == Last) {
9327 
9328       // Bail out if the remainder is too complex.
9329       if (isa<SCEVAddRecExpr>(R)) {
9330         Subscripts.clear();
9331         Sizes.clear();
9332         return;
9333       }
9334 
9335       continue;
9336     }
9337 
9338     // Record the access function for the current subscript.
9339     Subscripts.push_back(R);
9340   }
9341 
9342   // Also push in last position the remainder of the last division: it will be
9343   // the access function of the innermost dimension.
9344   Subscripts.push_back(Res);
9345 
9346   std::reverse(Subscripts.begin(), Subscripts.end());
9347 
9348   DEBUG({
9349       dbgs() << "Subscripts:\n";
9350       for (const SCEV *S : Subscripts)
9351         dbgs() << *S << "\n";
9352     });
9353 }
9354 
9355 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
9356 /// sizes of an array access. Returns the remainder of the delinearization that
9357 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
9358 /// the multiples of SCEV coefficients: that is a pattern matching of sub
9359 /// expressions in the stride and base of a SCEV corresponding to the
9360 /// computation of a GCD (greatest common divisor) of base and stride.  When
9361 /// SCEV->delinearize fails, it returns the SCEV unchanged.
9362 ///
9363 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
9364 ///
9365 ///  void foo(long n, long m, long o, double A[n][m][o]) {
9366 ///
9367 ///    for (long i = 0; i < n; i++)
9368 ///      for (long j = 0; j < m; j++)
9369 ///        for (long k = 0; k < o; k++)
9370 ///          A[i][j][k] = 1.0;
9371 ///  }
9372 ///
9373 /// the delinearization input is the following AddRec SCEV:
9374 ///
9375 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
9376 ///
9377 /// From this SCEV, we are able to say that the base offset of the access is %A
9378 /// because it appears as an offset that does not divide any of the strides in
9379 /// the loops:
9380 ///
9381 ///  CHECK: Base offset: %A
9382 ///
9383 /// and then SCEV->delinearize determines the size of some of the dimensions of
9384 /// the array as these are the multiples by which the strides are happening:
9385 ///
9386 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
9387 ///
9388 /// Note that the outermost dimension remains of UnknownSize because there are
9389 /// no strides that would help identifying the size of the last dimension: when
9390 /// the array has been statically allocated, one could compute the size of that
9391 /// dimension by dividing the overall size of the array by the size of the known
9392 /// dimensions: %m * %o * 8.
9393 ///
9394 /// Finally delinearize provides the access functions for the array reference
9395 /// that does correspond to A[i][j][k] of the above C testcase:
9396 ///
9397 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
9398 ///
9399 /// The testcases are checking the output of a function pass:
9400 /// DelinearizationPass that walks through all loads and stores of a function
9401 /// asking for the SCEV of the memory access with respect to all enclosing
9402 /// loops, calling SCEV->delinearize on that and printing the results.
9403 
9404 void ScalarEvolution::delinearize(const SCEV *Expr,
9405                                  SmallVectorImpl<const SCEV *> &Subscripts,
9406                                  SmallVectorImpl<const SCEV *> &Sizes,
9407                                  const SCEV *ElementSize) {
9408   // First step: collect parametric terms.
9409   SmallVector<const SCEV *, 4> Terms;
9410   collectParametricTerms(Expr, Terms);
9411 
9412   if (Terms.empty())
9413     return;
9414 
9415   // Second step: find subscript sizes.
9416   findArrayDimensions(Terms, Sizes, ElementSize);
9417 
9418   if (Sizes.empty())
9419     return;
9420 
9421   // Third step: compute the access functions for each subscript.
9422   computeAccessFunctions(Expr, Subscripts, Sizes);
9423 
9424   if (Subscripts.empty())
9425     return;
9426 
9427   DEBUG({
9428       dbgs() << "succeeded to delinearize " << *Expr << "\n";
9429       dbgs() << "ArrayDecl[UnknownSize]";
9430       for (const SCEV *S : Sizes)
9431         dbgs() << "[" << *S << "]";
9432 
9433       dbgs() << "\nArrayRef";
9434       for (const SCEV *S : Subscripts)
9435         dbgs() << "[" << *S << "]";
9436       dbgs() << "\n";
9437     });
9438 }
9439 
9440 //===----------------------------------------------------------------------===//
9441 //                   SCEVCallbackVH Class Implementation
9442 //===----------------------------------------------------------------------===//
9443 
9444 void ScalarEvolution::SCEVCallbackVH::deleted() {
9445   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
9446   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
9447     SE->ConstantEvolutionLoopExitValue.erase(PN);
9448   SE->eraseValueFromMap(getValPtr());
9449   // this now dangles!
9450 }
9451 
9452 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
9453   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
9454 
9455   // Forget all the expressions associated with users of the old value,
9456   // so that future queries will recompute the expressions using the new
9457   // value.
9458   Value *Old = getValPtr();
9459   SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
9460   SmallPtrSet<User *, 8> Visited;
9461   while (!Worklist.empty()) {
9462     User *U = Worklist.pop_back_val();
9463     // Deleting the Old value will cause this to dangle. Postpone
9464     // that until everything else is done.
9465     if (U == Old)
9466       continue;
9467     if (!Visited.insert(U).second)
9468       continue;
9469     if (PHINode *PN = dyn_cast<PHINode>(U))
9470       SE->ConstantEvolutionLoopExitValue.erase(PN);
9471     SE->eraseValueFromMap(U);
9472     Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
9473   }
9474   // Delete the Old value.
9475   if (PHINode *PN = dyn_cast<PHINode>(Old))
9476     SE->ConstantEvolutionLoopExitValue.erase(PN);
9477   SE->eraseValueFromMap(Old);
9478   // this now dangles!
9479 }
9480 
9481 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
9482   : CallbackVH(V), SE(se) {}
9483 
9484 //===----------------------------------------------------------------------===//
9485 //                   ScalarEvolution Class Implementation
9486 //===----------------------------------------------------------------------===//
9487 
9488 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
9489                                  AssumptionCache &AC, DominatorTree &DT,
9490                                  LoopInfo &LI)
9491     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
9492       CouldNotCompute(new SCEVCouldNotCompute()),
9493       WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9494       ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64),
9495       FirstUnknown(nullptr) {
9496 
9497   // To use guards for proving predicates, we need to scan every instruction in
9498   // relevant basic blocks, and not just terminators.  Doing this is a waste of
9499   // time if the IR does not actually contain any calls to
9500   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
9501   //
9502   // This pessimizes the case where a pass that preserves ScalarEvolution wants
9503   // to _add_ guards to the module when there weren't any before, and wants
9504   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
9505   // efficient in lieu of being smart in that rather obscure case.
9506 
9507   auto *GuardDecl = F.getParent()->getFunction(
9508       Intrinsic::getName(Intrinsic::experimental_guard));
9509   HasGuards = GuardDecl && !GuardDecl->use_empty();
9510 }
9511 
9512 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
9513     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
9514       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
9515       ValueExprMap(std::move(Arg.ValueExprMap)),
9516       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
9517       WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9518       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
9519       PredicatedBackedgeTakenCounts(
9520           std::move(Arg.PredicatedBackedgeTakenCounts)),
9521       ConstantEvolutionLoopExitValue(
9522           std::move(Arg.ConstantEvolutionLoopExitValue)),
9523       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
9524       LoopDispositions(std::move(Arg.LoopDispositions)),
9525       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
9526       BlockDispositions(std::move(Arg.BlockDispositions)),
9527       UnsignedRanges(std::move(Arg.UnsignedRanges)),
9528       SignedRanges(std::move(Arg.SignedRanges)),
9529       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
9530       UniquePreds(std::move(Arg.UniquePreds)),
9531       SCEVAllocator(std::move(Arg.SCEVAllocator)),
9532       FirstUnknown(Arg.FirstUnknown) {
9533   Arg.FirstUnknown = nullptr;
9534 }
9535 
9536 ScalarEvolution::~ScalarEvolution() {
9537   // Iterate through all the SCEVUnknown instances and call their
9538   // destructors, so that they release their references to their values.
9539   for (SCEVUnknown *U = FirstUnknown; U;) {
9540     SCEVUnknown *Tmp = U;
9541     U = U->Next;
9542     Tmp->~SCEVUnknown();
9543   }
9544   FirstUnknown = nullptr;
9545 
9546   ExprValueMap.clear();
9547   ValueExprMap.clear();
9548   HasRecMap.clear();
9549 
9550   // Free any extra memory created for ExitNotTakenInfo in the unlikely event
9551   // that a loop had multiple computable exits.
9552   for (auto &BTCI : BackedgeTakenCounts)
9553     BTCI.second.clear();
9554   for (auto &BTCI : PredicatedBackedgeTakenCounts)
9555     BTCI.second.clear();
9556 
9557   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
9558   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
9559   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
9560 }
9561 
9562 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
9563   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
9564 }
9565 
9566 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
9567                           const Loop *L) {
9568   // Print all inner loops first
9569   for (Loop *I : *L)
9570     PrintLoopInfo(OS, SE, I);
9571 
9572   OS << "Loop ";
9573   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9574   OS << ": ";
9575 
9576   SmallVector<BasicBlock *, 8> ExitBlocks;
9577   L->getExitBlocks(ExitBlocks);
9578   if (ExitBlocks.size() != 1)
9579     OS << "<multiple exits> ";
9580 
9581   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
9582     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
9583   } else {
9584     OS << "Unpredictable backedge-taken count. ";
9585   }
9586 
9587   OS << "\n"
9588         "Loop ";
9589   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9590   OS << ": ";
9591 
9592   if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
9593     OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
9594   } else {
9595     OS << "Unpredictable max backedge-taken count. ";
9596   }
9597 
9598   OS << "\n"
9599         "Loop ";
9600   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9601   OS << ": ";
9602 
9603   SCEVUnionPredicate Pred;
9604   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
9605   if (!isa<SCEVCouldNotCompute>(PBT)) {
9606     OS << "Predicated backedge-taken count is " << *PBT << "\n";
9607     OS << " Predicates:\n";
9608     Pred.print(OS, 4);
9609   } else {
9610     OS << "Unpredictable predicated backedge-taken count. ";
9611   }
9612   OS << "\n";
9613 }
9614 
9615 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
9616   switch (LD) {
9617   case ScalarEvolution::LoopVariant:
9618     return "Variant";
9619   case ScalarEvolution::LoopInvariant:
9620     return "Invariant";
9621   case ScalarEvolution::LoopComputable:
9622     return "Computable";
9623   }
9624   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
9625 }
9626 
9627 void ScalarEvolution::print(raw_ostream &OS) const {
9628   // ScalarEvolution's implementation of the print method is to print
9629   // out SCEV values of all instructions that are interesting. Doing
9630   // this potentially causes it to create new SCEV objects though,
9631   // which technically conflicts with the const qualifier. This isn't
9632   // observable from outside the class though, so casting away the
9633   // const isn't dangerous.
9634   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9635 
9636   OS << "Classifying expressions for: ";
9637   F.printAsOperand(OS, /*PrintType=*/false);
9638   OS << "\n";
9639   for (Instruction &I : instructions(F))
9640     if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
9641       OS << I << '\n';
9642       OS << "  -->  ";
9643       const SCEV *SV = SE.getSCEV(&I);
9644       SV->print(OS);
9645       if (!isa<SCEVCouldNotCompute>(SV)) {
9646         OS << " U: ";
9647         SE.getUnsignedRange(SV).print(OS);
9648         OS << " S: ";
9649         SE.getSignedRange(SV).print(OS);
9650       }
9651 
9652       const Loop *L = LI.getLoopFor(I.getParent());
9653 
9654       const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
9655       if (AtUse != SV) {
9656         OS << "  -->  ";
9657         AtUse->print(OS);
9658         if (!isa<SCEVCouldNotCompute>(AtUse)) {
9659           OS << " U: ";
9660           SE.getUnsignedRange(AtUse).print(OS);
9661           OS << " S: ";
9662           SE.getSignedRange(AtUse).print(OS);
9663         }
9664       }
9665 
9666       if (L) {
9667         OS << "\t\t" "Exits: ";
9668         const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
9669         if (!SE.isLoopInvariant(ExitValue, L)) {
9670           OS << "<<Unknown>>";
9671         } else {
9672           OS << *ExitValue;
9673         }
9674 
9675         bool First = true;
9676         for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
9677           if (First) {
9678             OS << "\t\t" "LoopDispositions: { ";
9679             First = false;
9680           } else {
9681             OS << ", ";
9682           }
9683 
9684           Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9685           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
9686         }
9687 
9688         for (auto *InnerL : depth_first(L)) {
9689           if (InnerL == L)
9690             continue;
9691           if (First) {
9692             OS << "\t\t" "LoopDispositions: { ";
9693             First = false;
9694           } else {
9695             OS << ", ";
9696           }
9697 
9698           InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9699           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
9700         }
9701 
9702         OS << " }";
9703       }
9704 
9705       OS << "\n";
9706     }
9707 
9708   OS << "Determining loop execution counts for: ";
9709   F.printAsOperand(OS, /*PrintType=*/false);
9710   OS << "\n";
9711   for (Loop *I : LI)
9712     PrintLoopInfo(OS, &SE, I);
9713 }
9714 
9715 ScalarEvolution::LoopDisposition
9716 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
9717   auto &Values = LoopDispositions[S];
9718   for (auto &V : Values) {
9719     if (V.getPointer() == L)
9720       return V.getInt();
9721   }
9722   Values.emplace_back(L, LoopVariant);
9723   LoopDisposition D = computeLoopDisposition(S, L);
9724   auto &Values2 = LoopDispositions[S];
9725   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9726     if (V.getPointer() == L) {
9727       V.setInt(D);
9728       break;
9729     }
9730   }
9731   return D;
9732 }
9733 
9734 ScalarEvolution::LoopDisposition
9735 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
9736   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
9737   case scConstant:
9738     return LoopInvariant;
9739   case scTruncate:
9740   case scZeroExtend:
9741   case scSignExtend:
9742     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
9743   case scAddRecExpr: {
9744     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
9745 
9746     // If L is the addrec's loop, it's computable.
9747     if (AR->getLoop() == L)
9748       return LoopComputable;
9749 
9750     // Add recurrences are never invariant in the function-body (null loop).
9751     if (!L)
9752       return LoopVariant;
9753 
9754     // This recurrence is variant w.r.t. L if L contains AR's loop.
9755     if (L->contains(AR->getLoop()))
9756       return LoopVariant;
9757 
9758     // This recurrence is invariant w.r.t. L if AR's loop contains L.
9759     if (AR->getLoop()->contains(L))
9760       return LoopInvariant;
9761 
9762     // This recurrence is variant w.r.t. L if any of its operands
9763     // are variant.
9764     for (auto *Op : AR->operands())
9765       if (!isLoopInvariant(Op, L))
9766         return LoopVariant;
9767 
9768     // Otherwise it's loop-invariant.
9769     return LoopInvariant;
9770   }
9771   case scAddExpr:
9772   case scMulExpr:
9773   case scUMaxExpr:
9774   case scSMaxExpr: {
9775     bool HasVarying = false;
9776     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
9777       LoopDisposition D = getLoopDisposition(Op, L);
9778       if (D == LoopVariant)
9779         return LoopVariant;
9780       if (D == LoopComputable)
9781         HasVarying = true;
9782     }
9783     return HasVarying ? LoopComputable : LoopInvariant;
9784   }
9785   case scUDivExpr: {
9786     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
9787     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
9788     if (LD == LoopVariant)
9789       return LoopVariant;
9790     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
9791     if (RD == LoopVariant)
9792       return LoopVariant;
9793     return (LD == LoopInvariant && RD == LoopInvariant) ?
9794            LoopInvariant : LoopComputable;
9795   }
9796   case scUnknown:
9797     // All non-instruction values are loop invariant.  All instructions are loop
9798     // invariant if they are not contained in the specified loop.
9799     // Instructions are never considered invariant in the function body
9800     // (null loop) because they are defined within the "loop".
9801     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
9802       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
9803     return LoopInvariant;
9804   case scCouldNotCompute:
9805     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
9806   }
9807   llvm_unreachable("Unknown SCEV kind!");
9808 }
9809 
9810 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
9811   return getLoopDisposition(S, L) == LoopInvariant;
9812 }
9813 
9814 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
9815   return getLoopDisposition(S, L) == LoopComputable;
9816 }
9817 
9818 ScalarEvolution::BlockDisposition
9819 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
9820   auto &Values = BlockDispositions[S];
9821   for (auto &V : Values) {
9822     if (V.getPointer() == BB)
9823       return V.getInt();
9824   }
9825   Values.emplace_back(BB, DoesNotDominateBlock);
9826   BlockDisposition D = computeBlockDisposition(S, BB);
9827   auto &Values2 = BlockDispositions[S];
9828   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9829     if (V.getPointer() == BB) {
9830       V.setInt(D);
9831       break;
9832     }
9833   }
9834   return D;
9835 }
9836 
9837 ScalarEvolution::BlockDisposition
9838 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
9839   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
9840   case scConstant:
9841     return ProperlyDominatesBlock;
9842   case scTruncate:
9843   case scZeroExtend:
9844   case scSignExtend:
9845     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
9846   case scAddRecExpr: {
9847     // This uses a "dominates" query instead of "properly dominates" query
9848     // to test for proper dominance too, because the instruction which
9849     // produces the addrec's value is a PHI, and a PHI effectively properly
9850     // dominates its entire containing block.
9851     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
9852     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
9853       return DoesNotDominateBlock;
9854 
9855     // Fall through into SCEVNAryExpr handling.
9856     LLVM_FALLTHROUGH;
9857   }
9858   case scAddExpr:
9859   case scMulExpr:
9860   case scUMaxExpr:
9861   case scSMaxExpr: {
9862     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
9863     bool Proper = true;
9864     for (const SCEV *NAryOp : NAry->operands()) {
9865       BlockDisposition D = getBlockDisposition(NAryOp, BB);
9866       if (D == DoesNotDominateBlock)
9867         return DoesNotDominateBlock;
9868       if (D == DominatesBlock)
9869         Proper = false;
9870     }
9871     return Proper ? ProperlyDominatesBlock : DominatesBlock;
9872   }
9873   case scUDivExpr: {
9874     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
9875     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
9876     BlockDisposition LD = getBlockDisposition(LHS, BB);
9877     if (LD == DoesNotDominateBlock)
9878       return DoesNotDominateBlock;
9879     BlockDisposition RD = getBlockDisposition(RHS, BB);
9880     if (RD == DoesNotDominateBlock)
9881       return DoesNotDominateBlock;
9882     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
9883       ProperlyDominatesBlock : DominatesBlock;
9884   }
9885   case scUnknown:
9886     if (Instruction *I =
9887           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
9888       if (I->getParent() == BB)
9889         return DominatesBlock;
9890       if (DT.properlyDominates(I->getParent(), BB))
9891         return ProperlyDominatesBlock;
9892       return DoesNotDominateBlock;
9893     }
9894     return ProperlyDominatesBlock;
9895   case scCouldNotCompute:
9896     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
9897   }
9898   llvm_unreachable("Unknown SCEV kind!");
9899 }
9900 
9901 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
9902   return getBlockDisposition(S, BB) >= DominatesBlock;
9903 }
9904 
9905 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
9906   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
9907 }
9908 
9909 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
9910   // Search for a SCEV expression node within an expression tree.
9911   // Implements SCEVTraversal::Visitor.
9912   struct SCEVSearch {
9913     const SCEV *Node;
9914     bool IsFound;
9915 
9916     SCEVSearch(const SCEV *N): Node(N), IsFound(false) {}
9917 
9918     bool follow(const SCEV *S) {
9919       IsFound |= (S == Node);
9920       return !IsFound;
9921     }
9922     bool isDone() const { return IsFound; }
9923   };
9924 
9925   SCEVSearch Search(Op);
9926   visitAll(S, Search);
9927   return Search.IsFound;
9928 }
9929 
9930 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
9931   ValuesAtScopes.erase(S);
9932   LoopDispositions.erase(S);
9933   BlockDispositions.erase(S);
9934   UnsignedRanges.erase(S);
9935   SignedRanges.erase(S);
9936   ExprValueMap.erase(S);
9937   HasRecMap.erase(S);
9938 
9939   auto RemoveSCEVFromBackedgeMap =
9940       [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
9941         for (auto I = Map.begin(), E = Map.end(); I != E;) {
9942           BackedgeTakenInfo &BEInfo = I->second;
9943           if (BEInfo.hasOperand(S, this)) {
9944             BEInfo.clear();
9945             Map.erase(I++);
9946           } else
9947             ++I;
9948         }
9949       };
9950 
9951   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
9952   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
9953 }
9954 
9955 typedef DenseMap<const Loop *, std::string> VerifyMap;
9956 
9957 /// replaceSubString - Replaces all occurrences of From in Str with To.
9958 static void replaceSubString(std::string &Str, StringRef From, StringRef To) {
9959   size_t Pos = 0;
9960   while ((Pos = Str.find(From, Pos)) != std::string::npos) {
9961     Str.replace(Pos, From.size(), To.data(), To.size());
9962     Pos += To.size();
9963   }
9964 }
9965 
9966 /// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis.
9967 static void
9968 getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) {
9969   std::string &S = Map[L];
9970   if (S.empty()) {
9971     raw_string_ostream OS(S);
9972     SE.getBackedgeTakenCount(L)->print(OS);
9973 
9974     // false and 0 are semantically equivalent. This can happen in dead loops.
9975     replaceSubString(OS.str(), "false", "0");
9976     // Remove wrap flags, their use in SCEV is highly fragile.
9977     // FIXME: Remove this when SCEV gets smarter about them.
9978     replaceSubString(OS.str(), "<nw>", "");
9979     replaceSubString(OS.str(), "<nsw>", "");
9980     replaceSubString(OS.str(), "<nuw>", "");
9981   }
9982 
9983   for (auto *R : reverse(*L))
9984     getLoopBackedgeTakenCounts(R, Map, SE); // recurse.
9985 }
9986 
9987 void ScalarEvolution::verify() const {
9988   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9989 
9990   // Gather stringified backedge taken counts for all loops using SCEV's caches.
9991   // FIXME: It would be much better to store actual values instead of strings,
9992   //        but SCEV pointers will change if we drop the caches.
9993   VerifyMap BackedgeDumpsOld, BackedgeDumpsNew;
9994   for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
9995     getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE);
9996 
9997   // Gather stringified backedge taken counts for all loops using a fresh
9998   // ScalarEvolution object.
9999   ScalarEvolution SE2(F, TLI, AC, DT, LI);
10000   for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
10001     getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2);
10002 
10003   // Now compare whether they're the same with and without caches. This allows
10004   // verifying that no pass changed the cache.
10005   assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() &&
10006          "New loops suddenly appeared!");
10007 
10008   for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(),
10009                            OldE = BackedgeDumpsOld.end(),
10010                            NewI = BackedgeDumpsNew.begin();
10011        OldI != OldE; ++OldI, ++NewI) {
10012     assert(OldI->first == NewI->first && "Loop order changed!");
10013 
10014     // Compare the stringified SCEVs. We don't care if undef backedgetaken count
10015     // changes.
10016     // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This
10017     // means that a pass is buggy or SCEV has to learn a new pattern but is
10018     // usually not harmful.
10019     if (OldI->second != NewI->second &&
10020         OldI->second.find("undef") == std::string::npos &&
10021         NewI->second.find("undef") == std::string::npos &&
10022         OldI->second != "***COULDNOTCOMPUTE***" &&
10023         NewI->second != "***COULDNOTCOMPUTE***") {
10024       dbgs() << "SCEVValidator: SCEV for loop '"
10025              << OldI->first->getHeader()->getName()
10026              << "' changed from '" << OldI->second
10027              << "' to '" << NewI->second << "'!\n";
10028       std::abort();
10029     }
10030   }
10031 
10032   // TODO: Verify more things.
10033 }
10034 
10035 char ScalarEvolutionAnalysis::PassID;
10036 
10037 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
10038                                              FunctionAnalysisManager &AM) {
10039   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
10040                          AM.getResult<AssumptionAnalysis>(F),
10041                          AM.getResult<DominatorTreeAnalysis>(F),
10042                          AM.getResult<LoopAnalysis>(F));
10043 }
10044 
10045 PreservedAnalyses
10046 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
10047   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
10048   return PreservedAnalyses::all();
10049 }
10050 
10051 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
10052                       "Scalar Evolution Analysis", false, true)
10053 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10054 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
10055 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
10056 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
10057 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
10058                     "Scalar Evolution Analysis", false, true)
10059 char ScalarEvolutionWrapperPass::ID = 0;
10060 
10061 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
10062   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
10063 }
10064 
10065 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
10066   SE.reset(new ScalarEvolution(
10067       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
10068       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
10069       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
10070       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
10071   return false;
10072 }
10073 
10074 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
10075 
10076 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
10077   SE->print(OS);
10078 }
10079 
10080 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
10081   if (!VerifySCEV)
10082     return;
10083 
10084   SE->verify();
10085 }
10086 
10087 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
10088   AU.setPreservesAll();
10089   AU.addRequiredTransitive<AssumptionCacheTracker>();
10090   AU.addRequiredTransitive<LoopInfoWrapperPass>();
10091   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
10092   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
10093 }
10094 
10095 const SCEVPredicate *
10096 ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS,
10097                                    const SCEVConstant *RHS) {
10098   FoldingSetNodeID ID;
10099   // Unique this node based on the arguments
10100   ID.AddInteger(SCEVPredicate::P_Equal);
10101   ID.AddPointer(LHS);
10102   ID.AddPointer(RHS);
10103   void *IP = nullptr;
10104   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10105     return S;
10106   SCEVEqualPredicate *Eq = new (SCEVAllocator)
10107       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
10108   UniquePreds.InsertNode(Eq, IP);
10109   return Eq;
10110 }
10111 
10112 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
10113     const SCEVAddRecExpr *AR,
10114     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10115   FoldingSetNodeID ID;
10116   // Unique this node based on the arguments
10117   ID.AddInteger(SCEVPredicate::P_Wrap);
10118   ID.AddPointer(AR);
10119   ID.AddInteger(AddedFlags);
10120   void *IP = nullptr;
10121   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10122     return S;
10123   auto *OF = new (SCEVAllocator)
10124       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
10125   UniquePreds.InsertNode(OF, IP);
10126   return OF;
10127 }
10128 
10129 namespace {
10130 
10131 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
10132 public:
10133   /// Rewrites \p S in the context of a loop L and the SCEV predication
10134   /// infrastructure.
10135   ///
10136   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
10137   /// equivalences present in \p Pred.
10138   ///
10139   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
10140   /// \p NewPreds such that the result will be an AddRecExpr.
10141   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
10142                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10143                              SCEVUnionPredicate *Pred) {
10144     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
10145     return Rewriter.visit(S);
10146   }
10147 
10148   SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
10149                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10150                         SCEVUnionPredicate *Pred)
10151       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
10152 
10153   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
10154     if (Pred) {
10155       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
10156       for (auto *Pred : ExprPreds)
10157         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
10158           if (IPred->getLHS() == Expr)
10159             return IPred->getRHS();
10160     }
10161 
10162     return Expr;
10163   }
10164 
10165   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
10166     const SCEV *Operand = visit(Expr->getOperand());
10167     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
10168     if (AR && AR->getLoop() == L && AR->isAffine()) {
10169       // This couldn't be folded because the operand didn't have the nuw
10170       // flag. Add the nusw flag as an assumption that we could make.
10171       const SCEV *Step = AR->getStepRecurrence(SE);
10172       Type *Ty = Expr->getType();
10173       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
10174         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
10175                                 SE.getSignExtendExpr(Step, Ty), L,
10176                                 AR->getNoWrapFlags());
10177     }
10178     return SE.getZeroExtendExpr(Operand, Expr->getType());
10179   }
10180 
10181   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
10182     const SCEV *Operand = visit(Expr->getOperand());
10183     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
10184     if (AR && AR->getLoop() == L && AR->isAffine()) {
10185       // This couldn't be folded because the operand didn't have the nsw
10186       // flag. Add the nssw flag as an assumption that we could make.
10187       const SCEV *Step = AR->getStepRecurrence(SE);
10188       Type *Ty = Expr->getType();
10189       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
10190         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
10191                                 SE.getSignExtendExpr(Step, Ty), L,
10192                                 AR->getNoWrapFlags());
10193     }
10194     return SE.getSignExtendExpr(Operand, Expr->getType());
10195   }
10196 
10197 private:
10198   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
10199                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10200     auto *A = SE.getWrapPredicate(AR, AddedFlags);
10201     if (!NewPreds) {
10202       // Check if we've already made this assumption.
10203       return Pred && Pred->implies(A);
10204     }
10205     NewPreds->insert(A);
10206     return true;
10207   }
10208 
10209   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
10210   SCEVUnionPredicate *Pred;
10211   const Loop *L;
10212 };
10213 } // end anonymous namespace
10214 
10215 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
10216                                                    SCEVUnionPredicate &Preds) {
10217   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
10218 }
10219 
10220 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
10221     const SCEV *S, const Loop *L,
10222     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
10223 
10224   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
10225   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
10226   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
10227 
10228   if (!AddRec)
10229     return nullptr;
10230 
10231   // Since the transformation was successful, we can now transfer the SCEV
10232   // predicates.
10233   for (auto *P : TransformPreds)
10234     Preds.insert(P);
10235 
10236   return AddRec;
10237 }
10238 
10239 /// SCEV predicates
10240 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
10241                              SCEVPredicateKind Kind)
10242     : FastID(ID), Kind(Kind) {}
10243 
10244 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
10245                                        const SCEVUnknown *LHS,
10246                                        const SCEVConstant *RHS)
10247     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {}
10248 
10249 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
10250   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
10251 
10252   if (!Op)
10253     return false;
10254 
10255   return Op->LHS == LHS && Op->RHS == RHS;
10256 }
10257 
10258 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
10259 
10260 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
10261 
10262 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
10263   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
10264 }
10265 
10266 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
10267                                      const SCEVAddRecExpr *AR,
10268                                      IncrementWrapFlags Flags)
10269     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
10270 
10271 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
10272 
10273 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
10274   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
10275 
10276   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
10277 }
10278 
10279 bool SCEVWrapPredicate::isAlwaysTrue() const {
10280   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
10281   IncrementWrapFlags IFlags = Flags;
10282 
10283   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
10284     IFlags = clearFlags(IFlags, IncrementNSSW);
10285 
10286   return IFlags == IncrementAnyWrap;
10287 }
10288 
10289 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
10290   OS.indent(Depth) << *getExpr() << " Added Flags: ";
10291   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
10292     OS << "<nusw>";
10293   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
10294     OS << "<nssw>";
10295   OS << "\n";
10296 }
10297 
10298 SCEVWrapPredicate::IncrementWrapFlags
10299 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
10300                                    ScalarEvolution &SE) {
10301   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
10302   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
10303 
10304   // We can safely transfer the NSW flag as NSSW.
10305   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
10306     ImpliedFlags = IncrementNSSW;
10307 
10308   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
10309     // If the increment is positive, the SCEV NUW flag will also imply the
10310     // WrapPredicate NUSW flag.
10311     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
10312       if (Step->getValue()->getValue().isNonNegative())
10313         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
10314   }
10315 
10316   return ImpliedFlags;
10317 }
10318 
10319 /// Union predicates don't get cached so create a dummy set ID for it.
10320 SCEVUnionPredicate::SCEVUnionPredicate()
10321     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
10322 
10323 bool SCEVUnionPredicate::isAlwaysTrue() const {
10324   return all_of(Preds,
10325                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
10326 }
10327 
10328 ArrayRef<const SCEVPredicate *>
10329 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
10330   auto I = SCEVToPreds.find(Expr);
10331   if (I == SCEVToPreds.end())
10332     return ArrayRef<const SCEVPredicate *>();
10333   return I->second;
10334 }
10335 
10336 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
10337   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
10338     return all_of(Set->Preds,
10339                   [this](const SCEVPredicate *I) { return this->implies(I); });
10340 
10341   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
10342   if (ScevPredsIt == SCEVToPreds.end())
10343     return false;
10344   auto &SCEVPreds = ScevPredsIt->second;
10345 
10346   return any_of(SCEVPreds,
10347                 [N](const SCEVPredicate *I) { return I->implies(N); });
10348 }
10349 
10350 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
10351 
10352 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
10353   for (auto Pred : Preds)
10354     Pred->print(OS, Depth);
10355 }
10356 
10357 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
10358   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
10359     for (auto Pred : Set->Preds)
10360       add(Pred);
10361     return;
10362   }
10363 
10364   if (implies(N))
10365     return;
10366 
10367   const SCEV *Key = N->getExpr();
10368   assert(Key && "Only SCEVUnionPredicate doesn't have an "
10369                 " associated expression!");
10370 
10371   SCEVToPreds[Key].push_back(N);
10372   Preds.push_back(N);
10373 }
10374 
10375 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
10376                                                      Loop &L)
10377     : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {}
10378 
10379 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
10380   const SCEV *Expr = SE.getSCEV(V);
10381   RewriteEntry &Entry = RewriteMap[Expr];
10382 
10383   // If we already have an entry and the version matches, return it.
10384   if (Entry.second && Generation == Entry.first)
10385     return Entry.second;
10386 
10387   // We found an entry but it's stale. Rewrite the stale entry
10388   // acording to the current predicate.
10389   if (Entry.second)
10390     Expr = Entry.second;
10391 
10392   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
10393   Entry = {Generation, NewSCEV};
10394 
10395   return NewSCEV;
10396 }
10397 
10398 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
10399   if (!BackedgeCount) {
10400     SCEVUnionPredicate BackedgePred;
10401     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
10402     addPredicate(BackedgePred);
10403   }
10404   return BackedgeCount;
10405 }
10406 
10407 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
10408   if (Preds.implies(&Pred))
10409     return;
10410   Preds.add(&Pred);
10411   updateGeneration();
10412 }
10413 
10414 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
10415   return Preds;
10416 }
10417 
10418 void PredicatedScalarEvolution::updateGeneration() {
10419   // If the generation number wrapped recompute everything.
10420   if (++Generation == 0) {
10421     for (auto &II : RewriteMap) {
10422       const SCEV *Rewritten = II.second.second;
10423       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
10424     }
10425   }
10426 }
10427 
10428 void PredicatedScalarEvolution::setNoOverflow(
10429     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10430   const SCEV *Expr = getSCEV(V);
10431   const auto *AR = cast<SCEVAddRecExpr>(Expr);
10432 
10433   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
10434 
10435   // Clear the statically implied flags.
10436   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
10437   addPredicate(*SE.getWrapPredicate(AR, Flags));
10438 
10439   auto II = FlagsMap.insert({V, Flags});
10440   if (!II.second)
10441     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
10442 }
10443 
10444 bool PredicatedScalarEvolution::hasNoOverflow(
10445     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10446   const SCEV *Expr = getSCEV(V);
10447   const auto *AR = cast<SCEVAddRecExpr>(Expr);
10448 
10449   Flags = SCEVWrapPredicate::clearFlags(
10450       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
10451 
10452   auto II = FlagsMap.find(V);
10453 
10454   if (II != FlagsMap.end())
10455     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
10456 
10457   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
10458 }
10459 
10460 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
10461   const SCEV *Expr = this->getSCEV(V);
10462   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
10463   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
10464 
10465   if (!New)
10466     return nullptr;
10467 
10468   for (auto *P : NewPreds)
10469     Preds.add(P);
10470 
10471   updateGeneration();
10472   RewriteMap[SE.getSCEV(V)] = {Generation, New};
10473   return New;
10474 }
10475 
10476 PredicatedScalarEvolution::PredicatedScalarEvolution(
10477     const PredicatedScalarEvolution &Init)
10478     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
10479       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
10480   for (const auto &I : Init.FlagsMap)
10481     FlagsMap.insert(I);
10482 }
10483 
10484 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
10485   // For each block.
10486   for (auto *BB : L.getBlocks())
10487     for (auto &I : *BB) {
10488       if (!SE.isSCEVable(I.getType()))
10489         continue;
10490 
10491       auto *Expr = SE.getSCEV(&I);
10492       auto II = RewriteMap.find(Expr);
10493 
10494       if (II == RewriteMap.end())
10495         continue;
10496 
10497       // Don't print things that are not interesting.
10498       if (II->second.second == Expr)
10499         continue;
10500 
10501       OS.indent(Depth) << "[PSE]" << I << ":\n";
10502       OS.indent(Depth + 2) << *Expr << "\n";
10503       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
10504     }
10505 }
10506