1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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.
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.
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.
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.
35 // TODO: We should use these routines and value representations to implement
36 // dependence analysis!
38 //===----------------------------------------------------------------------===//
40 // There are several good references for the techniques used in this analysis.
42 // Chains of recurrences -- a method to expedite the evaluation
43 // of closed-form functions
44 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima
46 // On computational properties of chains of recurrences
49 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50 // Robert A. van Engelen
52 // Efficient Symbolic Analysis for Optimizing Compilers
53 // Robert A. van Engelen
55 // Using the chains of recurrences algebra for data dependence testing and
56 // induction variable substitution
57 // MS Thesis, Johnie Birch
59 //===----------------------------------------------------------------------===//
61 #include "llvm/Analysis/ScalarEvolution.h"
62 #include "llvm/ADT/Optional.h"
63 #include "llvm/ADT/STLExtras.h"
64 #include "llvm/ADT/SmallPtrSet.h"
65 #include "llvm/ADT/Statistic.h"
66 #include "llvm/Analysis/AssumptionCache.h"
67 #include "llvm/Analysis/ConstantFolding.h"
68 #include "llvm/Analysis/InstructionSimplify.h"
69 #include "llvm/Analysis/LoopInfo.h"
70 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
71 #include "llvm/Analysis/TargetLibraryInfo.h"
72 #include "llvm/Analysis/ValueTracking.h"
73 #include "llvm/IR/ConstantRange.h"
74 #include "llvm/IR/Constants.h"
75 #include "llvm/IR/DataLayout.h"
76 #include "llvm/IR/DerivedTypes.h"
77 #include "llvm/IR/Dominators.h"
78 #include "llvm/IR/GetElementPtrTypeIterator.h"
79 #include "llvm/IR/GlobalAlias.h"
80 #include "llvm/IR/GlobalVariable.h"
81 #include "llvm/IR/InstIterator.h"
82 #include "llvm/IR/Instructions.h"
83 #include "llvm/IR/LLVMContext.h"
84 #include "llvm/IR/Metadata.h"
85 #include "llvm/IR/Operator.h"
86 #include "llvm/Support/CommandLine.h"
87 #include "llvm/Support/Debug.h"
88 #include "llvm/Support/ErrorHandling.h"
89 #include "llvm/Support/MathExtras.h"
90 #include "llvm/Support/raw_ostream.h"
94 #define DEBUG_TYPE "scalar-evolution"
96 STATISTIC(NumArrayLenItCounts,
97 "Number of trip counts computed with array length");
98 STATISTIC(NumTripCountsComputed,
99 "Number of loops with predictable loop counts");
100 STATISTIC(NumTripCountsNotComputed,
101 "Number of loops without predictable loop counts");
102 STATISTIC(NumBruteForceTripCountsComputed,
103 "Number of loops with trip counts computed by force");
105 static cl::opt<unsigned>
106 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
107 cl::desc("Maximum number of iterations SCEV will "
108 "symbolically execute a constant "
112 // FIXME: Enable this with XDEBUG when the test suite is clean.
114 VerifySCEV("verify-scev",
115 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
117 INITIALIZE_PASS_BEGIN(ScalarEvolution, "scalar-evolution",
118 "Scalar Evolution Analysis", false, true)
119 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
120 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
121 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
122 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
123 INITIALIZE_PASS_END(ScalarEvolution, "scalar-evolution",
124 "Scalar Evolution Analysis", false, true)
125 char ScalarEvolution::ID = 0;
127 //===----------------------------------------------------------------------===//
128 // SCEV class definitions
129 //===----------------------------------------------------------------------===//
131 //===----------------------------------------------------------------------===//
132 // Implementation of the SCEV class.
135 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
136 void SCEV::dump() const {
142 void SCEV::print(raw_ostream &OS) const {
143 switch (static_cast<SCEVTypes>(getSCEVType())) {
145 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
148 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
149 const SCEV *Op = Trunc->getOperand();
150 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
151 << *Trunc->getType() << ")";
155 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
156 const SCEV *Op = ZExt->getOperand();
157 OS << "(zext " << *Op->getType() << " " << *Op << " to "
158 << *ZExt->getType() << ")";
162 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
163 const SCEV *Op = SExt->getOperand();
164 OS << "(sext " << *Op->getType() << " " << *Op << " to "
165 << *SExt->getType() << ")";
169 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
170 OS << "{" << *AR->getOperand(0);
171 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
172 OS << ",+," << *AR->getOperand(i);
174 if (AR->getNoWrapFlags(FlagNUW))
176 if (AR->getNoWrapFlags(FlagNSW))
178 if (AR->getNoWrapFlags(FlagNW) &&
179 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
181 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
189 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
190 const char *OpStr = nullptr;
191 switch (NAry->getSCEVType()) {
192 case scAddExpr: OpStr = " + "; break;
193 case scMulExpr: OpStr = " * "; break;
194 case scUMaxExpr: OpStr = " umax "; break;
195 case scSMaxExpr: OpStr = " smax "; break;
198 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
201 if (std::next(I) != E)
205 switch (NAry->getSCEVType()) {
208 if (NAry->getNoWrapFlags(FlagNUW))
210 if (NAry->getNoWrapFlags(FlagNSW))
216 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
217 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
221 const SCEVUnknown *U = cast<SCEVUnknown>(this);
223 if (U->isSizeOf(AllocTy)) {
224 OS << "sizeof(" << *AllocTy << ")";
227 if (U->isAlignOf(AllocTy)) {
228 OS << "alignof(" << *AllocTy << ")";
234 if (U->isOffsetOf(CTy, FieldNo)) {
235 OS << "offsetof(" << *CTy << ", ";
236 FieldNo->printAsOperand(OS, false);
241 // Otherwise just print it normally.
242 U->getValue()->printAsOperand(OS, false);
245 case scCouldNotCompute:
246 OS << "***COULDNOTCOMPUTE***";
249 llvm_unreachable("Unknown SCEV kind!");
252 Type *SCEV::getType() const {
253 switch (static_cast<SCEVTypes>(getSCEVType())) {
255 return cast<SCEVConstant>(this)->getType();
259 return cast<SCEVCastExpr>(this)->getType();
264 return cast<SCEVNAryExpr>(this)->getType();
266 return cast<SCEVAddExpr>(this)->getType();
268 return cast<SCEVUDivExpr>(this)->getType();
270 return cast<SCEVUnknown>(this)->getType();
271 case scCouldNotCompute:
272 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
274 llvm_unreachable("Unknown SCEV kind!");
277 bool SCEV::isZero() const {
278 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
279 return SC->getValue()->isZero();
283 bool SCEV::isOne() const {
284 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
285 return SC->getValue()->isOne();
289 bool SCEV::isAllOnesValue() const {
290 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
291 return SC->getValue()->isAllOnesValue();
295 /// isNonConstantNegative - Return true if the specified scev is negated, but
297 bool SCEV::isNonConstantNegative() const {
298 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
299 if (!Mul) return false;
301 // If there is a constant factor, it will be first.
302 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
303 if (!SC) return false;
305 // Return true if the value is negative, this matches things like (-42 * V).
306 return SC->getValue()->getValue().isNegative();
309 SCEVCouldNotCompute::SCEVCouldNotCompute() :
310 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
312 bool SCEVCouldNotCompute::classof(const SCEV *S) {
313 return S->getSCEVType() == scCouldNotCompute;
316 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
318 ID.AddInteger(scConstant);
321 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
322 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
323 UniqueSCEVs.InsertNode(S, IP);
327 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
328 return getConstant(ConstantInt::get(getContext(), Val));
332 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
333 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
334 return getConstant(ConstantInt::get(ITy, V, isSigned));
337 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
338 unsigned SCEVTy, const SCEV *op, Type *ty)
339 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
341 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
342 const SCEV *op, Type *ty)
343 : SCEVCastExpr(ID, scTruncate, op, ty) {
344 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
345 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
346 "Cannot truncate non-integer value!");
349 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
350 const SCEV *op, Type *ty)
351 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
352 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
353 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
354 "Cannot zero extend non-integer value!");
357 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
358 const SCEV *op, Type *ty)
359 : SCEVCastExpr(ID, scSignExtend, op, ty) {
360 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
361 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
362 "Cannot sign extend non-integer value!");
365 void SCEVUnknown::deleted() {
366 // Clear this SCEVUnknown from various maps.
367 SE->forgetMemoizedResults(this);
369 // Remove this SCEVUnknown from the uniquing map.
370 SE->UniqueSCEVs.RemoveNode(this);
372 // Release the value.
376 void SCEVUnknown::allUsesReplacedWith(Value *New) {
377 // Clear this SCEVUnknown from various maps.
378 SE->forgetMemoizedResults(this);
380 // Remove this SCEVUnknown from the uniquing map.
381 SE->UniqueSCEVs.RemoveNode(this);
383 // Update this SCEVUnknown to point to the new value. This is needed
384 // because there may still be outstanding SCEVs which still point to
389 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
390 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
391 if (VCE->getOpcode() == Instruction::PtrToInt)
392 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
393 if (CE->getOpcode() == Instruction::GetElementPtr &&
394 CE->getOperand(0)->isNullValue() &&
395 CE->getNumOperands() == 2)
396 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
398 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
406 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
407 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
408 if (VCE->getOpcode() == Instruction::PtrToInt)
409 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
410 if (CE->getOpcode() == Instruction::GetElementPtr &&
411 CE->getOperand(0)->isNullValue()) {
413 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
414 if (StructType *STy = dyn_cast<StructType>(Ty))
415 if (!STy->isPacked() &&
416 CE->getNumOperands() == 3 &&
417 CE->getOperand(1)->isNullValue()) {
418 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
420 STy->getNumElements() == 2 &&
421 STy->getElementType(0)->isIntegerTy(1)) {
422 AllocTy = STy->getElementType(1);
431 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
432 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
433 if (VCE->getOpcode() == Instruction::PtrToInt)
434 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
435 if (CE->getOpcode() == Instruction::GetElementPtr &&
436 CE->getNumOperands() == 3 &&
437 CE->getOperand(0)->isNullValue() &&
438 CE->getOperand(1)->isNullValue()) {
440 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
441 // Ignore vector types here so that ScalarEvolutionExpander doesn't
442 // emit getelementptrs that index into vectors.
443 if (Ty->isStructTy() || Ty->isArrayTy()) {
445 FieldNo = CE->getOperand(2);
453 //===----------------------------------------------------------------------===//
455 //===----------------------------------------------------------------------===//
458 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
459 /// than the complexity of the RHS. This comparator is used to canonicalize
461 class SCEVComplexityCompare {
462 const LoopInfo *const LI;
464 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
466 // Return true or false if LHS is less than, or at least RHS, respectively.
467 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
468 return compare(LHS, RHS) < 0;
471 // Return negative, zero, or positive, if LHS is less than, equal to, or
472 // greater than RHS, respectively. A three-way result allows recursive
473 // comparisons to be more efficient.
474 int compare(const SCEV *LHS, const SCEV *RHS) const {
475 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
479 // Primarily, sort the SCEVs by their getSCEVType().
480 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
482 return (int)LType - (int)RType;
484 // Aside from the getSCEVType() ordering, the particular ordering
485 // isn't very important except that it's beneficial to be consistent,
486 // so that (a + b) and (b + a) don't end up as different expressions.
487 switch (static_cast<SCEVTypes>(LType)) {
489 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
490 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
492 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
493 // not as complete as it could be.
494 const Value *LV = LU->getValue(), *RV = RU->getValue();
496 // Order pointer values after integer values. This helps SCEVExpander
498 bool LIsPointer = LV->getType()->isPointerTy(),
499 RIsPointer = RV->getType()->isPointerTy();
500 if (LIsPointer != RIsPointer)
501 return (int)LIsPointer - (int)RIsPointer;
503 // Compare getValueID values.
504 unsigned LID = LV->getValueID(),
505 RID = RV->getValueID();
507 return (int)LID - (int)RID;
509 // Sort arguments by their position.
510 if (const Argument *LA = dyn_cast<Argument>(LV)) {
511 const Argument *RA = cast<Argument>(RV);
512 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
513 return (int)LArgNo - (int)RArgNo;
516 // For instructions, compare their loop depth, and their operand
517 // count. This is pretty loose.
518 if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
519 const Instruction *RInst = cast<Instruction>(RV);
521 // Compare loop depths.
522 const BasicBlock *LParent = LInst->getParent(),
523 *RParent = RInst->getParent();
524 if (LParent != RParent) {
525 unsigned LDepth = LI->getLoopDepth(LParent),
526 RDepth = LI->getLoopDepth(RParent);
527 if (LDepth != RDepth)
528 return (int)LDepth - (int)RDepth;
531 // Compare the number of operands.
532 unsigned LNumOps = LInst->getNumOperands(),
533 RNumOps = RInst->getNumOperands();
534 return (int)LNumOps - (int)RNumOps;
541 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
542 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
544 // Compare constant values.
545 const APInt &LA = LC->getValue()->getValue();
546 const APInt &RA = RC->getValue()->getValue();
547 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
548 if (LBitWidth != RBitWidth)
549 return (int)LBitWidth - (int)RBitWidth;
550 return LA.ult(RA) ? -1 : 1;
554 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
555 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
557 // Compare addrec loop depths.
558 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
559 if (LLoop != RLoop) {
560 unsigned LDepth = LLoop->getLoopDepth(),
561 RDepth = RLoop->getLoopDepth();
562 if (LDepth != RDepth)
563 return (int)LDepth - (int)RDepth;
566 // Addrec complexity grows with operand count.
567 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
568 if (LNumOps != RNumOps)
569 return (int)LNumOps - (int)RNumOps;
571 // Lexicographically compare.
572 for (unsigned i = 0; i != LNumOps; ++i) {
573 long X = compare(LA->getOperand(i), RA->getOperand(i));
585 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
586 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
588 // Lexicographically compare n-ary expressions.
589 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
590 if (LNumOps != RNumOps)
591 return (int)LNumOps - (int)RNumOps;
593 for (unsigned i = 0; i != LNumOps; ++i) {
596 long X = compare(LC->getOperand(i), RC->getOperand(i));
600 return (int)LNumOps - (int)RNumOps;
604 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
605 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
607 // Lexicographically compare udiv expressions.
608 long X = compare(LC->getLHS(), RC->getLHS());
611 return compare(LC->getRHS(), RC->getRHS());
617 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
618 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
620 // Compare cast expressions by operand.
621 return compare(LC->getOperand(), RC->getOperand());
624 case scCouldNotCompute:
625 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
627 llvm_unreachable("Unknown SCEV kind!");
632 /// GroupByComplexity - Given a list of SCEV objects, order them by their
633 /// complexity, and group objects of the same complexity together by value.
634 /// When this routine is finished, we know that any duplicates in the vector are
635 /// consecutive and that complexity is monotonically increasing.
637 /// Note that we go take special precautions to ensure that we get deterministic
638 /// results from this routine. In other words, we don't want the results of
639 /// this to depend on where the addresses of various SCEV objects happened to
642 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
644 if (Ops.size() < 2) return; // Noop
645 if (Ops.size() == 2) {
646 // This is the common case, which also happens to be trivially simple.
648 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
649 if (SCEVComplexityCompare(LI)(RHS, LHS))
654 // Do the rough sort by complexity.
655 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
657 // Now that we are sorted by complexity, group elements of the same
658 // complexity. Note that this is, at worst, N^2, but the vector is likely to
659 // be extremely short in practice. Note that we take this approach because we
660 // do not want to depend on the addresses of the objects we are grouping.
661 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
662 const SCEV *S = Ops[i];
663 unsigned Complexity = S->getSCEVType();
665 // If there are any objects of the same complexity and same value as this
667 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
668 if (Ops[j] == S) { // Found a duplicate.
669 // Move it to immediately after i'th element.
670 std::swap(Ops[i+1], Ops[j]);
671 ++i; // no need to rescan it.
672 if (i == e-2) return; // Done!
679 struct FindSCEVSize {
681 FindSCEVSize() : Size(0) {}
683 bool follow(const SCEV *S) {
685 // Keep looking at all operands of S.
688 bool isDone() const {
694 // Returns the size of the SCEV S.
695 static inline int sizeOfSCEV(const SCEV *S) {
697 SCEVTraversal<FindSCEVSize> ST(F);
704 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
706 // Computes the Quotient and Remainder of the division of Numerator by
708 static void divide(ScalarEvolution &SE, const SCEV *Numerator,
709 const SCEV *Denominator, const SCEV **Quotient,
710 const SCEV **Remainder) {
711 assert(Numerator && Denominator && "Uninitialized SCEV");
713 SCEVDivision D(SE, Numerator, Denominator);
715 // Check for the trivial case here to avoid having to check for it in the
717 if (Numerator == Denominator) {
723 if (Numerator->isZero()) {
729 // Split the Denominator when it is a product.
730 if (const SCEVMulExpr *T = dyn_cast<const SCEVMulExpr>(Denominator)) {
732 *Quotient = Numerator;
733 for (const SCEV *Op : T->operands()) {
734 divide(SE, *Quotient, Op, &Q, &R);
737 // Bail out when the Numerator is not divisible by one of the terms of
741 *Remainder = Numerator;
750 *Quotient = D.Quotient;
751 *Remainder = D.Remainder;
754 // Except in the trivial case described above, we do not know how to divide
755 // Expr by Denominator for the following functions with empty implementation.
756 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
757 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
758 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
759 void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
760 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
761 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
762 void visitUnknown(const SCEVUnknown *Numerator) {}
763 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
765 void visitConstant(const SCEVConstant *Numerator) {
766 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
767 APInt NumeratorVal = Numerator->getValue()->getValue();
768 APInt DenominatorVal = D->getValue()->getValue();
769 uint32_t NumeratorBW = NumeratorVal.getBitWidth();
770 uint32_t DenominatorBW = DenominatorVal.getBitWidth();
772 if (NumeratorBW > DenominatorBW)
773 DenominatorVal = DenominatorVal.sext(NumeratorBW);
774 else if (NumeratorBW < DenominatorBW)
775 NumeratorVal = NumeratorVal.sext(DenominatorBW);
777 APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
778 APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
779 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
780 Quotient = SE.getConstant(QuotientVal);
781 Remainder = SE.getConstant(RemainderVal);
786 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
787 const SCEV *StartQ, *StartR, *StepQ, *StepR;
788 assert(Numerator->isAffine() && "Numerator should be affine");
789 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
790 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
791 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
792 Numerator->getNoWrapFlags());
793 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
794 Numerator->getNoWrapFlags());
797 void visitAddExpr(const SCEVAddExpr *Numerator) {
798 SmallVector<const SCEV *, 2> Qs, Rs;
799 Type *Ty = Denominator->getType();
801 for (const SCEV *Op : Numerator->operands()) {
803 divide(SE, Op, Denominator, &Q, &R);
805 // Bail out if types do not match.
806 if (Ty != Q->getType() || Ty != R->getType()) {
808 Remainder = Numerator;
816 if (Qs.size() == 1) {
822 Quotient = SE.getAddExpr(Qs);
823 Remainder = SE.getAddExpr(Rs);
826 void visitMulExpr(const SCEVMulExpr *Numerator) {
827 SmallVector<const SCEV *, 2> Qs;
828 Type *Ty = Denominator->getType();
830 bool FoundDenominatorTerm = false;
831 for (const SCEV *Op : Numerator->operands()) {
832 // Bail out if types do not match.
833 if (Ty != Op->getType()) {
835 Remainder = Numerator;
839 if (FoundDenominatorTerm) {
844 // Check whether Denominator divides one of the product operands.
846 divide(SE, Op, Denominator, &Q, &R);
852 // Bail out if types do not match.
853 if (Ty != Q->getType()) {
855 Remainder = Numerator;
859 FoundDenominatorTerm = true;
863 if (FoundDenominatorTerm) {
868 Quotient = SE.getMulExpr(Qs);
872 if (!isa<SCEVUnknown>(Denominator)) {
874 Remainder = Numerator;
878 // The Remainder is obtained by replacing Denominator by 0 in Numerator.
879 ValueToValueMap RewriteMap;
880 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
881 cast<SCEVConstant>(Zero)->getValue();
882 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
884 if (Remainder->isZero()) {
885 // The Quotient is obtained by replacing Denominator by 1 in Numerator.
886 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
887 cast<SCEVConstant>(One)->getValue();
889 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
893 // Quotient is (Numerator - Remainder) divided by Denominator.
895 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
896 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) {
897 // This SCEV does not seem to simplify: fail the division here.
899 Remainder = Numerator;
902 divide(SE, Diff, Denominator, &Q, &R);
904 "(Numerator - Remainder) should evenly divide Denominator");
909 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
910 const SCEV *Denominator)
911 : SE(S), Denominator(Denominator) {
912 Zero = SE.getConstant(Denominator->getType(), 0);
913 One = SE.getConstant(Denominator->getType(), 1);
915 // By default, we don't know how to divide Expr by Denominator.
916 // Providing the default here simplifies the rest of the code.
918 Remainder = Numerator;
922 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
927 //===----------------------------------------------------------------------===//
928 // Simple SCEV method implementations
929 //===----------------------------------------------------------------------===//
931 /// BinomialCoefficient - Compute BC(It, K). The result has width W.
933 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
936 // Handle the simplest case efficiently.
938 return SE.getTruncateOrZeroExtend(It, ResultTy);
940 // We are using the following formula for BC(It, K):
942 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
944 // Suppose, W is the bitwidth of the return value. We must be prepared for
945 // overflow. Hence, we must assure that the result of our computation is
946 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
947 // safe in modular arithmetic.
949 // However, this code doesn't use exactly that formula; the formula it uses
950 // is something like the following, where T is the number of factors of 2 in
951 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
954 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
956 // This formula is trivially equivalent to the previous formula. However,
957 // this formula can be implemented much more efficiently. The trick is that
958 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
959 // arithmetic. To do exact division in modular arithmetic, all we have
960 // to do is multiply by the inverse. Therefore, this step can be done at
963 // The next issue is how to safely do the division by 2^T. The way this
964 // is done is by doing the multiplication step at a width of at least W + T
965 // bits. This way, the bottom W+T bits of the product are accurate. Then,
966 // when we perform the division by 2^T (which is equivalent to a right shift
967 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
968 // truncated out after the division by 2^T.
970 // In comparison to just directly using the first formula, this technique
971 // is much more efficient; using the first formula requires W * K bits,
972 // but this formula less than W + K bits. Also, the first formula requires
973 // a division step, whereas this formula only requires multiplies and shifts.
975 // It doesn't matter whether the subtraction step is done in the calculation
976 // width or the input iteration count's width; if the subtraction overflows,
977 // the result must be zero anyway. We prefer here to do it in the width of
978 // the induction variable because it helps a lot for certain cases; CodeGen
979 // isn't smart enough to ignore the overflow, which leads to much less
980 // efficient code if the width of the subtraction is wider than the native
983 // (It's possible to not widen at all by pulling out factors of 2 before
984 // the multiplication; for example, K=2 can be calculated as
985 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
986 // extra arithmetic, so it's not an obvious win, and it gets
987 // much more complicated for K > 3.)
989 // Protection from insane SCEVs; this bound is conservative,
990 // but it probably doesn't matter.
992 return SE.getCouldNotCompute();
994 unsigned W = SE.getTypeSizeInBits(ResultTy);
996 // Calculate K! / 2^T and T; we divide out the factors of two before
997 // multiplying for calculating K! / 2^T to avoid overflow.
998 // Other overflow doesn't matter because we only care about the bottom
999 // W bits of the result.
1000 APInt OddFactorial(W, 1);
1002 for (unsigned i = 3; i <= K; ++i) {
1004 unsigned TwoFactors = Mult.countTrailingZeros();
1006 Mult = Mult.lshr(TwoFactors);
1007 OddFactorial *= Mult;
1010 // We need at least W + T bits for the multiplication step
1011 unsigned CalculationBits = W + T;
1013 // Calculate 2^T, at width T+W.
1014 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1016 // Calculate the multiplicative inverse of K! / 2^T;
1017 // this multiplication factor will perform the exact division by
1019 APInt Mod = APInt::getSignedMinValue(W+1);
1020 APInt MultiplyFactor = OddFactorial.zext(W+1);
1021 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1022 MultiplyFactor = MultiplyFactor.trunc(W);
1024 // Calculate the product, at width T+W
1025 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1027 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1028 for (unsigned i = 1; i != K; ++i) {
1029 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1030 Dividend = SE.getMulExpr(Dividend,
1031 SE.getTruncateOrZeroExtend(S, CalculationTy));
1035 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1037 // Truncate the result, and divide by K! / 2^T.
1039 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1040 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1043 /// evaluateAtIteration - Return the value of this chain of recurrences at
1044 /// the specified iteration number. We can evaluate this recurrence by
1045 /// multiplying each element in the chain by the binomial coefficient
1046 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
1048 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1050 /// where BC(It, k) stands for binomial coefficient.
1052 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1053 ScalarEvolution &SE) const {
1054 const SCEV *Result = getStart();
1055 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1056 // The computation is correct in the face of overflow provided that the
1057 // multiplication is performed _after_ the evaluation of the binomial
1059 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1060 if (isa<SCEVCouldNotCompute>(Coeff))
1063 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1068 //===----------------------------------------------------------------------===//
1069 // SCEV Expression folder implementations
1070 //===----------------------------------------------------------------------===//
1072 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
1074 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1075 "This is not a truncating conversion!");
1076 assert(isSCEVable(Ty) &&
1077 "This is not a conversion to a SCEVable type!");
1078 Ty = getEffectiveSCEVType(Ty);
1080 FoldingSetNodeID ID;
1081 ID.AddInteger(scTruncate);
1085 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1087 // Fold if the operand is constant.
1088 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1090 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1092 // trunc(trunc(x)) --> trunc(x)
1093 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1094 return getTruncateExpr(ST->getOperand(), Ty);
1096 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1097 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1098 return getTruncateOrSignExtend(SS->getOperand(), Ty);
1100 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1101 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1102 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1104 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
1105 // eliminate all the truncates.
1106 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1107 SmallVector<const SCEV *, 4> Operands;
1108 bool hasTrunc = false;
1109 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1110 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
1111 hasTrunc = isa<SCEVTruncateExpr>(S);
1112 Operands.push_back(S);
1115 return getAddExpr(Operands);
1116 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
1119 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
1120 // eliminate all the truncates.
1121 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1122 SmallVector<const SCEV *, 4> Operands;
1123 bool hasTrunc = false;
1124 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1125 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
1126 hasTrunc = isa<SCEVTruncateExpr>(S);
1127 Operands.push_back(S);
1130 return getMulExpr(Operands);
1131 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
1134 // If the input value is a chrec scev, truncate the chrec's operands.
1135 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1136 SmallVector<const SCEV *, 4> Operands;
1137 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1138 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
1139 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1142 // The cast wasn't folded; create an explicit cast node. We can reuse
1143 // the existing insert position since if we get here, we won't have
1144 // made any changes which would invalidate it.
1145 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1147 UniqueSCEVs.InsertNode(S, IP);
1151 // Get the limit of a recurrence such that incrementing by Step cannot cause
1152 // signed overflow as long as the value of the recurrence within the
1153 // loop does not exceed this limit before incrementing.
1154 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1155 ICmpInst::Predicate *Pred,
1156 ScalarEvolution *SE) {
1157 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1158 if (SE->isKnownPositive(Step)) {
1159 *Pred = ICmpInst::ICMP_SLT;
1160 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1161 SE->getSignedRange(Step).getSignedMax());
1163 if (SE->isKnownNegative(Step)) {
1164 *Pred = ICmpInst::ICMP_SGT;
1165 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1166 SE->getSignedRange(Step).getSignedMin());
1171 // Get the limit of a recurrence such that incrementing by Step cannot cause
1172 // unsigned overflow as long as the value of the recurrence within the loop does
1173 // not exceed this limit before incrementing.
1174 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1175 ICmpInst::Predicate *Pred,
1176 ScalarEvolution *SE) {
1177 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1178 *Pred = ICmpInst::ICMP_ULT;
1180 return SE->getConstant(APInt::getMinValue(BitWidth) -
1181 SE->getUnsignedRange(Step).getUnsignedMax());
1186 struct ExtendOpTraitsBase {
1187 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *);
1190 // Used to make code generic over signed and unsigned overflow.
1191 template <typename ExtendOp> struct ExtendOpTraits {
1194 // static const SCEV::NoWrapFlags WrapType;
1196 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1198 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1199 // ICmpInst::Predicate *Pred,
1200 // ScalarEvolution *SE);
1204 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1205 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1207 static const GetExtendExprTy GetExtendExpr;
1209 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1210 ICmpInst::Predicate *Pred,
1211 ScalarEvolution *SE) {
1212 return getSignedOverflowLimitForStep(Step, Pred, SE);
1216 const ExtendOpTraits<SCEVSignExtendExpr>::GetExtendExprTy ExtendOpTraits<
1217 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1220 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1221 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1223 static const GetExtendExprTy GetExtendExpr;
1225 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1226 ICmpInst::Predicate *Pred,
1227 ScalarEvolution *SE) {
1228 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1232 const ExtendOpTraits<SCEVZeroExtendExpr>::GetExtendExprTy ExtendOpTraits<
1233 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1236 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1237 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1238 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1239 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1240 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1241 // expression "Step + sext/zext(PreIncAR)" is congruent with
1242 // "sext/zext(PostIncAR)"
1243 template <typename ExtendOpTy>
1244 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1245 ScalarEvolution *SE) {
1246 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1247 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1249 const Loop *L = AR->getLoop();
1250 const SCEV *Start = AR->getStart();
1251 const SCEV *Step = AR->getStepRecurrence(*SE);
1253 // Check for a simple looking step prior to loop entry.
1254 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1258 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1259 // subtraction is expensive. For this purpose, perform a quick and dirty
1260 // difference, by checking for Step in the operand list.
1261 SmallVector<const SCEV *, 4> DiffOps;
1262 for (const SCEV *Op : SA->operands())
1264 DiffOps.push_back(Op);
1266 if (DiffOps.size() == SA->getNumOperands())
1269 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1272 // 1. NSW/NUW flags on the step increment.
1273 const SCEV *PreStart = SE->getAddExpr(DiffOps, SA->getNoWrapFlags());
1274 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1275 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1277 // WARNING: FIXME: the optimization below assumes that a sign/zero-overflowing
1278 // nsw/nuw operation is undefined behavior. This is strictly more aggressive
1279 // than the interpretation of nsw in other parts of LLVM (for instance, they
1280 // may unconditionally hoist nsw/nuw arithmetic through control flow). This
1281 // logic needs to be revisited once we have a consistent semantics for poison
1284 // "{S,+,X} is <nsw>/<nuw>" and "{S,+,X} is evaluated at least once" implies
1285 // "S+X does not sign/unsign-overflow" (we'd have undefined behavior if it
1286 // did). If `L->getExitingBlock() == L->getLoopLatch()` then `PreAR` (=
1287 // {S,+,X}<nsw>/<nuw>) is evaluated every-time `AR` (= {S+X,+,X}) is
1288 // evaluated, and hence within `AR` we are safe to assume that "S+X" will not
1289 // sign/unsign-overflow.
1292 BasicBlock *ExitingBlock = L->getExitingBlock();
1293 BasicBlock *LatchBlock = L->getLoopLatch();
1294 if (PreAR && PreAR->getNoWrapFlags(WrapType) && ExitingBlock != nullptr &&
1295 ExitingBlock == LatchBlock)
1298 // 2. Direct overflow check on the step operation's expression.
1299 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1300 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1301 const SCEV *OperandExtendedStart =
1302 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy),
1303 (SE->*GetExtendExpr)(Step, WideTy));
1304 if ((SE->*GetExtendExpr)(Start, WideTy) == OperandExtendedStart) {
1305 if (PreAR && AR->getNoWrapFlags(WrapType)) {
1306 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1307 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1308 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1309 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1314 // 3. Loop precondition.
1315 ICmpInst::Predicate Pred;
1316 const SCEV *OverflowLimit =
1317 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1319 if (OverflowLimit &&
1320 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) {
1326 // Get the normalized zero or sign extended expression for this AddRec's Start.
1327 template <typename ExtendOpTy>
1328 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1329 ScalarEvolution *SE) {
1330 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1332 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE);
1334 return (SE->*GetExtendExpr)(AR->getStart(), Ty);
1336 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty),
1337 (SE->*GetExtendExpr)(PreStart, Ty));
1340 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
1342 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1343 "This is not an extending conversion!");
1344 assert(isSCEVable(Ty) &&
1345 "This is not a conversion to a SCEVable type!");
1346 Ty = getEffectiveSCEVType(Ty);
1348 // Fold if the operand is constant.
1349 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1351 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1353 // zext(zext(x)) --> zext(x)
1354 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1355 return getZeroExtendExpr(SZ->getOperand(), Ty);
1357 // Before doing any expensive analysis, check to see if we've already
1358 // computed a SCEV for this Op and Ty.
1359 FoldingSetNodeID ID;
1360 ID.AddInteger(scZeroExtend);
1364 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1366 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1367 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1368 // It's possible the bits taken off by the truncate were all zero bits. If
1369 // so, we should be able to simplify this further.
1370 const SCEV *X = ST->getOperand();
1371 ConstantRange CR = getUnsignedRange(X);
1372 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1373 unsigned NewBits = getTypeSizeInBits(Ty);
1374 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1375 CR.zextOrTrunc(NewBits)))
1376 return getTruncateOrZeroExtend(X, Ty);
1379 // If the input value is a chrec scev, and we can prove that the value
1380 // did not overflow the old, smaller, value, we can zero extend all of the
1381 // operands (often constants). This allows analysis of something like
1382 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1383 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1384 if (AR->isAffine()) {
1385 const SCEV *Start = AR->getStart();
1386 const SCEV *Step = AR->getStepRecurrence(*this);
1387 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1388 const Loop *L = AR->getLoop();
1390 // If we have special knowledge that this addrec won't overflow,
1391 // we don't need to do any further analysis.
1392 if (AR->getNoWrapFlags(SCEV::FlagNUW))
1393 return getAddRecExpr(
1394 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1395 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1397 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1398 // Note that this serves two purposes: It filters out loops that are
1399 // simply not analyzable, and it covers the case where this code is
1400 // being called from within backedge-taken count analysis, such that
1401 // attempting to ask for the backedge-taken count would likely result
1402 // in infinite recursion. In the later case, the analysis code will
1403 // cope with a conservative value, and it will take care to purge
1404 // that value once it has finished.
1405 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1406 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1407 // Manually compute the final value for AR, checking for
1410 // Check whether the backedge-taken count can be losslessly casted to
1411 // the addrec's type. The count is always unsigned.
1412 const SCEV *CastedMaxBECount =
1413 getTruncateOrZeroExtend(MaxBECount, Start->getType());
1414 const SCEV *RecastedMaxBECount =
1415 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1416 if (MaxBECount == RecastedMaxBECount) {
1417 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1418 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1419 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
1420 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy);
1421 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy);
1422 const SCEV *WideMaxBECount =
1423 getZeroExtendExpr(CastedMaxBECount, WideTy);
1424 const SCEV *OperandExtendedAdd =
1425 getAddExpr(WideStart,
1426 getMulExpr(WideMaxBECount,
1427 getZeroExtendExpr(Step, WideTy)));
1428 if (ZAdd == OperandExtendedAdd) {
1429 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1430 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1431 // Return the expression with the addrec on the outside.
1432 return getAddRecExpr(
1433 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1434 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1436 // Similar to above, only this time treat the step value as signed.
1437 // This covers loops that count down.
1438 OperandExtendedAdd =
1439 getAddExpr(WideStart,
1440 getMulExpr(WideMaxBECount,
1441 getSignExtendExpr(Step, WideTy)));
1442 if (ZAdd == OperandExtendedAdd) {
1443 // Cache knowledge of AR NW, which is propagated to this AddRec.
1444 // Negative step causes unsigned wrap, but it still can't self-wrap.
1445 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1446 // Return the expression with the addrec on the outside.
1447 return getAddRecExpr(
1448 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1449 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1453 // If the backedge is guarded by a comparison with the pre-inc value
1454 // the addrec is safe. Also, if the entry is guarded by a comparison
1455 // with the start value and the backedge is guarded by a comparison
1456 // with the post-inc value, the addrec is safe.
1457 if (isKnownPositive(Step)) {
1458 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1459 getUnsignedRange(Step).getUnsignedMax());
1460 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1461 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
1462 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
1463 AR->getPostIncExpr(*this), N))) {
1464 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1465 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1466 // Return the expression with the addrec on the outside.
1467 return getAddRecExpr(
1468 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1469 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1471 } else if (isKnownNegative(Step)) {
1472 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1473 getSignedRange(Step).getSignedMin());
1474 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1475 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
1476 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1477 AR->getPostIncExpr(*this), N))) {
1478 // Cache knowledge of AR NW, which is propagated to this AddRec.
1479 // Negative step causes unsigned wrap, but it still can't self-wrap.
1480 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1481 // Return the expression with the addrec on the outside.
1482 return getAddRecExpr(
1483 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1484 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1490 // The cast wasn't folded; create an explicit cast node.
1491 // Recompute the insert position, as it may have been invalidated.
1492 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1493 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1495 UniqueSCEVs.InsertNode(S, IP);
1499 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
1501 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1502 "This is not an extending conversion!");
1503 assert(isSCEVable(Ty) &&
1504 "This is not a conversion to a SCEVable type!");
1505 Ty = getEffectiveSCEVType(Ty);
1507 // Fold if the operand is constant.
1508 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1510 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1512 // sext(sext(x)) --> sext(x)
1513 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1514 return getSignExtendExpr(SS->getOperand(), Ty);
1516 // sext(zext(x)) --> zext(x)
1517 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1518 return getZeroExtendExpr(SZ->getOperand(), Ty);
1520 // Before doing any expensive analysis, check to see if we've already
1521 // computed a SCEV for this Op and Ty.
1522 FoldingSetNodeID ID;
1523 ID.AddInteger(scSignExtend);
1527 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1529 // If the input value is provably positive, build a zext instead.
1530 if (isKnownNonNegative(Op))
1531 return getZeroExtendExpr(Op, Ty);
1533 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1534 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1535 // It's possible the bits taken off by the truncate were all sign bits. If
1536 // so, we should be able to simplify this further.
1537 const SCEV *X = ST->getOperand();
1538 ConstantRange CR = getSignedRange(X);
1539 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1540 unsigned NewBits = getTypeSizeInBits(Ty);
1541 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1542 CR.sextOrTrunc(NewBits)))
1543 return getTruncateOrSignExtend(X, Ty);
1546 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
1547 if (auto SA = dyn_cast<SCEVAddExpr>(Op)) {
1548 if (SA->getNumOperands() == 2) {
1549 auto SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1550 auto SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
1552 if (auto SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
1553 const APInt &C1 = SC1->getValue()->getValue();
1554 const APInt &C2 = SC2->getValue()->getValue();
1555 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
1556 C2.ugt(C1) && C2.isPowerOf2())
1557 return getAddExpr(getSignExtendExpr(SC1, Ty),
1558 getSignExtendExpr(SMul, Ty));
1563 // If the input value is a chrec scev, and we can prove that the value
1564 // did not overflow the old, smaller, value, we can sign extend all of the
1565 // operands (often constants). This allows analysis of something like
1566 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1567 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1568 if (AR->isAffine()) {
1569 const SCEV *Start = AR->getStart();
1570 const SCEV *Step = AR->getStepRecurrence(*this);
1571 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1572 const Loop *L = AR->getLoop();
1574 // If we have special knowledge that this addrec won't overflow,
1575 // we don't need to do any further analysis.
1576 if (AR->getNoWrapFlags(SCEV::FlagNSW))
1577 return getAddRecExpr(
1578 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1579 getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW);
1581 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1582 // Note that this serves two purposes: It filters out loops that are
1583 // simply not analyzable, and it covers the case where this code is
1584 // being called from within backedge-taken count analysis, such that
1585 // attempting to ask for the backedge-taken count would likely result
1586 // in infinite recursion. In the later case, the analysis code will
1587 // cope with a conservative value, and it will take care to purge
1588 // that value once it has finished.
1589 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1590 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1591 // Manually compute the final value for AR, checking for
1594 // Check whether the backedge-taken count can be losslessly casted to
1595 // the addrec's type. The count is always unsigned.
1596 const SCEV *CastedMaxBECount =
1597 getTruncateOrZeroExtend(MaxBECount, Start->getType());
1598 const SCEV *RecastedMaxBECount =
1599 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1600 if (MaxBECount == RecastedMaxBECount) {
1601 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1602 // Check whether Start+Step*MaxBECount has no signed overflow.
1603 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
1604 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy);
1605 const SCEV *WideStart = getSignExtendExpr(Start, WideTy);
1606 const SCEV *WideMaxBECount =
1607 getZeroExtendExpr(CastedMaxBECount, WideTy);
1608 const SCEV *OperandExtendedAdd =
1609 getAddExpr(WideStart,
1610 getMulExpr(WideMaxBECount,
1611 getSignExtendExpr(Step, WideTy)));
1612 if (SAdd == OperandExtendedAdd) {
1613 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1614 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1615 // Return the expression with the addrec on the outside.
1616 return getAddRecExpr(
1617 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1618 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1620 // Similar to above, only this time treat the step value as unsigned.
1621 // This covers loops that count up with an unsigned step.
1622 OperandExtendedAdd =
1623 getAddExpr(WideStart,
1624 getMulExpr(WideMaxBECount,
1625 getZeroExtendExpr(Step, WideTy)));
1626 if (SAdd == OperandExtendedAdd) {
1627 // If AR wraps around then
1629 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
1630 // => SAdd != OperandExtendedAdd
1632 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1633 // (SAdd == OperandExtendedAdd => AR is NW)
1635 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1637 // Return the expression with the addrec on the outside.
1638 return getAddRecExpr(
1639 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1640 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1644 // If the backedge is guarded by a comparison with the pre-inc value
1645 // the addrec is safe. Also, if the entry is guarded by a comparison
1646 // with the start value and the backedge is guarded by a comparison
1647 // with the post-inc value, the addrec is safe.
1648 ICmpInst::Predicate Pred;
1649 const SCEV *OverflowLimit =
1650 getSignedOverflowLimitForStep(Step, &Pred, this);
1651 if (OverflowLimit &&
1652 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1653 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1654 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1656 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1657 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1658 return getAddRecExpr(
1659 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1660 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1663 // If Start and Step are constants, check if we can apply this
1665 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
1666 auto SC1 = dyn_cast<SCEVConstant>(Start);
1667 auto SC2 = dyn_cast<SCEVConstant>(Step);
1669 const APInt &C1 = SC1->getValue()->getValue();
1670 const APInt &C2 = SC2->getValue()->getValue();
1671 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1673 Start = getSignExtendExpr(Start, Ty);
1674 const SCEV *NewAR = getAddRecExpr(getConstant(AR->getType(), 0), Step,
1675 L, AR->getNoWrapFlags());
1676 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty));
1681 // The cast wasn't folded; create an explicit cast node.
1682 // Recompute the insert position, as it may have been invalidated.
1683 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1684 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1686 UniqueSCEVs.InsertNode(S, IP);
1690 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1691 /// unspecified bits out to the given type.
1693 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1695 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1696 "This is not an extending conversion!");
1697 assert(isSCEVable(Ty) &&
1698 "This is not a conversion to a SCEVable type!");
1699 Ty = getEffectiveSCEVType(Ty);
1701 // Sign-extend negative constants.
1702 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1703 if (SC->getValue()->getValue().isNegative())
1704 return getSignExtendExpr(Op, Ty);
1706 // Peel off a truncate cast.
1707 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
1708 const SCEV *NewOp = T->getOperand();
1709 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1710 return getAnyExtendExpr(NewOp, Ty);
1711 return getTruncateOrNoop(NewOp, Ty);
1714 // Next try a zext cast. If the cast is folded, use it.
1715 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
1716 if (!isa<SCEVZeroExtendExpr>(ZExt))
1719 // Next try a sext cast. If the cast is folded, use it.
1720 const SCEV *SExt = getSignExtendExpr(Op, Ty);
1721 if (!isa<SCEVSignExtendExpr>(SExt))
1724 // Force the cast to be folded into the operands of an addrec.
1725 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1726 SmallVector<const SCEV *, 4> Ops;
1727 for (const SCEV *Op : AR->operands())
1728 Ops.push_back(getAnyExtendExpr(Op, Ty));
1729 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
1732 // If the expression is obviously signed, use the sext cast value.
1733 if (isa<SCEVSMaxExpr>(Op))
1736 // Absent any other information, use the zext cast value.
1740 /// CollectAddOperandsWithScales - Process the given Ops list, which is
1741 /// a list of operands to be added under the given scale, update the given
1742 /// map. This is a helper function for getAddRecExpr. As an example of
1743 /// what it does, given a sequence of operands that would form an add
1744 /// expression like this:
1746 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
1748 /// where A and B are constants, update the map with these values:
1750 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1752 /// and add 13 + A*B*29 to AccumulatedConstant.
1753 /// This will allow getAddRecExpr to produce this:
1755 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1757 /// This form often exposes folding opportunities that are hidden in
1758 /// the original operand list.
1760 /// Return true iff it appears that any interesting folding opportunities
1761 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
1762 /// the common case where no interesting opportunities are present, and
1763 /// is also used as a check to avoid infinite recursion.
1766 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1767 SmallVectorImpl<const SCEV *> &NewOps,
1768 APInt &AccumulatedConstant,
1769 const SCEV *const *Ops, size_t NumOperands,
1771 ScalarEvolution &SE) {
1772 bool Interesting = false;
1774 // Iterate over the add operands. They are sorted, with constants first.
1776 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1778 // Pull a buried constant out to the outside.
1779 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1781 AccumulatedConstant += Scale * C->getValue()->getValue();
1784 // Next comes everything else. We're especially interested in multiplies
1785 // here, but they're in the middle, so just visit the rest with one loop.
1786 for (; i != NumOperands; ++i) {
1787 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1788 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1790 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1791 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1792 // A multiplication of a constant with another add; recurse.
1793 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
1795 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1796 Add->op_begin(), Add->getNumOperands(),
1799 // A multiplication of a constant with some other value. Update
1801 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1802 const SCEV *Key = SE.getMulExpr(MulOps);
1803 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1804 M.insert(std::make_pair(Key, NewScale));
1806 NewOps.push_back(Pair.first->first);
1808 Pair.first->second += NewScale;
1809 // The map already had an entry for this value, which may indicate
1810 // a folding opportunity.
1815 // An ordinary operand. Update the map.
1816 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1817 M.insert(std::make_pair(Ops[i], Scale));
1819 NewOps.push_back(Pair.first->first);
1821 Pair.first->second += Scale;
1822 // The map already had an entry for this value, which may indicate
1823 // a folding opportunity.
1833 struct APIntCompare {
1834 bool operator()(const APInt &LHS, const APInt &RHS) const {
1835 return LHS.ult(RHS);
1840 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
1841 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
1842 // can't-overflow flags for the operation if possible.
1843 static SCEV::NoWrapFlags
1844 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
1845 const SmallVectorImpl<const SCEV *> &Ops,
1846 SCEV::NoWrapFlags OldFlags) {
1847 using namespace std::placeholders;
1850 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
1852 assert(CanAnalyze && "don't call from other places!");
1854 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
1855 SCEV::NoWrapFlags SignOrUnsignWrap =
1856 ScalarEvolution::maskFlags(OldFlags, SignOrUnsignMask);
1858 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
1859 auto IsKnownNonNegative =
1860 std::bind(std::mem_fn(&ScalarEvolution::isKnownNonNegative), SE, _1);
1862 if (SignOrUnsignWrap == SCEV::FlagNSW &&
1863 std::all_of(Ops.begin(), Ops.end(), IsKnownNonNegative))
1864 return ScalarEvolution::setFlags(OldFlags,
1865 (SCEV::NoWrapFlags)SignOrUnsignMask);
1870 /// getAddExpr - Get a canonical add expression, or something simpler if
1872 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1873 SCEV::NoWrapFlags Flags) {
1874 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
1875 "only nuw or nsw allowed");
1876 assert(!Ops.empty() && "Cannot get empty add!");
1877 if (Ops.size() == 1) return Ops[0];
1879 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
1880 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1881 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
1882 "SCEVAddExpr operand types don't match!");
1885 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
1887 // Sort by complexity, this groups all similar expression types together.
1888 GroupByComplexity(Ops, LI);
1890 // If there are any constants, fold them together.
1892 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1894 assert(Idx < Ops.size());
1895 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1896 // We found two constants, fold them together!
1897 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1898 RHSC->getValue()->getValue());
1899 if (Ops.size() == 2) return Ops[0];
1900 Ops.erase(Ops.begin()+1); // Erase the folded element
1901 LHSC = cast<SCEVConstant>(Ops[0]);
1904 // If we are left with a constant zero being added, strip it off.
1905 if (LHSC->getValue()->isZero()) {
1906 Ops.erase(Ops.begin());
1910 if (Ops.size() == 1) return Ops[0];
1913 // Okay, check to see if the same value occurs in the operand list more than
1914 // once. If so, merge them together into an multiply expression. Since we
1915 // sorted the list, these values are required to be adjacent.
1916 Type *Ty = Ops[0]->getType();
1917 bool FoundMatch = false;
1918 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
1919 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1920 // Scan ahead to count how many equal operands there are.
1922 while (i+Count != e && Ops[i+Count] == Ops[i])
1924 // Merge the values into a multiply.
1925 const SCEV *Scale = getConstant(Ty, Count);
1926 const SCEV *Mul = getMulExpr(Scale, Ops[i]);
1927 if (Ops.size() == Count)
1930 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
1931 --i; e -= Count - 1;
1935 return getAddExpr(Ops, Flags);
1937 // Check for truncates. If all the operands are truncated from the same
1938 // type, see if factoring out the truncate would permit the result to be
1939 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1940 // if the contents of the resulting outer trunc fold to something simple.
1941 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1942 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1943 Type *DstType = Trunc->getType();
1944 Type *SrcType = Trunc->getOperand()->getType();
1945 SmallVector<const SCEV *, 8> LargeOps;
1947 // Check all the operands to see if they can be represented in the
1948 // source type of the truncate.
1949 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1950 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1951 if (T->getOperand()->getType() != SrcType) {
1955 LargeOps.push_back(T->getOperand());
1956 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1957 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
1958 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
1959 SmallVector<const SCEV *, 8> LargeMulOps;
1960 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1961 if (const SCEVTruncateExpr *T =
1962 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1963 if (T->getOperand()->getType() != SrcType) {
1967 LargeMulOps.push_back(T->getOperand());
1968 } else if (const SCEVConstant *C =
1969 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1970 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
1977 LargeOps.push_back(getMulExpr(LargeMulOps));
1984 // Evaluate the expression in the larger type.
1985 const SCEV *Fold = getAddExpr(LargeOps, Flags);
1986 // If it folds to something simple, use it. Otherwise, don't.
1987 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1988 return getTruncateExpr(Fold, DstType);
1992 // Skip past any other cast SCEVs.
1993 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1996 // If there are add operands they would be next.
1997 if (Idx < Ops.size()) {
1998 bool DeletedAdd = false;
1999 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2000 // If we have an add, expand the add operands onto the end of the operands
2002 Ops.erase(Ops.begin()+Idx);
2003 Ops.append(Add->op_begin(), Add->op_end());
2007 // If we deleted at least one add, we added operands to the end of the list,
2008 // and they are not necessarily sorted. Recurse to resort and resimplify
2009 // any operands we just acquired.
2011 return getAddExpr(Ops);
2014 // Skip over the add expression until we get to a multiply.
2015 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2018 // Check to see if there are any folding opportunities present with
2019 // operands multiplied by constant values.
2020 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2021 uint64_t BitWidth = getTypeSizeInBits(Ty);
2022 DenseMap<const SCEV *, APInt> M;
2023 SmallVector<const SCEV *, 8> NewOps;
2024 APInt AccumulatedConstant(BitWidth, 0);
2025 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2026 Ops.data(), Ops.size(),
2027 APInt(BitWidth, 1), *this)) {
2028 // Some interesting folding opportunity is present, so its worthwhile to
2029 // re-generate the operands list. Group the operands by constant scale,
2030 // to avoid multiplying by the same constant scale multiple times.
2031 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2032 for (SmallVectorImpl<const SCEV *>::const_iterator I = NewOps.begin(),
2033 E = NewOps.end(); I != E; ++I)
2034 MulOpLists[M.find(*I)->second].push_back(*I);
2035 // Re-generate the operands list.
2037 if (AccumulatedConstant != 0)
2038 Ops.push_back(getConstant(AccumulatedConstant));
2039 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
2040 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
2042 Ops.push_back(getMulExpr(getConstant(I->first),
2043 getAddExpr(I->second)));
2045 return getConstant(Ty, 0);
2046 if (Ops.size() == 1)
2048 return getAddExpr(Ops);
2052 // If we are adding something to a multiply expression, make sure the
2053 // something is not already an operand of the multiply. If so, merge it into
2055 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2056 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2057 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2058 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2059 if (isa<SCEVConstant>(MulOpSCEV))
2061 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2062 if (MulOpSCEV == Ops[AddOp]) {
2063 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2064 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2065 if (Mul->getNumOperands() != 2) {
2066 // If the multiply has more than two operands, we must get the
2068 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2069 Mul->op_begin()+MulOp);
2070 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2071 InnerMul = getMulExpr(MulOps);
2073 const SCEV *One = getConstant(Ty, 1);
2074 const SCEV *AddOne = getAddExpr(One, InnerMul);
2075 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
2076 if (Ops.size() == 2) return OuterMul;
2078 Ops.erase(Ops.begin()+AddOp);
2079 Ops.erase(Ops.begin()+Idx-1);
2081 Ops.erase(Ops.begin()+Idx);
2082 Ops.erase(Ops.begin()+AddOp-1);
2084 Ops.push_back(OuterMul);
2085 return getAddExpr(Ops);
2088 // Check this multiply against other multiplies being added together.
2089 for (unsigned OtherMulIdx = Idx+1;
2090 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2092 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2093 // If MulOp occurs in OtherMul, we can fold the two multiplies
2095 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2096 OMulOp != e; ++OMulOp)
2097 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2098 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2099 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2100 if (Mul->getNumOperands() != 2) {
2101 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2102 Mul->op_begin()+MulOp);
2103 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2104 InnerMul1 = getMulExpr(MulOps);
2106 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2107 if (OtherMul->getNumOperands() != 2) {
2108 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2109 OtherMul->op_begin()+OMulOp);
2110 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2111 InnerMul2 = getMulExpr(MulOps);
2113 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
2114 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
2115 if (Ops.size() == 2) return OuterMul;
2116 Ops.erase(Ops.begin()+Idx);
2117 Ops.erase(Ops.begin()+OtherMulIdx-1);
2118 Ops.push_back(OuterMul);
2119 return getAddExpr(Ops);
2125 // If there are any add recurrences in the operands list, see if any other
2126 // added values are loop invariant. If so, we can fold them into the
2128 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2131 // Scan over all recurrences, trying to fold loop invariants into them.
2132 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2133 // Scan all of the other operands to this add and add them to the vector if
2134 // they are loop invariant w.r.t. the recurrence.
2135 SmallVector<const SCEV *, 8> LIOps;
2136 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2137 const Loop *AddRecLoop = AddRec->getLoop();
2138 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2139 if (isLoopInvariant(Ops[i], AddRecLoop)) {
2140 LIOps.push_back(Ops[i]);
2141 Ops.erase(Ops.begin()+i);
2145 // If we found some loop invariants, fold them into the recurrence.
2146 if (!LIOps.empty()) {
2147 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2148 LIOps.push_back(AddRec->getStart());
2150 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2152 AddRecOps[0] = getAddExpr(LIOps);
2154 // Build the new addrec. Propagate the NUW and NSW flags if both the
2155 // outer add and the inner addrec are guaranteed to have no overflow.
2156 // Always propagate NW.
2157 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2158 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2160 // If all of the other operands were loop invariant, we are done.
2161 if (Ops.size() == 1) return NewRec;
2163 // Otherwise, add the folded AddRec by the non-invariant parts.
2164 for (unsigned i = 0;; ++i)
2165 if (Ops[i] == AddRec) {
2169 return getAddExpr(Ops);
2172 // Okay, if there weren't any loop invariants to be folded, check to see if
2173 // there are multiple AddRec's with the same loop induction variable being
2174 // added together. If so, we can fold them.
2175 for (unsigned OtherIdx = Idx+1;
2176 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2178 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2179 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2180 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2182 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2184 if (const SCEVAddRecExpr *OtherAddRec =
2185 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
2186 if (OtherAddRec->getLoop() == AddRecLoop) {
2187 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2189 if (i >= AddRecOps.size()) {
2190 AddRecOps.append(OtherAddRec->op_begin()+i,
2191 OtherAddRec->op_end());
2194 AddRecOps[i] = getAddExpr(AddRecOps[i],
2195 OtherAddRec->getOperand(i));
2197 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2199 // Step size has changed, so we cannot guarantee no self-wraparound.
2200 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2201 return getAddExpr(Ops);
2204 // Otherwise couldn't fold anything into this recurrence. Move onto the
2208 // Okay, it looks like we really DO need an add expr. Check to see if we
2209 // already have one, otherwise create a new one.
2210 FoldingSetNodeID ID;
2211 ID.AddInteger(scAddExpr);
2212 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2213 ID.AddPointer(Ops[i]);
2216 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2218 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2219 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2220 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
2222 UniqueSCEVs.InsertNode(S, IP);
2224 S->setNoWrapFlags(Flags);
2228 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2230 if (j > 1 && k / j != i) Overflow = true;
2234 /// Compute the result of "n choose k", the binomial coefficient. If an
2235 /// intermediate computation overflows, Overflow will be set and the return will
2236 /// be garbage. Overflow is not cleared on absence of overflow.
2237 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2238 // We use the multiplicative formula:
2239 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2240 // At each iteration, we take the n-th term of the numeral and divide by the
2241 // (k-n)th term of the denominator. This division will always produce an
2242 // integral result, and helps reduce the chance of overflow in the
2243 // intermediate computations. However, we can still overflow even when the
2244 // final result would fit.
2246 if (n == 0 || n == k) return 1;
2247 if (k > n) return 0;
2253 for (uint64_t i = 1; i <= k; ++i) {
2254 r = umul_ov(r, n-(i-1), Overflow);
2260 /// Determine if any of the operands in this SCEV are a constant or if
2261 /// any of the add or multiply expressions in this SCEV contain a constant.
2262 static bool containsConstantSomewhere(const SCEV *StartExpr) {
2263 SmallVector<const SCEV *, 4> Ops;
2264 Ops.push_back(StartExpr);
2265 while (!Ops.empty()) {
2266 const SCEV *CurrentExpr = Ops.pop_back_val();
2267 if (isa<SCEVConstant>(*CurrentExpr))
2270 if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) {
2271 const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr);
2272 Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end());
2278 /// getMulExpr - Get a canonical multiply expression, or something simpler if
2280 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2281 SCEV::NoWrapFlags Flags) {
2282 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2283 "only nuw or nsw allowed");
2284 assert(!Ops.empty() && "Cannot get empty mul!");
2285 if (Ops.size() == 1) return Ops[0];
2287 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2288 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2289 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2290 "SCEVMulExpr operand types don't match!");
2293 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2295 // Sort by complexity, this groups all similar expression types together.
2296 GroupByComplexity(Ops, LI);
2298 // If there are any constants, fold them together.
2300 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2302 // C1*(C2+V) -> C1*C2 + C1*V
2303 if (Ops.size() == 2)
2304 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2305 // If any of Add's ops are Adds or Muls with a constant,
2306 // apply this transformation as well.
2307 if (Add->getNumOperands() == 2)
2308 if (containsConstantSomewhere(Add))
2309 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
2310 getMulExpr(LHSC, Add->getOperand(1)));
2313 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2314 // We found two constants, fold them together!
2315 ConstantInt *Fold = ConstantInt::get(getContext(),
2316 LHSC->getValue()->getValue() *
2317 RHSC->getValue()->getValue());
2318 Ops[0] = getConstant(Fold);
2319 Ops.erase(Ops.begin()+1); // Erase the folded element
2320 if (Ops.size() == 1) return Ops[0];
2321 LHSC = cast<SCEVConstant>(Ops[0]);
2324 // If we are left with a constant one being multiplied, strip it off.
2325 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
2326 Ops.erase(Ops.begin());
2328 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2329 // If we have a multiply of zero, it will always be zero.
2331 } else if (Ops[0]->isAllOnesValue()) {
2332 // If we have a mul by -1 of an add, try distributing the -1 among the
2334 if (Ops.size() == 2) {
2335 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2336 SmallVector<const SCEV *, 4> NewOps;
2337 bool AnyFolded = false;
2338 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(),
2339 E = Add->op_end(); I != E; ++I) {
2340 const SCEV *Mul = getMulExpr(Ops[0], *I);
2341 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2342 NewOps.push_back(Mul);
2345 return getAddExpr(NewOps);
2347 else if (const SCEVAddRecExpr *
2348 AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2349 // Negation preserves a recurrence's no self-wrap property.
2350 SmallVector<const SCEV *, 4> Operands;
2351 for (SCEVAddRecExpr::op_iterator I = AddRec->op_begin(),
2352 E = AddRec->op_end(); I != E; ++I) {
2353 Operands.push_back(getMulExpr(Ops[0], *I));
2355 return getAddRecExpr(Operands, AddRec->getLoop(),
2356 AddRec->getNoWrapFlags(SCEV::FlagNW));
2361 if (Ops.size() == 1)
2365 // Skip over the add expression until we get to a multiply.
2366 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2369 // If there are mul operands inline them all into this expression.
2370 if (Idx < Ops.size()) {
2371 bool DeletedMul = false;
2372 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2373 // If we have an mul, expand the mul operands onto the end of the operands
2375 Ops.erase(Ops.begin()+Idx);
2376 Ops.append(Mul->op_begin(), Mul->op_end());
2380 // If we deleted at least one mul, we added operands to the end of the list,
2381 // and they are not necessarily sorted. Recurse to resort and resimplify
2382 // any operands we just acquired.
2384 return getMulExpr(Ops);
2387 // If there are any add recurrences in the operands list, see if any other
2388 // added values are loop invariant. If so, we can fold them into the
2390 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2393 // Scan over all recurrences, trying to fold loop invariants into them.
2394 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2395 // Scan all of the other operands to this mul and add them to the vector if
2396 // they are loop invariant w.r.t. the recurrence.
2397 SmallVector<const SCEV *, 8> LIOps;
2398 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2399 const Loop *AddRecLoop = AddRec->getLoop();
2400 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2401 if (isLoopInvariant(Ops[i], AddRecLoop)) {
2402 LIOps.push_back(Ops[i]);
2403 Ops.erase(Ops.begin()+i);
2407 // If we found some loop invariants, fold them into the recurrence.
2408 if (!LIOps.empty()) {
2409 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
2410 SmallVector<const SCEV *, 4> NewOps;
2411 NewOps.reserve(AddRec->getNumOperands());
2412 const SCEV *Scale = getMulExpr(LIOps);
2413 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2414 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
2416 // Build the new addrec. Propagate the NUW and NSW flags if both the
2417 // outer mul and the inner addrec are guaranteed to have no overflow.
2419 // No self-wrap cannot be guaranteed after changing the step size, but
2420 // will be inferred if either NUW or NSW is true.
2421 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2422 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
2424 // If all of the other operands were loop invariant, we are done.
2425 if (Ops.size() == 1) return NewRec;
2427 // Otherwise, multiply the folded AddRec by the non-invariant parts.
2428 for (unsigned i = 0;; ++i)
2429 if (Ops[i] == AddRec) {
2433 return getMulExpr(Ops);
2436 // Okay, if there weren't any loop invariants to be folded, check to see if
2437 // there are multiple AddRec's with the same loop induction variable being
2438 // multiplied together. If so, we can fold them.
2440 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2441 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2442 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2443 // ]]],+,...up to x=2n}.
2444 // Note that the arguments to choose() are always integers with values
2445 // known at compile time, never SCEV objects.
2447 // The implementation avoids pointless extra computations when the two
2448 // addrec's are of different length (mathematically, it's equivalent to
2449 // an infinite stream of zeros on the right).
2450 bool OpsModified = false;
2451 for (unsigned OtherIdx = Idx+1;
2452 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2454 const SCEVAddRecExpr *OtherAddRec =
2455 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2456 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
2459 bool Overflow = false;
2460 Type *Ty = AddRec->getType();
2461 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2462 SmallVector<const SCEV*, 7> AddRecOps;
2463 for (int x = 0, xe = AddRec->getNumOperands() +
2464 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
2465 const SCEV *Term = getConstant(Ty, 0);
2466 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2467 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2468 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2469 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2470 z < ze && !Overflow; ++z) {
2471 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2473 if (LargerThan64Bits)
2474 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2476 Coeff = Coeff1*Coeff2;
2477 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2478 const SCEV *Term1 = AddRec->getOperand(y-z);
2479 const SCEV *Term2 = OtherAddRec->getOperand(z);
2480 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
2483 AddRecOps.push_back(Term);
2486 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2488 if (Ops.size() == 2) return NewAddRec;
2489 Ops[Idx] = NewAddRec;
2490 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2492 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2498 return getMulExpr(Ops);
2500 // Otherwise couldn't fold anything into this recurrence. Move onto the
2504 // Okay, it looks like we really DO need an mul expr. Check to see if we
2505 // already have one, otherwise create a new one.
2506 FoldingSetNodeID ID;
2507 ID.AddInteger(scMulExpr);
2508 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2509 ID.AddPointer(Ops[i]);
2512 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2514 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2515 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2516 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2518 UniqueSCEVs.InsertNode(S, IP);
2520 S->setNoWrapFlags(Flags);
2524 /// getUDivExpr - Get a canonical unsigned division expression, or something
2525 /// simpler if possible.
2526 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2528 assert(getEffectiveSCEVType(LHS->getType()) ==
2529 getEffectiveSCEVType(RHS->getType()) &&
2530 "SCEVUDivExpr operand types don't match!");
2532 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
2533 if (RHSC->getValue()->equalsInt(1))
2534 return LHS; // X udiv 1 --> x
2535 // If the denominator is zero, the result of the udiv is undefined. Don't
2536 // try to analyze it, because the resolution chosen here may differ from
2537 // the resolution chosen in other parts of the compiler.
2538 if (!RHSC->getValue()->isZero()) {
2539 // Determine if the division can be folded into the operands of
2541 // TODO: Generalize this to non-constants by using known-bits information.
2542 Type *Ty = LHS->getType();
2543 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
2544 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
2545 // For non-power-of-two values, effectively round the value up to the
2546 // nearest power of two.
2547 if (!RHSC->getValue()->getValue().isPowerOf2())
2549 IntegerType *ExtTy =
2550 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
2551 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2552 if (const SCEVConstant *Step =
2553 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2554 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
2555 const APInt &StepInt = Step->getValue()->getValue();
2556 const APInt &DivInt = RHSC->getValue()->getValue();
2557 if (!StepInt.urem(DivInt) &&
2558 getZeroExtendExpr(AR, ExtTy) ==
2559 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2560 getZeroExtendExpr(Step, ExtTy),
2561 AR->getLoop(), SCEV::FlagAnyWrap)) {
2562 SmallVector<const SCEV *, 4> Operands;
2563 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
2564 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
2565 return getAddRecExpr(Operands, AR->getLoop(),
2568 /// Get a canonical UDivExpr for a recurrence.
2569 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2570 // We can currently only fold X%N if X is constant.
2571 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2572 if (StartC && !DivInt.urem(StepInt) &&
2573 getZeroExtendExpr(AR, ExtTy) ==
2574 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2575 getZeroExtendExpr(Step, ExtTy),
2576 AR->getLoop(), SCEV::FlagAnyWrap)) {
2577 const APInt &StartInt = StartC->getValue()->getValue();
2578 const APInt &StartRem = StartInt.urem(StepInt);
2580 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2581 AR->getLoop(), SCEV::FlagNW);
2584 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2585 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2586 SmallVector<const SCEV *, 4> Operands;
2587 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
2588 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
2589 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2590 // Find an operand that's safely divisible.
2591 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2592 const SCEV *Op = M->getOperand(i);
2593 const SCEV *Div = getUDivExpr(Op, RHSC);
2594 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2595 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2598 return getMulExpr(Operands);
2602 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
2603 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
2604 SmallVector<const SCEV *, 4> Operands;
2605 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
2606 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
2607 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2609 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2610 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2611 if (isa<SCEVUDivExpr>(Op) ||
2612 getMulExpr(Op, RHS) != A->getOperand(i))
2614 Operands.push_back(Op);
2616 if (Operands.size() == A->getNumOperands())
2617 return getAddExpr(Operands);
2621 // Fold if both operands are constant.
2622 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2623 Constant *LHSCV = LHSC->getValue();
2624 Constant *RHSCV = RHSC->getValue();
2625 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2631 FoldingSetNodeID ID;
2632 ID.AddInteger(scUDivExpr);
2636 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2637 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2639 UniqueSCEVs.InsertNode(S, IP);
2643 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
2644 APInt A = C1->getValue()->getValue().abs();
2645 APInt B = C2->getValue()->getValue().abs();
2646 uint32_t ABW = A.getBitWidth();
2647 uint32_t BBW = B.getBitWidth();
2654 return APIntOps::GreatestCommonDivisor(A, B);
2657 /// getUDivExactExpr - Get a canonical unsigned division expression, or
2658 /// something simpler if possible. There is no representation for an exact udiv
2659 /// in SCEV IR, but we can attempt to remove factors from the LHS and RHS.
2660 /// We can't do this when it's not exact because the udiv may be clearing bits.
2661 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
2663 // TODO: we could try to find factors in all sorts of things, but for now we
2664 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
2665 // end of this file for inspiration.
2667 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
2669 return getUDivExpr(LHS, RHS);
2671 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
2672 // If the mulexpr multiplies by a constant, then that constant must be the
2673 // first element of the mulexpr.
2674 if (const SCEVConstant *LHSCst =
2675 dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
2676 if (LHSCst == RHSCst) {
2677 SmallVector<const SCEV *, 2> Operands;
2678 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2679 return getMulExpr(Operands);
2682 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
2683 // that there's a factor provided by one of the other terms. We need to
2685 APInt Factor = gcd(LHSCst, RHSCst);
2686 if (!Factor.isIntN(1)) {
2687 LHSCst = cast<SCEVConstant>(
2688 getConstant(LHSCst->getValue()->getValue().udiv(Factor)));
2689 RHSCst = cast<SCEVConstant>(
2690 getConstant(RHSCst->getValue()->getValue().udiv(Factor)));
2691 SmallVector<const SCEV *, 2> Operands;
2692 Operands.push_back(LHSCst);
2693 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2694 LHS = getMulExpr(Operands);
2696 Mul = dyn_cast<SCEVMulExpr>(LHS);
2698 return getUDivExactExpr(LHS, RHS);
2703 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
2704 if (Mul->getOperand(i) == RHS) {
2705 SmallVector<const SCEV *, 2> Operands;
2706 Operands.append(Mul->op_begin(), Mul->op_begin() + i);
2707 Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
2708 return getMulExpr(Operands);
2712 return getUDivExpr(LHS, RHS);
2715 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
2716 /// Simplify the expression as much as possible.
2717 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
2719 SCEV::NoWrapFlags Flags) {
2720 SmallVector<const SCEV *, 4> Operands;
2721 Operands.push_back(Start);
2722 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
2723 if (StepChrec->getLoop() == L) {
2724 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
2725 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
2728 Operands.push_back(Step);
2729 return getAddRecExpr(Operands, L, Flags);
2732 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
2733 /// Simplify the expression as much as possible.
2735 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
2736 const Loop *L, SCEV::NoWrapFlags Flags) {
2737 if (Operands.size() == 1) return Operands[0];
2739 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
2740 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
2741 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
2742 "SCEVAddRecExpr operand types don't match!");
2743 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2744 assert(isLoopInvariant(Operands[i], L) &&
2745 "SCEVAddRecExpr operand is not loop-invariant!");
2748 if (Operands.back()->isZero()) {
2749 Operands.pop_back();
2750 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
2753 // It's tempting to want to call getMaxBackedgeTakenCount count here and
2754 // use that information to infer NUW and NSW flags. However, computing a
2755 // BE count requires calling getAddRecExpr, so we may not yet have a
2756 // meaningful BE count at this point (and if we don't, we'd be stuck
2757 // with a SCEVCouldNotCompute as the cached BE count).
2759 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
2761 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
2762 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
2763 const Loop *NestedLoop = NestedAR->getLoop();
2764 if (L->contains(NestedLoop) ?
2765 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
2766 (!NestedLoop->contains(L) &&
2767 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
2768 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
2769 NestedAR->op_end());
2770 Operands[0] = NestedAR->getStart();
2771 // AddRecs require their operands be loop-invariant with respect to their
2772 // loops. Don't perform this transformation if it would break this
2774 bool AllInvariant = true;
2775 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2776 if (!isLoopInvariant(Operands[i], L)) {
2777 AllInvariant = false;
2781 // Create a recurrence for the outer loop with the same step size.
2783 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
2784 // inner recurrence has the same property.
2785 SCEV::NoWrapFlags OuterFlags =
2786 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
2788 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
2789 AllInvariant = true;
2790 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
2791 if (!isLoopInvariant(NestedOperands[i], NestedLoop)) {
2792 AllInvariant = false;
2796 // Ok, both add recurrences are valid after the transformation.
2798 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
2799 // the outer recurrence has the same property.
2800 SCEV::NoWrapFlags InnerFlags =
2801 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
2802 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
2805 // Reset Operands to its original state.
2806 Operands[0] = NestedAR;
2810 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2811 // already have one, otherwise create a new one.
2812 FoldingSetNodeID ID;
2813 ID.AddInteger(scAddRecExpr);
2814 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2815 ID.AddPointer(Operands[i]);
2819 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2821 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2822 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
2823 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2824 O, Operands.size(), L);
2825 UniqueSCEVs.InsertNode(S, IP);
2827 S->setNoWrapFlags(Flags);
2831 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2833 SmallVector<const SCEV *, 2> Ops;
2836 return getSMaxExpr(Ops);
2840 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2841 assert(!Ops.empty() && "Cannot get empty smax!");
2842 if (Ops.size() == 1) return Ops[0];
2844 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2845 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2846 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2847 "SCEVSMaxExpr operand types don't match!");
2850 // Sort by complexity, this groups all similar expression types together.
2851 GroupByComplexity(Ops, LI);
2853 // If there are any constants, fold them together.
2855 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2857 assert(Idx < Ops.size());
2858 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2859 // We found two constants, fold them together!
2860 ConstantInt *Fold = ConstantInt::get(getContext(),
2861 APIntOps::smax(LHSC->getValue()->getValue(),
2862 RHSC->getValue()->getValue()));
2863 Ops[0] = getConstant(Fold);
2864 Ops.erase(Ops.begin()+1); // Erase the folded element
2865 if (Ops.size() == 1) return Ops[0];
2866 LHSC = cast<SCEVConstant>(Ops[0]);
2869 // If we are left with a constant minimum-int, strip it off.
2870 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2871 Ops.erase(Ops.begin());
2873 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2874 // If we have an smax with a constant maximum-int, it will always be
2879 if (Ops.size() == 1) return Ops[0];
2882 // Find the first SMax
2883 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2886 // Check to see if one of the operands is an SMax. If so, expand its operands
2887 // onto our operand list, and recurse to simplify.
2888 if (Idx < Ops.size()) {
2889 bool DeletedSMax = false;
2890 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
2891 Ops.erase(Ops.begin()+Idx);
2892 Ops.append(SMax->op_begin(), SMax->op_end());
2897 return getSMaxExpr(Ops);
2900 // Okay, check to see if the same value occurs in the operand list twice. If
2901 // so, delete one. Since we sorted the list, these values are required to
2903 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2904 // X smax Y smax Y --> X smax Y
2905 // X smax Y --> X, if X is always greater than Y
2906 if (Ops[i] == Ops[i+1] ||
2907 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
2908 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2910 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
2911 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2915 if (Ops.size() == 1) return Ops[0];
2917 assert(!Ops.empty() && "Reduced smax down to nothing!");
2919 // Okay, it looks like we really DO need an smax expr. Check to see if we
2920 // already have one, otherwise create a new one.
2921 FoldingSetNodeID ID;
2922 ID.AddInteger(scSMaxExpr);
2923 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2924 ID.AddPointer(Ops[i]);
2926 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2927 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2928 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2929 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
2931 UniqueSCEVs.InsertNode(S, IP);
2935 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2937 SmallVector<const SCEV *, 2> Ops;
2940 return getUMaxExpr(Ops);
2944 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2945 assert(!Ops.empty() && "Cannot get empty umax!");
2946 if (Ops.size() == 1) return Ops[0];
2948 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2949 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2950 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2951 "SCEVUMaxExpr operand types don't match!");
2954 // Sort by complexity, this groups all similar expression types together.
2955 GroupByComplexity(Ops, LI);
2957 // If there are any constants, fold them together.
2959 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2961 assert(Idx < Ops.size());
2962 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2963 // We found two constants, fold them together!
2964 ConstantInt *Fold = ConstantInt::get(getContext(),
2965 APIntOps::umax(LHSC->getValue()->getValue(),
2966 RHSC->getValue()->getValue()));
2967 Ops[0] = getConstant(Fold);
2968 Ops.erase(Ops.begin()+1); // Erase the folded element
2969 if (Ops.size() == 1) return Ops[0];
2970 LHSC = cast<SCEVConstant>(Ops[0]);
2973 // If we are left with a constant minimum-int, strip it off.
2974 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2975 Ops.erase(Ops.begin());
2977 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2978 // If we have an umax with a constant maximum-int, it will always be
2983 if (Ops.size() == 1) return Ops[0];
2986 // Find the first UMax
2987 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2990 // Check to see if one of the operands is a UMax. If so, expand its operands
2991 // onto our operand list, and recurse to simplify.
2992 if (Idx < Ops.size()) {
2993 bool DeletedUMax = false;
2994 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
2995 Ops.erase(Ops.begin()+Idx);
2996 Ops.append(UMax->op_begin(), UMax->op_end());
3001 return getUMaxExpr(Ops);
3004 // Okay, check to see if the same value occurs in the operand list twice. If
3005 // so, delete one. Since we sorted the list, these values are required to
3007 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3008 // X umax Y umax Y --> X umax Y
3009 // X umax Y --> X, if X is always greater than Y
3010 if (Ops[i] == Ops[i+1] ||
3011 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3012 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3014 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
3015 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3019 if (Ops.size() == 1) return Ops[0];
3021 assert(!Ops.empty() && "Reduced umax down to nothing!");
3023 // Okay, it looks like we really DO need a umax expr. Check to see if we
3024 // already have one, otherwise create a new one.
3025 FoldingSetNodeID ID;
3026 ID.AddInteger(scUMaxExpr);
3027 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3028 ID.AddPointer(Ops[i]);
3030 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3031 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3032 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3033 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3035 UniqueSCEVs.InsertNode(S, IP);
3039 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3041 // ~smax(~x, ~y) == smin(x, y).
3042 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3045 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3047 // ~umax(~x, ~y) == umin(x, y)
3048 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3051 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3052 // If we have DataLayout, we can bypass creating a target-independent
3053 // constant expression and then folding it back into a ConstantInt.
3054 // This is just a compile-time optimization.
3056 return getConstant(IntTy, DL->getTypeAllocSize(AllocTy));
3058 Constant *C = ConstantExpr::getSizeOf(AllocTy);
3059 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
3060 if (Constant *Folded = ConstantFoldConstantExpression(CE, DL, TLI))
3062 Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
3063 assert(Ty == IntTy && "Effective SCEV type doesn't match");
3064 return getTruncateOrZeroExtend(getSCEV(C), Ty);
3067 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3070 // If we have DataLayout, we can bypass creating a target-independent
3071 // constant expression and then folding it back into a ConstantInt.
3072 // This is just a compile-time optimization.
3074 return getConstant(IntTy,
3075 DL->getStructLayout(STy)->getElementOffset(FieldNo));
3078 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
3079 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
3080 if (Constant *Folded = ConstantFoldConstantExpression(CE, DL, TLI))
3083 Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
3084 return getTruncateOrZeroExtend(getSCEV(C), Ty);
3087 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3088 // Don't attempt to do anything other than create a SCEVUnknown object
3089 // here. createSCEV only calls getUnknown after checking for all other
3090 // interesting possibilities, and any other code that calls getUnknown
3091 // is doing so in order to hide a value from SCEV canonicalization.
3093 FoldingSetNodeID ID;
3094 ID.AddInteger(scUnknown);
3097 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3098 assert(cast<SCEVUnknown>(S)->getValue() == V &&
3099 "Stale SCEVUnknown in uniquing map!");
3102 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3104 FirstUnknown = cast<SCEVUnknown>(S);
3105 UniqueSCEVs.InsertNode(S, IP);
3109 //===----------------------------------------------------------------------===//
3110 // Basic SCEV Analysis and PHI Idiom Recognition Code
3113 /// isSCEVable - Test if values of the given type are analyzable within
3114 /// the SCEV framework. This primarily includes integer types, and it
3115 /// can optionally include pointer types if the ScalarEvolution class
3116 /// has access to target-specific information.
3117 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3118 // Integers and pointers are always SCEVable.
3119 return Ty->isIntegerTy() || Ty->isPointerTy();
3122 /// getTypeSizeInBits - Return the size in bits of the specified type,
3123 /// for which isSCEVable must return true.
3124 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3125 assert(isSCEVable(Ty) && "Type is not SCEVable!");
3127 // If we have a DataLayout, use it!
3129 return DL->getTypeSizeInBits(Ty);
3131 // Integer types have fixed sizes.
3132 if (Ty->isIntegerTy())
3133 return Ty->getPrimitiveSizeInBits();
3135 // The only other support type is pointer. Without DataLayout, conservatively
3136 // assume pointers are 64-bit.
3137 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
3141 /// getEffectiveSCEVType - Return a type with the same bitwidth as
3142 /// the given type and which represents how SCEV will treat the given
3143 /// type, for which isSCEVable must return true. For pointer types,
3144 /// this is the pointer-sized integer type.
3145 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3146 assert(isSCEVable(Ty) && "Type is not SCEVable!");
3148 if (Ty->isIntegerTy()) {
3152 // The only other support type is pointer.
3153 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3156 return DL->getIntPtrType(Ty);
3158 // Without DataLayout, conservatively assume pointers are 64-bit.
3159 return Type::getInt64Ty(getContext());
3162 const SCEV *ScalarEvolution::getCouldNotCompute() {
3163 return &CouldNotCompute;
3167 // Helper class working with SCEVTraversal to figure out if a SCEV contains
3168 // a SCEVUnknown with null value-pointer. FindInvalidSCEVUnknown::FindOne
3169 // is set iff if find such SCEVUnknown.
3171 struct FindInvalidSCEVUnknown {
3173 FindInvalidSCEVUnknown() { FindOne = false; }
3174 bool follow(const SCEV *S) {
3175 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
3179 if (!cast<SCEVUnknown>(S)->getValue())
3186 bool isDone() const { return FindOne; }
3190 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3191 FindInvalidSCEVUnknown F;
3192 SCEVTraversal<FindInvalidSCEVUnknown> ST(F);
3198 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
3199 /// expression and create a new one.
3200 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3201 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3203 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3204 if (I != ValueExprMap.end()) {
3205 const SCEV *S = I->second;
3206 if (checkValidity(S))
3209 ValueExprMap.erase(I);
3211 const SCEV *S = createSCEV(V);
3213 // The process of creating a SCEV for V may have caused other SCEVs
3214 // to have been created, so it's necessary to insert the new entry
3215 // from scratch, rather than trying to remember the insert position
3217 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(V, this), S));
3221 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
3223 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
3224 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3226 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3228 Type *Ty = V->getType();
3229 Ty = getEffectiveSCEVType(Ty);
3230 return getMulExpr(V,
3231 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
3234 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
3235 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3236 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3238 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3240 Type *Ty = V->getType();
3241 Ty = getEffectiveSCEVType(Ty);
3242 const SCEV *AllOnes =
3243 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3244 return getMinusSCEV(AllOnes, V);
3247 /// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
3248 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3249 SCEV::NoWrapFlags Flags) {
3250 assert(!maskFlags(Flags, SCEV::FlagNUW) && "subtraction does not have NUW");
3252 // Fast path: X - X --> 0.
3254 return getConstant(LHS->getType(), 0);
3256 // X - Y --> X + -Y.
3257 // X -(nsw || nuw) Y --> X + -Y.
3258 return getAddExpr(LHS, getNegativeSCEV(RHS));
3261 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
3262 /// input value to the specified type. If the type must be extended, it is zero
3265 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3266 Type *SrcTy = V->getType();
3267 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3268 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3269 "Cannot truncate or zero extend with non-integer arguments!");
3270 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3271 return V; // No conversion
3272 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3273 return getTruncateExpr(V, Ty);
3274 return getZeroExtendExpr(V, Ty);
3277 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
3278 /// input value to the specified type. If the type must be extended, it is sign
3281 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
3283 Type *SrcTy = V->getType();
3284 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3285 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3286 "Cannot truncate or zero extend with non-integer arguments!");
3287 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3288 return V; // No conversion
3289 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3290 return getTruncateExpr(V, Ty);
3291 return getSignExtendExpr(V, Ty);
3294 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
3295 /// input value to the specified type. If the type must be extended, it is zero
3296 /// extended. The conversion must not be narrowing.
3298 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3299 Type *SrcTy = V->getType();
3300 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3301 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3302 "Cannot noop or zero extend with non-integer arguments!");
3303 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3304 "getNoopOrZeroExtend cannot truncate!");
3305 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3306 return V; // No conversion
3307 return getZeroExtendExpr(V, Ty);
3310 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
3311 /// input value to the specified type. If the type must be extended, it is sign
3312 /// extended. The conversion must not be narrowing.
3314 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3315 Type *SrcTy = V->getType();
3316 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3317 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3318 "Cannot noop or sign extend with non-integer arguments!");
3319 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3320 "getNoopOrSignExtend cannot truncate!");
3321 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3322 return V; // No conversion
3323 return getSignExtendExpr(V, Ty);
3326 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
3327 /// the input value to the specified type. If the type must be extended,
3328 /// it is extended with unspecified bits. The conversion must not be
3331 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3332 Type *SrcTy = V->getType();
3333 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3334 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3335 "Cannot noop or any extend with non-integer arguments!");
3336 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3337 "getNoopOrAnyExtend cannot truncate!");
3338 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3339 return V; // No conversion
3340 return getAnyExtendExpr(V, Ty);
3343 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
3344 /// input value to the specified type. The conversion must not be widening.
3346 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3347 Type *SrcTy = V->getType();
3348 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3349 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3350 "Cannot truncate or noop with non-integer arguments!");
3351 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3352 "getTruncateOrNoop cannot extend!");
3353 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3354 return V; // No conversion
3355 return getTruncateExpr(V, Ty);
3358 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
3359 /// the types using zero-extension, and then perform a umax operation
3361 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3363 const SCEV *PromotedLHS = LHS;
3364 const SCEV *PromotedRHS = RHS;
3366 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3367 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3369 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3371 return getUMaxExpr(PromotedLHS, PromotedRHS);
3374 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
3375 /// the types using zero-extension, and then perform a umin operation
3377 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3379 const SCEV *PromotedLHS = LHS;
3380 const SCEV *PromotedRHS = RHS;
3382 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3383 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3385 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3387 return getUMinExpr(PromotedLHS, PromotedRHS);
3390 /// getPointerBase - Transitively follow the chain of pointer-type operands
3391 /// until reaching a SCEV that does not have a single pointer operand. This
3392 /// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
3393 /// but corner cases do exist.
3394 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3395 // A pointer operand may evaluate to a nonpointer expression, such as null.
3396 if (!V->getType()->isPointerTy())
3399 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3400 return getPointerBase(Cast->getOperand());
3402 else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
3403 const SCEV *PtrOp = nullptr;
3404 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
3406 if ((*I)->getType()->isPointerTy()) {
3407 // Cannot find the base of an expression with multiple pointer operands.
3415 return getPointerBase(PtrOp);
3420 /// PushDefUseChildren - Push users of the given Instruction
3421 /// onto the given Worklist.
3423 PushDefUseChildren(Instruction *I,
3424 SmallVectorImpl<Instruction *> &Worklist) {
3425 // Push the def-use children onto the Worklist stack.
3426 for (User *U : I->users())
3427 Worklist.push_back(cast<Instruction>(U));
3430 /// ForgetSymbolicValue - This looks up computed SCEV values for all
3431 /// instructions that depend on the given instruction and removes them from
3432 /// the ValueExprMapType map if they reference SymName. This is used during PHI
3435 ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
3436 SmallVector<Instruction *, 16> Worklist;
3437 PushDefUseChildren(PN, Worklist);
3439 SmallPtrSet<Instruction *, 8> Visited;
3441 while (!Worklist.empty()) {
3442 Instruction *I = Worklist.pop_back_val();
3443 if (!Visited.insert(I).second)
3446 ValueExprMapType::iterator It =
3447 ValueExprMap.find_as(static_cast<Value *>(I));
3448 if (It != ValueExprMap.end()) {
3449 const SCEV *Old = It->second;
3451 // Short-circuit the def-use traversal if the symbolic name
3452 // ceases to appear in expressions.
3453 if (Old != SymName && !hasOperand(Old, SymName))
3456 // SCEVUnknown for a PHI either means that it has an unrecognized
3457 // structure, it's a PHI that's in the progress of being computed
3458 // by createNodeForPHI, or it's a single-value PHI. In the first case,
3459 // additional loop trip count information isn't going to change anything.
3460 // In the second case, createNodeForPHI will perform the necessary
3461 // updates on its own when it gets to that point. In the third, we do
3462 // want to forget the SCEVUnknown.
3463 if (!isa<PHINode>(I) ||
3464 !isa<SCEVUnknown>(Old) ||
3465 (I != PN && Old == SymName)) {
3466 forgetMemoizedResults(Old);
3467 ValueExprMap.erase(It);
3471 PushDefUseChildren(I, Worklist);
3475 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
3476 /// a loop header, making it a potential recurrence, or it doesn't.
3478 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
3479 if (const Loop *L = LI->getLoopFor(PN->getParent()))
3480 if (L->getHeader() == PN->getParent()) {
3481 // The loop may have multiple entrances or multiple exits; we can analyze
3482 // this phi as an addrec if it has a unique entry value and a unique
3484 Value *BEValueV = nullptr, *StartValueV = nullptr;
3485 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3486 Value *V = PN->getIncomingValue(i);
3487 if (L->contains(PN->getIncomingBlock(i))) {
3490 } else if (BEValueV != V) {
3494 } else if (!StartValueV) {
3496 } else if (StartValueV != V) {
3497 StartValueV = nullptr;
3501 if (BEValueV && StartValueV) {
3502 // While we are analyzing this PHI node, handle its value symbolically.
3503 const SCEV *SymbolicName = getUnknown(PN);
3504 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
3505 "PHI node already processed?");
3506 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
3508 // Using this symbolic name for the PHI, analyze the value coming around
3510 const SCEV *BEValue = getSCEV(BEValueV);
3512 // NOTE: If BEValue is loop invariant, we know that the PHI node just
3513 // has a special value for the first iteration of the loop.
3515 // If the value coming around the backedge is an add with the symbolic
3516 // value we just inserted, then we found a simple induction variable!
3517 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
3518 // If there is a single occurrence of the symbolic value, replace it
3519 // with a recurrence.
3520 unsigned FoundIndex = Add->getNumOperands();
3521 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
3522 if (Add->getOperand(i) == SymbolicName)
3523 if (FoundIndex == e) {
3528 if (FoundIndex != Add->getNumOperands()) {
3529 // Create an add with everything but the specified operand.
3530 SmallVector<const SCEV *, 8> Ops;
3531 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
3532 if (i != FoundIndex)
3533 Ops.push_back(Add->getOperand(i));
3534 const SCEV *Accum = getAddExpr(Ops);
3536 // This is not a valid addrec if the step amount is varying each
3537 // loop iteration, but is not itself an addrec in this loop.
3538 if (isLoopInvariant(Accum, L) ||
3539 (isa<SCEVAddRecExpr>(Accum) &&
3540 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
3541 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
3543 // If the increment doesn't overflow, then neither the addrec nor
3544 // the post-increment will overflow.
3545 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
3546 if (OBO->hasNoUnsignedWrap())
3547 Flags = setFlags(Flags, SCEV::FlagNUW);
3548 if (OBO->hasNoSignedWrap())
3549 Flags = setFlags(Flags, SCEV::FlagNSW);
3550 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
3551 // If the increment is an inbounds GEP, then we know the address
3552 // space cannot be wrapped around. We cannot make any guarantee
3553 // about signed or unsigned overflow because pointers are
3554 // unsigned but we may have a negative index from the base
3555 // pointer. We can guarantee that no unsigned wrap occurs if the
3556 // indices form a positive value.
3557 if (GEP->isInBounds()) {
3558 Flags = setFlags(Flags, SCEV::FlagNW);
3560 const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
3561 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
3562 Flags = setFlags(Flags, SCEV::FlagNUW);
3565 // We cannot transfer nuw and nsw flags from subtraction
3566 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
3570 const SCEV *StartVal = getSCEV(StartValueV);
3571 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
3573 // Since the no-wrap flags are on the increment, they apply to the
3574 // post-incremented value as well.
3575 if (isLoopInvariant(Accum, L))
3576 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
3579 // Okay, for the entire analysis of this edge we assumed the PHI
3580 // to be symbolic. We now need to go back and purge all of the
3581 // entries for the scalars that use the symbolic expression.
3582 ForgetSymbolicName(PN, SymbolicName);
3583 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
3587 } else if (const SCEVAddRecExpr *AddRec =
3588 dyn_cast<SCEVAddRecExpr>(BEValue)) {
3589 // Otherwise, this could be a loop like this:
3590 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
3591 // In this case, j = {1,+,1} and BEValue is j.
3592 // Because the other in-value of i (0) fits the evolution of BEValue
3593 // i really is an addrec evolution.
3594 if (AddRec->getLoop() == L && AddRec->isAffine()) {
3595 const SCEV *StartVal = getSCEV(StartValueV);
3597 // If StartVal = j.start - j.stride, we can use StartVal as the
3598 // initial step of the addrec evolution.
3599 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
3600 AddRec->getOperand(1))) {
3601 // FIXME: For constant StartVal, we should be able to infer
3603 const SCEV *PHISCEV =
3604 getAddRecExpr(StartVal, AddRec->getOperand(1), L,
3607 // Okay, for the entire analysis of this edge we assumed the PHI
3608 // to be symbolic. We now need to go back and purge all of the
3609 // entries for the scalars that use the symbolic expression.
3610 ForgetSymbolicName(PN, SymbolicName);
3611 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
3619 // If the PHI has a single incoming value, follow that value, unless the
3620 // PHI's incoming blocks are in a different loop, in which case doing so
3621 // risks breaking LCSSA form. Instcombine would normally zap these, but
3622 // it doesn't have DominatorTree information, so it may miss cases.
3623 if (Value *V = SimplifyInstruction(PN, DL, TLI, DT, AC))
3624 if (LI->replacementPreservesLCSSAForm(PN, V))
3627 // If it's not a loop phi, we can't handle it yet.
3628 return getUnknown(PN);
3631 /// createNodeForGEP - Expand GEP instructions into add and multiply
3632 /// operations. This allows them to be analyzed by regular SCEV code.
3634 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
3635 Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
3636 Value *Base = GEP->getOperand(0);
3637 // Don't attempt to analyze GEPs over unsized objects.
3638 if (!Base->getType()->getPointerElementType()->isSized())
3639 return getUnknown(GEP);
3641 // Don't blindly transfer the inbounds flag from the GEP instruction to the
3642 // Add expression, because the Instruction may be guarded by control flow
3643 // and the no-overflow bits may not be valid for the expression in any
3645 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3647 const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
3648 gep_type_iterator GTI = gep_type_begin(GEP);
3649 for (GetElementPtrInst::op_iterator I = std::next(GEP->op_begin()),
3653 // Compute the (potentially symbolic) offset in bytes for this index.
3654 if (StructType *STy = dyn_cast<StructType>(*GTI++)) {
3655 // For a struct, add the member offset.
3656 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
3657 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3659 // Add the field offset to the running total offset.
3660 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3662 // For an array, add the element offset, explicitly scaled.
3663 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, *GTI);
3664 const SCEV *IndexS = getSCEV(Index);
3665 // Getelementptr indices are signed.
3666 IndexS = getTruncateOrSignExtend(IndexS, IntPtrTy);
3668 // Multiply the index by the element size to compute the element offset.
3669 const SCEV *LocalOffset = getMulExpr(IndexS, ElementSize, Wrap);
3671 // Add the element offset to the running total offset.
3672 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3676 // Get the SCEV for the GEP base.
3677 const SCEV *BaseS = getSCEV(Base);
3679 // Add the total offset from all the GEP indices to the base.
3680 return getAddExpr(BaseS, TotalOffset, Wrap);
3683 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
3684 /// guaranteed to end in (at every loop iteration). It is, at the same time,
3685 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
3686 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
3688 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
3689 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
3690 return C->getValue()->getValue().countTrailingZeros();
3692 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
3693 return std::min(GetMinTrailingZeros(T->getOperand()),
3694 (uint32_t)getTypeSizeInBits(T->getType()));
3696 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
3697 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
3698 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
3699 getTypeSizeInBits(E->getType()) : OpRes;
3702 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
3703 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
3704 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
3705 getTypeSizeInBits(E->getType()) : OpRes;
3708 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
3709 // The result is the min of all operands results.
3710 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
3711 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
3712 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
3716 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
3717 // The result is the sum of all operands results.
3718 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
3719 uint32_t BitWidth = getTypeSizeInBits(M->getType());
3720 for (unsigned i = 1, e = M->getNumOperands();
3721 SumOpRes != BitWidth && i != e; ++i)
3722 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
3727 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
3728 // The result is the min of all operands results.
3729 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
3730 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
3731 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
3735 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
3736 // The result is the min of all operands results.
3737 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
3738 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
3739 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
3743 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
3744 // The result is the min of all operands results.
3745 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
3746 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
3747 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
3751 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3752 // For a SCEVUnknown, ask ValueTracking.
3753 unsigned BitWidth = getTypeSizeInBits(U->getType());
3754 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3755 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, AC, nullptr, DT);
3756 return Zeros.countTrailingOnes();
3763 /// GetRangeFromMetadata - Helper method to assign a range to V from
3764 /// metadata present in the IR.
3765 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
3766 if (Instruction *I = dyn_cast<Instruction>(V)) {
3767 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) {
3768 ConstantRange TotalRange(
3769 cast<IntegerType>(I->getType())->getBitWidth(), false);
3771 unsigned NumRanges = MD->getNumOperands() / 2;
3772 assert(NumRanges >= 1);
3774 for (unsigned i = 0; i < NumRanges; ++i) {
3775 ConstantInt *Lower =
3776 mdconst::extract<ConstantInt>(MD->getOperand(2 * i + 0));
3777 ConstantInt *Upper =
3778 mdconst::extract<ConstantInt>(MD->getOperand(2 * i + 1));
3779 ConstantRange Range(Lower->getValue(), Upper->getValue());
3780 TotalRange = TotalRange.unionWith(Range);
3790 /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
3793 ScalarEvolution::getUnsignedRange(const SCEV *S) {
3794 // See if we've computed this range already.
3795 DenseMap<const SCEV *, ConstantRange>::iterator I = UnsignedRanges.find(S);
3796 if (I != UnsignedRanges.end())
3799 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
3800 return setUnsignedRange(C, ConstantRange(C->getValue()->getValue()));
3802 unsigned BitWidth = getTypeSizeInBits(S->getType());
3803 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3805 // If the value has known zeros, the maximum unsigned value will have those
3806 // known zeros as well.
3807 uint32_t TZ = GetMinTrailingZeros(S);
3809 ConservativeResult =
3810 ConstantRange(APInt::getMinValue(BitWidth),
3811 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
3813 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3814 ConstantRange X = getUnsignedRange(Add->getOperand(0));
3815 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3816 X = X.add(getUnsignedRange(Add->getOperand(i)));
3817 return setUnsignedRange(Add, ConservativeResult.intersectWith(X));
3820 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3821 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
3822 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3823 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
3824 return setUnsignedRange(Mul, ConservativeResult.intersectWith(X));
3827 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3828 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
3829 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3830 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
3831 return setUnsignedRange(SMax, ConservativeResult.intersectWith(X));
3834 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3835 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
3836 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3837 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
3838 return setUnsignedRange(UMax, ConservativeResult.intersectWith(X));
3841 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3842 ConstantRange X = getUnsignedRange(UDiv->getLHS());
3843 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
3844 return setUnsignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
3847 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3848 ConstantRange X = getUnsignedRange(ZExt->getOperand());
3849 return setUnsignedRange(ZExt,
3850 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
3853 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3854 ConstantRange X = getUnsignedRange(SExt->getOperand());
3855 return setUnsignedRange(SExt,
3856 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
3859 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3860 ConstantRange X = getUnsignedRange(Trunc->getOperand());
3861 return setUnsignedRange(Trunc,
3862 ConservativeResult.intersectWith(X.truncate(BitWidth)));
3865 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
3866 // If there's no unsigned wrap, the value will never be less than its
3868 if (AddRec->getNoWrapFlags(SCEV::FlagNUW))
3869 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
3870 if (!C->getValue()->isZero())
3871 ConservativeResult =
3872 ConservativeResult.intersectWith(
3873 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0)));
3875 // TODO: non-affine addrec
3876 if (AddRec->isAffine()) {
3877 Type *Ty = AddRec->getType();
3878 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
3879 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3880 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
3881 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3883 const SCEV *Start = AddRec->getStart();
3884 const SCEV *Step = AddRec->getStepRecurrence(*this);
3886 ConstantRange StartRange = getUnsignedRange(Start);
3887 ConstantRange StepRange = getSignedRange(Step);
3888 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3889 ConstantRange EndRange =
3890 StartRange.add(MaxBECountRange.multiply(StepRange));
3892 // Check for overflow. This must be done with ConstantRange arithmetic
3893 // because we could be called from within the ScalarEvolution overflow
3895 ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
3896 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3897 ConstantRange ExtMaxBECountRange =
3898 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3899 ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
3900 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3902 return setUnsignedRange(AddRec, ConservativeResult);
3904 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
3905 EndRange.getUnsignedMin());
3906 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
3907 EndRange.getUnsignedMax());
3908 if (Min.isMinValue() && Max.isMaxValue())
3909 return setUnsignedRange(AddRec, ConservativeResult);
3910 return setUnsignedRange(AddRec,
3911 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
3915 return setUnsignedRange(AddRec, ConservativeResult);
3918 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3919 // Check if the IR explicitly contains !range metadata.
3920 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
3921 if (MDRange.hasValue())
3922 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
3924 // For a SCEVUnknown, ask ValueTracking.
3925 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3926 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, AC, nullptr, DT);
3927 if (Ones == ~Zeros + 1)
3928 return setUnsignedRange(U, ConservativeResult);
3929 return setUnsignedRange(U,
3930 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)));
3933 return setUnsignedRange(S, ConservativeResult);
3936 /// getSignedRange - Determine the signed range for a particular SCEV.
3939 ScalarEvolution::getSignedRange(const SCEV *S) {
3940 // See if we've computed this range already.
3941 DenseMap<const SCEV *, ConstantRange>::iterator I = SignedRanges.find(S);
3942 if (I != SignedRanges.end())
3945 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
3946 return setSignedRange(C, ConstantRange(C->getValue()->getValue()));
3948 unsigned BitWidth = getTypeSizeInBits(S->getType());
3949 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3951 // If the value has known zeros, the maximum signed value will have those
3952 // known zeros as well.
3953 uint32_t TZ = GetMinTrailingZeros(S);
3955 ConservativeResult =
3956 ConstantRange(APInt::getSignedMinValue(BitWidth),
3957 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
3959 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3960 ConstantRange X = getSignedRange(Add->getOperand(0));
3961 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3962 X = X.add(getSignedRange(Add->getOperand(i)));
3963 return setSignedRange(Add, ConservativeResult.intersectWith(X));
3966 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3967 ConstantRange X = getSignedRange(Mul->getOperand(0));
3968 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3969 X = X.multiply(getSignedRange(Mul->getOperand(i)));
3970 return setSignedRange(Mul, ConservativeResult.intersectWith(X));
3973 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3974 ConstantRange X = getSignedRange(SMax->getOperand(0));
3975 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3976 X = X.smax(getSignedRange(SMax->getOperand(i)));
3977 return setSignedRange(SMax, ConservativeResult.intersectWith(X));
3980 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3981 ConstantRange X = getSignedRange(UMax->getOperand(0));
3982 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3983 X = X.umax(getSignedRange(UMax->getOperand(i)));
3984 return setSignedRange(UMax, ConservativeResult.intersectWith(X));
3987 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3988 ConstantRange X = getSignedRange(UDiv->getLHS());
3989 ConstantRange Y = getSignedRange(UDiv->getRHS());
3990 return setSignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
3993 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3994 ConstantRange X = getSignedRange(ZExt->getOperand());
3995 return setSignedRange(ZExt,
3996 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
3999 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
4000 ConstantRange X = getSignedRange(SExt->getOperand());
4001 return setSignedRange(SExt,
4002 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
4005 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
4006 ConstantRange X = getSignedRange(Trunc->getOperand());
4007 return setSignedRange(Trunc,
4008 ConservativeResult.intersectWith(X.truncate(BitWidth)));
4011 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
4012 // If there's no signed wrap, and all the operands have the same sign or
4013 // zero, the value won't ever change sign.
4014 if (AddRec->getNoWrapFlags(SCEV::FlagNSW)) {
4015 bool AllNonNeg = true;
4016 bool AllNonPos = true;
4017 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4018 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
4019 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
4022 ConservativeResult = ConservativeResult.intersectWith(
4023 ConstantRange(APInt(BitWidth, 0),
4024 APInt::getSignedMinValue(BitWidth)));
4026 ConservativeResult = ConservativeResult.intersectWith(
4027 ConstantRange(APInt::getSignedMinValue(BitWidth),
4028 APInt(BitWidth, 1)));
4031 // TODO: non-affine addrec
4032 if (AddRec->isAffine()) {
4033 Type *Ty = AddRec->getType();
4034 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
4035 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
4036 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
4037 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
4039 const SCEV *Start = AddRec->getStart();
4040 const SCEV *Step = AddRec->getStepRecurrence(*this);
4042 ConstantRange StartRange = getSignedRange(Start);
4043 ConstantRange StepRange = getSignedRange(Step);
4044 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
4045 ConstantRange EndRange =
4046 StartRange.add(MaxBECountRange.multiply(StepRange));
4048 // Check for overflow. This must be done with ConstantRange arithmetic
4049 // because we could be called from within the ScalarEvolution overflow
4051 ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
4052 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
4053 ConstantRange ExtMaxBECountRange =
4054 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
4055 ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
4056 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
4058 return setSignedRange(AddRec, ConservativeResult);
4060 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
4061 EndRange.getSignedMin());
4062 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
4063 EndRange.getSignedMax());
4064 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
4065 return setSignedRange(AddRec, ConservativeResult);
4066 return setSignedRange(AddRec,
4067 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
4071 return setSignedRange(AddRec, ConservativeResult);
4074 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4075 // Check if the IR explicitly contains !range metadata.
4076 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
4077 if (MDRange.hasValue())
4078 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
4080 // For a SCEVUnknown, ask ValueTracking.
4081 if (!U->getValue()->getType()->isIntegerTy() && !DL)
4082 return setSignedRange(U, ConservativeResult);
4083 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, AC, nullptr, DT);
4085 return setSignedRange(U, ConservativeResult);
4086 return setSignedRange(U, ConservativeResult.intersectWith(
4087 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
4088 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1)));
4091 return setSignedRange(S, ConservativeResult);
4094 /// createSCEV - We know that there is no SCEV for the specified value.
4095 /// Analyze the expression.
4097 const SCEV *ScalarEvolution::createSCEV(Value *V) {
4098 if (!isSCEVable(V->getType()))
4099 return getUnknown(V);
4101 unsigned Opcode = Instruction::UserOp1;
4102 if (Instruction *I = dyn_cast<Instruction>(V)) {
4103 Opcode = I->getOpcode();
4105 // Don't attempt to analyze instructions in blocks that aren't
4106 // reachable. Such instructions don't matter, and they aren't required
4107 // to obey basic rules for definitions dominating uses which this
4108 // analysis depends on.
4109 if (!DT->isReachableFromEntry(I->getParent()))
4110 return getUnknown(V);
4111 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
4112 Opcode = CE->getOpcode();
4113 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
4114 return getConstant(CI);
4115 else if (isa<ConstantPointerNull>(V))
4116 return getConstant(V->getType(), 0);
4117 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
4118 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
4120 return getUnknown(V);
4122 Operator *U = cast<Operator>(V);
4124 case Instruction::Add: {
4125 // The simple thing to do would be to just call getSCEV on both operands
4126 // and call getAddExpr with the result. However if we're looking at a
4127 // bunch of things all added together, this can be quite inefficient,
4128 // because it leads to N-1 getAddExpr calls for N ultimate operands.
4129 // Instead, gather up all the operands and make a single getAddExpr call.
4130 // LLVM IR canonical form means we need only traverse the left operands.
4132 // Don't apply this instruction's NSW or NUW flags to the new
4133 // expression. The instruction may be guarded by control flow that the
4134 // no-wrap behavior depends on. Non-control-equivalent instructions can be
4135 // mapped to the same SCEV expression, and it would be incorrect to transfer
4136 // NSW/NUW semantics to those operations.
4137 SmallVector<const SCEV *, 4> AddOps;
4138 AddOps.push_back(getSCEV(U->getOperand(1)));
4139 for (Value *Op = U->getOperand(0); ; Op = U->getOperand(0)) {
4140 unsigned Opcode = Op->getValueID() - Value::InstructionVal;
4141 if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
4143 U = cast<Operator>(Op);
4144 const SCEV *Op1 = getSCEV(U->getOperand(1));
4145 if (Opcode == Instruction::Sub)
4146 AddOps.push_back(getNegativeSCEV(Op1));
4148 AddOps.push_back(Op1);
4150 AddOps.push_back(getSCEV(U->getOperand(0)));
4151 return getAddExpr(AddOps);
4153 case Instruction::Mul: {
4154 // Don't transfer NSW/NUW for the same reason as AddExpr.
4155 SmallVector<const SCEV *, 4> MulOps;
4156 MulOps.push_back(getSCEV(U->getOperand(1)));
4157 for (Value *Op = U->getOperand(0);
4158 Op->getValueID() == Instruction::Mul + Value::InstructionVal;
4159 Op = U->getOperand(0)) {
4160 U = cast<Operator>(Op);
4161 MulOps.push_back(getSCEV(U->getOperand(1)));
4163 MulOps.push_back(getSCEV(U->getOperand(0)));
4164 return getMulExpr(MulOps);
4166 case Instruction::UDiv:
4167 return getUDivExpr(getSCEV(U->getOperand(0)),
4168 getSCEV(U->getOperand(1)));
4169 case Instruction::Sub:
4170 return getMinusSCEV(getSCEV(U->getOperand(0)),
4171 getSCEV(U->getOperand(1)));
4172 case Instruction::And:
4173 // For an expression like x&255 that merely masks off the high bits,
4174 // use zext(trunc(x)) as the SCEV expression.
4175 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
4176 if (CI->isNullValue())
4177 return getSCEV(U->getOperand(1));
4178 if (CI->isAllOnesValue())
4179 return getSCEV(U->getOperand(0));
4180 const APInt &A = CI->getValue();
4182 // Instcombine's ShrinkDemandedConstant may strip bits out of
4183 // constants, obscuring what would otherwise be a low-bits mask.
4184 // Use computeKnownBits to compute what ShrinkDemandedConstant
4185 // knew about to reconstruct a low-bits mask value.
4186 unsigned LZ = A.countLeadingZeros();
4187 unsigned TZ = A.countTrailingZeros();
4188 unsigned BitWidth = A.getBitWidth();
4189 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4190 computeKnownBits(U->getOperand(0), KnownZero, KnownOne, DL, 0, AC,
4193 APInt EffectiveMask =
4194 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
4195 if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) {
4196 const SCEV *MulCount = getConstant(
4197 ConstantInt::get(getContext(), APInt::getOneBitSet(BitWidth, TZ)));
4201 getUDivExactExpr(getSCEV(U->getOperand(0)), MulCount),
4202 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
4209 case Instruction::Or:
4210 // If the RHS of the Or is a constant, we may have something like:
4211 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
4212 // optimizations will transparently handle this case.
4214 // In order for this transformation to be safe, the LHS must be of the
4215 // form X*(2^n) and the Or constant must be less than 2^n.
4216 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
4217 const SCEV *LHS = getSCEV(U->getOperand(0));
4218 const APInt &CIVal = CI->getValue();
4219 if (GetMinTrailingZeros(LHS) >=
4220 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
4221 // Build a plain add SCEV.
4222 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
4223 // If the LHS of the add was an addrec and it has no-wrap flags,
4224 // transfer the no-wrap flags, since an or won't introduce a wrap.
4225 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
4226 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
4227 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
4228 OldAR->getNoWrapFlags());
4234 case Instruction::Xor:
4235 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
4236 // If the RHS of the xor is a signbit, then this is just an add.
4237 // Instcombine turns add of signbit into xor as a strength reduction step.
4238 if (CI->getValue().isSignBit())
4239 return getAddExpr(getSCEV(U->getOperand(0)),
4240 getSCEV(U->getOperand(1)));
4242 // If the RHS of xor is -1, then this is a not operation.
4243 if (CI->isAllOnesValue())
4244 return getNotSCEV(getSCEV(U->getOperand(0)));
4246 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
4247 // This is a variant of the check for xor with -1, and it handles
4248 // the case where instcombine has trimmed non-demanded bits out
4249 // of an xor with -1.
4250 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
4251 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
4252 if (BO->getOpcode() == Instruction::And &&
4253 LCI->getValue() == CI->getValue())
4254 if (const SCEVZeroExtendExpr *Z =
4255 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
4256 Type *UTy = U->getType();
4257 const SCEV *Z0 = Z->getOperand();
4258 Type *Z0Ty = Z0->getType();
4259 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
4261 // If C is a low-bits mask, the zero extend is serving to
4262 // mask off the high bits. Complement the operand and
4263 // re-apply the zext.
4264 if (APIntOps::isMask(Z0TySize, CI->getValue()))
4265 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
4267 // If C is a single bit, it may be in the sign-bit position
4268 // before the zero-extend. In this case, represent the xor
4269 // using an add, which is equivalent, and re-apply the zext.
4270 APInt Trunc = CI->getValue().trunc(Z0TySize);
4271 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
4273 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
4279 case Instruction::Shl:
4280 // Turn shift left of a constant amount into a multiply.
4281 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
4282 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
4284 // If the shift count is not less than the bitwidth, the result of
4285 // the shift is undefined. Don't try to analyze it, because the
4286 // resolution chosen here may differ from the resolution chosen in
4287 // other parts of the compiler.
4288 if (SA->getValue().uge(BitWidth))
4291 Constant *X = ConstantInt::get(getContext(),
4292 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4293 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
4297 case Instruction::LShr:
4298 // Turn logical shift right of a constant into a unsigned divide.
4299 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
4300 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
4302 // If the shift count is not less than the bitwidth, the result of
4303 // the shift is undefined. Don't try to analyze it, because the
4304 // resolution chosen here may differ from the resolution chosen in
4305 // other parts of the compiler.
4306 if (SA->getValue().uge(BitWidth))
4309 Constant *X = ConstantInt::get(getContext(),
4310 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4311 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
4315 case Instruction::AShr:
4316 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
4317 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
4318 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
4319 if (L->getOpcode() == Instruction::Shl &&
4320 L->getOperand(1) == U->getOperand(1)) {
4321 uint64_t BitWidth = getTypeSizeInBits(U->getType());
4323 // If the shift count is not less than the bitwidth, the result of
4324 // the shift is undefined. Don't try to analyze it, because the
4325 // resolution chosen here may differ from the resolution chosen in
4326 // other parts of the compiler.
4327 if (CI->getValue().uge(BitWidth))
4330 uint64_t Amt = BitWidth - CI->getZExtValue();
4331 if (Amt == BitWidth)
4332 return getSCEV(L->getOperand(0)); // shift by zero --> noop
4334 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
4335 IntegerType::get(getContext(),
4341 case Instruction::Trunc:
4342 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
4344 case Instruction::ZExt:
4345 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
4347 case Instruction::SExt:
4348 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
4350 case Instruction::BitCast:
4351 // BitCasts are no-op casts so we just eliminate the cast.
4352 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
4353 return getSCEV(U->getOperand(0));
4356 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
4357 // lead to pointer expressions which cannot safely be expanded to GEPs,
4358 // because ScalarEvolution doesn't respect the GEP aliasing rules when
4359 // simplifying integer expressions.
4361 case Instruction::GetElementPtr:
4362 return createNodeForGEP(cast<GEPOperator>(U));
4364 case Instruction::PHI:
4365 return createNodeForPHI(cast<PHINode>(U));
4367 case Instruction::Select:
4368 // This could be a smax or umax that was lowered earlier.
4369 // Try to recover it.
4370 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
4371 Value *LHS = ICI->getOperand(0);
4372 Value *RHS = ICI->getOperand(1);
4373 switch (ICI->getPredicate()) {
4374 case ICmpInst::ICMP_SLT:
4375 case ICmpInst::ICMP_SLE:
4376 std::swap(LHS, RHS);
4378 case ICmpInst::ICMP_SGT:
4379 case ICmpInst::ICMP_SGE:
4380 // a >s b ? a+x : b+x -> smax(a, b)+x
4381 // a >s b ? b+x : a+x -> smin(a, b)+x
4382 if (getTypeSizeInBits(LHS->getType()) <=
4383 getTypeSizeInBits(U->getType())) {
4384 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), U->getType());
4385 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), U->getType());
4386 const SCEV *LA = getSCEV(U->getOperand(1));
4387 const SCEV *RA = getSCEV(U->getOperand(2));
4388 const SCEV *LDiff = getMinusSCEV(LA, LS);
4389 const SCEV *RDiff = getMinusSCEV(RA, RS);
4391 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
4392 LDiff = getMinusSCEV(LA, RS);
4393 RDiff = getMinusSCEV(RA, LS);
4395 return getAddExpr(getSMinExpr(LS, RS), LDiff);
4398 case ICmpInst::ICMP_ULT:
4399 case ICmpInst::ICMP_ULE:
4400 std::swap(LHS, RHS);
4402 case ICmpInst::ICMP_UGT:
4403 case ICmpInst::ICMP_UGE:
4404 // a >u b ? a+x : b+x -> umax(a, b)+x
4405 // a >u b ? b+x : a+x -> umin(a, b)+x
4406 if (getTypeSizeInBits(LHS->getType()) <=
4407 getTypeSizeInBits(U->getType())) {
4408 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), U->getType());
4409 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), U->getType());
4410 const SCEV *LA = getSCEV(U->getOperand(1));
4411 const SCEV *RA = getSCEV(U->getOperand(2));
4412 const SCEV *LDiff = getMinusSCEV(LA, LS);
4413 const SCEV *RDiff = getMinusSCEV(RA, RS);
4415 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4416 LDiff = getMinusSCEV(LA, RS);
4417 RDiff = getMinusSCEV(RA, LS);
4419 return getAddExpr(getUMinExpr(LS, RS), LDiff);
4422 case ICmpInst::ICMP_NE:
4423 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
4424 if (getTypeSizeInBits(LHS->getType()) <=
4425 getTypeSizeInBits(U->getType()) &&
4426 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4427 const SCEV *One = getConstant(U->getType(), 1);
4428 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), U->getType());
4429 const SCEV *LA = getSCEV(U->getOperand(1));
4430 const SCEV *RA = getSCEV(U->getOperand(2));
4431 const SCEV *LDiff = getMinusSCEV(LA, LS);
4432 const SCEV *RDiff = getMinusSCEV(RA, One);
4434 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4437 case ICmpInst::ICMP_EQ:
4438 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
4439 if (getTypeSizeInBits(LHS->getType()) <=
4440 getTypeSizeInBits(U->getType()) &&
4441 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4442 const SCEV *One = getConstant(U->getType(), 1);
4443 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), U->getType());
4444 const SCEV *LA = getSCEV(U->getOperand(1));
4445 const SCEV *RA = getSCEV(U->getOperand(2));
4446 const SCEV *LDiff = getMinusSCEV(LA, One);
4447 const SCEV *RDiff = getMinusSCEV(RA, LS);
4449 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4457 default: // We cannot analyze this expression.
4461 return getUnknown(V);
4466 //===----------------------------------------------------------------------===//
4467 // Iteration Count Computation Code
4470 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) {
4471 if (BasicBlock *ExitingBB = L->getExitingBlock())
4472 return getSmallConstantTripCount(L, ExitingBB);
4474 // No trip count information for multiple exits.
4478 /// getSmallConstantTripCount - Returns the maximum trip count of this loop as a
4479 /// normal unsigned value. Returns 0 if the trip count is unknown or not
4480 /// constant. Will also return 0 if the maximum trip count is very large (>=
4483 /// This "trip count" assumes that control exits via ExitingBlock. More
4484 /// precisely, it is the number of times that control may reach ExitingBlock
4485 /// before taking the branch. For loops with multiple exits, it may not be the
4486 /// number times that the loop header executes because the loop may exit
4487 /// prematurely via another branch.
4488 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L,
4489 BasicBlock *ExitingBlock) {
4490 assert(ExitingBlock && "Must pass a non-null exiting block!");
4491 assert(L->isLoopExiting(ExitingBlock) &&
4492 "Exiting block must actually branch out of the loop!");
4493 const SCEVConstant *ExitCount =
4494 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
4498 ConstantInt *ExitConst = ExitCount->getValue();
4500 // Guard against huge trip counts.
4501 if (ExitConst->getValue().getActiveBits() > 32)
4504 // In case of integer overflow, this returns 0, which is correct.
4505 return ((unsigned)ExitConst->getZExtValue()) + 1;
4508 unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) {
4509 if (BasicBlock *ExitingBB = L->getExitingBlock())
4510 return getSmallConstantTripMultiple(L, ExitingBB);
4512 // No trip multiple information for multiple exits.
4516 /// getSmallConstantTripMultiple - Returns the largest constant divisor of the
4517 /// trip count of this loop as a normal unsigned value, if possible. This
4518 /// means that the actual trip count is always a multiple of the returned
4519 /// value (don't forget the trip count could very well be zero as well!).
4521 /// Returns 1 if the trip count is unknown or not guaranteed to be the
4522 /// multiple of a constant (which is also the case if the trip count is simply
4523 /// constant, use getSmallConstantTripCount for that case), Will also return 1
4524 /// if the trip count is very large (>= 2^32).
4526 /// As explained in the comments for getSmallConstantTripCount, this assumes
4527 /// that control exits the loop via ExitingBlock.
4529 ScalarEvolution::getSmallConstantTripMultiple(Loop *L,
4530 BasicBlock *ExitingBlock) {
4531 assert(ExitingBlock && "Must pass a non-null exiting block!");
4532 assert(L->isLoopExiting(ExitingBlock) &&
4533 "Exiting block must actually branch out of the loop!");
4534 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
4535 if (ExitCount == getCouldNotCompute())
4538 // Get the trip count from the BE count by adding 1.
4539 const SCEV *TCMul = getAddExpr(ExitCount,
4540 getConstant(ExitCount->getType(), 1));
4541 // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt
4542 // to factor simple cases.
4543 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul))
4544 TCMul = Mul->getOperand(0);
4546 const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul);
4550 ConstantInt *Result = MulC->getValue();
4552 // Guard against huge trip counts (this requires checking
4553 // for zero to handle the case where the trip count == -1 and the
4555 if (!Result || Result->getValue().getActiveBits() > 32 ||
4556 Result->getValue().getActiveBits() == 0)
4559 return (unsigned)Result->getZExtValue();
4562 // getExitCount - Get the expression for the number of loop iterations for which
4563 // this loop is guaranteed not to exit via ExitingBlock. Otherwise return
4564 // SCEVCouldNotCompute.
4565 const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) {
4566 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
4569 /// getBackedgeTakenCount - If the specified loop has a predictable
4570 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
4571 /// object. The backedge-taken count is the number of times the loop header
4572 /// will be branched to from within the loop. This is one less than the
4573 /// trip count of the loop, since it doesn't count the first iteration,
4574 /// when the header is branched to from outside the loop.
4576 /// Note that it is not valid to call this method on a loop without a
4577 /// loop-invariant backedge-taken count (see
4578 /// hasLoopInvariantBackedgeTakenCount).
4580 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
4581 return getBackedgeTakenInfo(L).getExact(this);
4584 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
4585 /// return the least SCEV value that is known never to be less than the
4586 /// actual backedge taken count.
4587 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
4588 return getBackedgeTakenInfo(L).getMax(this);
4591 /// PushLoopPHIs - Push PHI nodes in the header of the given loop
4592 /// onto the given Worklist.
4594 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
4595 BasicBlock *Header = L->getHeader();
4597 // Push all Loop-header PHIs onto the Worklist stack.
4598 for (BasicBlock::iterator I = Header->begin();
4599 PHINode *PN = dyn_cast<PHINode>(I); ++I)
4600 Worklist.push_back(PN);
4603 const ScalarEvolution::BackedgeTakenInfo &
4604 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
4605 // Initially insert an invalid entry for this loop. If the insertion
4606 // succeeds, proceed to actually compute a backedge-taken count and
4607 // update the value. The temporary CouldNotCompute value tells SCEV
4608 // code elsewhere that it shouldn't attempt to request a new
4609 // backedge-taken count, which could result in infinite recursion.
4610 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
4611 BackedgeTakenCounts.insert(std::make_pair(L, BackedgeTakenInfo()));
4613 return Pair.first->second;
4615 // ComputeBackedgeTakenCount may allocate memory for its result. Inserting it
4616 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
4617 // must be cleared in this scope.
4618 BackedgeTakenInfo Result = ComputeBackedgeTakenCount(L);
4620 if (Result.getExact(this) != getCouldNotCompute()) {
4621 assert(isLoopInvariant(Result.getExact(this), L) &&
4622 isLoopInvariant(Result.getMax(this), L) &&
4623 "Computed backedge-taken count isn't loop invariant for loop!");
4624 ++NumTripCountsComputed;
4626 else if (Result.getMax(this) == getCouldNotCompute() &&
4627 isa<PHINode>(L->getHeader()->begin())) {
4628 // Only count loops that have phi nodes as not being computable.
4629 ++NumTripCountsNotComputed;
4632 // Now that we know more about the trip count for this loop, forget any
4633 // existing SCEV values for PHI nodes in this loop since they are only
4634 // conservative estimates made without the benefit of trip count
4635 // information. This is similar to the code in forgetLoop, except that
4636 // it handles SCEVUnknown PHI nodes specially.
4637 if (Result.hasAnyInfo()) {
4638 SmallVector<Instruction *, 16> Worklist;
4639 PushLoopPHIs(L, Worklist);
4641 SmallPtrSet<Instruction *, 8> Visited;
4642 while (!Worklist.empty()) {
4643 Instruction *I = Worklist.pop_back_val();
4644 if (!Visited.insert(I).second)
4647 ValueExprMapType::iterator It =
4648 ValueExprMap.find_as(static_cast<Value *>(I));
4649 if (It != ValueExprMap.end()) {
4650 const SCEV *Old = It->second;
4652 // SCEVUnknown for a PHI either means that it has an unrecognized
4653 // structure, or it's a PHI that's in the progress of being computed
4654 // by createNodeForPHI. In the former case, additional loop trip
4655 // count information isn't going to change anything. In the later
4656 // case, createNodeForPHI will perform the necessary updates on its
4657 // own when it gets to that point.
4658 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
4659 forgetMemoizedResults(Old);
4660 ValueExprMap.erase(It);
4662 if (PHINode *PN = dyn_cast<PHINode>(I))
4663 ConstantEvolutionLoopExitValue.erase(PN);
4666 PushDefUseChildren(I, Worklist);
4670 // Re-lookup the insert position, since the call to
4671 // ComputeBackedgeTakenCount above could result in a
4672 // recusive call to getBackedgeTakenInfo (on a different
4673 // loop), which would invalidate the iterator computed
4675 return BackedgeTakenCounts.find(L)->second = Result;
4678 /// forgetLoop - This method should be called by the client when it has
4679 /// changed a loop in a way that may effect ScalarEvolution's ability to
4680 /// compute a trip count, or if the loop is deleted.
4681 void ScalarEvolution::forgetLoop(const Loop *L) {
4682 // Drop any stored trip count value.
4683 DenseMap<const Loop*, BackedgeTakenInfo>::iterator BTCPos =
4684 BackedgeTakenCounts.find(L);
4685 if (BTCPos != BackedgeTakenCounts.end()) {
4686 BTCPos->second.clear();
4687 BackedgeTakenCounts.erase(BTCPos);
4690 // Drop information about expressions based on loop-header PHIs.
4691 SmallVector<Instruction *, 16> Worklist;
4692 PushLoopPHIs(L, Worklist);
4694 SmallPtrSet<Instruction *, 8> Visited;
4695 while (!Worklist.empty()) {
4696 Instruction *I = Worklist.pop_back_val();
4697 if (!Visited.insert(I).second)
4700 ValueExprMapType::iterator It =
4701 ValueExprMap.find_as(static_cast<Value *>(I));
4702 if (It != ValueExprMap.end()) {
4703 forgetMemoizedResults(It->second);
4704 ValueExprMap.erase(It);
4705 if (PHINode *PN = dyn_cast<PHINode>(I))
4706 ConstantEvolutionLoopExitValue.erase(PN);
4709 PushDefUseChildren(I, Worklist);
4712 // Forget all contained loops too, to avoid dangling entries in the
4713 // ValuesAtScopes map.
4714 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4718 /// forgetValue - This method should be called by the client when it has
4719 /// changed a value in a way that may effect its value, or which may
4720 /// disconnect it from a def-use chain linking it to a loop.
4721 void ScalarEvolution::forgetValue(Value *V) {
4722 Instruction *I = dyn_cast<Instruction>(V);
4725 // Drop information about expressions based on loop-header PHIs.
4726 SmallVector<Instruction *, 16> Worklist;
4727 Worklist.push_back(I);
4729 SmallPtrSet<Instruction *, 8> Visited;
4730 while (!Worklist.empty()) {
4731 I = Worklist.pop_back_val();
4732 if (!Visited.insert(I).second)
4735 ValueExprMapType::iterator It =
4736 ValueExprMap.find_as(static_cast<Value *>(I));
4737 if (It != ValueExprMap.end()) {
4738 forgetMemoizedResults(It->second);
4739 ValueExprMap.erase(It);
4740 if (PHINode *PN = dyn_cast<PHINode>(I))
4741 ConstantEvolutionLoopExitValue.erase(PN);
4744 PushDefUseChildren(I, Worklist);
4748 /// getExact - Get the exact loop backedge taken count considering all loop
4749 /// exits. A computable result can only be return for loops with a single exit.
4750 /// Returning the minimum taken count among all exits is incorrect because one
4751 /// of the loop's exit limit's may have been skipped. HowFarToZero assumes that
4752 /// the limit of each loop test is never skipped. This is a valid assumption as
4753 /// long as the loop exits via that test. For precise results, it is the
4754 /// caller's responsibility to specify the relevant loop exit using
4755 /// getExact(ExitingBlock, SE).
4757 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE) const {
4758 // If any exits were not computable, the loop is not computable.
4759 if (!ExitNotTaken.isCompleteList()) return SE->getCouldNotCompute();
4761 // We need exactly one computable exit.
4762 if (!ExitNotTaken.ExitingBlock) return SE->getCouldNotCompute();
4763 assert(ExitNotTaken.ExactNotTaken && "uninitialized not-taken info");
4765 const SCEV *BECount = nullptr;
4766 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
4767 ENT != nullptr; ENT = ENT->getNextExit()) {
4769 assert(ENT->ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
4772 BECount = ENT->ExactNotTaken;
4773 else if (BECount != ENT->ExactNotTaken)
4774 return SE->getCouldNotCompute();
4776 assert(BECount && "Invalid not taken count for loop exit");
4780 /// getExact - Get the exact not taken count for this loop exit.
4782 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
4783 ScalarEvolution *SE) const {
4784 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
4785 ENT != nullptr; ENT = ENT->getNextExit()) {
4787 if (ENT->ExitingBlock == ExitingBlock)
4788 return ENT->ExactNotTaken;
4790 return SE->getCouldNotCompute();
4793 /// getMax - Get the max backedge taken count for the loop.
4795 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
4796 return Max ? Max : SE->getCouldNotCompute();
4799 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
4800 ScalarEvolution *SE) const {
4801 if (Max && Max != SE->getCouldNotCompute() && SE->hasOperand(Max, S))
4804 if (!ExitNotTaken.ExitingBlock)
4807 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
4808 ENT != nullptr; ENT = ENT->getNextExit()) {
4810 if (ENT->ExactNotTaken != SE->getCouldNotCompute()
4811 && SE->hasOperand(ENT->ExactNotTaken, S)) {
4818 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
4819 /// computable exit into a persistent ExitNotTakenInfo array.
4820 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
4821 SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts,
4822 bool Complete, const SCEV *MaxCount) : Max(MaxCount) {
4825 ExitNotTaken.setIncomplete();
4827 unsigned NumExits = ExitCounts.size();
4828 if (NumExits == 0) return;
4830 ExitNotTaken.ExitingBlock = ExitCounts[0].first;
4831 ExitNotTaken.ExactNotTaken = ExitCounts[0].second;
4832 if (NumExits == 1) return;
4834 // Handle the rare case of multiple computable exits.
4835 ExitNotTakenInfo *ENT = new ExitNotTakenInfo[NumExits-1];
4837 ExitNotTakenInfo *PrevENT = &ExitNotTaken;
4838 for (unsigned i = 1; i < NumExits; ++i, PrevENT = ENT, ++ENT) {
4839 PrevENT->setNextExit(ENT);
4840 ENT->ExitingBlock = ExitCounts[i].first;
4841 ENT->ExactNotTaken = ExitCounts[i].second;
4845 /// clear - Invalidate this result and free the ExitNotTakenInfo array.
4846 void ScalarEvolution::BackedgeTakenInfo::clear() {
4847 ExitNotTaken.ExitingBlock = nullptr;
4848 ExitNotTaken.ExactNotTaken = nullptr;
4849 delete[] ExitNotTaken.getNextExit();
4852 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
4853 /// of the specified loop will execute.
4854 ScalarEvolution::BackedgeTakenInfo
4855 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
4856 SmallVector<BasicBlock *, 8> ExitingBlocks;
4857 L->getExitingBlocks(ExitingBlocks);
4859 SmallVector<std::pair<BasicBlock *, const SCEV *>, 4> ExitCounts;
4860 bool CouldComputeBECount = true;
4861 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
4862 const SCEV *MustExitMaxBECount = nullptr;
4863 const SCEV *MayExitMaxBECount = nullptr;
4865 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
4866 // and compute maxBECount.
4867 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
4868 BasicBlock *ExitBB = ExitingBlocks[i];
4869 ExitLimit EL = ComputeExitLimit(L, ExitBB);
4871 // 1. For each exit that can be computed, add an entry to ExitCounts.
4872 // CouldComputeBECount is true only if all exits can be computed.
4873 if (EL.Exact == getCouldNotCompute())
4874 // We couldn't compute an exact value for this exit, so
4875 // we won't be able to compute an exact value for the loop.
4876 CouldComputeBECount = false;
4878 ExitCounts.push_back(std::make_pair(ExitBB, EL.Exact));
4880 // 2. Derive the loop's MaxBECount from each exit's max number of
4881 // non-exiting iterations. Partition the loop exits into two kinds:
4882 // LoopMustExits and LoopMayExits.
4884 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
4885 // is a LoopMayExit. If any computable LoopMustExit is found, then
4886 // MaxBECount is the minimum EL.Max of computable LoopMustExits. Otherwise,
4887 // MaxBECount is conservatively the maximum EL.Max, where CouldNotCompute is
4888 // considered greater than any computable EL.Max.
4889 if (EL.Max != getCouldNotCompute() && Latch &&
4890 DT->dominates(ExitBB, Latch)) {
4891 if (!MustExitMaxBECount)
4892 MustExitMaxBECount = EL.Max;
4894 MustExitMaxBECount =
4895 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.Max);
4897 } else if (MayExitMaxBECount != getCouldNotCompute()) {
4898 if (!MayExitMaxBECount || EL.Max == getCouldNotCompute())
4899 MayExitMaxBECount = EL.Max;
4902 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.Max);
4906 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
4907 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
4908 return BackedgeTakenInfo(ExitCounts, CouldComputeBECount, MaxBECount);
4911 /// ComputeExitLimit - Compute the number of times the backedge of the specified
4912 /// loop will execute if it exits via the specified block.
4913 ScalarEvolution::ExitLimit
4914 ScalarEvolution::ComputeExitLimit(const Loop *L, BasicBlock *ExitingBlock) {
4916 // Okay, we've chosen an exiting block. See what condition causes us to
4917 // exit at this block and remember the exit block and whether all other targets
4918 // lead to the loop header.
4919 bool MustExecuteLoopHeader = true;
4920 BasicBlock *Exit = nullptr;
4921 for (succ_iterator SI = succ_begin(ExitingBlock), SE = succ_end(ExitingBlock);
4923 if (!L->contains(*SI)) {
4924 if (Exit) // Multiple exit successors.
4925 return getCouldNotCompute();
4927 } else if (*SI != L->getHeader()) {
4928 MustExecuteLoopHeader = false;
4931 // At this point, we know we have a conditional branch that determines whether
4932 // the loop is exited. However, we don't know if the branch is executed each
4933 // time through the loop. If not, then the execution count of the branch will
4934 // not be equal to the trip count of the loop.
4936 // Currently we check for this by checking to see if the Exit branch goes to
4937 // the loop header. If so, we know it will always execute the same number of
4938 // times as the loop. We also handle the case where the exit block *is* the
4939 // loop header. This is common for un-rotated loops.
4941 // If both of those tests fail, walk up the unique predecessor chain to the
4942 // header, stopping if there is an edge that doesn't exit the loop. If the
4943 // header is reached, the execution count of the branch will be equal to the
4944 // trip count of the loop.
4946 // More extensive analysis could be done to handle more cases here.
4948 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
4949 // The simple checks failed, try climbing the unique predecessor chain
4950 // up to the header.
4952 for (BasicBlock *BB = ExitingBlock; BB; ) {
4953 BasicBlock *Pred = BB->getUniquePredecessor();
4955 return getCouldNotCompute();
4956 TerminatorInst *PredTerm = Pred->getTerminator();
4957 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
4958 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
4961 // If the predecessor has a successor that isn't BB and isn't
4962 // outside the loop, assume the worst.
4963 if (L->contains(PredSucc))
4964 return getCouldNotCompute();
4966 if (Pred == L->getHeader()) {
4973 return getCouldNotCompute();
4976 bool IsOnlyExit = (L->getExitingBlock() != nullptr);
4977 TerminatorInst *Term = ExitingBlock->getTerminator();
4978 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
4979 assert(BI->isConditional() && "If unconditional, it can't be in loop!");
4980 // Proceed to the next level to examine the exit condition expression.
4981 return ComputeExitLimitFromCond(L, BI->getCondition(), BI->getSuccessor(0),
4982 BI->getSuccessor(1),
4983 /*ControlsExit=*/IsOnlyExit);
4986 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
4987 return ComputeExitLimitFromSingleExitSwitch(L, SI, Exit,
4988 /*ControlsExit=*/IsOnlyExit);
4990 return getCouldNotCompute();
4993 /// ComputeExitLimitFromCond - Compute the number of times the
4994 /// backedge of the specified loop will execute if its exit condition
4995 /// were a conditional branch of ExitCond, TBB, and FBB.
4997 /// @param ControlsExit is true if ExitCond directly controls the exit
4998 /// branch. In this case, we can assume that the loop exits only if the
4999 /// condition is true and can infer that failing to meet the condition prior to
5000 /// integer wraparound results in undefined behavior.
5001 ScalarEvolution::ExitLimit
5002 ScalarEvolution::ComputeExitLimitFromCond(const Loop *L,
5006 bool ControlsExit) {
5007 // Check if the controlling expression for this loop is an And or Or.
5008 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
5009 if (BO->getOpcode() == Instruction::And) {
5010 // Recurse on the operands of the and.
5011 bool EitherMayExit = L->contains(TBB);
5012 ExitLimit EL0 = ComputeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
5013 ControlsExit && !EitherMayExit);
5014 ExitLimit EL1 = ComputeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
5015 ControlsExit && !EitherMayExit);
5016 const SCEV *BECount = getCouldNotCompute();
5017 const SCEV *MaxBECount = getCouldNotCompute();
5018 if (EitherMayExit) {
5019 // Both conditions must be true for the loop to continue executing.
5020 // Choose the less conservative count.
5021 if (EL0.Exact == getCouldNotCompute() ||
5022 EL1.Exact == getCouldNotCompute())
5023 BECount = getCouldNotCompute();
5025 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
5026 if (EL0.Max == getCouldNotCompute())
5027 MaxBECount = EL1.Max;
5028 else if (EL1.Max == getCouldNotCompute())
5029 MaxBECount = EL0.Max;
5031 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
5033 // Both conditions must be true at the same time for the loop to exit.
5034 // For now, be conservative.
5035 assert(L->contains(FBB) && "Loop block has no successor in loop!");
5036 if (EL0.Max == EL1.Max)
5037 MaxBECount = EL0.Max;
5038 if (EL0.Exact == EL1.Exact)
5039 BECount = EL0.Exact;
5042 return ExitLimit(BECount, MaxBECount);
5044 if (BO->getOpcode() == Instruction::Or) {
5045 // Recurse on the operands of the or.
5046 bool EitherMayExit = L->contains(FBB);
5047 ExitLimit EL0 = ComputeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
5048 ControlsExit && !EitherMayExit);
5049 ExitLimit EL1 = ComputeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
5050 ControlsExit && !EitherMayExit);
5051 const SCEV *BECount = getCouldNotCompute();
5052 const SCEV *MaxBECount = getCouldNotCompute();
5053 if (EitherMayExit) {
5054 // Both conditions must be false for the loop to continue executing.
5055 // Choose the less conservative count.
5056 if (EL0.Exact == getCouldNotCompute() ||
5057 EL1.Exact == getCouldNotCompute())
5058 BECount = getCouldNotCompute();
5060 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
5061 if (EL0.Max == getCouldNotCompute())
5062 MaxBECount = EL1.Max;
5063 else if (EL1.Max == getCouldNotCompute())
5064 MaxBECount = EL0.Max;
5066 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
5068 // Both conditions must be false at the same time for the loop to exit.
5069 // For now, be conservative.
5070 assert(L->contains(TBB) && "Loop block has no successor in loop!");
5071 if (EL0.Max == EL1.Max)
5072 MaxBECount = EL0.Max;
5073 if (EL0.Exact == EL1.Exact)
5074 BECount = EL0.Exact;
5077 return ExitLimit(BECount, MaxBECount);
5081 // With an icmp, it may be feasible to compute an exact backedge-taken count.
5082 // Proceed to the next level to examine the icmp.
5083 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
5084 return ComputeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
5086 // Check for a constant condition. These are normally stripped out by
5087 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
5088 // preserve the CFG and is temporarily leaving constant conditions
5090 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
5091 if (L->contains(FBB) == !CI->getZExtValue())
5092 // The backedge is always taken.
5093 return getCouldNotCompute();
5095 // The backedge is never taken.
5096 return getConstant(CI->getType(), 0);
5099 // If it's not an integer or pointer comparison then compute it the hard way.
5100 return ComputeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
5103 /// ComputeExitLimitFromICmp - Compute the number of times the
5104 /// backedge of the specified loop will execute if its exit condition
5105 /// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
5106 ScalarEvolution::ExitLimit
5107 ScalarEvolution::ComputeExitLimitFromICmp(const Loop *L,
5111 bool ControlsExit) {
5113 // If the condition was exit on true, convert the condition to exit on false
5114 ICmpInst::Predicate Cond;
5115 if (!L->contains(FBB))
5116 Cond = ExitCond->getPredicate();
5118 Cond = ExitCond->getInversePredicate();
5120 // Handle common loops like: for (X = "string"; *X; ++X)
5121 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
5122 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
5124 ComputeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
5125 if (ItCnt.hasAnyInfo())
5129 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
5130 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
5132 // Try to evaluate any dependencies out of the loop.
5133 LHS = getSCEVAtScope(LHS, L);
5134 RHS = getSCEVAtScope(RHS, L);
5136 // At this point, we would like to compute how many iterations of the
5137 // loop the predicate will return true for these inputs.
5138 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
5139 // If there is a loop-invariant, force it into the RHS.
5140 std::swap(LHS, RHS);
5141 Cond = ICmpInst::getSwappedPredicate(Cond);
5144 // Simplify the operands before analyzing them.
5145 (void)SimplifyICmpOperands(Cond, LHS, RHS);
5147 // If we have a comparison of a chrec against a constant, try to use value
5148 // ranges to answer this query.
5149 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
5150 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
5151 if (AddRec->getLoop() == L) {
5152 // Form the constant range.
5153 ConstantRange CompRange(
5154 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
5156 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
5157 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
5161 case ICmpInst::ICMP_NE: { // while (X != Y)
5162 // Convert to: while (X-Y != 0)
5163 ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
5164 if (EL.hasAnyInfo()) return EL;
5167 case ICmpInst::ICMP_EQ: { // while (X == Y)
5168 // Convert to: while (X-Y == 0)
5169 ExitLimit EL = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
5170 if (EL.hasAnyInfo()) return EL;
5173 case ICmpInst::ICMP_SLT:
5174 case ICmpInst::ICMP_ULT: { // while (X < Y)
5175 bool IsSigned = Cond == ICmpInst::ICMP_SLT;
5176 ExitLimit EL = HowManyLessThans(LHS, RHS, L, IsSigned, ControlsExit);
5177 if (EL.hasAnyInfo()) return EL;
5180 case ICmpInst::ICMP_SGT:
5181 case ICmpInst::ICMP_UGT: { // while (X > Y)
5182 bool IsSigned = Cond == ICmpInst::ICMP_SGT;
5183 ExitLimit EL = HowManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit);
5184 if (EL.hasAnyInfo()) return EL;
5189 dbgs() << "ComputeBackedgeTakenCount ";
5190 if (ExitCond->getOperand(0)->getType()->isUnsigned())
5191 dbgs() << "[unsigned] ";
5192 dbgs() << *LHS << " "
5193 << Instruction::getOpcodeName(Instruction::ICmp)
5194 << " " << *RHS << "\n";
5198 return ComputeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
5201 ScalarEvolution::ExitLimit
5202 ScalarEvolution::ComputeExitLimitFromSingleExitSwitch(const Loop *L,
5204 BasicBlock *ExitingBlock,
5205 bool ControlsExit) {
5206 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
5208 // Give up if the exit is the default dest of a switch.
5209 if (Switch->getDefaultDest() == ExitingBlock)
5210 return getCouldNotCompute();
5212 assert(L->contains(Switch->getDefaultDest()) &&
5213 "Default case must not exit the loop!");
5214 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
5215 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
5217 // while (X != Y) --> while (X-Y != 0)
5218 ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
5219 if (EL.hasAnyInfo())
5222 return getCouldNotCompute();
5225 static ConstantInt *
5226 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
5227 ScalarEvolution &SE) {
5228 const SCEV *InVal = SE.getConstant(C);
5229 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
5230 assert(isa<SCEVConstant>(Val) &&
5231 "Evaluation of SCEV at constant didn't fold correctly?");
5232 return cast<SCEVConstant>(Val)->getValue();
5235 /// ComputeLoadConstantCompareExitLimit - Given an exit condition of
5236 /// 'icmp op load X, cst', try to see if we can compute the backedge
5237 /// execution count.
5238 ScalarEvolution::ExitLimit
5239 ScalarEvolution::ComputeLoadConstantCompareExitLimit(
5243 ICmpInst::Predicate predicate) {
5245 if (LI->isVolatile()) return getCouldNotCompute();
5247 // Check to see if the loaded pointer is a getelementptr of a global.
5248 // TODO: Use SCEV instead of manually grubbing with GEPs.
5249 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
5250 if (!GEP) return getCouldNotCompute();
5252 // Make sure that it is really a constant global we are gepping, with an
5253 // initializer, and make sure the first IDX is really 0.
5254 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
5255 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
5256 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
5257 !cast<Constant>(GEP->getOperand(1))->isNullValue())
5258 return getCouldNotCompute();
5260 // Okay, we allow one non-constant index into the GEP instruction.
5261 Value *VarIdx = nullptr;
5262 std::vector<Constant*> Indexes;
5263 unsigned VarIdxNum = 0;
5264 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
5265 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5266 Indexes.push_back(CI);
5267 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
5268 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
5269 VarIdx = GEP->getOperand(i);
5271 Indexes.push_back(nullptr);
5274 // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
5276 return getCouldNotCompute();
5278 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
5279 // Check to see if X is a loop variant variable value now.
5280 const SCEV *Idx = getSCEV(VarIdx);
5281 Idx = getSCEVAtScope(Idx, L);
5283 // We can only recognize very limited forms of loop index expressions, in
5284 // particular, only affine AddRec's like {C1,+,C2}.
5285 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
5286 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
5287 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
5288 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
5289 return getCouldNotCompute();
5291 unsigned MaxSteps = MaxBruteForceIterations;
5292 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
5293 ConstantInt *ItCst = ConstantInt::get(
5294 cast<IntegerType>(IdxExpr->getType()), IterationNum);
5295 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
5297 // Form the GEP offset.
5298 Indexes[VarIdxNum] = Val;
5300 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
5302 if (!Result) break; // Cannot compute!
5304 // Evaluate the condition for this iteration.
5305 Result = ConstantExpr::getICmp(predicate, Result, RHS);
5306 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
5307 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
5309 dbgs() << "\n***\n*** Computed loop count " << *ItCst
5310 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
5313 ++NumArrayLenItCounts;
5314 return getConstant(ItCst); // Found terminating iteration!
5317 return getCouldNotCompute();
5321 /// CanConstantFold - Return true if we can constant fold an instruction of the
5322 /// specified type, assuming that all operands were constants.
5323 static bool CanConstantFold(const Instruction *I) {
5324 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
5325 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
5329 if (const CallInst *CI = dyn_cast<CallInst>(I))
5330 if (const Function *F = CI->getCalledFunction())
5331 return canConstantFoldCallTo(F);
5335 /// Determine whether this instruction can constant evolve within this loop
5336 /// assuming its operands can all constant evolve.
5337 static bool canConstantEvolve(Instruction *I, const Loop *L) {
5338 // An instruction outside of the loop can't be derived from a loop PHI.
5339 if (!L->contains(I)) return false;
5341 if (isa<PHINode>(I)) {
5342 if (L->getHeader() == I->getParent())
5345 // We don't currently keep track of the control flow needed to evaluate
5346 // PHIs, so we cannot handle PHIs inside of loops.
5350 // If we won't be able to constant fold this expression even if the operands
5351 // are constants, bail early.
5352 return CanConstantFold(I);
5355 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
5356 /// recursing through each instruction operand until reaching a loop header phi.
5358 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
5359 DenseMap<Instruction *, PHINode *> &PHIMap) {
5361 // Otherwise, we can evaluate this instruction if all of its operands are
5362 // constant or derived from a PHI node themselves.
5363 PHINode *PHI = nullptr;
5364 for (Instruction::op_iterator OpI = UseInst->op_begin(),
5365 OpE = UseInst->op_end(); OpI != OpE; ++OpI) {
5367 if (isa<Constant>(*OpI)) continue;
5369 Instruction *OpInst = dyn_cast<Instruction>(*OpI);
5370 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
5372 PHINode *P = dyn_cast<PHINode>(OpInst);
5374 // If this operand is already visited, reuse the prior result.
5375 // We may have P != PHI if this is the deepest point at which the
5376 // inconsistent paths meet.
5377 P = PHIMap.lookup(OpInst);
5379 // Recurse and memoize the results, whether a phi is found or not.
5380 // This recursive call invalidates pointers into PHIMap.
5381 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap);
5385 return nullptr; // Not evolving from PHI
5386 if (PHI && PHI != P)
5387 return nullptr; // Evolving from multiple different PHIs.
5390 // This is a expression evolving from a constant PHI!
5394 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
5395 /// in the loop that V is derived from. We allow arbitrary operations along the
5396 /// way, but the operands of an operation must either be constants or a value
5397 /// derived from a constant PHI. If this expression does not fit with these
5398 /// constraints, return null.
5399 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
5400 Instruction *I = dyn_cast<Instruction>(V);
5401 if (!I || !canConstantEvolve(I, L)) return nullptr;
5403 if (PHINode *PN = dyn_cast<PHINode>(I)) {
5407 // Record non-constant instructions contained by the loop.
5408 DenseMap<Instruction *, PHINode *> PHIMap;
5409 return getConstantEvolvingPHIOperands(I, L, PHIMap);
5412 /// EvaluateExpression - Given an expression that passes the
5413 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
5414 /// in the loop has the value PHIVal. If we can't fold this expression for some
5415 /// reason, return null.
5416 static Constant *EvaluateExpression(Value *V, const Loop *L,
5417 DenseMap<Instruction *, Constant *> &Vals,
5418 const DataLayout *DL,
5419 const TargetLibraryInfo *TLI) {
5420 // Convenient constant check, but redundant for recursive calls.
5421 if (Constant *C = dyn_cast<Constant>(V)) return C;
5422 Instruction *I = dyn_cast<Instruction>(V);
5423 if (!I) return nullptr;
5425 if (Constant *C = Vals.lookup(I)) return C;
5427 // An instruction inside the loop depends on a value outside the loop that we
5428 // weren't given a mapping for, or a value such as a call inside the loop.
5429 if (!canConstantEvolve(I, L)) return nullptr;
5431 // An unmapped PHI can be due to a branch or another loop inside this loop,
5432 // or due to this not being the initial iteration through a loop where we
5433 // couldn't compute the evolution of this particular PHI last time.
5434 if (isa<PHINode>(I)) return nullptr;
5436 std::vector<Constant*> Operands(I->getNumOperands());
5438 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
5439 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
5441 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
5442 if (!Operands[i]) return nullptr;
5445 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
5447 if (!C) return nullptr;
5451 if (CmpInst *CI = dyn_cast<CmpInst>(I))
5452 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
5453 Operands[1], DL, TLI);
5454 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
5455 if (!LI->isVolatile())
5456 return ConstantFoldLoadFromConstPtr(Operands[0], DL);
5458 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Operands, DL,
5462 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
5463 /// in the header of its containing loop, we know the loop executes a
5464 /// constant number of times, and the PHI node is just a recurrence
5465 /// involving constants, fold it.
5467 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
5470 DenseMap<PHINode*, Constant*>::const_iterator I =
5471 ConstantEvolutionLoopExitValue.find(PN);
5472 if (I != ConstantEvolutionLoopExitValue.end())
5475 if (BEs.ugt(MaxBruteForceIterations))
5476 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
5478 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
5480 DenseMap<Instruction *, Constant *> CurrentIterVals;
5481 BasicBlock *Header = L->getHeader();
5482 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
5484 // Since the loop is canonicalized, the PHI node must have two entries. One
5485 // entry must be a constant (coming in from outside of the loop), and the
5486 // second must be derived from the same PHI.
5487 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
5488 PHINode *PHI = nullptr;
5489 for (BasicBlock::iterator I = Header->begin();
5490 (PHI = dyn_cast<PHINode>(I)); ++I) {
5491 Constant *StartCST =
5492 dyn_cast<Constant>(PHI->getIncomingValue(!SecondIsBackedge));
5493 if (!StartCST) continue;
5494 CurrentIterVals[PHI] = StartCST;
5496 if (!CurrentIterVals.count(PN))
5497 return RetVal = nullptr;
5499 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
5501 // Execute the loop symbolically to determine the exit value.
5502 if (BEs.getActiveBits() >= 32)
5503 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
5505 unsigned NumIterations = BEs.getZExtValue(); // must be in range
5506 unsigned IterationNum = 0;
5507 for (; ; ++IterationNum) {
5508 if (IterationNum == NumIterations)
5509 return RetVal = CurrentIterVals[PN]; // Got exit value!
5511 // Compute the value of the PHIs for the next iteration.
5512 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
5513 DenseMap<Instruction *, Constant *> NextIterVals;
5514 Constant *NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL,
5517 return nullptr; // Couldn't evaluate!
5518 NextIterVals[PN] = NextPHI;
5520 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
5522 // Also evaluate the other PHI nodes. However, we don't get to stop if we
5523 // cease to be able to evaluate one of them or if they stop evolving,
5524 // because that doesn't necessarily prevent us from computing PN.
5525 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
5526 for (DenseMap<Instruction *, Constant *>::const_iterator
5527 I = CurrentIterVals.begin(), E = CurrentIterVals.end(); I != E; ++I){
5528 PHINode *PHI = dyn_cast<PHINode>(I->first);
5529 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
5530 PHIsToCompute.push_back(std::make_pair(PHI, I->second));
5532 // We use two distinct loops because EvaluateExpression may invalidate any
5533 // iterators into CurrentIterVals.
5534 for (SmallVectorImpl<std::pair<PHINode *, Constant*> >::const_iterator
5535 I = PHIsToCompute.begin(), E = PHIsToCompute.end(); I != E; ++I) {
5536 PHINode *PHI = I->first;
5537 Constant *&NextPHI = NextIterVals[PHI];
5538 if (!NextPHI) { // Not already computed.
5539 Value *BEValue = PHI->getIncomingValue(SecondIsBackedge);
5540 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, TLI);
5542 if (NextPHI != I->second)
5543 StoppedEvolving = false;
5546 // If all entries in CurrentIterVals == NextIterVals then we can stop
5547 // iterating, the loop can't continue to change.
5548 if (StoppedEvolving)
5549 return RetVal = CurrentIterVals[PN];
5551 CurrentIterVals.swap(NextIterVals);
5555 /// ComputeExitCountExhaustively - If the loop is known to execute a
5556 /// constant number of times (the condition evolves only from constants),
5557 /// try to evaluate a few iterations of the loop until we get the exit
5558 /// condition gets a value of ExitWhen (true or false). If we cannot
5559 /// evaluate the trip count of the loop, return getCouldNotCompute().
5560 const SCEV *ScalarEvolution::ComputeExitCountExhaustively(const Loop *L,
5563 PHINode *PN = getConstantEvolvingPHI(Cond, L);
5564 if (!PN) return getCouldNotCompute();
5566 // If the loop is canonicalized, the PHI will have exactly two entries.
5567 // That's the only form we support here.
5568 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
5570 DenseMap<Instruction *, Constant *> CurrentIterVals;
5571 BasicBlock *Header = L->getHeader();
5572 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
5574 // One entry must be a constant (coming in from outside of the loop), and the
5575 // second must be derived from the same PHI.
5576 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
5577 PHINode *PHI = nullptr;
5578 for (BasicBlock::iterator I = Header->begin();
5579 (PHI = dyn_cast<PHINode>(I)); ++I) {
5580 Constant *StartCST =
5581 dyn_cast<Constant>(PHI->getIncomingValue(!SecondIsBackedge));
5582 if (!StartCST) continue;
5583 CurrentIterVals[PHI] = StartCST;
5585 if (!CurrentIterVals.count(PN))
5586 return getCouldNotCompute();
5588 // Okay, we find a PHI node that defines the trip count of this loop. Execute
5589 // the loop symbolically to determine when the condition gets a value of
5592 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
5593 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
5594 ConstantInt *CondVal =
5595 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, L, CurrentIterVals,
5598 // Couldn't symbolically evaluate.
5599 if (!CondVal) return getCouldNotCompute();
5601 if (CondVal->getValue() == uint64_t(ExitWhen)) {
5602 ++NumBruteForceTripCountsComputed;
5603 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
5606 // Update all the PHI nodes for the next iteration.
5607 DenseMap<Instruction *, Constant *> NextIterVals;
5609 // Create a list of which PHIs we need to compute. We want to do this before
5610 // calling EvaluateExpression on them because that may invalidate iterators
5611 // into CurrentIterVals.
5612 SmallVector<PHINode *, 8> PHIsToCompute;
5613 for (DenseMap<Instruction *, Constant *>::const_iterator
5614 I = CurrentIterVals.begin(), E = CurrentIterVals.end(); I != E; ++I){
5615 PHINode *PHI = dyn_cast<PHINode>(I->first);
5616 if (!PHI || PHI->getParent() != Header) continue;
5617 PHIsToCompute.push_back(PHI);
5619 for (SmallVectorImpl<PHINode *>::const_iterator I = PHIsToCompute.begin(),
5620 E = PHIsToCompute.end(); I != E; ++I) {
5622 Constant *&NextPHI = NextIterVals[PHI];
5623 if (NextPHI) continue; // Already computed!
5625 Value *BEValue = PHI->getIncomingValue(SecondIsBackedge);
5626 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, TLI);
5628 CurrentIterVals.swap(NextIterVals);
5631 // Too many iterations were needed to evaluate.
5632 return getCouldNotCompute();
5635 /// getSCEVAtScope - Return a SCEV expression for the specified value
5636 /// at the specified scope in the program. The L value specifies a loop
5637 /// nest to evaluate the expression at, where null is the top-level or a
5638 /// specified loop is immediately inside of the loop.
5640 /// This method can be used to compute the exit value for a variable defined
5641 /// in a loop by querying what the value will hold in the parent loop.
5643 /// In the case that a relevant loop exit value cannot be computed, the
5644 /// original value V is returned.
5645 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
5646 // Check to see if we've folded this expression at this loop before.
5647 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = ValuesAtScopes[V];
5648 for (unsigned u = 0; u < Values.size(); u++) {
5649 if (Values[u].first == L)
5650 return Values[u].second ? Values[u].second : V;
5652 Values.push_back(std::make_pair(L, static_cast<const SCEV *>(nullptr)));
5653 // Otherwise compute it.
5654 const SCEV *C = computeSCEVAtScope(V, L);
5655 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values2 = ValuesAtScopes[V];
5656 for (unsigned u = Values2.size(); u > 0; u--) {
5657 if (Values2[u - 1].first == L) {
5658 Values2[u - 1].second = C;
5665 /// This builds up a Constant using the ConstantExpr interface. That way, we
5666 /// will return Constants for objects which aren't represented by a
5667 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
5668 /// Returns NULL if the SCEV isn't representable as a Constant.
5669 static Constant *BuildConstantFromSCEV(const SCEV *V) {
5670 switch (static_cast<SCEVTypes>(V->getSCEVType())) {
5671 case scCouldNotCompute:
5675 return cast<SCEVConstant>(V)->getValue();
5677 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
5678 case scSignExtend: {
5679 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
5680 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
5681 return ConstantExpr::getSExt(CastOp, SS->getType());
5684 case scZeroExtend: {
5685 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
5686 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
5687 return ConstantExpr::getZExt(CastOp, SZ->getType());
5691 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
5692 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
5693 return ConstantExpr::getTrunc(CastOp, ST->getType());
5697 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
5698 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
5699 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
5700 unsigned AS = PTy->getAddressSpace();
5701 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
5702 C = ConstantExpr::getBitCast(C, DestPtrTy);
5704 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
5705 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
5706 if (!C2) return nullptr;
5709 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
5710 unsigned AS = C2->getType()->getPointerAddressSpace();
5712 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
5713 // The offsets have been converted to bytes. We can add bytes to an
5714 // i8* by GEP with the byte count in the first index.
5715 C = ConstantExpr::getBitCast(C, DestPtrTy);
5718 // Don't bother trying to sum two pointers. We probably can't
5719 // statically compute a load that results from it anyway.
5720 if (C2->getType()->isPointerTy())
5723 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
5724 if (PTy->getElementType()->isStructTy())
5725 C2 = ConstantExpr::getIntegerCast(
5726 C2, Type::getInt32Ty(C->getContext()), true);
5727 C = ConstantExpr::getGetElementPtr(C, C2);
5729 C = ConstantExpr::getAdd(C, C2);
5736 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
5737 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
5738 // Don't bother with pointers at all.
5739 if (C->getType()->isPointerTy()) return nullptr;
5740 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
5741 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
5742 if (!C2 || C2->getType()->isPointerTy()) return nullptr;
5743 C = ConstantExpr::getMul(C, C2);
5750 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
5751 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
5752 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
5753 if (LHS->getType() == RHS->getType())
5754 return ConstantExpr::getUDiv(LHS, RHS);
5759 break; // TODO: smax, umax.
5764 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
5765 if (isa<SCEVConstant>(V)) return V;
5767 // If this instruction is evolved from a constant-evolving PHI, compute the
5768 // exit value from the loop without using SCEVs.
5769 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
5770 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
5771 const Loop *LI = (*this->LI)[I->getParent()];
5772 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
5773 if (PHINode *PN = dyn_cast<PHINode>(I))
5774 if (PN->getParent() == LI->getHeader()) {
5775 // Okay, there is no closed form solution for the PHI node. Check
5776 // to see if the loop that contains it has a known backedge-taken
5777 // count. If so, we may be able to force computation of the exit
5779 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
5780 if (const SCEVConstant *BTCC =
5781 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
5782 // Okay, we know how many times the containing loop executes. If
5783 // this is a constant evolving PHI node, get the final value at
5784 // the specified iteration number.
5785 Constant *RV = getConstantEvolutionLoopExitValue(PN,
5786 BTCC->getValue()->getValue(),
5788 if (RV) return getSCEV(RV);
5792 // Okay, this is an expression that we cannot symbolically evaluate
5793 // into a SCEV. Check to see if it's possible to symbolically evaluate
5794 // the arguments into constants, and if so, try to constant propagate the
5795 // result. This is particularly useful for computing loop exit values.
5796 if (CanConstantFold(I)) {
5797 SmallVector<Constant *, 4> Operands;
5798 bool MadeImprovement = false;
5799 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
5800 Value *Op = I->getOperand(i);
5801 if (Constant *C = dyn_cast<Constant>(Op)) {
5802 Operands.push_back(C);
5806 // If any of the operands is non-constant and if they are
5807 // non-integer and non-pointer, don't even try to analyze them
5808 // with scev techniques.
5809 if (!isSCEVable(Op->getType()))
5812 const SCEV *OrigV = getSCEV(Op);
5813 const SCEV *OpV = getSCEVAtScope(OrigV, L);
5814 MadeImprovement |= OrigV != OpV;
5816 Constant *C = BuildConstantFromSCEV(OpV);
5818 if (C->getType() != Op->getType())
5819 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
5823 Operands.push_back(C);
5826 // Check to see if getSCEVAtScope actually made an improvement.
5827 if (MadeImprovement) {
5828 Constant *C = nullptr;
5829 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
5830 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
5831 Operands[0], Operands[1], DL,
5833 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
5834 if (!LI->isVolatile())
5835 C = ConstantFoldLoadFromConstPtr(Operands[0], DL);
5837 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
5845 // This is some other type of SCEVUnknown, just return it.
5849 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
5850 // Avoid performing the look-up in the common case where the specified
5851 // expression has no loop-variant portions.
5852 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
5853 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
5854 if (OpAtScope != Comm->getOperand(i)) {
5855 // Okay, at least one of these operands is loop variant but might be
5856 // foldable. Build a new instance of the folded commutative expression.
5857 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
5858 Comm->op_begin()+i);
5859 NewOps.push_back(OpAtScope);
5861 for (++i; i != e; ++i) {
5862 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
5863 NewOps.push_back(OpAtScope);
5865 if (isa<SCEVAddExpr>(Comm))
5866 return getAddExpr(NewOps);
5867 if (isa<SCEVMulExpr>(Comm))
5868 return getMulExpr(NewOps);
5869 if (isa<SCEVSMaxExpr>(Comm))
5870 return getSMaxExpr(NewOps);
5871 if (isa<SCEVUMaxExpr>(Comm))
5872 return getUMaxExpr(NewOps);
5873 llvm_unreachable("Unknown commutative SCEV type!");
5876 // If we got here, all operands are loop invariant.
5880 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
5881 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
5882 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
5883 if (LHS == Div->getLHS() && RHS == Div->getRHS())
5884 return Div; // must be loop invariant
5885 return getUDivExpr(LHS, RHS);
5888 // If this is a loop recurrence for a loop that does not contain L, then we
5889 // are dealing with the final value computed by the loop.
5890 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
5891 // First, attempt to evaluate each operand.
5892 // Avoid performing the look-up in the common case where the specified
5893 // expression has no loop-variant portions.
5894 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
5895 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
5896 if (OpAtScope == AddRec->getOperand(i))
5899 // Okay, at least one of these operands is loop variant but might be
5900 // foldable. Build a new instance of the folded commutative expression.
5901 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
5902 AddRec->op_begin()+i);
5903 NewOps.push_back(OpAtScope);
5904 for (++i; i != e; ++i)
5905 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
5907 const SCEV *FoldedRec =
5908 getAddRecExpr(NewOps, AddRec->getLoop(),
5909 AddRec->getNoWrapFlags(SCEV::FlagNW));
5910 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
5911 // The addrec may be folded to a nonrecurrence, for example, if the
5912 // induction variable is multiplied by zero after constant folding. Go
5913 // ahead and return the folded value.
5919 // If the scope is outside the addrec's loop, evaluate it by using the
5920 // loop exit value of the addrec.
5921 if (!AddRec->getLoop()->contains(L)) {
5922 // To evaluate this recurrence, we need to know how many times the AddRec
5923 // loop iterates. Compute this now.
5924 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
5925 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
5927 // Then, evaluate the AddRec.
5928 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
5934 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
5935 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
5936 if (Op == Cast->getOperand())
5937 return Cast; // must be loop invariant
5938 return getZeroExtendExpr(Op, Cast->getType());
5941 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
5942 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
5943 if (Op == Cast->getOperand())
5944 return Cast; // must be loop invariant
5945 return getSignExtendExpr(Op, Cast->getType());
5948 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
5949 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
5950 if (Op == Cast->getOperand())
5951 return Cast; // must be loop invariant
5952 return getTruncateExpr(Op, Cast->getType());
5955 llvm_unreachable("Unknown SCEV type!");
5958 /// getSCEVAtScope - This is a convenience function which does
5959 /// getSCEVAtScope(getSCEV(V), L).
5960 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
5961 return getSCEVAtScope(getSCEV(V), L);
5964 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
5965 /// following equation:
5967 /// A * X = B (mod N)
5969 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
5970 /// A and B isn't important.
5972 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
5973 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
5974 ScalarEvolution &SE) {
5975 uint32_t BW = A.getBitWidth();
5976 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
5977 assert(A != 0 && "A must be non-zero.");
5981 // The gcd of A and N may have only one prime factor: 2. The number of
5982 // trailing zeros in A is its multiplicity
5983 uint32_t Mult2 = A.countTrailingZeros();
5986 // 2. Check if B is divisible by D.
5988 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
5989 // is not less than multiplicity of this prime factor for D.
5990 if (B.countTrailingZeros() < Mult2)
5991 return SE.getCouldNotCompute();
5993 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
5996 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
5997 // bit width during computations.
5998 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
5999 APInt Mod(BW + 1, 0);
6000 Mod.setBit(BW - Mult2); // Mod = N / D
6001 APInt I = AD.multiplicativeInverse(Mod);
6003 // 4. Compute the minimum unsigned root of the equation:
6004 // I * (B / D) mod (N / D)
6005 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
6007 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
6009 return SE.getConstant(Result.trunc(BW));
6012 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
6013 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
6014 /// might be the same) or two SCEVCouldNotCompute objects.
6016 static std::pair<const SCEV *,const SCEV *>
6017 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
6018 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
6019 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
6020 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
6021 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
6023 // We currently can only solve this if the coefficients are constants.
6024 if (!LC || !MC || !NC) {
6025 const SCEV *CNC = SE.getCouldNotCompute();
6026 return std::make_pair(CNC, CNC);
6029 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
6030 const APInt &L = LC->getValue()->getValue();
6031 const APInt &M = MC->getValue()->getValue();
6032 const APInt &N = NC->getValue()->getValue();
6033 APInt Two(BitWidth, 2);
6034 APInt Four(BitWidth, 4);
6037 using namespace APIntOps;
6039 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
6040 // The B coefficient is M-N/2
6044 // The A coefficient is N/2
6045 APInt A(N.sdiv(Two));
6047 // Compute the B^2-4ac term.
6050 SqrtTerm -= Four * (A * C);
6052 if (SqrtTerm.isNegative()) {
6053 // The loop is provably infinite.
6054 const SCEV *CNC = SE.getCouldNotCompute();
6055 return std::make_pair(CNC, CNC);
6058 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
6059 // integer value or else APInt::sqrt() will assert.
6060 APInt SqrtVal(SqrtTerm.sqrt());
6062 // Compute the two solutions for the quadratic formula.
6063 // The divisions must be performed as signed divisions.
6066 if (TwoA.isMinValue()) {
6067 const SCEV *CNC = SE.getCouldNotCompute();
6068 return std::make_pair(CNC, CNC);
6071 LLVMContext &Context = SE.getContext();
6073 ConstantInt *Solution1 =
6074 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
6075 ConstantInt *Solution2 =
6076 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
6078 return std::make_pair(SE.getConstant(Solution1),
6079 SE.getConstant(Solution2));
6080 } // end APIntOps namespace
6083 /// HowFarToZero - Return the number of times a backedge comparing the specified
6084 /// value to zero will execute. If not computable, return CouldNotCompute.
6086 /// This is only used for loops with a "x != y" exit test. The exit condition is
6087 /// now expressed as a single expression, V = x-y. So the exit test is
6088 /// effectively V != 0. We know and take advantage of the fact that this
6089 /// expression only being used in a comparison by zero context.
6090 ScalarEvolution::ExitLimit
6091 ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L, bool ControlsExit) {
6092 // If the value is a constant
6093 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
6094 // If the value is already zero, the branch will execute zero times.
6095 if (C->getValue()->isZero()) return C;
6096 return getCouldNotCompute(); // Otherwise it will loop infinitely.
6099 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
6100 if (!AddRec || AddRec->getLoop() != L)
6101 return getCouldNotCompute();
6103 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
6104 // the quadratic equation to solve it.
6105 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
6106 std::pair<const SCEV *,const SCEV *> Roots =
6107 SolveQuadraticEquation(AddRec, *this);
6108 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
6109 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
6112 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
6113 << " sol#2: " << *R2 << "\n";
6115 // Pick the smallest positive root value.
6116 if (ConstantInt *CB =
6117 dyn_cast<ConstantInt>(ConstantExpr::getICmp(CmpInst::ICMP_ULT,
6120 if (CB->getZExtValue() == false)
6121 std::swap(R1, R2); // R1 is the minimum root now.
6123 // We can only use this value if the chrec ends up with an exact zero
6124 // value at this index. When solving for "X*X != 5", for example, we
6125 // should not accept a root of 2.
6126 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
6128 return R1; // We found a quadratic root!
6131 return getCouldNotCompute();
6134 // Otherwise we can only handle this if it is affine.
6135 if (!AddRec->isAffine())
6136 return getCouldNotCompute();
6138 // If this is an affine expression, the execution count of this branch is
6139 // the minimum unsigned root of the following equation:
6141 // Start + Step*N = 0 (mod 2^BW)
6145 // Step*N = -Start (mod 2^BW)
6147 // where BW is the common bit width of Start and Step.
6149 // Get the initial value for the loop.
6150 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
6151 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
6153 // For now we handle only constant steps.
6155 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
6156 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
6157 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
6158 // We have not yet seen any such cases.
6159 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
6160 if (!StepC || StepC->getValue()->equalsInt(0))
6161 return getCouldNotCompute();
6163 // For positive steps (counting up until unsigned overflow):
6164 // N = -Start/Step (as unsigned)
6165 // For negative steps (counting down to zero):
6167 // First compute the unsigned distance from zero in the direction of Step.
6168 bool CountDown = StepC->getValue()->getValue().isNegative();
6169 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
6171 // Handle unitary steps, which cannot wraparound.
6172 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
6173 // N = Distance (as unsigned)
6174 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
6175 ConstantRange CR = getUnsignedRange(Start);
6176 const SCEV *MaxBECount;
6177 if (!CountDown && CR.getUnsignedMin().isMinValue())
6178 // When counting up, the worst starting value is 1, not 0.
6179 MaxBECount = CR.getUnsignedMax().isMinValue()
6180 ? getConstant(APInt::getMinValue(CR.getBitWidth()))
6181 : getConstant(APInt::getMaxValue(CR.getBitWidth()));
6183 MaxBECount = getConstant(CountDown ? CR.getUnsignedMax()
6184 : -CR.getUnsignedMin());
6185 return ExitLimit(Distance, MaxBECount);
6188 // As a special case, handle the instance where Step is a positive power of
6189 // two. In this case, determining whether Step divides Distance evenly can be
6190 // done by counting and comparing the number of trailing zeros of Step and
6193 const APInt &StepV = StepC->getValue()->getValue();
6194 // StepV.isPowerOf2() returns true if StepV is an positive power of two. It
6195 // also returns true if StepV is maximally negative (eg, INT_MIN), but that
6196 // case is not handled as this code is guarded by !CountDown.
6197 if (StepV.isPowerOf2() &&
6198 GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros())
6199 return getUDivExactExpr(Distance, Step);
6202 // If the condition controls loop exit (the loop exits only if the expression
6203 // is true) and the addition is no-wrap we can use unsigned divide to
6204 // compute the backedge count. In this case, the step may not divide the
6205 // distance, but we don't care because if the condition is "missed" the loop
6206 // will have undefined behavior due to wrapping.
6207 if (ControlsExit && AddRec->getNoWrapFlags(SCEV::FlagNW)) {
6209 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
6210 return ExitLimit(Exact, Exact);
6213 // Then, try to solve the above equation provided that Start is constant.
6214 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
6215 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
6216 -StartC->getValue()->getValue(),
6218 return getCouldNotCompute();
6221 /// HowFarToNonZero - Return the number of times a backedge checking the
6222 /// specified value for nonzero will execute. If not computable, return
6224 ScalarEvolution::ExitLimit
6225 ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
6226 // Loops that look like: while (X == 0) are very strange indeed. We don't
6227 // handle them yet except for the trivial case. This could be expanded in the
6228 // future as needed.
6230 // If the value is a constant, check to see if it is known to be non-zero
6231 // already. If so, the backedge will execute zero times.
6232 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
6233 if (!C->getValue()->isNullValue())
6234 return getConstant(C->getType(), 0);
6235 return getCouldNotCompute(); // Otherwise it will loop infinitely.
6238 // We could implement others, but I really doubt anyone writes loops like
6239 // this, and if they did, they would already be constant folded.
6240 return getCouldNotCompute();
6243 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
6244 /// (which may not be an immediate predecessor) which has exactly one
6245 /// successor from which BB is reachable, or null if no such block is
6248 std::pair<BasicBlock *, BasicBlock *>
6249 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
6250 // If the block has a unique predecessor, then there is no path from the
6251 // predecessor to the block that does not go through the direct edge
6252 // from the predecessor to the block.
6253 if (BasicBlock *Pred = BB->getSinglePredecessor())
6254 return std::make_pair(Pred, BB);
6256 // A loop's header is defined to be a block that dominates the loop.
6257 // If the header has a unique predecessor outside the loop, it must be
6258 // a block that has exactly one successor that can reach the loop.
6259 if (Loop *L = LI->getLoopFor(BB))
6260 return std::make_pair(L->getLoopPredecessor(), L->getHeader());
6262 return std::pair<BasicBlock *, BasicBlock *>();
6265 /// HasSameValue - SCEV structural equivalence is usually sufficient for
6266 /// testing whether two expressions are equal, however for the purposes of
6267 /// looking for a condition guarding a loop, it can be useful to be a little
6268 /// more general, since a front-end may have replicated the controlling
6271 static bool HasSameValue(const SCEV *A, const SCEV *B) {
6272 // Quick check to see if they are the same SCEV.
6273 if (A == B) return true;
6275 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
6276 // two different instructions with the same value. Check for this case.
6277 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
6278 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
6279 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
6280 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
6281 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
6284 // Otherwise assume they may have a different value.
6288 /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
6289 /// predicate Pred. Return true iff any changes were made.
6291 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
6292 const SCEV *&LHS, const SCEV *&RHS,
6294 bool Changed = false;
6296 // If we hit the max recursion limit bail out.
6300 // Canonicalize a constant to the right side.
6301 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
6302 // Check for both operands constant.
6303 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
6304 if (ConstantExpr::getICmp(Pred,
6306 RHSC->getValue())->isNullValue())
6307 goto trivially_false;
6309 goto trivially_true;
6311 // Otherwise swap the operands to put the constant on the right.
6312 std::swap(LHS, RHS);
6313 Pred = ICmpInst::getSwappedPredicate(Pred);
6317 // If we're comparing an addrec with a value which is loop-invariant in the
6318 // addrec's loop, put the addrec on the left. Also make a dominance check,
6319 // as both operands could be addrecs loop-invariant in each other's loop.
6320 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
6321 const Loop *L = AR->getLoop();
6322 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
6323 std::swap(LHS, RHS);
6324 Pred = ICmpInst::getSwappedPredicate(Pred);
6329 // If there's a constant operand, canonicalize comparisons with boundary
6330 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
6331 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
6332 const APInt &RA = RC->getValue()->getValue();
6334 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
6335 case ICmpInst::ICMP_EQ:
6336 case ICmpInst::ICMP_NE:
6337 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
6339 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
6340 if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
6341 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
6342 ME->getOperand(0)->isAllOnesValue()) {
6343 RHS = AE->getOperand(1);
6344 LHS = ME->getOperand(1);
6348 case ICmpInst::ICMP_UGE:
6349 if ((RA - 1).isMinValue()) {
6350 Pred = ICmpInst::ICMP_NE;
6351 RHS = getConstant(RA - 1);
6355 if (RA.isMaxValue()) {
6356 Pred = ICmpInst::ICMP_EQ;
6360 if (RA.isMinValue()) goto trivially_true;
6362 Pred = ICmpInst::ICMP_UGT;
6363 RHS = getConstant(RA - 1);
6366 case ICmpInst::ICMP_ULE:
6367 if ((RA + 1).isMaxValue()) {
6368 Pred = ICmpInst::ICMP_NE;
6369 RHS = getConstant(RA + 1);
6373 if (RA.isMinValue()) {
6374 Pred = ICmpInst::ICMP_EQ;
6378 if (RA.isMaxValue()) goto trivially_true;
6380 Pred = ICmpInst::ICMP_ULT;
6381 RHS = getConstant(RA + 1);
6384 case ICmpInst::ICMP_SGE:
6385 if ((RA - 1).isMinSignedValue()) {
6386 Pred = ICmpInst::ICMP_NE;
6387 RHS = getConstant(RA - 1);
6391 if (RA.isMaxSignedValue()) {
6392 Pred = ICmpInst::ICMP_EQ;
6396 if (RA.isMinSignedValue()) goto trivially_true;
6398 Pred = ICmpInst::ICMP_SGT;
6399 RHS = getConstant(RA - 1);
6402 case ICmpInst::ICMP_SLE:
6403 if ((RA + 1).isMaxSignedValue()) {
6404 Pred = ICmpInst::ICMP_NE;
6405 RHS = getConstant(RA + 1);
6409 if (RA.isMinSignedValue()) {
6410 Pred = ICmpInst::ICMP_EQ;
6414 if (RA.isMaxSignedValue()) goto trivially_true;
6416 Pred = ICmpInst::ICMP_SLT;
6417 RHS = getConstant(RA + 1);
6420 case ICmpInst::ICMP_UGT:
6421 if (RA.isMinValue()) {
6422 Pred = ICmpInst::ICMP_NE;
6426 if ((RA + 1).isMaxValue()) {
6427 Pred = ICmpInst::ICMP_EQ;
6428 RHS = getConstant(RA + 1);
6432 if (RA.isMaxValue()) goto trivially_false;
6434 case ICmpInst::ICMP_ULT:
6435 if (RA.isMaxValue()) {
6436 Pred = ICmpInst::ICMP_NE;
6440 if ((RA - 1).isMinValue()) {
6441 Pred = ICmpInst::ICMP_EQ;
6442 RHS = getConstant(RA - 1);
6446 if (RA.isMinValue()) goto trivially_false;
6448 case ICmpInst::ICMP_SGT:
6449 if (RA.isMinSignedValue()) {
6450 Pred = ICmpInst::ICMP_NE;
6454 if ((RA + 1).isMaxSignedValue()) {
6455 Pred = ICmpInst::ICMP_EQ;
6456 RHS = getConstant(RA + 1);
6460 if (RA.isMaxSignedValue()) goto trivially_false;
6462 case ICmpInst::ICMP_SLT:
6463 if (RA.isMaxSignedValue()) {
6464 Pred = ICmpInst::ICMP_NE;
6468 if ((RA - 1).isMinSignedValue()) {
6469 Pred = ICmpInst::ICMP_EQ;
6470 RHS = getConstant(RA - 1);
6474 if (RA.isMinSignedValue()) goto trivially_false;
6479 // Check for obvious equality.
6480 if (HasSameValue(LHS, RHS)) {
6481 if (ICmpInst::isTrueWhenEqual(Pred))
6482 goto trivially_true;
6483 if (ICmpInst::isFalseWhenEqual(Pred))
6484 goto trivially_false;
6487 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
6488 // adding or subtracting 1 from one of the operands.
6490 case ICmpInst::ICMP_SLE:
6491 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
6492 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
6494 Pred = ICmpInst::ICMP_SLT;
6496 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
6497 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
6499 Pred = ICmpInst::ICMP_SLT;
6503 case ICmpInst::ICMP_SGE:
6504 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
6505 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
6507 Pred = ICmpInst::ICMP_SGT;
6509 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
6510 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
6512 Pred = ICmpInst::ICMP_SGT;
6516 case ICmpInst::ICMP_ULE:
6517 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
6518 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
6520 Pred = ICmpInst::ICMP_ULT;
6522 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
6523 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
6525 Pred = ICmpInst::ICMP_ULT;
6529 case ICmpInst::ICMP_UGE:
6530 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
6531 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
6533 Pred = ICmpInst::ICMP_UGT;
6535 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
6536 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
6538 Pred = ICmpInst::ICMP_UGT;
6546 // TODO: More simplifications are possible here.
6548 // Recursively simplify until we either hit a recursion limit or nothing
6551 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
6557 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
6558 Pred = ICmpInst::ICMP_EQ;
6563 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
6564 Pred = ICmpInst::ICMP_NE;
6568 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
6569 return getSignedRange(S).getSignedMax().isNegative();
6572 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
6573 return getSignedRange(S).getSignedMin().isStrictlyPositive();
6576 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
6577 return !getSignedRange(S).getSignedMin().isNegative();
6580 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
6581 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
6584 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
6585 return isKnownNegative(S) || isKnownPositive(S);
6588 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
6589 const SCEV *LHS, const SCEV *RHS) {
6590 // Canonicalize the inputs first.
6591 (void)SimplifyICmpOperands(Pred, LHS, RHS);
6593 // If LHS or RHS is an addrec, check to see if the condition is true in
6594 // every iteration of the loop.
6595 // If LHS and RHS are both addrec, both conditions must be true in
6596 // every iteration of the loop.
6597 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
6598 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
6599 bool LeftGuarded = false;
6600 bool RightGuarded = false;
6602 const Loop *L = LAR->getLoop();
6603 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
6604 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
6605 if (!RAR) return true;
6610 const Loop *L = RAR->getLoop();
6611 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
6612 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
6613 if (!LAR) return true;
6614 RightGuarded = true;
6617 if (LeftGuarded && RightGuarded)
6620 // Otherwise see what can be done with known constant ranges.
6621 return isKnownPredicateWithRanges(Pred, LHS, RHS);
6625 ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
6626 const SCEV *LHS, const SCEV *RHS) {
6627 if (HasSameValue(LHS, RHS))
6628 return ICmpInst::isTrueWhenEqual(Pred);
6630 // This code is split out from isKnownPredicate because it is called from
6631 // within isLoopEntryGuardedByCond.
6634 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
6635 case ICmpInst::ICMP_SGT:
6636 std::swap(LHS, RHS);
6637 case ICmpInst::ICMP_SLT: {
6638 ConstantRange LHSRange = getSignedRange(LHS);
6639 ConstantRange RHSRange = getSignedRange(RHS);
6640 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
6642 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
6646 case ICmpInst::ICMP_SGE:
6647 std::swap(LHS, RHS);
6648 case ICmpInst::ICMP_SLE: {
6649 ConstantRange LHSRange = getSignedRange(LHS);
6650 ConstantRange RHSRange = getSignedRange(RHS);
6651 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
6653 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
6657 case ICmpInst::ICMP_UGT:
6658 std::swap(LHS, RHS);
6659 case ICmpInst::ICMP_ULT: {
6660 ConstantRange LHSRange = getUnsignedRange(LHS);
6661 ConstantRange RHSRange = getUnsignedRange(RHS);
6662 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
6664 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
6668 case ICmpInst::ICMP_UGE:
6669 std::swap(LHS, RHS);
6670 case ICmpInst::ICMP_ULE: {
6671 ConstantRange LHSRange = getUnsignedRange(LHS);
6672 ConstantRange RHSRange = getUnsignedRange(RHS);
6673 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
6675 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
6679 case ICmpInst::ICMP_NE: {
6680 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
6682 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
6685 const SCEV *Diff = getMinusSCEV(LHS, RHS);
6686 if (isKnownNonZero(Diff))
6690 case ICmpInst::ICMP_EQ:
6691 // The check at the top of the function catches the case where
6692 // the values are known to be equal.
6698 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
6699 /// protected by a conditional between LHS and RHS. This is used to
6700 /// to eliminate casts.
6702 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
6703 ICmpInst::Predicate Pred,
6704 const SCEV *LHS, const SCEV *RHS) {
6705 // Interpret a null as meaning no loop, where there is obviously no guard
6706 // (interprocedural conditions notwithstanding).
6707 if (!L) return true;
6709 if (isKnownPredicateWithRanges(Pred, LHS, RHS)) return true;
6711 BasicBlock *Latch = L->getLoopLatch();
6715 BranchInst *LoopContinuePredicate =
6716 dyn_cast<BranchInst>(Latch->getTerminator());
6717 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
6718 isImpliedCond(Pred, LHS, RHS,
6719 LoopContinuePredicate->getCondition(),
6720 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
6723 // Check conditions due to any @llvm.assume intrinsics.
6724 for (auto &AssumeVH : AC->assumptions()) {
6727 auto *CI = cast<CallInst>(AssumeVH);
6728 if (!DT->dominates(CI, Latch->getTerminator()))
6731 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
6738 /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
6739 /// by a conditional between LHS and RHS. This is used to help avoid max
6740 /// expressions in loop trip counts, and to eliminate casts.
6742 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
6743 ICmpInst::Predicate Pred,
6744 const SCEV *LHS, const SCEV *RHS) {
6745 // Interpret a null as meaning no loop, where there is obviously no guard
6746 // (interprocedural conditions notwithstanding).
6747 if (!L) return false;
6749 if (isKnownPredicateWithRanges(Pred, LHS, RHS)) return true;
6751 // Starting at the loop predecessor, climb up the predecessor chain, as long
6752 // as there are predecessors that can be found that have unique successors
6753 // leading to the original header.
6754 for (std::pair<BasicBlock *, BasicBlock *>
6755 Pair(L->getLoopPredecessor(), L->getHeader());
6757 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
6759 BranchInst *LoopEntryPredicate =
6760 dyn_cast<BranchInst>(Pair.first->getTerminator());
6761 if (!LoopEntryPredicate ||
6762 LoopEntryPredicate->isUnconditional())
6765 if (isImpliedCond(Pred, LHS, RHS,
6766 LoopEntryPredicate->getCondition(),
6767 LoopEntryPredicate->getSuccessor(0) != Pair.second))
6771 // Check conditions due to any @llvm.assume intrinsics.
6772 for (auto &AssumeVH : AC->assumptions()) {
6775 auto *CI = cast<CallInst>(AssumeVH);
6776 if (!DT->dominates(CI, L->getHeader()))
6779 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
6786 /// RAII wrapper to prevent recursive application of isImpliedCond.
6787 /// ScalarEvolution's PendingLoopPredicates set must be empty unless we are
6788 /// currently evaluating isImpliedCond.
6789 struct MarkPendingLoopPredicate {
6791 DenseSet<Value*> &LoopPreds;
6794 MarkPendingLoopPredicate(Value *C, DenseSet<Value*> &LP)
6795 : Cond(C), LoopPreds(LP) {
6796 Pending = !LoopPreds.insert(Cond).second;
6798 ~MarkPendingLoopPredicate() {
6800 LoopPreds.erase(Cond);
6804 /// isImpliedCond - Test whether the condition described by Pred, LHS,
6805 /// and RHS is true whenever the given Cond value evaluates to true.
6806 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
6807 const SCEV *LHS, const SCEV *RHS,
6808 Value *FoundCondValue,
6810 MarkPendingLoopPredicate Mark(FoundCondValue, PendingLoopPredicates);
6814 // Recursively handle And and Or conditions.
6815 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
6816 if (BO->getOpcode() == Instruction::And) {
6818 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
6819 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
6820 } else if (BO->getOpcode() == Instruction::Or) {
6822 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
6823 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
6827 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
6828 if (!ICI) return false;
6830 // Bail if the ICmp's operands' types are wider than the needed type
6831 // before attempting to call getSCEV on them. This avoids infinite
6832 // recursion, since the analysis of widening casts can require loop
6833 // exit condition information for overflow checking, which would
6835 if (getTypeSizeInBits(LHS->getType()) <
6836 getTypeSizeInBits(ICI->getOperand(0)->getType()))
6839 // Now that we found a conditional branch that dominates the loop or controls
6840 // the loop latch. Check to see if it is the comparison we are looking for.
6841 ICmpInst::Predicate FoundPred;
6843 FoundPred = ICI->getInversePredicate();
6845 FoundPred = ICI->getPredicate();
6847 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
6848 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
6850 // Balance the types. The case where FoundLHS' type is wider than
6851 // LHS' type is checked for above.
6852 if (getTypeSizeInBits(LHS->getType()) >
6853 getTypeSizeInBits(FoundLHS->getType())) {
6854 if (CmpInst::isSigned(FoundPred)) {
6855 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
6856 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
6858 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
6859 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
6863 // Canonicalize the query to match the way instcombine will have
6864 // canonicalized the comparison.
6865 if (SimplifyICmpOperands(Pred, LHS, RHS))
6867 return CmpInst::isTrueWhenEqual(Pred);
6868 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
6869 if (FoundLHS == FoundRHS)
6870 return CmpInst::isFalseWhenEqual(FoundPred);
6872 // Check to see if we can make the LHS or RHS match.
6873 if (LHS == FoundRHS || RHS == FoundLHS) {
6874 if (isa<SCEVConstant>(RHS)) {
6875 std::swap(FoundLHS, FoundRHS);
6876 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
6878 std::swap(LHS, RHS);
6879 Pred = ICmpInst::getSwappedPredicate(Pred);
6883 // Check whether the found predicate is the same as the desired predicate.
6884 if (FoundPred == Pred)
6885 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
6887 // Check whether swapping the found predicate makes it the same as the
6888 // desired predicate.
6889 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
6890 if (isa<SCEVConstant>(RHS))
6891 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
6893 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
6894 RHS, LHS, FoundLHS, FoundRHS);
6897 // Check if we can make progress by sharpening ranges.
6898 if (FoundPred == ICmpInst::ICMP_NE &&
6899 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
6901 const SCEVConstant *C = nullptr;
6902 const SCEV *V = nullptr;
6904 if (isa<SCEVConstant>(FoundLHS)) {
6905 C = cast<SCEVConstant>(FoundLHS);
6908 C = cast<SCEVConstant>(FoundRHS);
6912 // The guarding predicate tells us that C != V. If the known range
6913 // of V is [C, t), we can sharpen the range to [C + 1, t). The
6914 // range we consider has to correspond to same signedness as the
6915 // predicate we're interested in folding.
6917 APInt Min = ICmpInst::isSigned(Pred) ?
6918 getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin();
6920 if (Min == C->getValue()->getValue()) {
6921 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
6922 // This is true even if (Min + 1) wraps around -- in case of
6923 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
6925 APInt SharperMin = Min + 1;
6928 case ICmpInst::ICMP_SGE:
6929 case ICmpInst::ICMP_UGE:
6930 // We know V `Pred` SharperMin. If this implies LHS `Pred`
6932 if (isImpliedCondOperands(Pred, LHS, RHS, V,
6933 getConstant(SharperMin)))
6936 case ICmpInst::ICMP_SGT:
6937 case ICmpInst::ICMP_UGT:
6938 // We know from the range information that (V `Pred` Min ||
6939 // V == Min). We know from the guarding condition that !(V
6940 // == Min). This gives us
6942 // V `Pred` Min || V == Min && !(V == Min)
6945 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
6947 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
6957 // Check whether the actual condition is beyond sufficient.
6958 if (FoundPred == ICmpInst::ICMP_EQ)
6959 if (ICmpInst::isTrueWhenEqual(Pred))
6960 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
6962 if (Pred == ICmpInst::ICMP_NE)
6963 if (!ICmpInst::isTrueWhenEqual(FoundPred))
6964 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
6967 // Otherwise assume the worst.
6971 /// isImpliedCondOperands - Test whether the condition described by Pred,
6972 /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
6973 /// and FoundRHS is true.
6974 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
6975 const SCEV *LHS, const SCEV *RHS,
6976 const SCEV *FoundLHS,
6977 const SCEV *FoundRHS) {
6978 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
6979 FoundLHS, FoundRHS) ||
6980 // ~x < ~y --> x > y
6981 isImpliedCondOperandsHelper(Pred, LHS, RHS,
6982 getNotSCEV(FoundRHS),
6983 getNotSCEV(FoundLHS));
6987 /// If Expr computes ~A, return A else return nullptr
6988 static const SCEV *MatchNotExpr(const SCEV *Expr) {
6989 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
6990 if (!Add || Add->getNumOperands() != 2) return nullptr;
6992 const SCEVConstant *AddLHS = dyn_cast<SCEVConstant>(Add->getOperand(0));
6993 if (!(AddLHS && AddLHS->getValue()->getValue().isAllOnesValue()))
6996 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
6997 if (!AddRHS || AddRHS->getNumOperands() != 2) return nullptr;
6999 const SCEVConstant *MulLHS = dyn_cast<SCEVConstant>(AddRHS->getOperand(0));
7000 if (!(MulLHS && MulLHS->getValue()->getValue().isAllOnesValue()))
7003 return AddRHS->getOperand(1);
7007 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
7008 template<typename MaxExprType>
7009 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
7010 const SCEV *Candidate) {
7011 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
7012 if (!MaxExpr) return false;
7014 auto It = std::find(MaxExpr->op_begin(), MaxExpr->op_end(), Candidate);
7015 return It != MaxExpr->op_end();
7019 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
7020 template<typename MaxExprType>
7021 static bool IsMinConsistingOf(ScalarEvolution &SE,
7022 const SCEV *MaybeMinExpr,
7023 const SCEV *Candidate) {
7024 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
7028 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
7032 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
7034 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
7035 ICmpInst::Predicate Pred,
7036 const SCEV *LHS, const SCEV *RHS) {
7041 case ICmpInst::ICMP_SGE:
7042 std::swap(LHS, RHS);
7044 case ICmpInst::ICMP_SLE:
7047 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
7049 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
7051 case ICmpInst::ICMP_UGE:
7052 std::swap(LHS, RHS);
7054 case ICmpInst::ICMP_ULE:
7057 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
7059 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
7062 llvm_unreachable("covered switch fell through?!");
7065 /// isImpliedCondOperandsHelper - Test whether the condition described by
7066 /// Pred, LHS, and RHS is true whenever the condition described by Pred,
7067 /// FoundLHS, and FoundRHS is true.
7069 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
7070 const SCEV *LHS, const SCEV *RHS,
7071 const SCEV *FoundLHS,
7072 const SCEV *FoundRHS) {
7073 auto IsKnownPredicateFull =
7074 [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
7075 return isKnownPredicateWithRanges(Pred, LHS, RHS) ||
7076 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS);
7080 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
7081 case ICmpInst::ICMP_EQ:
7082 case ICmpInst::ICMP_NE:
7083 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
7086 case ICmpInst::ICMP_SLT:
7087 case ICmpInst::ICMP_SLE:
7088 if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
7089 IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS))
7092 case ICmpInst::ICMP_SGT:
7093 case ICmpInst::ICMP_SGE:
7094 if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
7095 IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS))
7098 case ICmpInst::ICMP_ULT:
7099 case ICmpInst::ICMP_ULE:
7100 if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
7101 IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS))
7104 case ICmpInst::ICMP_UGT:
7105 case ICmpInst::ICMP_UGE:
7106 if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
7107 IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS))
7115 // Verify if an linear IV with positive stride can overflow when in a
7116 // less-than comparison, knowing the invariant term of the comparison, the
7117 // stride and the knowledge of NSW/NUW flags on the recurrence.
7118 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
7119 bool IsSigned, bool NoWrap) {
7120 if (NoWrap) return false;
7122 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
7123 const SCEV *One = getConstant(Stride->getType(), 1);
7126 APInt MaxRHS = getSignedRange(RHS).getSignedMax();
7127 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
7128 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
7131 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
7132 return (MaxValue - MaxStrideMinusOne).slt(MaxRHS);
7135 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
7136 APInt MaxValue = APInt::getMaxValue(BitWidth);
7137 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
7140 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
7141 return (MaxValue - MaxStrideMinusOne).ult(MaxRHS);
7144 // Verify if an linear IV with negative stride can overflow when in a
7145 // greater-than comparison, knowing the invariant term of the comparison,
7146 // the stride and the knowledge of NSW/NUW flags on the recurrence.
7147 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
7148 bool IsSigned, bool NoWrap) {
7149 if (NoWrap) return false;
7151 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
7152 const SCEV *One = getConstant(Stride->getType(), 1);
7155 APInt MinRHS = getSignedRange(RHS).getSignedMin();
7156 APInt MinValue = APInt::getSignedMinValue(BitWidth);
7157 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
7160 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
7161 return (MinValue + MaxStrideMinusOne).sgt(MinRHS);
7164 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
7165 APInt MinValue = APInt::getMinValue(BitWidth);
7166 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
7169 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
7170 return (MinValue + MaxStrideMinusOne).ugt(MinRHS);
7173 // Compute the backedge taken count knowing the interval difference, the
7174 // stride and presence of the equality in the comparison.
7175 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
7177 const SCEV *One = getConstant(Step->getType(), 1);
7178 Delta = Equality ? getAddExpr(Delta, Step)
7179 : getAddExpr(Delta, getMinusSCEV(Step, One));
7180 return getUDivExpr(Delta, Step);
7183 /// HowManyLessThans - Return the number of times a backedge containing the
7184 /// specified less-than comparison will execute. If not computable, return
7185 /// CouldNotCompute.
7187 /// @param ControlsExit is true when the LHS < RHS condition directly controls
7188 /// the branch (loops exits only if condition is true). In this case, we can use
7189 /// NoWrapFlags to skip overflow checks.
7190 ScalarEvolution::ExitLimit
7191 ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
7192 const Loop *L, bool IsSigned,
7193 bool ControlsExit) {
7194 // We handle only IV < Invariant
7195 if (!isLoopInvariant(RHS, L))
7196 return getCouldNotCompute();
7198 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
7200 // Avoid weird loops
7201 if (!IV || IV->getLoop() != L || !IV->isAffine())
7202 return getCouldNotCompute();
7204 bool NoWrap = ControlsExit &&
7205 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
7207 const SCEV *Stride = IV->getStepRecurrence(*this);
7209 // Avoid negative or zero stride values
7210 if (!isKnownPositive(Stride))
7211 return getCouldNotCompute();
7213 // Avoid proven overflow cases: this will ensure that the backedge taken count
7214 // will not generate any unsigned overflow. Relaxed no-overflow conditions
7215 // exploit NoWrapFlags, allowing to optimize in presence of undefined
7216 // behaviors like the case of C language.
7217 if (!Stride->isOne() && doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
7218 return getCouldNotCompute();
7220 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
7221 : ICmpInst::ICMP_ULT;
7222 const SCEV *Start = IV->getStart();
7223 const SCEV *End = RHS;
7224 if (!isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) {
7225 const SCEV *Diff = getMinusSCEV(RHS, Start);
7226 // If we have NoWrap set, then we can assume that the increment won't
7227 // overflow, in which case if RHS - Start is a constant, we don't need to
7228 // do a max operation since we can just figure it out statically
7229 if (NoWrap && isa<SCEVConstant>(Diff)) {
7230 APInt D = dyn_cast<const SCEVConstant>(Diff)->getValue()->getValue();
7234 End = IsSigned ? getSMaxExpr(RHS, Start)
7235 : getUMaxExpr(RHS, Start);
7238 const SCEV *BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
7240 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
7241 : getUnsignedRange(Start).getUnsignedMin();
7243 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
7244 : getUnsignedRange(Stride).getUnsignedMin();
7246 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
7247 APInt Limit = IsSigned ? APInt::getSignedMaxValue(BitWidth) - (MinStride - 1)
7248 : APInt::getMaxValue(BitWidth) - (MinStride - 1);
7250 // Although End can be a MAX expression we estimate MaxEnd considering only
7251 // the case End = RHS. This is safe because in the other case (End - Start)
7252 // is zero, leading to a zero maximum backedge taken count.
7254 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
7255 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
7257 const SCEV *MaxBECount;
7258 if (isa<SCEVConstant>(BECount))
7259 MaxBECount = BECount;
7261 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
7262 getConstant(MinStride), false);
7264 if (isa<SCEVCouldNotCompute>(MaxBECount))
7265 MaxBECount = BECount;
7267 return ExitLimit(BECount, MaxBECount);
7270 ScalarEvolution::ExitLimit
7271 ScalarEvolution::HowManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
7272 const Loop *L, bool IsSigned,
7273 bool ControlsExit) {
7274 // We handle only IV > Invariant
7275 if (!isLoopInvariant(RHS, L))
7276 return getCouldNotCompute();
7278 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
7280 // Avoid weird loops
7281 if (!IV || IV->getLoop() != L || !IV->isAffine())
7282 return getCouldNotCompute();
7284 bool NoWrap = ControlsExit &&
7285 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
7287 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
7289 // Avoid negative or zero stride values
7290 if (!isKnownPositive(Stride))
7291 return getCouldNotCompute();
7293 // Avoid proven overflow cases: this will ensure that the backedge taken count
7294 // will not generate any unsigned overflow. Relaxed no-overflow conditions
7295 // exploit NoWrapFlags, allowing to optimize in presence of undefined
7296 // behaviors like the case of C language.
7297 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
7298 return getCouldNotCompute();
7300 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
7301 : ICmpInst::ICMP_UGT;
7303 const SCEV *Start = IV->getStart();
7304 const SCEV *End = RHS;
7305 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
7306 const SCEV *Diff = getMinusSCEV(RHS, Start);
7307 // If we have NoWrap set, then we can assume that the increment won't
7308 // overflow, in which case if RHS - Start is a constant, we don't need to
7309 // do a max operation since we can just figure it out statically
7310 if (NoWrap && isa<SCEVConstant>(Diff)) {
7311 APInt D = dyn_cast<const SCEVConstant>(Diff)->getValue()->getValue();
7312 if (!D.isNegative())
7315 End = IsSigned ? getSMinExpr(RHS, Start)
7316 : getUMinExpr(RHS, Start);
7319 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
7321 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
7322 : getUnsignedRange(Start).getUnsignedMax();
7324 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
7325 : getUnsignedRange(Stride).getUnsignedMin();
7327 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
7328 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
7329 : APInt::getMinValue(BitWidth) + (MinStride - 1);
7331 // Although End can be a MIN expression we estimate MinEnd considering only
7332 // the case End = RHS. This is safe because in the other case (Start - End)
7333 // is zero, leading to a zero maximum backedge taken count.
7335 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
7336 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
7339 const SCEV *MaxBECount = getCouldNotCompute();
7340 if (isa<SCEVConstant>(BECount))
7341 MaxBECount = BECount;
7343 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
7344 getConstant(MinStride), false);
7346 if (isa<SCEVCouldNotCompute>(MaxBECount))
7347 MaxBECount = BECount;
7349 return ExitLimit(BECount, MaxBECount);
7352 /// getNumIterationsInRange - Return the number of iterations of this loop that
7353 /// produce values in the specified constant range. Another way of looking at
7354 /// this is that it returns the first iteration number where the value is not in
7355 /// the condition, thus computing the exit count. If the iteration count can't
7356 /// be computed, an instance of SCEVCouldNotCompute is returned.
7357 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
7358 ScalarEvolution &SE) const {
7359 if (Range.isFullSet()) // Infinite loop.
7360 return SE.getCouldNotCompute();
7362 // If the start is a non-zero constant, shift the range to simplify things.
7363 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
7364 if (!SC->getValue()->isZero()) {
7365 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
7366 Operands[0] = SE.getConstant(SC->getType(), 0);
7367 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
7368 getNoWrapFlags(FlagNW));
7369 if (const SCEVAddRecExpr *ShiftedAddRec =
7370 dyn_cast<SCEVAddRecExpr>(Shifted))
7371 return ShiftedAddRec->getNumIterationsInRange(
7372 Range.subtract(SC->getValue()->getValue()), SE);
7373 // This is strange and shouldn't happen.
7374 return SE.getCouldNotCompute();
7377 // The only time we can solve this is when we have all constant indices.
7378 // Otherwise, we cannot determine the overflow conditions.
7379 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
7380 if (!isa<SCEVConstant>(getOperand(i)))
7381 return SE.getCouldNotCompute();
7384 // Okay at this point we know that all elements of the chrec are constants and
7385 // that the start element is zero.
7387 // First check to see if the range contains zero. If not, the first
7389 unsigned BitWidth = SE.getTypeSizeInBits(getType());
7390 if (!Range.contains(APInt(BitWidth, 0)))
7391 return SE.getConstant(getType(), 0);
7394 // If this is an affine expression then we have this situation:
7395 // Solve {0,+,A} in Range === Ax in Range
7397 // We know that zero is in the range. If A is positive then we know that
7398 // the upper value of the range must be the first possible exit value.
7399 // If A is negative then the lower of the range is the last possible loop
7400 // value. Also note that we already checked for a full range.
7401 APInt One(BitWidth,1);
7402 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
7403 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
7405 // The exit value should be (End+A)/A.
7406 APInt ExitVal = (End + A).udiv(A);
7407 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
7409 // Evaluate at the exit value. If we really did fall out of the valid
7410 // range, then we computed our trip count, otherwise wrap around or other
7411 // things must have happened.
7412 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
7413 if (Range.contains(Val->getValue()))
7414 return SE.getCouldNotCompute(); // Something strange happened
7416 // Ensure that the previous value is in the range. This is a sanity check.
7417 assert(Range.contains(
7418 EvaluateConstantChrecAtConstant(this,
7419 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
7420 "Linear scev computation is off in a bad way!");
7421 return SE.getConstant(ExitValue);
7422 } else if (isQuadratic()) {
7423 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
7424 // quadratic equation to solve it. To do this, we must frame our problem in
7425 // terms of figuring out when zero is crossed, instead of when
7426 // Range.getUpper() is crossed.
7427 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
7428 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
7429 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(),
7430 // getNoWrapFlags(FlagNW)
7433 // Next, solve the constructed addrec
7434 std::pair<const SCEV *,const SCEV *> Roots =
7435 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
7436 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
7437 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
7439 // Pick the smallest positive root value.
7440 if (ConstantInt *CB =
7441 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
7442 R1->getValue(), R2->getValue()))) {
7443 if (CB->getZExtValue() == false)
7444 std::swap(R1, R2); // R1 is the minimum root now.
7446 // Make sure the root is not off by one. The returned iteration should
7447 // not be in the range, but the previous one should be. When solving
7448 // for "X*X < 5", for example, we should not return a root of 2.
7449 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
7452 if (Range.contains(R1Val->getValue())) {
7453 // The next iteration must be out of the range...
7454 ConstantInt *NextVal =
7455 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
7457 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
7458 if (!Range.contains(R1Val->getValue()))
7459 return SE.getConstant(NextVal);
7460 return SE.getCouldNotCompute(); // Something strange happened
7463 // If R1 was not in the range, then it is a good return value. Make
7464 // sure that R1-1 WAS in the range though, just in case.
7465 ConstantInt *NextVal =
7466 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
7467 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
7468 if (Range.contains(R1Val->getValue()))
7470 return SE.getCouldNotCompute(); // Something strange happened
7475 return SE.getCouldNotCompute();
7481 FindUndefs() : Found(false) {}
7483 bool follow(const SCEV *S) {
7484 if (const SCEVUnknown *C = dyn_cast<SCEVUnknown>(S)) {
7485 if (isa<UndefValue>(C->getValue()))
7487 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
7488 if (isa<UndefValue>(C->getValue()))
7492 // Keep looking if we haven't found it yet.
7495 bool isDone() const {
7496 // Stop recursion if we have found an undef.
7502 // Return true when S contains at least an undef value.
7504 containsUndefs(const SCEV *S) {
7506 SCEVTraversal<FindUndefs> ST(F);
7513 // Collect all steps of SCEV expressions.
7514 struct SCEVCollectStrides {
7515 ScalarEvolution &SE;
7516 SmallVectorImpl<const SCEV *> &Strides;
7518 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
7519 : SE(SE), Strides(S) {}
7521 bool follow(const SCEV *S) {
7522 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
7523 Strides.push_back(AR->getStepRecurrence(SE));
7526 bool isDone() const { return false; }
7529 // Collect all SCEVUnknown and SCEVMulExpr expressions.
7530 struct SCEVCollectTerms {
7531 SmallVectorImpl<const SCEV *> &Terms;
7533 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
7536 bool follow(const SCEV *S) {
7537 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S)) {
7538 if (!containsUndefs(S))
7541 // Stop recursion: once we collected a term, do not walk its operands.
7548 bool isDone() const { return false; }
7552 /// Find parametric terms in this SCEVAddRecExpr.
7553 void SCEVAddRecExpr::collectParametricTerms(
7554 ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &Terms) const {
7555 SmallVector<const SCEV *, 4> Strides;
7556 SCEVCollectStrides StrideCollector(SE, Strides);
7557 visitAll(this, StrideCollector);
7560 dbgs() << "Strides:\n";
7561 for (const SCEV *S : Strides)
7562 dbgs() << *S << "\n";
7565 for (const SCEV *S : Strides) {
7566 SCEVCollectTerms TermCollector(Terms);
7567 visitAll(S, TermCollector);
7571 dbgs() << "Terms:\n";
7572 for (const SCEV *T : Terms)
7573 dbgs() << *T << "\n";
7577 static bool findArrayDimensionsRec(ScalarEvolution &SE,
7578 SmallVectorImpl<const SCEV *> &Terms,
7579 SmallVectorImpl<const SCEV *> &Sizes) {
7580 int Last = Terms.size() - 1;
7581 const SCEV *Step = Terms[Last];
7583 // End of recursion.
7585 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
7586 SmallVector<const SCEV *, 2> Qs;
7587 for (const SCEV *Op : M->operands())
7588 if (!isa<SCEVConstant>(Op))
7591 Step = SE.getMulExpr(Qs);
7594 Sizes.push_back(Step);
7598 for (const SCEV *&Term : Terms) {
7599 // Normalize the terms before the next call to findArrayDimensionsRec.
7601 SCEVDivision::divide(SE, Term, Step, &Q, &R);
7603 // Bail out when GCD does not evenly divide one of the terms.
7610 // Remove all SCEVConstants.
7611 Terms.erase(std::remove_if(Terms.begin(), Terms.end(), [](const SCEV *E) {
7612 return isa<SCEVConstant>(E);
7616 if (Terms.size() > 0)
7617 if (!findArrayDimensionsRec(SE, Terms, Sizes))
7620 Sizes.push_back(Step);
7625 struct FindParameter {
7626 bool FoundParameter;
7627 FindParameter() : FoundParameter(false) {}
7629 bool follow(const SCEV *S) {
7630 if (isa<SCEVUnknown>(S)) {
7631 FoundParameter = true;
7632 // Stop recursion: we found a parameter.
7638 bool isDone() const {
7639 // Stop recursion if we have found a parameter.
7640 return FoundParameter;
7645 // Returns true when S contains at least a SCEVUnknown parameter.
7647 containsParameters(const SCEV *S) {
7649 SCEVTraversal<FindParameter> ST(F);
7652 return F.FoundParameter;
7655 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
7657 containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
7658 for (const SCEV *T : Terms)
7659 if (containsParameters(T))
7664 // Return the number of product terms in S.
7665 static inline int numberOfTerms(const SCEV *S) {
7666 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
7667 return Expr->getNumOperands();
7671 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
7672 if (isa<SCEVConstant>(T))
7675 if (isa<SCEVUnknown>(T))
7678 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
7679 SmallVector<const SCEV *, 2> Factors;
7680 for (const SCEV *Op : M->operands())
7681 if (!isa<SCEVConstant>(Op))
7682 Factors.push_back(Op);
7684 return SE.getMulExpr(Factors);
7690 /// Return the size of an element read or written by Inst.
7691 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
7693 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
7694 Ty = Store->getValueOperand()->getType();
7695 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
7696 Ty = Load->getType();
7700 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
7701 return getSizeOfExpr(ETy, Ty);
7704 /// Second step of delinearization: compute the array dimensions Sizes from the
7705 /// set of Terms extracted from the memory access function of this SCEVAddRec.
7706 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
7707 SmallVectorImpl<const SCEV *> &Sizes,
7708 const SCEV *ElementSize) const {
7710 if (Terms.size() < 1 || !ElementSize)
7713 // Early return when Terms do not contain parameters: we do not delinearize
7714 // non parametric SCEVs.
7715 if (!containsParameters(Terms))
7719 dbgs() << "Terms:\n";
7720 for (const SCEV *T : Terms)
7721 dbgs() << *T << "\n";
7724 // Remove duplicates.
7725 std::sort(Terms.begin(), Terms.end());
7726 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
7728 // Put larger terms first.
7729 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
7730 return numberOfTerms(LHS) > numberOfTerms(RHS);
7733 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
7735 // Divide all terms by the element size.
7736 for (const SCEV *&Term : Terms) {
7738 SCEVDivision::divide(SE, Term, ElementSize, &Q, &R);
7742 SmallVector<const SCEV *, 4> NewTerms;
7744 // Remove constant factors.
7745 for (const SCEV *T : Terms)
7746 if (const SCEV *NewT = removeConstantFactors(SE, T))
7747 NewTerms.push_back(NewT);
7750 dbgs() << "Terms after sorting:\n";
7751 for (const SCEV *T : NewTerms)
7752 dbgs() << *T << "\n";
7755 if (NewTerms.empty() ||
7756 !findArrayDimensionsRec(SE, NewTerms, Sizes)) {
7761 // The last element to be pushed into Sizes is the size of an element.
7762 Sizes.push_back(ElementSize);
7765 dbgs() << "Sizes:\n";
7766 for (const SCEV *S : Sizes)
7767 dbgs() << *S << "\n";
7771 /// Third step of delinearization: compute the access functions for the
7772 /// Subscripts based on the dimensions in Sizes.
7773 void SCEVAddRecExpr::computeAccessFunctions(
7774 ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &Subscripts,
7775 SmallVectorImpl<const SCEV *> &Sizes) const {
7777 // Early exit in case this SCEV is not an affine multivariate function.
7778 if (Sizes.empty() || !this->isAffine())
7781 const SCEV *Res = this;
7782 int Last = Sizes.size() - 1;
7783 for (int i = Last; i >= 0; i--) {
7785 SCEVDivision::divide(SE, Res, Sizes[i], &Q, &R);
7788 dbgs() << "Res: " << *Res << "\n";
7789 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
7790 dbgs() << "Res divided by Sizes[i]:\n";
7791 dbgs() << "Quotient: " << *Q << "\n";
7792 dbgs() << "Remainder: " << *R << "\n";
7797 // Do not record the last subscript corresponding to the size of elements in
7801 // Bail out if the remainder is too complex.
7802 if (isa<SCEVAddRecExpr>(R)) {
7811 // Record the access function for the current subscript.
7812 Subscripts.push_back(R);
7815 // Also push in last position the remainder of the last division: it will be
7816 // the access function of the innermost dimension.
7817 Subscripts.push_back(Res);
7819 std::reverse(Subscripts.begin(), Subscripts.end());
7822 dbgs() << "Subscripts:\n";
7823 for (const SCEV *S : Subscripts)
7824 dbgs() << *S << "\n";
7828 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
7829 /// sizes of an array access. Returns the remainder of the delinearization that
7830 /// is the offset start of the array. The SCEV->delinearize algorithm computes
7831 /// the multiples of SCEV coefficients: that is a pattern matching of sub
7832 /// expressions in the stride and base of a SCEV corresponding to the
7833 /// computation of a GCD (greatest common divisor) of base and stride. When
7834 /// SCEV->delinearize fails, it returns the SCEV unchanged.
7836 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
7838 /// void foo(long n, long m, long o, double A[n][m][o]) {
7840 /// for (long i = 0; i < n; i++)
7841 /// for (long j = 0; j < m; j++)
7842 /// for (long k = 0; k < o; k++)
7843 /// A[i][j][k] = 1.0;
7846 /// the delinearization input is the following AddRec SCEV:
7848 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
7850 /// From this SCEV, we are able to say that the base offset of the access is %A
7851 /// because it appears as an offset that does not divide any of the strides in
7854 /// CHECK: Base offset: %A
7856 /// and then SCEV->delinearize determines the size of some of the dimensions of
7857 /// the array as these are the multiples by which the strides are happening:
7859 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
7861 /// Note that the outermost dimension remains of UnknownSize because there are
7862 /// no strides that would help identifying the size of the last dimension: when
7863 /// the array has been statically allocated, one could compute the size of that
7864 /// dimension by dividing the overall size of the array by the size of the known
7865 /// dimensions: %m * %o * 8.
7867 /// Finally delinearize provides the access functions for the array reference
7868 /// that does correspond to A[i][j][k] of the above C testcase:
7870 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
7872 /// The testcases are checking the output of a function pass:
7873 /// DelinearizationPass that walks through all loads and stores of a function
7874 /// asking for the SCEV of the memory access with respect to all enclosing
7875 /// loops, calling SCEV->delinearize on that and printing the results.
7877 void SCEVAddRecExpr::delinearize(ScalarEvolution &SE,
7878 SmallVectorImpl<const SCEV *> &Subscripts,
7879 SmallVectorImpl<const SCEV *> &Sizes,
7880 const SCEV *ElementSize) const {
7881 // First step: collect parametric terms.
7882 SmallVector<const SCEV *, 4> Terms;
7883 collectParametricTerms(SE, Terms);
7888 // Second step: find subscript sizes.
7889 SE.findArrayDimensions(Terms, Sizes, ElementSize);
7894 // Third step: compute the access functions for each subscript.
7895 computeAccessFunctions(SE, Subscripts, Sizes);
7897 if (Subscripts.empty())
7901 dbgs() << "succeeded to delinearize " << *this << "\n";
7902 dbgs() << "ArrayDecl[UnknownSize]";
7903 for (const SCEV *S : Sizes)
7904 dbgs() << "[" << *S << "]";
7906 dbgs() << "\nArrayRef";
7907 for (const SCEV *S : Subscripts)
7908 dbgs() << "[" << *S << "]";
7913 //===----------------------------------------------------------------------===//
7914 // SCEVCallbackVH Class Implementation
7915 //===----------------------------------------------------------------------===//
7917 void ScalarEvolution::SCEVCallbackVH::deleted() {
7918 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
7919 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
7920 SE->ConstantEvolutionLoopExitValue.erase(PN);
7921 SE->ValueExprMap.erase(getValPtr());
7922 // this now dangles!
7925 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
7926 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
7928 // Forget all the expressions associated with users of the old value,
7929 // so that future queries will recompute the expressions using the new
7931 Value *Old = getValPtr();
7932 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
7933 SmallPtrSet<User *, 8> Visited;
7934 while (!Worklist.empty()) {
7935 User *U = Worklist.pop_back_val();
7936 // Deleting the Old value will cause this to dangle. Postpone
7937 // that until everything else is done.
7940 if (!Visited.insert(U).second)
7942 if (PHINode *PN = dyn_cast<PHINode>(U))
7943 SE->ConstantEvolutionLoopExitValue.erase(PN);
7944 SE->ValueExprMap.erase(U);
7945 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
7947 // Delete the Old value.
7948 if (PHINode *PN = dyn_cast<PHINode>(Old))
7949 SE->ConstantEvolutionLoopExitValue.erase(PN);
7950 SE->ValueExprMap.erase(Old);
7951 // this now dangles!
7954 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
7955 : CallbackVH(V), SE(se) {}
7957 //===----------------------------------------------------------------------===//
7958 // ScalarEvolution Class Implementation
7959 //===----------------------------------------------------------------------===//
7961 ScalarEvolution::ScalarEvolution()
7962 : FunctionPass(ID), ValuesAtScopes(64), LoopDispositions(64),
7963 BlockDispositions(64), FirstUnknown(nullptr) {
7964 initializeScalarEvolutionPass(*PassRegistry::getPassRegistry());
7967 bool ScalarEvolution::runOnFunction(Function &F) {
7969 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
7970 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
7971 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
7972 DL = DLP ? &DLP->getDataLayout() : nullptr;
7973 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
7974 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
7978 void ScalarEvolution::releaseMemory() {
7979 // Iterate through all the SCEVUnknown instances and call their
7980 // destructors, so that they release their references to their values.
7981 for (SCEVUnknown *U = FirstUnknown; U; U = U->Next)
7983 FirstUnknown = nullptr;
7985 ValueExprMap.clear();
7987 // Free any extra memory created for ExitNotTakenInfo in the unlikely event
7988 // that a loop had multiple computable exits.
7989 for (DenseMap<const Loop*, BackedgeTakenInfo>::iterator I =
7990 BackedgeTakenCounts.begin(), E = BackedgeTakenCounts.end();
7995 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
7997 BackedgeTakenCounts.clear();
7998 ConstantEvolutionLoopExitValue.clear();
7999 ValuesAtScopes.clear();
8000 LoopDispositions.clear();
8001 BlockDispositions.clear();
8002 UnsignedRanges.clear();
8003 SignedRanges.clear();
8004 UniqueSCEVs.clear();
8005 SCEVAllocator.Reset();
8008 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
8009 AU.setPreservesAll();
8010 AU.addRequired<AssumptionCacheTracker>();
8011 AU.addRequiredTransitive<LoopInfoWrapperPass>();
8012 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
8013 AU.addRequired<TargetLibraryInfoWrapperPass>();
8016 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
8017 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
8020 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
8022 // Print all inner loops first
8023 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
8024 PrintLoopInfo(OS, SE, *I);
8027 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
8030 SmallVector<BasicBlock *, 8> ExitBlocks;
8031 L->getExitBlocks(ExitBlocks);
8032 if (ExitBlocks.size() != 1)
8033 OS << "<multiple exits> ";
8035 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
8036 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
8038 OS << "Unpredictable backedge-taken count. ";
8043 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
8046 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
8047 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
8049 OS << "Unpredictable max backedge-taken count. ";
8055 void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
8056 // ScalarEvolution's implementation of the print method is to print
8057 // out SCEV values of all instructions that are interesting. Doing
8058 // this potentially causes it to create new SCEV objects though,
8059 // which technically conflicts with the const qualifier. This isn't
8060 // observable from outside the class though, so casting away the
8061 // const isn't dangerous.
8062 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
8064 OS << "Classifying expressions for: ";
8065 F->printAsOperand(OS, /*PrintType=*/false);
8067 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
8068 if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) {
8071 const SCEV *SV = SE.getSCEV(&*I);
8074 const Loop *L = LI->getLoopFor((*I).getParent());
8076 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
8083 OS << "\t\t" "Exits: ";
8084 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
8085 if (!SE.isLoopInvariant(ExitValue, L)) {
8086 OS << "<<Unknown>>";
8095 OS << "Determining loop execution counts for: ";
8096 F->printAsOperand(OS, /*PrintType=*/false);
8098 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
8099 PrintLoopInfo(OS, &SE, *I);
8102 ScalarEvolution::LoopDisposition
8103 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
8104 auto &Values = LoopDispositions[S];
8105 for (auto &V : Values) {
8106 if (V.getPointer() == L)
8109 Values.emplace_back(L, LoopVariant);
8110 LoopDisposition D = computeLoopDisposition(S, L);
8111 auto &Values2 = LoopDispositions[S];
8112 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
8113 if (V.getPointer() == L) {
8121 ScalarEvolution::LoopDisposition
8122 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
8123 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
8125 return LoopInvariant;
8129 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
8130 case scAddRecExpr: {
8131 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
8133 // If L is the addrec's loop, it's computable.
8134 if (AR->getLoop() == L)
8135 return LoopComputable;
8137 // Add recurrences are never invariant in the function-body (null loop).
8141 // This recurrence is variant w.r.t. L if L contains AR's loop.
8142 if (L->contains(AR->getLoop()))
8145 // This recurrence is invariant w.r.t. L if AR's loop contains L.
8146 if (AR->getLoop()->contains(L))
8147 return LoopInvariant;
8149 // This recurrence is variant w.r.t. L if any of its operands
8151 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
8153 if (!isLoopInvariant(*I, L))
8156 // Otherwise it's loop-invariant.
8157 return LoopInvariant;
8163 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
8164 bool HasVarying = false;
8165 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
8167 LoopDisposition D = getLoopDisposition(*I, L);
8168 if (D == LoopVariant)
8170 if (D == LoopComputable)
8173 return HasVarying ? LoopComputable : LoopInvariant;
8176 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
8177 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
8178 if (LD == LoopVariant)
8180 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
8181 if (RD == LoopVariant)
8183 return (LD == LoopInvariant && RD == LoopInvariant) ?
8184 LoopInvariant : LoopComputable;
8187 // All non-instruction values are loop invariant. All instructions are loop
8188 // invariant if they are not contained in the specified loop.
8189 // Instructions are never considered invariant in the function body
8190 // (null loop) because they are defined within the "loop".
8191 if (Instruction *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
8192 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
8193 return LoopInvariant;
8194 case scCouldNotCompute:
8195 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
8197 llvm_unreachable("Unknown SCEV kind!");
8200 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
8201 return getLoopDisposition(S, L) == LoopInvariant;
8204 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
8205 return getLoopDisposition(S, L) == LoopComputable;
8208 ScalarEvolution::BlockDisposition
8209 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
8210 auto &Values = BlockDispositions[S];
8211 for (auto &V : Values) {
8212 if (V.getPointer() == BB)
8215 Values.emplace_back(BB, DoesNotDominateBlock);
8216 BlockDisposition D = computeBlockDisposition(S, BB);
8217 auto &Values2 = BlockDispositions[S];
8218 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
8219 if (V.getPointer() == BB) {
8227 ScalarEvolution::BlockDisposition
8228 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
8229 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
8231 return ProperlyDominatesBlock;
8235 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
8236 case scAddRecExpr: {
8237 // This uses a "dominates" query instead of "properly dominates" query
8238 // to test for proper dominance too, because the instruction which
8239 // produces the addrec's value is a PHI, and a PHI effectively properly
8240 // dominates its entire containing block.
8241 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
8242 if (!DT->dominates(AR->getLoop()->getHeader(), BB))
8243 return DoesNotDominateBlock;
8245 // FALL THROUGH into SCEVNAryExpr handling.
8250 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
8252 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
8254 BlockDisposition D = getBlockDisposition(*I, BB);
8255 if (D == DoesNotDominateBlock)
8256 return DoesNotDominateBlock;
8257 if (D == DominatesBlock)
8260 return Proper ? ProperlyDominatesBlock : DominatesBlock;
8263 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
8264 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
8265 BlockDisposition LD = getBlockDisposition(LHS, BB);
8266 if (LD == DoesNotDominateBlock)
8267 return DoesNotDominateBlock;
8268 BlockDisposition RD = getBlockDisposition(RHS, BB);
8269 if (RD == DoesNotDominateBlock)
8270 return DoesNotDominateBlock;
8271 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
8272 ProperlyDominatesBlock : DominatesBlock;
8275 if (Instruction *I =
8276 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
8277 if (I->getParent() == BB)
8278 return DominatesBlock;
8279 if (DT->properlyDominates(I->getParent(), BB))
8280 return ProperlyDominatesBlock;
8281 return DoesNotDominateBlock;
8283 return ProperlyDominatesBlock;
8284 case scCouldNotCompute:
8285 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
8287 llvm_unreachable("Unknown SCEV kind!");
8290 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
8291 return getBlockDisposition(S, BB) >= DominatesBlock;
8294 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
8295 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
8299 // Search for a SCEV expression node within an expression tree.
8300 // Implements SCEVTraversal::Visitor.
8305 SCEVSearch(const SCEV *N): Node(N), IsFound(false) {}
8307 bool follow(const SCEV *S) {
8308 IsFound |= (S == Node);
8311 bool isDone() const { return IsFound; }
8315 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
8316 SCEVSearch Search(Op);
8317 visitAll(S, Search);
8318 return Search.IsFound;
8321 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
8322 ValuesAtScopes.erase(S);
8323 LoopDispositions.erase(S);
8324 BlockDispositions.erase(S);
8325 UnsignedRanges.erase(S);
8326 SignedRanges.erase(S);
8328 for (DenseMap<const Loop*, BackedgeTakenInfo>::iterator I =
8329 BackedgeTakenCounts.begin(), E = BackedgeTakenCounts.end(); I != E; ) {
8330 BackedgeTakenInfo &BEInfo = I->second;
8331 if (BEInfo.hasOperand(S, this)) {
8333 BackedgeTakenCounts.erase(I++);
8340 typedef DenseMap<const Loop *, std::string> VerifyMap;
8342 /// replaceSubString - Replaces all occurrences of From in Str with To.
8343 static void replaceSubString(std::string &Str, StringRef From, StringRef To) {
8345 while ((Pos = Str.find(From, Pos)) != std::string::npos) {
8346 Str.replace(Pos, From.size(), To.data(), To.size());
8351 /// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis.
8353 getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) {
8354 for (Loop::reverse_iterator I = L->rbegin(), E = L->rend(); I != E; ++I) {
8355 getLoopBackedgeTakenCounts(*I, Map, SE); // recurse.
8357 std::string &S = Map[L];
8359 raw_string_ostream OS(S);
8360 SE.getBackedgeTakenCount(L)->print(OS);
8362 // false and 0 are semantically equivalent. This can happen in dead loops.
8363 replaceSubString(OS.str(), "false", "0");
8364 // Remove wrap flags, their use in SCEV is highly fragile.
8365 // FIXME: Remove this when SCEV gets smarter about them.
8366 replaceSubString(OS.str(), "<nw>", "");
8367 replaceSubString(OS.str(), "<nsw>", "");
8368 replaceSubString(OS.str(), "<nuw>", "");
8373 void ScalarEvolution::verifyAnalysis() const {
8377 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
8379 // Gather stringified backedge taken counts for all loops using SCEV's caches.
8380 // FIXME: It would be much better to store actual values instead of strings,
8381 // but SCEV pointers will change if we drop the caches.
8382 VerifyMap BackedgeDumpsOld, BackedgeDumpsNew;
8383 for (LoopInfo::reverse_iterator I = LI->rbegin(), E = LI->rend(); I != E; ++I)
8384 getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE);
8386 // Gather stringified backedge taken counts for all loops without using
8389 for (LoopInfo::reverse_iterator I = LI->rbegin(), E = LI->rend(); I != E; ++I)
8390 getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE);
8392 // Now compare whether they're the same with and without caches. This allows
8393 // verifying that no pass changed the cache.
8394 assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() &&
8395 "New loops suddenly appeared!");
8397 for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(),
8398 OldE = BackedgeDumpsOld.end(),
8399 NewI = BackedgeDumpsNew.begin();
8400 OldI != OldE; ++OldI, ++NewI) {
8401 assert(OldI->first == NewI->first && "Loop order changed!");
8403 // Compare the stringified SCEVs. We don't care if undef backedgetaken count
8405 // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This
8406 // means that a pass is buggy or SCEV has to learn a new pattern but is
8407 // usually not harmful.
8408 if (OldI->second != NewI->second &&
8409 OldI->second.find("undef") == std::string::npos &&
8410 NewI->second.find("undef") == std::string::npos &&
8411 OldI->second != "***COULDNOTCOMPUTE***" &&
8412 NewI->second != "***COULDNOTCOMPUTE***") {
8413 dbgs() << "SCEVValidator: SCEV for loop '"
8414 << OldI->first->getHeader()->getName()
8415 << "' changed from '" << OldI->second
8416 << "' to '" << NewI->second << "'!\n";
8421 // TODO: Verify more things.