1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
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 #define DEBUG_TYPE "scalar-evolution"
62 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
63 #include "llvm/Constants.h"
64 #include "llvm/DerivedTypes.h"
65 #include "llvm/GlobalVariable.h"
66 #include "llvm/GlobalAlias.h"
67 #include "llvm/Instructions.h"
68 #include "llvm/LLVMContext.h"
69 #include "llvm/Operator.h"
70 #include "llvm/Analysis/ConstantFolding.h"
71 #include "llvm/Analysis/Dominators.h"
72 #include "llvm/Analysis/LoopInfo.h"
73 #include "llvm/Analysis/ValueTracking.h"
74 #include "llvm/Assembly/Writer.h"
75 #include "llvm/Target/TargetData.h"
76 #include "llvm/Support/CommandLine.h"
77 #include "llvm/Support/Compiler.h"
78 #include "llvm/Support/ConstantRange.h"
79 #include "llvm/Support/ErrorHandling.h"
80 #include "llvm/Support/GetElementPtrTypeIterator.h"
81 #include "llvm/Support/InstIterator.h"
82 #include "llvm/Support/MathExtras.h"
83 #include "llvm/Support/raw_ostream.h"
84 #include "llvm/ADT/Statistic.h"
85 #include "llvm/ADT/STLExtras.h"
86 #include "llvm/ADT/SmallPtrSet.h"
90 STATISTIC(NumArrayLenItCounts,
91 "Number of trip counts computed with array length");
92 STATISTIC(NumTripCountsComputed,
93 "Number of loops with predictable loop counts");
94 STATISTIC(NumTripCountsNotComputed,
95 "Number of loops without predictable loop counts");
96 STATISTIC(NumBruteForceTripCountsComputed,
97 "Number of loops with trip counts computed by force");
99 static cl::opt<unsigned>
100 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
101 cl::desc("Maximum number of iterations SCEV will "
102 "symbolically execute a constant "
106 static RegisterPass<ScalarEvolution>
107 R("scalar-evolution", "Scalar Evolution Analysis", false, true);
108 char ScalarEvolution::ID = 0;
110 //===----------------------------------------------------------------------===//
111 // SCEV class definitions
112 //===----------------------------------------------------------------------===//
114 //===----------------------------------------------------------------------===//
115 // Implementation of the SCEV class.
120 void SCEV::dump() const {
125 bool SCEV::isZero() const {
126 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
127 return SC->getValue()->isZero();
131 bool SCEV::isOne() const {
132 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
133 return SC->getValue()->isOne();
137 bool SCEV::isAllOnesValue() const {
138 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
139 return SC->getValue()->isAllOnesValue();
143 SCEVCouldNotCompute::SCEVCouldNotCompute() :
144 SCEV(FoldingSetNodeID(), scCouldNotCompute) {}
146 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
147 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
151 const Type *SCEVCouldNotCompute::getType() const {
152 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
156 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
157 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
161 bool SCEVCouldNotCompute::hasOperand(const SCEV *) const {
162 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
166 void SCEVCouldNotCompute::print(raw_ostream &OS) const {
167 OS << "***COULDNOTCOMPUTE***";
170 bool SCEVCouldNotCompute::classof(const SCEV *S) {
171 return S->getSCEVType() == scCouldNotCompute;
174 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
176 ID.AddInteger(scConstant);
179 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
180 SCEV *S = SCEVAllocator.Allocate<SCEVConstant>();
181 new (S) SCEVConstant(ID, V);
182 UniqueSCEVs.InsertNode(S, IP);
186 const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
187 return getConstant(ConstantInt::get(getContext(), Val));
191 ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
193 ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
196 const Type *SCEVConstant::getType() const { return V->getType(); }
198 void SCEVConstant::print(raw_ostream &OS) const {
199 WriteAsOperand(OS, V, false);
202 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeID &ID,
203 unsigned SCEVTy, const SCEV *op, const Type *ty)
204 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
206 bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
207 return Op->dominates(BB, DT);
210 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeID &ID,
211 const SCEV *op, const Type *ty)
212 : SCEVCastExpr(ID, scTruncate, op, ty) {
213 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
214 (Ty->isInteger() || isa<PointerType>(Ty)) &&
215 "Cannot truncate non-integer value!");
218 void SCEVTruncateExpr::print(raw_ostream &OS) const {
219 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
222 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeID &ID,
223 const SCEV *op, const Type *ty)
224 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
225 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
226 (Ty->isInteger() || isa<PointerType>(Ty)) &&
227 "Cannot zero extend non-integer value!");
230 void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
231 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
234 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeID &ID,
235 const SCEV *op, const Type *ty)
236 : SCEVCastExpr(ID, scSignExtend, op, ty) {
237 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
238 (Ty->isInteger() || isa<PointerType>(Ty)) &&
239 "Cannot sign extend non-integer value!");
242 void SCEVSignExtendExpr::print(raw_ostream &OS) const {
243 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
246 void SCEVCommutativeExpr::print(raw_ostream &OS) const {
247 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
248 const char *OpStr = getOperationStr();
249 OS << "(" << *Operands[0];
250 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
251 OS << OpStr << *Operands[i];
255 bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
256 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
257 if (!getOperand(i)->dominates(BB, DT))
263 bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
264 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
267 void SCEVUDivExpr::print(raw_ostream &OS) const {
268 OS << "(" << *LHS << " /u " << *RHS << ")";
271 const Type *SCEVUDivExpr::getType() const {
272 // In most cases the types of LHS and RHS will be the same, but in some
273 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
274 // depend on the type for correctness, but handling types carefully can
275 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
276 // a pointer type than the RHS, so use the RHS' type here.
277 return RHS->getType();
280 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
281 // Add recurrences are never invariant in the function-body (null loop).
285 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
286 if (QueryLoop->contains(L->getHeader()))
289 // This recurrence is variant w.r.t. QueryLoop if any of its operands
291 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
292 if (!getOperand(i)->isLoopInvariant(QueryLoop))
295 // Otherwise it's loop-invariant.
299 void SCEVAddRecExpr::print(raw_ostream &OS) const {
300 OS << "{" << *Operands[0];
301 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
302 OS << ",+," << *Operands[i];
303 OS << "}<" << L->getHeader()->getName() + ">";
306 void SCEVFieldOffsetExpr::print(raw_ostream &OS) const {
307 // LLVM struct fields don't have names, so just print the field number.
308 OS << "offsetof(" << *STy << ", " << FieldNo << ")";
311 void SCEVAllocSizeExpr::print(raw_ostream &OS) const {
312 OS << "sizeof(" << *AllocTy << ")";
315 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
316 // All non-instruction values are loop invariant. All instructions are loop
317 // invariant if they are not contained in the specified loop.
318 // Instructions are never considered invariant in the function body
319 // (null loop) because they are defined within the "loop".
320 if (Instruction *I = dyn_cast<Instruction>(V))
321 return L && !L->contains(I->getParent());
325 bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
326 if (Instruction *I = dyn_cast<Instruction>(getValue()))
327 return DT->dominates(I->getParent(), BB);
331 const Type *SCEVUnknown::getType() const {
335 void SCEVUnknown::print(raw_ostream &OS) const {
336 WriteAsOperand(OS, V, false);
339 //===----------------------------------------------------------------------===//
341 //===----------------------------------------------------------------------===//
343 static bool CompareTypes(const Type *A, const Type *B) {
344 if (A->getTypeID() != B->getTypeID())
345 return A->getTypeID() < B->getTypeID();
346 if (const IntegerType *AI = dyn_cast<IntegerType>(A)) {
347 const IntegerType *BI = cast<IntegerType>(B);
348 return AI->getBitWidth() < BI->getBitWidth();
350 if (const PointerType *AI = dyn_cast<PointerType>(A)) {
351 const PointerType *BI = cast<PointerType>(B);
352 return CompareTypes(AI->getElementType(), BI->getElementType());
354 if (const ArrayType *AI = dyn_cast<ArrayType>(A)) {
355 const ArrayType *BI = cast<ArrayType>(B);
356 if (AI->getNumElements() != BI->getNumElements())
357 return AI->getNumElements() < BI->getNumElements();
358 return CompareTypes(AI->getElementType(), BI->getElementType());
360 if (const VectorType *AI = dyn_cast<VectorType>(A)) {
361 const VectorType *BI = cast<VectorType>(B);
362 if (AI->getNumElements() != BI->getNumElements())
363 return AI->getNumElements() < BI->getNumElements();
364 return CompareTypes(AI->getElementType(), BI->getElementType());
366 if (const StructType *AI = dyn_cast<StructType>(A)) {
367 const StructType *BI = cast<StructType>(B);
368 if (AI->getNumElements() != BI->getNumElements())
369 return AI->getNumElements() < BI->getNumElements();
370 for (unsigned i = 0, e = AI->getNumElements(); i != e; ++i)
371 if (CompareTypes(AI->getElementType(i), BI->getElementType(i)) ||
372 CompareTypes(BI->getElementType(i), AI->getElementType(i)))
373 return CompareTypes(AI->getElementType(i), BI->getElementType(i));
379 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
380 /// than the complexity of the RHS. This comparator is used to canonicalize
382 class VISIBILITY_HIDDEN SCEVComplexityCompare {
385 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
387 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
388 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
392 // Primarily, sort the SCEVs by their getSCEVType().
393 if (LHS->getSCEVType() != RHS->getSCEVType())
394 return LHS->getSCEVType() < RHS->getSCEVType();
396 // Aside from the getSCEVType() ordering, the particular ordering
397 // isn't very important except that it's beneficial to be consistent,
398 // so that (a + b) and (b + a) don't end up as different expressions.
400 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
401 // not as complete as it could be.
402 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
403 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
405 // Order pointer values after integer values. This helps SCEVExpander
407 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
409 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
412 // Compare getValueID values.
413 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
414 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
416 // Sort arguments by their position.
417 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
418 const Argument *RA = cast<Argument>(RU->getValue());
419 return LA->getArgNo() < RA->getArgNo();
422 // For instructions, compare their loop depth, and their opcode.
423 // This is pretty loose.
424 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
425 Instruction *RV = cast<Instruction>(RU->getValue());
427 // Compare loop depths.
428 if (LI->getLoopDepth(LV->getParent()) !=
429 LI->getLoopDepth(RV->getParent()))
430 return LI->getLoopDepth(LV->getParent()) <
431 LI->getLoopDepth(RV->getParent());
434 if (LV->getOpcode() != RV->getOpcode())
435 return LV->getOpcode() < RV->getOpcode();
437 // Compare the number of operands.
438 if (LV->getNumOperands() != RV->getNumOperands())
439 return LV->getNumOperands() < RV->getNumOperands();
445 // Compare constant values.
446 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
447 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
448 if (LC->getValue()->getBitWidth() != RC->getValue()->getBitWidth())
449 return LC->getValue()->getBitWidth() < RC->getValue()->getBitWidth();
450 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
453 // Compare addrec loop depths.
454 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
455 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
456 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
457 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
460 // Lexicographically compare n-ary expressions.
461 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
462 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
463 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
464 if (i >= RC->getNumOperands())
466 if (operator()(LC->getOperand(i), RC->getOperand(i)))
468 if (operator()(RC->getOperand(i), LC->getOperand(i)))
471 return LC->getNumOperands() < RC->getNumOperands();
474 // Lexicographically compare udiv expressions.
475 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
476 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
477 if (operator()(LC->getLHS(), RC->getLHS()))
479 if (operator()(RC->getLHS(), LC->getLHS()))
481 if (operator()(LC->getRHS(), RC->getRHS()))
483 if (operator()(RC->getRHS(), LC->getRHS()))
488 // Compare cast expressions by operand.
489 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
490 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
491 return operator()(LC->getOperand(), RC->getOperand());
494 // Compare offsetof expressions.
495 if (const SCEVFieldOffsetExpr *LA = dyn_cast<SCEVFieldOffsetExpr>(LHS)) {
496 const SCEVFieldOffsetExpr *RA = cast<SCEVFieldOffsetExpr>(RHS);
497 if (CompareTypes(LA->getStructType(), RA->getStructType()) ||
498 CompareTypes(RA->getStructType(), LA->getStructType()))
499 return CompareTypes(LA->getStructType(), RA->getStructType());
500 return LA->getFieldNo() < RA->getFieldNo();
503 // Compare sizeof expressions by the allocation type.
504 if (const SCEVAllocSizeExpr *LA = dyn_cast<SCEVAllocSizeExpr>(LHS)) {
505 const SCEVAllocSizeExpr *RA = cast<SCEVAllocSizeExpr>(RHS);
506 return CompareTypes(LA->getAllocType(), RA->getAllocType());
509 llvm_unreachable("Unknown SCEV kind!");
515 /// GroupByComplexity - Given a list of SCEV objects, order them by their
516 /// complexity, and group objects of the same complexity together by value.
517 /// When this routine is finished, we know that any duplicates in the vector are
518 /// consecutive and that complexity is monotonically increasing.
520 /// Note that we go take special precautions to ensure that we get determinstic
521 /// results from this routine. In other words, we don't want the results of
522 /// this to depend on where the addresses of various SCEV objects happened to
525 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
527 if (Ops.size() < 2) return; // Noop
528 if (Ops.size() == 2) {
529 // This is the common case, which also happens to be trivially simple.
531 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
532 std::swap(Ops[0], Ops[1]);
536 // Do the rough sort by complexity.
537 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
539 // Now that we are sorted by complexity, group elements of the same
540 // complexity. Note that this is, at worst, N^2, but the vector is likely to
541 // be extremely short in practice. Note that we take this approach because we
542 // do not want to depend on the addresses of the objects we are grouping.
543 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
544 const SCEV *S = Ops[i];
545 unsigned Complexity = S->getSCEVType();
547 // If there are any objects of the same complexity and same value as this
549 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
550 if (Ops[j] == S) { // Found a duplicate.
551 // Move it to immediately after i'th element.
552 std::swap(Ops[i+1], Ops[j]);
553 ++i; // no need to rescan it.
554 if (i == e-2) return; // Done!
562 //===----------------------------------------------------------------------===//
563 // Simple SCEV method implementations
564 //===----------------------------------------------------------------------===//
566 /// BinomialCoefficient - Compute BC(It, K). The result has width W.
568 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
570 const Type* ResultTy) {
571 // Handle the simplest case efficiently.
573 return SE.getTruncateOrZeroExtend(It, ResultTy);
575 // We are using the following formula for BC(It, K):
577 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
579 // Suppose, W is the bitwidth of the return value. We must be prepared for
580 // overflow. Hence, we must assure that the result of our computation is
581 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
582 // safe in modular arithmetic.
584 // However, this code doesn't use exactly that formula; the formula it uses
585 // is something like the following, where T is the number of factors of 2 in
586 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
589 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
591 // This formula is trivially equivalent to the previous formula. However,
592 // this formula can be implemented much more efficiently. The trick is that
593 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
594 // arithmetic. To do exact division in modular arithmetic, all we have
595 // to do is multiply by the inverse. Therefore, this step can be done at
598 // The next issue is how to safely do the division by 2^T. The way this
599 // is done is by doing the multiplication step at a width of at least W + T
600 // bits. This way, the bottom W+T bits of the product are accurate. Then,
601 // when we perform the division by 2^T (which is equivalent to a right shift
602 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
603 // truncated out after the division by 2^T.
605 // In comparison to just directly using the first formula, this technique
606 // is much more efficient; using the first formula requires W * K bits,
607 // but this formula less than W + K bits. Also, the first formula requires
608 // a division step, whereas this formula only requires multiplies and shifts.
610 // It doesn't matter whether the subtraction step is done in the calculation
611 // width or the input iteration count's width; if the subtraction overflows,
612 // the result must be zero anyway. We prefer here to do it in the width of
613 // the induction variable because it helps a lot for certain cases; CodeGen
614 // isn't smart enough to ignore the overflow, which leads to much less
615 // efficient code if the width of the subtraction is wider than the native
618 // (It's possible to not widen at all by pulling out factors of 2 before
619 // the multiplication; for example, K=2 can be calculated as
620 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
621 // extra arithmetic, so it's not an obvious win, and it gets
622 // much more complicated for K > 3.)
624 // Protection from insane SCEVs; this bound is conservative,
625 // but it probably doesn't matter.
627 return SE.getCouldNotCompute();
629 unsigned W = SE.getTypeSizeInBits(ResultTy);
631 // Calculate K! / 2^T and T; we divide out the factors of two before
632 // multiplying for calculating K! / 2^T to avoid overflow.
633 // Other overflow doesn't matter because we only care about the bottom
634 // W bits of the result.
635 APInt OddFactorial(W, 1);
637 for (unsigned i = 3; i <= K; ++i) {
639 unsigned TwoFactors = Mult.countTrailingZeros();
641 Mult = Mult.lshr(TwoFactors);
642 OddFactorial *= Mult;
645 // We need at least W + T bits for the multiplication step
646 unsigned CalculationBits = W + T;
648 // Calcuate 2^T, at width T+W.
649 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
651 // Calculate the multiplicative inverse of K! / 2^T;
652 // this multiplication factor will perform the exact division by
654 APInt Mod = APInt::getSignedMinValue(W+1);
655 APInt MultiplyFactor = OddFactorial.zext(W+1);
656 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
657 MultiplyFactor = MultiplyFactor.trunc(W);
659 // Calculate the product, at width T+W
660 const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
662 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
663 for (unsigned i = 1; i != K; ++i) {
664 const SCEV *S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
665 Dividend = SE.getMulExpr(Dividend,
666 SE.getTruncateOrZeroExtend(S, CalculationTy));
670 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
672 // Truncate the result, and divide by K! / 2^T.
674 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
675 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
678 /// evaluateAtIteration - Return the value of this chain of recurrences at
679 /// the specified iteration number. We can evaluate this recurrence by
680 /// multiplying each element in the chain by the binomial coefficient
681 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
683 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
685 /// where BC(It, k) stands for binomial coefficient.
687 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
688 ScalarEvolution &SE) const {
689 const SCEV *Result = getStart();
690 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
691 // The computation is correct in the face of overflow provided that the
692 // multiplication is performed _after_ the evaluation of the binomial
694 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
695 if (isa<SCEVCouldNotCompute>(Coeff))
698 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
703 //===----------------------------------------------------------------------===//
704 // SCEV Expression folder implementations
705 //===----------------------------------------------------------------------===//
707 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
709 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
710 "This is not a truncating conversion!");
711 assert(isSCEVable(Ty) &&
712 "This is not a conversion to a SCEVable type!");
713 Ty = getEffectiveSCEVType(Ty);
716 ID.AddInteger(scTruncate);
720 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
722 // Fold if the operand is constant.
723 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
725 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
727 // trunc(trunc(x)) --> trunc(x)
728 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
729 return getTruncateExpr(ST->getOperand(), Ty);
731 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
732 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
733 return getTruncateOrSignExtend(SS->getOperand(), Ty);
735 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
736 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
737 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
739 // If the input value is a chrec scev, truncate the chrec's operands.
740 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
741 SmallVector<const SCEV *, 4> Operands;
742 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
743 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
744 return getAddRecExpr(Operands, AddRec->getLoop());
747 // The cast wasn't folded; create an explicit cast node.
748 // Recompute the insert position, as it may have been invalidated.
749 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
750 SCEV *S = SCEVAllocator.Allocate<SCEVTruncateExpr>();
751 new (S) SCEVTruncateExpr(ID, Op, Ty);
752 UniqueSCEVs.InsertNode(S, IP);
756 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
758 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
759 "This is not an extending conversion!");
760 assert(isSCEVable(Ty) &&
761 "This is not a conversion to a SCEVable type!");
762 Ty = getEffectiveSCEVType(Ty);
764 // Fold if the operand is constant.
765 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
766 const Type *IntTy = getEffectiveSCEVType(Ty);
767 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
768 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
769 return getConstant(cast<ConstantInt>(C));
772 // zext(zext(x)) --> zext(x)
773 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
774 return getZeroExtendExpr(SZ->getOperand(), Ty);
776 // Before doing any expensive analysis, check to see if we've already
777 // computed a SCEV for this Op and Ty.
779 ID.AddInteger(scZeroExtend);
783 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
785 // If the input value is a chrec scev, and we can prove that the value
786 // did not overflow the old, smaller, value, we can zero extend all of the
787 // operands (often constants). This allows analysis of something like
788 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
789 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
790 if (AR->isAffine()) {
791 const SCEV *Start = AR->getStart();
792 const SCEV *Step = AR->getStepRecurrence(*this);
793 unsigned BitWidth = getTypeSizeInBits(AR->getType());
794 const Loop *L = AR->getLoop();
796 // If we have special knowledge that this addrec won't overflow,
797 // we don't need to do any further analysis.
798 if (AR->hasNoUnsignedWrap())
799 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
800 getZeroExtendExpr(Step, Ty),
803 // Check whether the backedge-taken count is SCEVCouldNotCompute.
804 // Note that this serves two purposes: It filters out loops that are
805 // simply not analyzable, and it covers the case where this code is
806 // being called from within backedge-taken count analysis, such that
807 // attempting to ask for the backedge-taken count would likely result
808 // in infinite recursion. In the later case, the analysis code will
809 // cope with a conservative value, and it will take care to purge
810 // that value once it has finished.
811 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
812 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
813 // Manually compute the final value for AR, checking for
816 // Check whether the backedge-taken count can be losslessly casted to
817 // the addrec's type. The count is always unsigned.
818 const SCEV *CastedMaxBECount =
819 getTruncateOrZeroExtend(MaxBECount, Start->getType());
820 const SCEV *RecastedMaxBECount =
821 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
822 if (MaxBECount == RecastedMaxBECount) {
823 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
824 // Check whether Start+Step*MaxBECount has no unsigned overflow.
826 getMulExpr(CastedMaxBECount,
827 getTruncateOrZeroExtend(Step, Start->getType()));
828 const SCEV *Add = getAddExpr(Start, ZMul);
829 const SCEV *OperandExtendedAdd =
830 getAddExpr(getZeroExtendExpr(Start, WideTy),
831 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
832 getZeroExtendExpr(Step, WideTy)));
833 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
834 // Return the expression with the addrec on the outside.
835 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
836 getZeroExtendExpr(Step, Ty),
839 // Similar to above, only this time treat the step value as signed.
840 // This covers loops that count down.
842 getMulExpr(CastedMaxBECount,
843 getTruncateOrSignExtend(Step, Start->getType()));
844 Add = getAddExpr(Start, SMul);
846 getAddExpr(getZeroExtendExpr(Start, WideTy),
847 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
848 getSignExtendExpr(Step, WideTy)));
849 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
850 // Return the expression with the addrec on the outside.
851 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
852 getSignExtendExpr(Step, Ty),
856 // If the backedge is guarded by a comparison with the pre-inc value
857 // the addrec is safe. Also, if the entry is guarded by a comparison
858 // with the start value and the backedge is guarded by a comparison
859 // with the post-inc value, the addrec is safe.
860 if (isKnownPositive(Step)) {
861 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
862 getUnsignedRange(Step).getUnsignedMax());
863 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
864 (isLoopGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
865 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
866 AR->getPostIncExpr(*this), N)))
867 // Return the expression with the addrec on the outside.
868 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
869 getZeroExtendExpr(Step, Ty),
871 } else if (isKnownNegative(Step)) {
872 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
873 getSignedRange(Step).getSignedMin());
874 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) &&
875 (isLoopGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) ||
876 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
877 AR->getPostIncExpr(*this), N)))
878 // Return the expression with the addrec on the outside.
879 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
880 getSignExtendExpr(Step, Ty),
886 // The cast wasn't folded; create an explicit cast node.
887 // Recompute the insert position, as it may have been invalidated.
888 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
889 SCEV *S = SCEVAllocator.Allocate<SCEVZeroExtendExpr>();
890 new (S) SCEVZeroExtendExpr(ID, Op, Ty);
891 UniqueSCEVs.InsertNode(S, IP);
895 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
897 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
898 "This is not an extending conversion!");
899 assert(isSCEVable(Ty) &&
900 "This is not a conversion to a SCEVable type!");
901 Ty = getEffectiveSCEVType(Ty);
903 // Fold if the operand is constant.
904 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
905 const Type *IntTy = getEffectiveSCEVType(Ty);
906 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
907 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
908 return getConstant(cast<ConstantInt>(C));
911 // sext(sext(x)) --> sext(x)
912 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
913 return getSignExtendExpr(SS->getOperand(), Ty);
915 // Before doing any expensive analysis, check to see if we've already
916 // computed a SCEV for this Op and Ty.
918 ID.AddInteger(scSignExtend);
922 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
924 // If the input value is a chrec scev, and we can prove that the value
925 // did not overflow the old, smaller, value, we can sign extend all of the
926 // operands (often constants). This allows analysis of something like
927 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
928 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
929 if (AR->isAffine()) {
930 const SCEV *Start = AR->getStart();
931 const SCEV *Step = AR->getStepRecurrence(*this);
932 unsigned BitWidth = getTypeSizeInBits(AR->getType());
933 const Loop *L = AR->getLoop();
935 // If we have special knowledge that this addrec won't overflow,
936 // we don't need to do any further analysis.
937 if (AR->hasNoSignedWrap())
938 return getAddRecExpr(getSignExtendExpr(Start, Ty),
939 getSignExtendExpr(Step, Ty),
942 // Check whether the backedge-taken count is SCEVCouldNotCompute.
943 // Note that this serves two purposes: It filters out loops that are
944 // simply not analyzable, and it covers the case where this code is
945 // being called from within backedge-taken count analysis, such that
946 // attempting to ask for the backedge-taken count would likely result
947 // in infinite recursion. In the later case, the analysis code will
948 // cope with a conservative value, and it will take care to purge
949 // that value once it has finished.
950 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
951 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
952 // Manually compute the final value for AR, checking for
955 // Check whether the backedge-taken count can be losslessly casted to
956 // the addrec's type. The count is always unsigned.
957 const SCEV *CastedMaxBECount =
958 getTruncateOrZeroExtend(MaxBECount, Start->getType());
959 const SCEV *RecastedMaxBECount =
960 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
961 if (MaxBECount == RecastedMaxBECount) {
962 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
963 // Check whether Start+Step*MaxBECount has no signed overflow.
965 getMulExpr(CastedMaxBECount,
966 getTruncateOrSignExtend(Step, Start->getType()));
967 const SCEV *Add = getAddExpr(Start, SMul);
968 const SCEV *OperandExtendedAdd =
969 getAddExpr(getSignExtendExpr(Start, WideTy),
970 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
971 getSignExtendExpr(Step, WideTy)));
972 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
973 // Return the expression with the addrec on the outside.
974 return getAddRecExpr(getSignExtendExpr(Start, Ty),
975 getSignExtendExpr(Step, Ty),
978 // Similar to above, only this time treat the step value as unsigned.
979 // This covers loops that count up with an unsigned step.
981 getMulExpr(CastedMaxBECount,
982 getTruncateOrZeroExtend(Step, Start->getType()));
983 Add = getAddExpr(Start, UMul);
985 getAddExpr(getSignExtendExpr(Start, WideTy),
986 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
987 getZeroExtendExpr(Step, WideTy)));
988 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
989 // Return the expression with the addrec on the outside.
990 return getAddRecExpr(getSignExtendExpr(Start, Ty),
991 getZeroExtendExpr(Step, Ty),
995 // If the backedge is guarded by a comparison with the pre-inc value
996 // the addrec is safe. Also, if the entry is guarded by a comparison
997 // with the start value and the backedge is guarded by a comparison
998 // with the post-inc value, the addrec is safe.
999 if (isKnownPositive(Step)) {
1000 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
1001 getSignedRange(Step).getSignedMax());
1002 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
1003 (isLoopGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
1004 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
1005 AR->getPostIncExpr(*this), N)))
1006 // Return the expression with the addrec on the outside.
1007 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1008 getSignExtendExpr(Step, Ty),
1010 } else if (isKnownNegative(Step)) {
1011 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1012 getSignedRange(Step).getSignedMin());
1013 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
1014 (isLoopGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
1015 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1016 AR->getPostIncExpr(*this), N)))
1017 // Return the expression with the addrec on the outside.
1018 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1019 getSignExtendExpr(Step, Ty),
1025 // The cast wasn't folded; create an explicit cast node.
1026 // Recompute the insert position, as it may have been invalidated.
1027 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1028 SCEV *S = SCEVAllocator.Allocate<SCEVSignExtendExpr>();
1029 new (S) SCEVSignExtendExpr(ID, Op, Ty);
1030 UniqueSCEVs.InsertNode(S, IP);
1034 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1035 /// unspecified bits out to the given type.
1037 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1039 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1040 "This is not an extending conversion!");
1041 assert(isSCEVable(Ty) &&
1042 "This is not a conversion to a SCEVable type!");
1043 Ty = getEffectiveSCEVType(Ty);
1045 // Sign-extend negative constants.
1046 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1047 if (SC->getValue()->getValue().isNegative())
1048 return getSignExtendExpr(Op, Ty);
1050 // Peel off a truncate cast.
1051 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
1052 const SCEV *NewOp = T->getOperand();
1053 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1054 return getAnyExtendExpr(NewOp, Ty);
1055 return getTruncateOrNoop(NewOp, Ty);
1058 // Next try a zext cast. If the cast is folded, use it.
1059 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
1060 if (!isa<SCEVZeroExtendExpr>(ZExt))
1063 // Next try a sext cast. If the cast is folded, use it.
1064 const SCEV *SExt = getSignExtendExpr(Op, Ty);
1065 if (!isa<SCEVSignExtendExpr>(SExt))
1068 // If the expression is obviously signed, use the sext cast value.
1069 if (isa<SCEVSMaxExpr>(Op))
1072 // Absent any other information, use the zext cast value.
1076 /// CollectAddOperandsWithScales - Process the given Ops list, which is
1077 /// a list of operands to be added under the given scale, update the given
1078 /// map. This is a helper function for getAddRecExpr. As an example of
1079 /// what it does, given a sequence of operands that would form an add
1080 /// expression like this:
1082 /// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1084 /// where A and B are constants, update the map with these values:
1086 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1088 /// and add 13 + A*B*29 to AccumulatedConstant.
1089 /// This will allow getAddRecExpr to produce this:
1091 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1093 /// This form often exposes folding opportunities that are hidden in
1094 /// the original operand list.
1096 /// Return true iff it appears that any interesting folding opportunities
1097 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
1098 /// the common case where no interesting opportunities are present, and
1099 /// is also used as a check to avoid infinite recursion.
1102 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1103 SmallVector<const SCEV *, 8> &NewOps,
1104 APInt &AccumulatedConstant,
1105 const SmallVectorImpl<const SCEV *> &Ops,
1107 ScalarEvolution &SE) {
1108 bool Interesting = false;
1110 // Iterate over the add operands.
1111 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1112 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1113 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1115 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1116 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1117 // A multiplication of a constant with another add; recurse.
1119 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1120 cast<SCEVAddExpr>(Mul->getOperand(1))
1124 // A multiplication of a constant with some other value. Update
1126 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1127 const SCEV *Key = SE.getMulExpr(MulOps);
1128 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1129 M.insert(std::make_pair(Key, NewScale));
1131 NewOps.push_back(Pair.first->first);
1133 Pair.first->second += NewScale;
1134 // The map already had an entry for this value, which may indicate
1135 // a folding opportunity.
1139 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1140 // Pull a buried constant out to the outside.
1141 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1143 AccumulatedConstant += Scale * C->getValue()->getValue();
1145 // An ordinary operand. Update the map.
1146 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1147 M.insert(std::make_pair(Ops[i], Scale));
1149 NewOps.push_back(Pair.first->first);
1151 Pair.first->second += Scale;
1152 // The map already had an entry for this value, which may indicate
1153 // a folding opportunity.
1163 struct APIntCompare {
1164 bool operator()(const APInt &LHS, const APInt &RHS) const {
1165 return LHS.ult(RHS);
1170 /// getAddExpr - Get a canonical add expression, or something simpler if
1172 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops) {
1173 assert(!Ops.empty() && "Cannot get empty add!");
1174 if (Ops.size() == 1) return Ops[0];
1176 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1177 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1178 getEffectiveSCEVType(Ops[0]->getType()) &&
1179 "SCEVAddExpr operand types don't match!");
1182 // Sort by complexity, this groups all similar expression types together.
1183 GroupByComplexity(Ops, LI);
1185 // If there are any constants, fold them together.
1187 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1189 assert(Idx < Ops.size());
1190 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1191 // We found two constants, fold them together!
1192 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1193 RHSC->getValue()->getValue());
1194 if (Ops.size() == 2) return Ops[0];
1195 Ops.erase(Ops.begin()+1); // Erase the folded element
1196 LHSC = cast<SCEVConstant>(Ops[0]);
1199 // If we are left with a constant zero being added, strip it off.
1200 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1201 Ops.erase(Ops.begin());
1206 if (Ops.size() == 1) return Ops[0];
1208 // Okay, check to see if the same value occurs in the operand list twice. If
1209 // so, merge them together into an multiply expression. Since we sorted the
1210 // list, these values are required to be adjacent.
1211 const Type *Ty = Ops[0]->getType();
1212 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1213 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1214 // Found a match, merge the two values into a multiply, and add any
1215 // remaining values to the result.
1216 const SCEV *Two = getIntegerSCEV(2, Ty);
1217 const SCEV *Mul = getMulExpr(Ops[i], Two);
1218 if (Ops.size() == 2)
1220 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1222 return getAddExpr(Ops);
1225 // Check for truncates. If all the operands are truncated from the same
1226 // type, see if factoring out the truncate would permit the result to be
1227 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1228 // if the contents of the resulting outer trunc fold to something simple.
1229 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1230 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1231 const Type *DstType = Trunc->getType();
1232 const Type *SrcType = Trunc->getOperand()->getType();
1233 SmallVector<const SCEV *, 8> LargeOps;
1235 // Check all the operands to see if they can be represented in the
1236 // source type of the truncate.
1237 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1238 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1239 if (T->getOperand()->getType() != SrcType) {
1243 LargeOps.push_back(T->getOperand());
1244 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1245 // This could be either sign or zero extension, but sign extension
1246 // is much more likely to be foldable here.
1247 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1248 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
1249 SmallVector<const SCEV *, 8> LargeMulOps;
1250 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1251 if (const SCEVTruncateExpr *T =
1252 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1253 if (T->getOperand()->getType() != SrcType) {
1257 LargeMulOps.push_back(T->getOperand());
1258 } else if (const SCEVConstant *C =
1259 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1260 // This could be either sign or zero extension, but sign extension
1261 // is much more likely to be foldable here.
1262 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1269 LargeOps.push_back(getMulExpr(LargeMulOps));
1276 // Evaluate the expression in the larger type.
1277 const SCEV *Fold = getAddExpr(LargeOps);
1278 // If it folds to something simple, use it. Otherwise, don't.
1279 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1280 return getTruncateExpr(Fold, DstType);
1284 // Skip past any other cast SCEVs.
1285 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1288 // If there are add operands they would be next.
1289 if (Idx < Ops.size()) {
1290 bool DeletedAdd = false;
1291 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
1292 // If we have an add, expand the add operands onto the end of the operands
1294 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1295 Ops.erase(Ops.begin()+Idx);
1299 // If we deleted at least one add, we added operands to the end of the list,
1300 // and they are not necessarily sorted. Recurse to resort and resimplify
1301 // any operands we just aquired.
1303 return getAddExpr(Ops);
1306 // Skip over the add expression until we get to a multiply.
1307 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1310 // Check to see if there are any folding opportunities present with
1311 // operands multiplied by constant values.
1312 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1313 uint64_t BitWidth = getTypeSizeInBits(Ty);
1314 DenseMap<const SCEV *, APInt> M;
1315 SmallVector<const SCEV *, 8> NewOps;
1316 APInt AccumulatedConstant(BitWidth, 0);
1317 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1318 Ops, APInt(BitWidth, 1), *this)) {
1319 // Some interesting folding opportunity is present, so its worthwhile to
1320 // re-generate the operands list. Group the operands by constant scale,
1321 // to avoid multiplying by the same constant scale multiple times.
1322 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1323 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
1324 E = NewOps.end(); I != E; ++I)
1325 MulOpLists[M.find(*I)->second].push_back(*I);
1326 // Re-generate the operands list.
1328 if (AccumulatedConstant != 0)
1329 Ops.push_back(getConstant(AccumulatedConstant));
1330 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1331 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
1333 Ops.push_back(getMulExpr(getConstant(I->first),
1334 getAddExpr(I->second)));
1336 return getIntegerSCEV(0, Ty);
1337 if (Ops.size() == 1)
1339 return getAddExpr(Ops);
1343 // If we are adding something to a multiply expression, make sure the
1344 // something is not already an operand of the multiply. If so, merge it into
1346 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
1347 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
1348 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
1349 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
1350 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
1351 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
1352 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1353 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
1354 if (Mul->getNumOperands() != 2) {
1355 // If the multiply has more than two operands, we must get the
1357 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
1358 MulOps.erase(MulOps.begin()+MulOp);
1359 InnerMul = getMulExpr(MulOps);
1361 const SCEV *One = getIntegerSCEV(1, Ty);
1362 const SCEV *AddOne = getAddExpr(InnerMul, One);
1363 const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
1364 if (Ops.size() == 2) return OuterMul;
1366 Ops.erase(Ops.begin()+AddOp);
1367 Ops.erase(Ops.begin()+Idx-1);
1369 Ops.erase(Ops.begin()+Idx);
1370 Ops.erase(Ops.begin()+AddOp-1);
1372 Ops.push_back(OuterMul);
1373 return getAddExpr(Ops);
1376 // Check this multiply against other multiplies being added together.
1377 for (unsigned OtherMulIdx = Idx+1;
1378 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1380 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
1381 // If MulOp occurs in OtherMul, we can fold the two multiplies
1383 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1384 OMulOp != e; ++OMulOp)
1385 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1386 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1387 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
1388 if (Mul->getNumOperands() != 2) {
1389 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1391 MulOps.erase(MulOps.begin()+MulOp);
1392 InnerMul1 = getMulExpr(MulOps);
1394 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1395 if (OtherMul->getNumOperands() != 2) {
1396 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1397 OtherMul->op_end());
1398 MulOps.erase(MulOps.begin()+OMulOp);
1399 InnerMul2 = getMulExpr(MulOps);
1401 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1402 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
1403 if (Ops.size() == 2) return OuterMul;
1404 Ops.erase(Ops.begin()+Idx);
1405 Ops.erase(Ops.begin()+OtherMulIdx-1);
1406 Ops.push_back(OuterMul);
1407 return getAddExpr(Ops);
1413 // If there are any add recurrences in the operands list, see if any other
1414 // added values are loop invariant. If so, we can fold them into the
1416 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1419 // Scan over all recurrences, trying to fold loop invariants into them.
1420 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1421 // Scan all of the other operands to this add and add them to the vector if
1422 // they are loop invariant w.r.t. the recurrence.
1423 SmallVector<const SCEV *, 8> LIOps;
1424 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1425 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1426 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1427 LIOps.push_back(Ops[i]);
1428 Ops.erase(Ops.begin()+i);
1432 // If we found some loop invariants, fold them into the recurrence.
1433 if (!LIOps.empty()) {
1434 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
1435 LIOps.push_back(AddRec->getStart());
1437 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
1439 AddRecOps[0] = getAddExpr(LIOps);
1441 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
1442 // If all of the other operands were loop invariant, we are done.
1443 if (Ops.size() == 1) return NewRec;
1445 // Otherwise, add the folded AddRec by the non-liv parts.
1446 for (unsigned i = 0;; ++i)
1447 if (Ops[i] == AddRec) {
1451 return getAddExpr(Ops);
1454 // Okay, if there weren't any loop invariants to be folded, check to see if
1455 // there are multiple AddRec's with the same loop induction variable being
1456 // added together. If so, we can fold them.
1457 for (unsigned OtherIdx = Idx+1;
1458 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1459 if (OtherIdx != Idx) {
1460 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1461 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1462 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1463 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1465 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1466 if (i >= NewOps.size()) {
1467 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1468 OtherAddRec->op_end());
1471 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
1473 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
1475 if (Ops.size() == 2) return NewAddRec;
1477 Ops.erase(Ops.begin()+Idx);
1478 Ops.erase(Ops.begin()+OtherIdx-1);
1479 Ops.push_back(NewAddRec);
1480 return getAddExpr(Ops);
1484 // Otherwise couldn't fold anything into this recurrence. Move onto the
1488 // Okay, it looks like we really DO need an add expr. Check to see if we
1489 // already have one, otherwise create a new one.
1490 FoldingSetNodeID ID;
1491 ID.AddInteger(scAddExpr);
1492 ID.AddInteger(Ops.size());
1493 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1494 ID.AddPointer(Ops[i]);
1496 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1497 SCEV *S = SCEVAllocator.Allocate<SCEVAddExpr>();
1498 new (S) SCEVAddExpr(ID, Ops);
1499 UniqueSCEVs.InsertNode(S, IP);
1504 /// getMulExpr - Get a canonical multiply expression, or something simpler if
1506 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops) {
1507 assert(!Ops.empty() && "Cannot get empty mul!");
1509 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1510 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1511 getEffectiveSCEVType(Ops[0]->getType()) &&
1512 "SCEVMulExpr operand types don't match!");
1515 // Sort by complexity, this groups all similar expression types together.
1516 GroupByComplexity(Ops, LI);
1518 // If there are any constants, fold them together.
1520 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1522 // C1*(C2+V) -> C1*C2 + C1*V
1523 if (Ops.size() == 2)
1524 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1525 if (Add->getNumOperands() == 2 &&
1526 isa<SCEVConstant>(Add->getOperand(0)))
1527 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1528 getMulExpr(LHSC, Add->getOperand(1)));
1532 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1533 // We found two constants, fold them together!
1534 ConstantInt *Fold = ConstantInt::get(getContext(),
1535 LHSC->getValue()->getValue() *
1536 RHSC->getValue()->getValue());
1537 Ops[0] = getConstant(Fold);
1538 Ops.erase(Ops.begin()+1); // Erase the folded element
1539 if (Ops.size() == 1) return Ops[0];
1540 LHSC = cast<SCEVConstant>(Ops[0]);
1543 // If we are left with a constant one being multiplied, strip it off.
1544 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1545 Ops.erase(Ops.begin());
1547 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1548 // If we have a multiply of zero, it will always be zero.
1553 // Skip over the add expression until we get to a multiply.
1554 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1557 if (Ops.size() == 1)
1560 // If there are mul operands inline them all into this expression.
1561 if (Idx < Ops.size()) {
1562 bool DeletedMul = false;
1563 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1564 // If we have an mul, expand the mul operands onto the end of the operands
1566 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1567 Ops.erase(Ops.begin()+Idx);
1571 // If we deleted at least one mul, we added operands to the end of the list,
1572 // and they are not necessarily sorted. Recurse to resort and resimplify
1573 // any operands we just aquired.
1575 return getMulExpr(Ops);
1578 // If there are any add recurrences in the operands list, see if any other
1579 // added values are loop invariant. If so, we can fold them into the
1581 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1584 // Scan over all recurrences, trying to fold loop invariants into them.
1585 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1586 // Scan all of the other operands to this mul and add them to the vector if
1587 // they are loop invariant w.r.t. the recurrence.
1588 SmallVector<const SCEV *, 8> LIOps;
1589 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1590 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1591 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1592 LIOps.push_back(Ops[i]);
1593 Ops.erase(Ops.begin()+i);
1597 // If we found some loop invariants, fold them into the recurrence.
1598 if (!LIOps.empty()) {
1599 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
1600 SmallVector<const SCEV *, 4> NewOps;
1601 NewOps.reserve(AddRec->getNumOperands());
1602 if (LIOps.size() == 1) {
1603 const SCEV *Scale = LIOps[0];
1604 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1605 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1607 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1608 SmallVector<const SCEV *, 4> MulOps(LIOps.begin(), LIOps.end());
1609 MulOps.push_back(AddRec->getOperand(i));
1610 NewOps.push_back(getMulExpr(MulOps));
1614 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
1616 // If all of the other operands were loop invariant, we are done.
1617 if (Ops.size() == 1) return NewRec;
1619 // Otherwise, multiply the folded AddRec by the non-liv parts.
1620 for (unsigned i = 0;; ++i)
1621 if (Ops[i] == AddRec) {
1625 return getMulExpr(Ops);
1628 // Okay, if there weren't any loop invariants to be folded, check to see if
1629 // there are multiple AddRec's with the same loop induction variable being
1630 // multiplied together. If so, we can fold them.
1631 for (unsigned OtherIdx = Idx+1;
1632 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1633 if (OtherIdx != Idx) {
1634 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1635 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1636 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1637 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1638 const SCEV *NewStart = getMulExpr(F->getStart(),
1640 const SCEV *B = F->getStepRecurrence(*this);
1641 const SCEV *D = G->getStepRecurrence(*this);
1642 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
1645 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
1647 if (Ops.size() == 2) return NewAddRec;
1649 Ops.erase(Ops.begin()+Idx);
1650 Ops.erase(Ops.begin()+OtherIdx-1);
1651 Ops.push_back(NewAddRec);
1652 return getMulExpr(Ops);
1656 // Otherwise couldn't fold anything into this recurrence. Move onto the
1660 // Okay, it looks like we really DO need an mul expr. Check to see if we
1661 // already have one, otherwise create a new one.
1662 FoldingSetNodeID ID;
1663 ID.AddInteger(scMulExpr);
1664 ID.AddInteger(Ops.size());
1665 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1666 ID.AddPointer(Ops[i]);
1668 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1669 SCEV *S = SCEVAllocator.Allocate<SCEVMulExpr>();
1670 new (S) SCEVMulExpr(ID, Ops);
1671 UniqueSCEVs.InsertNode(S, IP);
1675 /// getUDivExpr - Get a canonical unsigned division expression, or something
1676 /// simpler if possible.
1677 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1679 assert(getEffectiveSCEVType(LHS->getType()) ==
1680 getEffectiveSCEVType(RHS->getType()) &&
1681 "SCEVUDivExpr operand types don't match!");
1683 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1684 if (RHSC->getValue()->equalsInt(1))
1685 return LHS; // X udiv 1 --> x
1687 return getIntegerSCEV(0, LHS->getType()); // value is undefined
1689 // Determine if the division can be folded into the operands of
1691 // TODO: Generalize this to non-constants by using known-bits information.
1692 const Type *Ty = LHS->getType();
1693 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1694 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1695 // For non-power-of-two values, effectively round the value up to the
1696 // nearest power of two.
1697 if (!RHSC->getValue()->getValue().isPowerOf2())
1699 const IntegerType *ExtTy =
1700 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
1701 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1702 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1703 if (const SCEVConstant *Step =
1704 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1705 if (!Step->getValue()->getValue()
1706 .urem(RHSC->getValue()->getValue()) &&
1707 getZeroExtendExpr(AR, ExtTy) ==
1708 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1709 getZeroExtendExpr(Step, ExtTy),
1711 SmallVector<const SCEV *, 4> Operands;
1712 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1713 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1714 return getAddRecExpr(Operands, AR->getLoop());
1716 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1717 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1718 SmallVector<const SCEV *, 4> Operands;
1719 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1720 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1721 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
1722 // Find an operand that's safely divisible.
1723 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1724 const SCEV *Op = M->getOperand(i);
1725 const SCEV *Div = getUDivExpr(Op, RHSC);
1726 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1727 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
1728 Operands = SmallVector<const SCEV *, 4>(MOperands.begin(),
1731 return getMulExpr(Operands);
1735 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
1736 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1737 SmallVector<const SCEV *, 4> Operands;
1738 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1739 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1740 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1742 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1743 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
1744 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1746 Operands.push_back(Op);
1748 if (Operands.size() == A->getNumOperands())
1749 return getAddExpr(Operands);
1753 // Fold if both operands are constant.
1754 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1755 Constant *LHSCV = LHSC->getValue();
1756 Constant *RHSCV = RHSC->getValue();
1757 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1762 FoldingSetNodeID ID;
1763 ID.AddInteger(scUDivExpr);
1767 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1768 SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>();
1769 new (S) SCEVUDivExpr(ID, LHS, RHS);
1770 UniqueSCEVs.InsertNode(S, IP);
1775 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1776 /// Simplify the expression as much as possible.
1777 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
1778 const SCEV *Step, const Loop *L) {
1779 SmallVector<const SCEV *, 4> Operands;
1780 Operands.push_back(Start);
1781 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1782 if (StepChrec->getLoop() == L) {
1783 Operands.insert(Operands.end(), StepChrec->op_begin(),
1784 StepChrec->op_end());
1785 return getAddRecExpr(Operands, L);
1788 Operands.push_back(Step);
1789 return getAddRecExpr(Operands, L);
1792 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1793 /// Simplify the expression as much as possible.
1795 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
1797 if (Operands.size() == 1) return Operands[0];
1799 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1800 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1801 getEffectiveSCEVType(Operands[0]->getType()) &&
1802 "SCEVAddRecExpr operand types don't match!");
1805 if (Operands.back()->isZero()) {
1806 Operands.pop_back();
1807 return getAddRecExpr(Operands, L); // {X,+,0} --> X
1810 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1811 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1812 const Loop* NestedLoop = NestedAR->getLoop();
1813 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1814 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
1815 NestedAR->op_end());
1816 Operands[0] = NestedAR->getStart();
1817 // AddRecs require their operands be loop-invariant with respect to their
1818 // loops. Don't perform this transformation if it would break this
1820 bool AllInvariant = true;
1821 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1822 if (!Operands[i]->isLoopInvariant(L)) {
1823 AllInvariant = false;
1827 NestedOperands[0] = getAddRecExpr(Operands, L);
1828 AllInvariant = true;
1829 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
1830 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
1831 AllInvariant = false;
1835 // Ok, both add recurrences are valid after the transformation.
1836 return getAddRecExpr(NestedOperands, NestedLoop);
1838 // Reset Operands to its original state.
1839 Operands[0] = NestedAR;
1843 FoldingSetNodeID ID;
1844 ID.AddInteger(scAddRecExpr);
1845 ID.AddInteger(Operands.size());
1846 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1847 ID.AddPointer(Operands[i]);
1850 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1851 SCEV *S = SCEVAllocator.Allocate<SCEVAddRecExpr>();
1852 new (S) SCEVAddRecExpr(ID, Operands, L);
1853 UniqueSCEVs.InsertNode(S, IP);
1857 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
1859 SmallVector<const SCEV *, 2> Ops;
1862 return getSMaxExpr(Ops);
1866 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
1867 assert(!Ops.empty() && "Cannot get empty smax!");
1868 if (Ops.size() == 1) return Ops[0];
1870 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1871 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1872 getEffectiveSCEVType(Ops[0]->getType()) &&
1873 "SCEVSMaxExpr operand types don't match!");
1876 // Sort by complexity, this groups all similar expression types together.
1877 GroupByComplexity(Ops, LI);
1879 // If there are any constants, fold them together.
1881 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1883 assert(Idx < Ops.size());
1884 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1885 // We found two constants, fold them together!
1886 ConstantInt *Fold = ConstantInt::get(getContext(),
1887 APIntOps::smax(LHSC->getValue()->getValue(),
1888 RHSC->getValue()->getValue()));
1889 Ops[0] = getConstant(Fold);
1890 Ops.erase(Ops.begin()+1); // Erase the folded element
1891 if (Ops.size() == 1) return Ops[0];
1892 LHSC = cast<SCEVConstant>(Ops[0]);
1895 // If we are left with a constant minimum-int, strip it off.
1896 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1897 Ops.erase(Ops.begin());
1899 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
1900 // If we have an smax with a constant maximum-int, it will always be
1906 if (Ops.size() == 1) return Ops[0];
1908 // Find the first SMax
1909 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1912 // Check to see if one of the operands is an SMax. If so, expand its operands
1913 // onto our operand list, and recurse to simplify.
1914 if (Idx < Ops.size()) {
1915 bool DeletedSMax = false;
1916 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1917 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1918 Ops.erase(Ops.begin()+Idx);
1923 return getSMaxExpr(Ops);
1926 // Okay, check to see if the same value occurs in the operand list twice. If
1927 // so, delete one. Since we sorted the list, these values are required to
1929 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1930 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1931 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1935 if (Ops.size() == 1) return Ops[0];
1937 assert(!Ops.empty() && "Reduced smax down to nothing!");
1939 // Okay, it looks like we really DO need an smax expr. Check to see if we
1940 // already have one, otherwise create a new one.
1941 FoldingSetNodeID ID;
1942 ID.AddInteger(scSMaxExpr);
1943 ID.AddInteger(Ops.size());
1944 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1945 ID.AddPointer(Ops[i]);
1947 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1948 SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>();
1949 new (S) SCEVSMaxExpr(ID, Ops);
1950 UniqueSCEVs.InsertNode(S, IP);
1954 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
1956 SmallVector<const SCEV *, 2> Ops;
1959 return getUMaxExpr(Ops);
1963 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
1964 assert(!Ops.empty() && "Cannot get empty umax!");
1965 if (Ops.size() == 1) return Ops[0];
1967 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1968 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1969 getEffectiveSCEVType(Ops[0]->getType()) &&
1970 "SCEVUMaxExpr operand types don't match!");
1973 // Sort by complexity, this groups all similar expression types together.
1974 GroupByComplexity(Ops, LI);
1976 // If there are any constants, fold them together.
1978 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1980 assert(Idx < Ops.size());
1981 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1982 // We found two constants, fold them together!
1983 ConstantInt *Fold = ConstantInt::get(getContext(),
1984 APIntOps::umax(LHSC->getValue()->getValue(),
1985 RHSC->getValue()->getValue()));
1986 Ops[0] = getConstant(Fold);
1987 Ops.erase(Ops.begin()+1); // Erase the folded element
1988 if (Ops.size() == 1) return Ops[0];
1989 LHSC = cast<SCEVConstant>(Ops[0]);
1992 // If we are left with a constant minimum-int, strip it off.
1993 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1994 Ops.erase(Ops.begin());
1996 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
1997 // If we have an umax with a constant maximum-int, it will always be
2003 if (Ops.size() == 1) return Ops[0];
2005 // Find the first UMax
2006 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2009 // Check to see if one of the operands is a UMax. If so, expand its operands
2010 // onto our operand list, and recurse to simplify.
2011 if (Idx < Ops.size()) {
2012 bool DeletedUMax = false;
2013 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
2014 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
2015 Ops.erase(Ops.begin()+Idx);
2020 return getUMaxExpr(Ops);
2023 // Okay, check to see if the same value occurs in the operand list twice. If
2024 // so, delete one. Since we sorted the list, these values are required to
2026 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2027 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
2028 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2032 if (Ops.size() == 1) return Ops[0];
2034 assert(!Ops.empty() && "Reduced umax down to nothing!");
2036 // Okay, it looks like we really DO need a umax expr. Check to see if we
2037 // already have one, otherwise create a new one.
2038 FoldingSetNodeID ID;
2039 ID.AddInteger(scUMaxExpr);
2040 ID.AddInteger(Ops.size());
2041 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2042 ID.AddPointer(Ops[i]);
2044 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2045 SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>();
2046 new (S) SCEVUMaxExpr(ID, Ops);
2047 UniqueSCEVs.InsertNode(S, IP);
2051 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2053 // ~smax(~x, ~y) == smin(x, y).
2054 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2057 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2059 // ~umax(~x, ~y) == umin(x, y)
2060 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2063 const SCEV *ScalarEvolution::getFieldOffsetExpr(const StructType *STy,
2065 // If we have TargetData we can determine the constant offset.
2067 const Type *IntPtrTy = TD->getIntPtrType(getContext());
2068 const StructLayout &SL = *TD->getStructLayout(STy);
2069 uint64_t Offset = SL.getElementOffset(FieldNo);
2070 return getIntegerSCEV(Offset, IntPtrTy);
2073 // Field 0 is always at offset 0.
2075 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
2076 return getIntegerSCEV(0, Ty);
2079 // Okay, it looks like we really DO need an offsetof expr. Check to see if we
2080 // already have one, otherwise create a new one.
2081 FoldingSetNodeID ID;
2082 ID.AddInteger(scFieldOffset);
2084 ID.AddInteger(FieldNo);
2086 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2087 SCEV *S = SCEVAllocator.Allocate<SCEVFieldOffsetExpr>();
2088 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
2089 new (S) SCEVFieldOffsetExpr(ID, Ty, STy, FieldNo);
2090 UniqueSCEVs.InsertNode(S, IP);
2094 const SCEV *ScalarEvolution::getAllocSizeExpr(const Type *AllocTy) {
2095 // If we have TargetData we can determine the constant size.
2096 if (TD && AllocTy->isSized()) {
2097 const Type *IntPtrTy = TD->getIntPtrType(getContext());
2098 return getIntegerSCEV(TD->getTypeAllocSize(AllocTy), IntPtrTy);
2101 // Expand an array size into the element size times the number
2103 if (const ArrayType *ATy = dyn_cast<ArrayType>(AllocTy)) {
2104 const SCEV *E = getAllocSizeExpr(ATy->getElementType());
2106 E, getConstant(ConstantInt::get(cast<IntegerType>(E->getType()),
2107 ATy->getNumElements())));
2110 // Expand a vector size into the element size times the number
2112 if (const VectorType *VTy = dyn_cast<VectorType>(AllocTy)) {
2113 const SCEV *E = getAllocSizeExpr(VTy->getElementType());
2115 E, getConstant(ConstantInt::get(cast<IntegerType>(E->getType()),
2116 VTy->getNumElements())));
2119 // Okay, it looks like we really DO need a sizeof expr. Check to see if we
2120 // already have one, otherwise create a new one.
2121 FoldingSetNodeID ID;
2122 ID.AddInteger(scAllocSize);
2123 ID.AddPointer(AllocTy);
2125 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2126 SCEV *S = SCEVAllocator.Allocate<SCEVAllocSizeExpr>();
2127 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2128 new (S) SCEVAllocSizeExpr(ID, Ty, AllocTy);
2129 UniqueSCEVs.InsertNode(S, IP);
2133 const SCEV *ScalarEvolution::getUnknown(Value *V) {
2134 // Don't attempt to do anything other than create a SCEVUnknown object
2135 // here. createSCEV only calls getUnknown after checking for all other
2136 // interesting possibilities, and any other code that calls getUnknown
2137 // is doing so in order to hide a value from SCEV canonicalization.
2139 FoldingSetNodeID ID;
2140 ID.AddInteger(scUnknown);
2143 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2144 SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>();
2145 new (S) SCEVUnknown(ID, V);
2146 UniqueSCEVs.InsertNode(S, IP);
2150 //===----------------------------------------------------------------------===//
2151 // Basic SCEV Analysis and PHI Idiom Recognition Code
2154 /// isSCEVable - Test if values of the given type are analyzable within
2155 /// the SCEV framework. This primarily includes integer types, and it
2156 /// can optionally include pointer types if the ScalarEvolution class
2157 /// has access to target-specific information.
2158 bool ScalarEvolution::isSCEVable(const Type *Ty) const {
2159 // Integers and pointers are always SCEVable.
2160 return Ty->isInteger() || isa<PointerType>(Ty);
2163 /// getTypeSizeInBits - Return the size in bits of the specified type,
2164 /// for which isSCEVable must return true.
2165 uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
2166 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2168 // If we have a TargetData, use it!
2170 return TD->getTypeSizeInBits(Ty);
2172 // Integer types have fixed sizes.
2173 if (Ty->isInteger())
2174 return Ty->getPrimitiveSizeInBits();
2176 // The only other support type is pointer. Without TargetData, conservatively
2177 // assume pointers are 64-bit.
2178 assert(isa<PointerType>(Ty) && "isSCEVable permitted a non-SCEVable type!");
2182 /// getEffectiveSCEVType - Return a type with the same bitwidth as
2183 /// the given type and which represents how SCEV will treat the given
2184 /// type, for which isSCEVable must return true. For pointer types,
2185 /// this is the pointer-sized integer type.
2186 const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
2187 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2189 if (Ty->isInteger())
2192 // The only other support type is pointer.
2193 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
2194 if (TD) return TD->getIntPtrType(getContext());
2196 // Without TargetData, conservatively assume pointers are 64-bit.
2197 return Type::getInt64Ty(getContext());
2200 const SCEV *ScalarEvolution::getCouldNotCompute() {
2201 return &CouldNotCompute;
2204 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2205 /// expression and create a new one.
2206 const SCEV *ScalarEvolution::getSCEV(Value *V) {
2207 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
2209 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
2210 if (I != Scalars.end()) return I->second;
2211 const SCEV *S = createSCEV(V);
2212 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
2216 /// getIntegerSCEV - Given a SCEVable type, create a constant for the
2217 /// specified signed integer value and return a SCEV for the constant.
2218 const SCEV *ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
2219 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
2220 return getConstant(ConstantInt::get(ITy, Val));
2223 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2225 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
2226 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2228 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
2230 const Type *Ty = V->getType();
2231 Ty = getEffectiveSCEVType(Ty);
2232 return getMulExpr(V,
2233 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
2236 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
2237 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
2238 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2240 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
2242 const Type *Ty = V->getType();
2243 Ty = getEffectiveSCEVType(Ty);
2244 const SCEV *AllOnes =
2245 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
2246 return getMinusSCEV(AllOnes, V);
2249 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2251 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2254 return getAddExpr(LHS, getNegativeSCEV(RHS));
2257 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2258 /// input value to the specified type. If the type must be extended, it is zero
2261 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
2263 const Type *SrcTy = V->getType();
2264 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2265 (Ty->isInteger() || isa<PointerType>(Ty)) &&
2266 "Cannot truncate or zero extend with non-integer arguments!");
2267 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2268 return V; // No conversion
2269 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2270 return getTruncateExpr(V, Ty);
2271 return getZeroExtendExpr(V, Ty);
2274 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2275 /// input value to the specified type. If the type must be extended, it is sign
2278 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
2280 const Type *SrcTy = V->getType();
2281 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2282 (Ty->isInteger() || isa<PointerType>(Ty)) &&
2283 "Cannot truncate or zero extend with non-integer arguments!");
2284 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2285 return V; // No conversion
2286 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2287 return getTruncateExpr(V, Ty);
2288 return getSignExtendExpr(V, Ty);
2291 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2292 /// input value to the specified type. If the type must be extended, it is zero
2293 /// extended. The conversion must not be narrowing.
2295 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
2296 const Type *SrcTy = V->getType();
2297 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2298 (Ty->isInteger() || isa<PointerType>(Ty)) &&
2299 "Cannot noop or zero extend with non-integer arguments!");
2300 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2301 "getNoopOrZeroExtend cannot truncate!");
2302 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2303 return V; // No conversion
2304 return getZeroExtendExpr(V, Ty);
2307 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2308 /// input value to the specified type. If the type must be extended, it is sign
2309 /// extended. The conversion must not be narrowing.
2311 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
2312 const Type *SrcTy = V->getType();
2313 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2314 (Ty->isInteger() || isa<PointerType>(Ty)) &&
2315 "Cannot noop or sign extend with non-integer arguments!");
2316 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2317 "getNoopOrSignExtend cannot truncate!");
2318 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2319 return V; // No conversion
2320 return getSignExtendExpr(V, Ty);
2323 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2324 /// the input value to the specified type. If the type must be extended,
2325 /// it is extended with unspecified bits. The conversion must not be
2328 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
2329 const Type *SrcTy = V->getType();
2330 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2331 (Ty->isInteger() || isa<PointerType>(Ty)) &&
2332 "Cannot noop or any extend with non-integer arguments!");
2333 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2334 "getNoopOrAnyExtend cannot truncate!");
2335 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2336 return V; // No conversion
2337 return getAnyExtendExpr(V, Ty);
2340 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2341 /// input value to the specified type. The conversion must not be widening.
2343 ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
2344 const Type *SrcTy = V->getType();
2345 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2346 (Ty->isInteger() || isa<PointerType>(Ty)) &&
2347 "Cannot truncate or noop with non-integer arguments!");
2348 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2349 "getTruncateOrNoop cannot extend!");
2350 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2351 return V; // No conversion
2352 return getTruncateExpr(V, Ty);
2355 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2356 /// the types using zero-extension, and then perform a umax operation
2358 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2360 const SCEV *PromotedLHS = LHS;
2361 const SCEV *PromotedRHS = RHS;
2363 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2364 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2366 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2368 return getUMaxExpr(PromotedLHS, PromotedRHS);
2371 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
2372 /// the types using zero-extension, and then perform a umin operation
2374 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2376 const SCEV *PromotedLHS = LHS;
2377 const SCEV *PromotedRHS = RHS;
2379 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2380 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2382 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2384 return getUMinExpr(PromotedLHS, PromotedRHS);
2387 /// PushDefUseChildren - Push users of the given Instruction
2388 /// onto the given Worklist.
2390 PushDefUseChildren(Instruction *I,
2391 SmallVectorImpl<Instruction *> &Worklist) {
2392 // Push the def-use children onto the Worklist stack.
2393 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2395 Worklist.push_back(cast<Instruction>(UI));
2398 /// ForgetSymbolicValue - This looks up computed SCEV values for all
2399 /// instructions that depend on the given instruction and removes them from
2400 /// the Scalars map if they reference SymName. This is used during PHI
2403 ScalarEvolution::ForgetSymbolicName(Instruction *I, const SCEV *SymName) {
2404 SmallVector<Instruction *, 16> Worklist;
2405 PushDefUseChildren(I, Worklist);
2407 SmallPtrSet<Instruction *, 8> Visited;
2409 while (!Worklist.empty()) {
2410 Instruction *I = Worklist.pop_back_val();
2411 if (!Visited.insert(I)) continue;
2413 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
2414 Scalars.find(static_cast<Value *>(I));
2415 if (It != Scalars.end()) {
2416 // Short-circuit the def-use traversal if the symbolic name
2417 // ceases to appear in expressions.
2418 if (!It->second->hasOperand(SymName))
2421 // SCEVUnknown for a PHI either means that it has an unrecognized
2422 // structure, or it's a PHI that's in the progress of being computed
2423 // by createNodeForPHI. In the former case, additional loop trip
2424 // count information isn't going to change anything. In the later
2425 // case, createNodeForPHI will perform the necessary updates on its
2426 // own when it gets to that point.
2427 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
2428 ValuesAtScopes.erase(It->second);
2433 PushDefUseChildren(I, Worklist);
2437 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2438 /// a loop header, making it a potential recurrence, or it doesn't.
2440 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
2441 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
2442 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2443 if (L->getHeader() == PN->getParent()) {
2444 // If it lives in the loop header, it has two incoming values, one
2445 // from outside the loop, and one from inside.
2446 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2447 unsigned BackEdge = IncomingEdge^1;
2449 // While we are analyzing this PHI node, handle its value symbolically.
2450 const SCEV *SymbolicName = getUnknown(PN);
2451 assert(Scalars.find(PN) == Scalars.end() &&
2452 "PHI node already processed?");
2453 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
2455 // Using this symbolic name for the PHI, analyze the value coming around
2457 Value *BEValueV = PN->getIncomingValue(BackEdge);
2458 const SCEV *BEValue = getSCEV(BEValueV);
2460 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2461 // has a special value for the first iteration of the loop.
2463 // If the value coming around the backedge is an add with the symbolic
2464 // value we just inserted, then we found a simple induction variable!
2465 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
2466 // If there is a single occurrence of the symbolic value, replace it
2467 // with a recurrence.
2468 unsigned FoundIndex = Add->getNumOperands();
2469 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2470 if (Add->getOperand(i) == SymbolicName)
2471 if (FoundIndex == e) {
2476 if (FoundIndex != Add->getNumOperands()) {
2477 // Create an add with everything but the specified operand.
2478 SmallVector<const SCEV *, 8> Ops;
2479 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2480 if (i != FoundIndex)
2481 Ops.push_back(Add->getOperand(i));
2482 const SCEV *Accum = getAddExpr(Ops);
2484 // This is not a valid addrec if the step amount is varying each
2485 // loop iteration, but is not itself an addrec in this loop.
2486 if (Accum->isLoopInvariant(L) ||
2487 (isa<SCEVAddRecExpr>(Accum) &&
2488 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
2489 const SCEV *StartVal =
2490 getSCEV(PN->getIncomingValue(IncomingEdge));
2491 const SCEVAddRecExpr *PHISCEV =
2492 cast<SCEVAddRecExpr>(getAddRecExpr(StartVal, Accum, L));
2494 // If the increment doesn't overflow, then neither the addrec nor the
2495 // post-increment will overflow.
2496 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV))
2497 if (OBO->getOperand(0) == PN &&
2498 getSCEV(OBO->getOperand(1)) ==
2499 PHISCEV->getStepRecurrence(*this)) {
2500 const SCEVAddRecExpr *PostInc = PHISCEV->getPostIncExpr(*this);
2501 if (OBO->hasNoUnsignedWrap()) {
2502 const_cast<SCEVAddRecExpr *>(PHISCEV)
2503 ->setHasNoUnsignedWrap(true);
2504 const_cast<SCEVAddRecExpr *>(PostInc)
2505 ->setHasNoUnsignedWrap(true);
2507 if (OBO->hasNoSignedWrap()) {
2508 const_cast<SCEVAddRecExpr *>(PHISCEV)
2509 ->setHasNoSignedWrap(true);
2510 const_cast<SCEVAddRecExpr *>(PostInc)
2511 ->setHasNoSignedWrap(true);
2515 // Okay, for the entire analysis of this edge we assumed the PHI
2516 // to be symbolic. We now need to go back and purge all of the
2517 // entries for the scalars that use the symbolic expression.
2518 ForgetSymbolicName(PN, SymbolicName);
2519 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
2523 } else if (const SCEVAddRecExpr *AddRec =
2524 dyn_cast<SCEVAddRecExpr>(BEValue)) {
2525 // Otherwise, this could be a loop like this:
2526 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2527 // In this case, j = {1,+,1} and BEValue is j.
2528 // Because the other in-value of i (0) fits the evolution of BEValue
2529 // i really is an addrec evolution.
2530 if (AddRec->getLoop() == L && AddRec->isAffine()) {
2531 const SCEV *StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
2533 // If StartVal = j.start - j.stride, we can use StartVal as the
2534 // initial step of the addrec evolution.
2535 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
2536 AddRec->getOperand(1))) {
2537 const SCEV *PHISCEV =
2538 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
2540 // Okay, for the entire analysis of this edge we assumed the PHI
2541 // to be symbolic. We now need to go back and purge all of the
2542 // entries for the scalars that use the symbolic expression.
2543 ForgetSymbolicName(PN, SymbolicName);
2544 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
2550 return SymbolicName;
2553 // It's tempting to recognize PHIs with a unique incoming value, however
2554 // this leads passes like indvars to break LCSSA form. Fortunately, such
2555 // PHIs are rare, as instcombine zaps them.
2557 // If it's not a loop phi, we can't handle it yet.
2558 return getUnknown(PN);
2561 /// createNodeForGEP - Expand GEP instructions into add and multiply
2562 /// operations. This allows them to be analyzed by regular SCEV code.
2564 const SCEV *ScalarEvolution::createNodeForGEP(Operator *GEP) {
2566 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
2567 Value *Base = GEP->getOperand(0);
2568 // Don't attempt to analyze GEPs over unsized objects.
2569 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2570 return getUnknown(GEP);
2571 const SCEV *TotalOffset = getIntegerSCEV(0, IntPtrTy);
2572 gep_type_iterator GTI = gep_type_begin(GEP);
2573 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2577 // Compute the (potentially symbolic) offset in bytes for this index.
2578 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2579 // For a struct, add the member offset.
2580 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2581 TotalOffset = getAddExpr(TotalOffset,
2582 getFieldOffsetExpr(STy, FieldNo));
2584 // For an array, add the element offset, explicitly scaled.
2585 const SCEV *LocalOffset = getSCEV(Index);
2586 if (!isa<PointerType>(LocalOffset->getType()))
2587 // Getelementptr indicies are signed.
2588 LocalOffset = getTruncateOrSignExtend(LocalOffset, IntPtrTy);
2589 LocalOffset = getMulExpr(LocalOffset, getAllocSizeExpr(*GTI));
2590 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2593 return getAddExpr(getSCEV(Base), TotalOffset);
2596 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2597 /// guaranteed to end in (at every loop iteration). It is, at the same time,
2598 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2599 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
2601 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
2602 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2603 return C->getValue()->getValue().countTrailingZeros();
2605 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
2606 return std::min(GetMinTrailingZeros(T->getOperand()),
2607 (uint32_t)getTypeSizeInBits(T->getType()));
2609 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
2610 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2611 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2612 getTypeSizeInBits(E->getType()) : OpRes;
2615 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
2616 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2617 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2618 getTypeSizeInBits(E->getType()) : OpRes;
2621 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
2622 // The result is the min of all operands results.
2623 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2624 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2625 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2629 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
2630 // The result is the sum of all operands results.
2631 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2632 uint32_t BitWidth = getTypeSizeInBits(M->getType());
2633 for (unsigned i = 1, e = M->getNumOperands();
2634 SumOpRes != BitWidth && i != e; ++i)
2635 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
2640 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
2641 // The result is the min of all operands results.
2642 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2643 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2644 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2648 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
2649 // The result is the min of all operands results.
2650 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2651 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2652 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2656 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
2657 // The result is the min of all operands results.
2658 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2659 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2660 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2664 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2665 // For a SCEVUnknown, ask ValueTracking.
2666 unsigned BitWidth = getTypeSizeInBits(U->getType());
2667 APInt Mask = APInt::getAllOnesValue(BitWidth);
2668 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2669 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2670 return Zeros.countTrailingOnes();
2677 /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2680 ScalarEvolution::getUnsignedRange(const SCEV *S) {
2682 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2683 return ConstantRange(C->getValue()->getValue());
2685 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2686 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2687 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2688 X = X.add(getUnsignedRange(Add->getOperand(i)));
2692 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2693 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2694 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2695 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
2699 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2700 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2701 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2702 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
2706 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2707 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2708 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2709 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
2713 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2714 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2715 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
2719 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2720 ConstantRange X = getUnsignedRange(ZExt->getOperand());
2721 return X.zeroExtend(cast<IntegerType>(ZExt->getType())->getBitWidth());
2724 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2725 ConstantRange X = getUnsignedRange(SExt->getOperand());
2726 return X.signExtend(cast<IntegerType>(SExt->getType())->getBitWidth());
2729 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2730 ConstantRange X = getUnsignedRange(Trunc->getOperand());
2731 return X.truncate(cast<IntegerType>(Trunc->getType())->getBitWidth());
2734 ConstantRange FullSet(getTypeSizeInBits(S->getType()), true);
2736 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2737 const SCEV *T = getBackedgeTakenCount(AddRec->getLoop());
2738 const SCEVConstant *Trip = dyn_cast<SCEVConstant>(T);
2739 if (!Trip) return FullSet;
2741 // TODO: non-affine addrec
2742 if (AddRec->isAffine()) {
2743 const Type *Ty = AddRec->getType();
2744 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2745 if (getTypeSizeInBits(MaxBECount->getType()) <= getTypeSizeInBits(Ty)) {
2746 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2748 const SCEV *Start = AddRec->getStart();
2749 const SCEV *Step = AddRec->getStepRecurrence(*this);
2750 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2752 // Check for overflow.
2753 // TODO: This is very conservative.
2754 if (!(Step->isOne() &&
2755 isKnownPredicate(ICmpInst::ICMP_ULT, Start, End)) &&
2756 !(Step->isAllOnesValue() &&
2757 isKnownPredicate(ICmpInst::ICMP_UGT, Start, End)))
2760 ConstantRange StartRange = getUnsignedRange(Start);
2761 ConstantRange EndRange = getUnsignedRange(End);
2762 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
2763 EndRange.getUnsignedMin());
2764 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
2765 EndRange.getUnsignedMax());
2766 if (Min.isMinValue() && Max.isMaxValue())
2768 return ConstantRange(Min, Max+1);
2773 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2774 // For a SCEVUnknown, ask ValueTracking.
2775 unsigned BitWidth = getTypeSizeInBits(U->getType());
2776 APInt Mask = APInt::getAllOnesValue(BitWidth);
2777 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2778 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
2779 if (Ones == ~Zeros + 1)
2781 return ConstantRange(Ones, ~Zeros + 1);
2787 /// getSignedRange - Determine the signed range for a particular SCEV.
2790 ScalarEvolution::getSignedRange(const SCEV *S) {
2792 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2793 return ConstantRange(C->getValue()->getValue());
2795 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2796 ConstantRange X = getSignedRange(Add->getOperand(0));
2797 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2798 X = X.add(getSignedRange(Add->getOperand(i)));
2802 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2803 ConstantRange X = getSignedRange(Mul->getOperand(0));
2804 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2805 X = X.multiply(getSignedRange(Mul->getOperand(i)));
2809 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2810 ConstantRange X = getSignedRange(SMax->getOperand(0));
2811 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2812 X = X.smax(getSignedRange(SMax->getOperand(i)));
2816 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2817 ConstantRange X = getSignedRange(UMax->getOperand(0));
2818 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2819 X = X.umax(getSignedRange(UMax->getOperand(i)));
2823 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2824 ConstantRange X = getSignedRange(UDiv->getLHS());
2825 ConstantRange Y = getSignedRange(UDiv->getRHS());
2829 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2830 ConstantRange X = getSignedRange(ZExt->getOperand());
2831 return X.zeroExtend(cast<IntegerType>(ZExt->getType())->getBitWidth());
2834 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2835 ConstantRange X = getSignedRange(SExt->getOperand());
2836 return X.signExtend(cast<IntegerType>(SExt->getType())->getBitWidth());
2839 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2840 ConstantRange X = getSignedRange(Trunc->getOperand());
2841 return X.truncate(cast<IntegerType>(Trunc->getType())->getBitWidth());
2844 ConstantRange FullSet(getTypeSizeInBits(S->getType()), true);
2846 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2847 const SCEV *T = getBackedgeTakenCount(AddRec->getLoop());
2848 const SCEVConstant *Trip = dyn_cast<SCEVConstant>(T);
2849 if (!Trip) return FullSet;
2851 // TODO: non-affine addrec
2852 if (AddRec->isAffine()) {
2853 const Type *Ty = AddRec->getType();
2854 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2855 if (getTypeSizeInBits(MaxBECount->getType()) <= getTypeSizeInBits(Ty)) {
2856 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2858 const SCEV *Start = AddRec->getStart();
2859 const SCEV *Step = AddRec->getStepRecurrence(*this);
2860 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2862 // Check for overflow.
2863 // TODO: This is very conservative.
2864 if (!(Step->isOne() &&
2865 isKnownPredicate(ICmpInst::ICMP_SLT, Start, End)) &&
2866 !(Step->isAllOnesValue() &&
2867 isKnownPredicate(ICmpInst::ICMP_SGT, Start, End)))
2870 ConstantRange StartRange = getSignedRange(Start);
2871 ConstantRange EndRange = getSignedRange(End);
2872 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
2873 EndRange.getSignedMin());
2874 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
2875 EndRange.getSignedMax());
2876 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
2878 return ConstantRange(Min, Max+1);
2883 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2884 // For a SCEVUnknown, ask ValueTracking.
2885 unsigned BitWidth = getTypeSizeInBits(U->getType());
2886 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
2890 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
2891 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1);
2897 /// createSCEV - We know that there is no SCEV for the specified value.
2898 /// Analyze the expression.
2900 const SCEV *ScalarEvolution::createSCEV(Value *V) {
2901 if (!isSCEVable(V->getType()))
2902 return getUnknown(V);
2904 unsigned Opcode = Instruction::UserOp1;
2905 if (Instruction *I = dyn_cast<Instruction>(V))
2906 Opcode = I->getOpcode();
2907 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2908 Opcode = CE->getOpcode();
2909 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2910 return getConstant(CI);
2911 else if (isa<ConstantPointerNull>(V))
2912 return getIntegerSCEV(0, V->getType());
2913 else if (isa<UndefValue>(V))
2914 return getIntegerSCEV(0, V->getType());
2915 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
2916 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
2918 return getUnknown(V);
2920 Operator *U = cast<Operator>(V);
2922 case Instruction::Add:
2923 return getAddExpr(getSCEV(U->getOperand(0)),
2924 getSCEV(U->getOperand(1)));
2925 case Instruction::Mul:
2926 return getMulExpr(getSCEV(U->getOperand(0)),
2927 getSCEV(U->getOperand(1)));
2928 case Instruction::UDiv:
2929 return getUDivExpr(getSCEV(U->getOperand(0)),
2930 getSCEV(U->getOperand(1)));
2931 case Instruction::Sub:
2932 return getMinusSCEV(getSCEV(U->getOperand(0)),
2933 getSCEV(U->getOperand(1)));
2934 case Instruction::And:
2935 // For an expression like x&255 that merely masks off the high bits,
2936 // use zext(trunc(x)) as the SCEV expression.
2937 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2938 if (CI->isNullValue())
2939 return getSCEV(U->getOperand(1));
2940 if (CI->isAllOnesValue())
2941 return getSCEV(U->getOperand(0));
2942 const APInt &A = CI->getValue();
2944 // Instcombine's ShrinkDemandedConstant may strip bits out of
2945 // constants, obscuring what would otherwise be a low-bits mask.
2946 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2947 // knew about to reconstruct a low-bits mask value.
2948 unsigned LZ = A.countLeadingZeros();
2949 unsigned BitWidth = A.getBitWidth();
2950 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2951 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2952 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2954 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2956 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
2958 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
2959 IntegerType::get(getContext(), BitWidth - LZ)),
2964 case Instruction::Or:
2965 // If the RHS of the Or is a constant, we may have something like:
2966 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2967 // optimizations will transparently handle this case.
2969 // In order for this transformation to be safe, the LHS must be of the
2970 // form X*(2^n) and the Or constant must be less than 2^n.
2971 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2972 const SCEV *LHS = getSCEV(U->getOperand(0));
2973 const APInt &CIVal = CI->getValue();
2974 if (GetMinTrailingZeros(LHS) >=
2975 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
2976 // Build a plain add SCEV.
2977 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
2978 // If the LHS of the add was an addrec and it has no-wrap flags,
2979 // transfer the no-wrap flags, since an or won't introduce a wrap.
2980 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
2981 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
2982 if (OldAR->hasNoUnsignedWrap())
2983 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoUnsignedWrap(true);
2984 if (OldAR->hasNoSignedWrap())
2985 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoSignedWrap(true);
2991 case Instruction::Xor:
2992 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2993 // If the RHS of the xor is a signbit, then this is just an add.
2994 // Instcombine turns add of signbit into xor as a strength reduction step.
2995 if (CI->getValue().isSignBit())
2996 return getAddExpr(getSCEV(U->getOperand(0)),
2997 getSCEV(U->getOperand(1)));
2999 // If the RHS of xor is -1, then this is a not operation.
3000 if (CI->isAllOnesValue())
3001 return getNotSCEV(getSCEV(U->getOperand(0)));
3003 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3004 // This is a variant of the check for xor with -1, and it handles
3005 // the case where instcombine has trimmed non-demanded bits out
3006 // of an xor with -1.
3007 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3008 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3009 if (BO->getOpcode() == Instruction::And &&
3010 LCI->getValue() == CI->getValue())
3011 if (const SCEVZeroExtendExpr *Z =
3012 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
3013 const Type *UTy = U->getType();
3014 const SCEV *Z0 = Z->getOperand();
3015 const Type *Z0Ty = Z0->getType();
3016 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3018 // If C is a low-bits mask, the zero extend is zerving to
3019 // mask off the high bits. Complement the operand and
3020 // re-apply the zext.
3021 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3022 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3024 // If C is a single bit, it may be in the sign-bit position
3025 // before the zero-extend. In this case, represent the xor
3026 // using an add, which is equivalent, and re-apply the zext.
3027 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
3028 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3030 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3036 case Instruction::Shl:
3037 // Turn shift left of a constant amount into a multiply.
3038 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3039 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
3040 Constant *X = ConstantInt::get(getContext(),
3041 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
3042 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3046 case Instruction::LShr:
3047 // Turn logical shift right of a constant into a unsigned divide.
3048 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3049 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
3050 Constant *X = ConstantInt::get(getContext(),
3051 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
3052 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3056 case Instruction::AShr:
3057 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3058 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
3059 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
3060 if (L->getOpcode() == Instruction::Shl &&
3061 L->getOperand(1) == U->getOperand(1)) {
3062 unsigned BitWidth = getTypeSizeInBits(U->getType());
3063 uint64_t Amt = BitWidth - CI->getZExtValue();
3064 if (Amt == BitWidth)
3065 return getSCEV(L->getOperand(0)); // shift by zero --> noop
3067 return getIntegerSCEV(0, U->getType()); // value is undefined
3069 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
3070 IntegerType::get(getContext(), Amt)),
3075 case Instruction::Trunc:
3076 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
3078 case Instruction::ZExt:
3079 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3081 case Instruction::SExt:
3082 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3084 case Instruction::BitCast:
3085 // BitCasts are no-op casts so we just eliminate the cast.
3086 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
3087 return getSCEV(U->getOperand(0));
3090 // It's tempting to handle inttoptr and ptrtoint, however this can
3091 // lead to pointer expressions which cannot be expanded to GEPs
3092 // (because they may overflow). For now, the only pointer-typed
3093 // expressions we handle are GEPs and address literals.
3095 case Instruction::GetElementPtr:
3096 return createNodeForGEP(U);
3098 case Instruction::PHI:
3099 return createNodeForPHI(cast<PHINode>(U));
3101 case Instruction::Select:
3102 // This could be a smax or umax that was lowered earlier.
3103 // Try to recover it.
3104 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3105 Value *LHS = ICI->getOperand(0);
3106 Value *RHS = ICI->getOperand(1);
3107 switch (ICI->getPredicate()) {
3108 case ICmpInst::ICMP_SLT:
3109 case ICmpInst::ICMP_SLE:
3110 std::swap(LHS, RHS);
3112 case ICmpInst::ICMP_SGT:
3113 case ICmpInst::ICMP_SGE:
3114 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
3115 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
3116 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
3117 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
3119 case ICmpInst::ICMP_ULT:
3120 case ICmpInst::ICMP_ULE:
3121 std::swap(LHS, RHS);
3123 case ICmpInst::ICMP_UGT:
3124 case ICmpInst::ICMP_UGE:
3125 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
3126 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
3127 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
3128 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
3130 case ICmpInst::ICMP_NE:
3131 // n != 0 ? n : 1 -> umax(n, 1)
3132 if (LHS == U->getOperand(1) &&
3133 isa<ConstantInt>(U->getOperand(2)) &&
3134 cast<ConstantInt>(U->getOperand(2))->isOne() &&
3135 isa<ConstantInt>(RHS) &&
3136 cast<ConstantInt>(RHS)->isZero())
3137 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
3139 case ICmpInst::ICMP_EQ:
3140 // n == 0 ? 1 : n -> umax(n, 1)
3141 if (LHS == U->getOperand(2) &&
3142 isa<ConstantInt>(U->getOperand(1)) &&
3143 cast<ConstantInt>(U->getOperand(1))->isOne() &&
3144 isa<ConstantInt>(RHS) &&
3145 cast<ConstantInt>(RHS)->isZero())
3146 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
3153 default: // We cannot analyze this expression.
3157 return getUnknown(V);
3162 //===----------------------------------------------------------------------===//
3163 // Iteration Count Computation Code
3166 /// getBackedgeTakenCount - If the specified loop has a predictable
3167 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3168 /// object. The backedge-taken count is the number of times the loop header
3169 /// will be branched to from within the loop. This is one less than the
3170 /// trip count of the loop, since it doesn't count the first iteration,
3171 /// when the header is branched to from outside the loop.
3173 /// Note that it is not valid to call this method on a loop without a
3174 /// loop-invariant backedge-taken count (see
3175 /// hasLoopInvariantBackedgeTakenCount).
3177 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
3178 return getBackedgeTakenInfo(L).Exact;
3181 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3182 /// return the least SCEV value that is known never to be less than the
3183 /// actual backedge taken count.
3184 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
3185 return getBackedgeTakenInfo(L).Max;
3188 /// PushLoopPHIs - Push PHI nodes in the header of the given loop
3189 /// onto the given Worklist.
3191 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3192 BasicBlock *Header = L->getHeader();
3194 // Push all Loop-header PHIs onto the Worklist stack.
3195 for (BasicBlock::iterator I = Header->begin();
3196 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3197 Worklist.push_back(PN);
3200 const ScalarEvolution::BackedgeTakenInfo &
3201 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
3202 // Initially insert a CouldNotCompute for this loop. If the insertion
3203 // succeeds, procede to actually compute a backedge-taken count and
3204 // update the value. The temporary CouldNotCompute value tells SCEV
3205 // code elsewhere that it shouldn't attempt to request a new
3206 // backedge-taken count, which could result in infinite recursion.
3207 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
3208 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3210 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
3211 if (ItCount.Exact != getCouldNotCompute()) {
3212 assert(ItCount.Exact->isLoopInvariant(L) &&
3213 ItCount.Max->isLoopInvariant(L) &&
3214 "Computed trip count isn't loop invariant for loop!");
3215 ++NumTripCountsComputed;
3217 // Update the value in the map.
3218 Pair.first->second = ItCount;
3220 if (ItCount.Max != getCouldNotCompute())
3221 // Update the value in the map.
3222 Pair.first->second = ItCount;
3223 if (isa<PHINode>(L->getHeader()->begin()))
3224 // Only count loops that have phi nodes as not being computable.
3225 ++NumTripCountsNotComputed;
3228 // Now that we know more about the trip count for this loop, forget any
3229 // existing SCEV values for PHI nodes in this loop since they are only
3230 // conservative estimates made without the benefit of trip count
3231 // information. This is similar to the code in
3232 // forgetLoopBackedgeTakenCount, except that it handles SCEVUnknown PHI
3234 if (ItCount.hasAnyInfo()) {
3235 SmallVector<Instruction *, 16> Worklist;
3236 PushLoopPHIs(L, Worklist);
3238 SmallPtrSet<Instruction *, 8> Visited;
3239 while (!Worklist.empty()) {
3240 Instruction *I = Worklist.pop_back_val();
3241 if (!Visited.insert(I)) continue;
3243 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
3244 Scalars.find(static_cast<Value *>(I));
3245 if (It != Scalars.end()) {
3246 // SCEVUnknown for a PHI either means that it has an unrecognized
3247 // structure, or it's a PHI that's in the progress of being computed
3248 // by createNodeForPHI. In the former case, additional loop trip
3249 // count information isn't going to change anything. In the later
3250 // case, createNodeForPHI will perform the necessary updates on its
3251 // own when it gets to that point.
3252 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
3253 ValuesAtScopes.erase(It->second);
3256 if (PHINode *PN = dyn_cast<PHINode>(I))
3257 ConstantEvolutionLoopExitValue.erase(PN);
3260 PushDefUseChildren(I, Worklist);
3264 return Pair.first->second;
3267 /// forgetLoopBackedgeTakenCount - This method should be called by the
3268 /// client when it has changed a loop in a way that may effect
3269 /// ScalarEvolution's ability to compute a trip count, or if the loop
3271 void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
3272 BackedgeTakenCounts.erase(L);
3274 SmallVector<Instruction *, 16> Worklist;
3275 PushLoopPHIs(L, Worklist);
3277 SmallPtrSet<Instruction *, 8> Visited;
3278 while (!Worklist.empty()) {
3279 Instruction *I = Worklist.pop_back_val();
3280 if (!Visited.insert(I)) continue;
3282 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
3283 Scalars.find(static_cast<Value *>(I));
3284 if (It != Scalars.end()) {
3285 ValuesAtScopes.erase(It->second);
3287 if (PHINode *PN = dyn_cast<PHINode>(I))
3288 ConstantEvolutionLoopExitValue.erase(PN);
3291 PushDefUseChildren(I, Worklist);
3295 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
3296 /// of the specified loop will execute.
3297 ScalarEvolution::BackedgeTakenInfo
3298 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
3299 SmallVector<BasicBlock*, 8> ExitingBlocks;
3300 L->getExitingBlocks(ExitingBlocks);
3302 // Examine all exits and pick the most conservative values.
3303 const SCEV *BECount = getCouldNotCompute();
3304 const SCEV *MaxBECount = getCouldNotCompute();
3305 bool CouldNotComputeBECount = false;
3306 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3307 BackedgeTakenInfo NewBTI =
3308 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
3310 if (NewBTI.Exact == getCouldNotCompute()) {
3311 // We couldn't compute an exact value for this exit, so
3312 // we won't be able to compute an exact value for the loop.
3313 CouldNotComputeBECount = true;
3314 BECount = getCouldNotCompute();
3315 } else if (!CouldNotComputeBECount) {
3316 if (BECount == getCouldNotCompute())
3317 BECount = NewBTI.Exact;
3319 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
3321 if (MaxBECount == getCouldNotCompute())
3322 MaxBECount = NewBTI.Max;
3323 else if (NewBTI.Max != getCouldNotCompute())
3324 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
3327 return BackedgeTakenInfo(BECount, MaxBECount);
3330 /// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3331 /// of the specified loop will execute if it exits via the specified block.
3332 ScalarEvolution::BackedgeTakenInfo
3333 ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3334 BasicBlock *ExitingBlock) {
3336 // Okay, we've chosen an exiting block. See what condition causes us to
3337 // exit at this block.
3339 // FIXME: we should be able to handle switch instructions (with a single exit)
3340 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
3341 if (ExitBr == 0) return getCouldNotCompute();
3342 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
3344 // At this point, we know we have a conditional branch that determines whether
3345 // the loop is exited. However, we don't know if the branch is executed each
3346 // time through the loop. If not, then the execution count of the branch will
3347 // not be equal to the trip count of the loop.
3349 // Currently we check for this by checking to see if the Exit branch goes to
3350 // the loop header. If so, we know it will always execute the same number of
3351 // times as the loop. We also handle the case where the exit block *is* the
3352 // loop header. This is common for un-rotated loops.
3354 // If both of those tests fail, walk up the unique predecessor chain to the
3355 // header, stopping if there is an edge that doesn't exit the loop. If the
3356 // header is reached, the execution count of the branch will be equal to the
3357 // trip count of the loop.
3359 // More extensive analysis could be done to handle more cases here.
3361 if (ExitBr->getSuccessor(0) != L->getHeader() &&
3362 ExitBr->getSuccessor(1) != L->getHeader() &&
3363 ExitBr->getParent() != L->getHeader()) {
3364 // The simple checks failed, try climbing the unique predecessor chain
3365 // up to the header.
3367 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3368 BasicBlock *Pred = BB->getUniquePredecessor();
3370 return getCouldNotCompute();
3371 TerminatorInst *PredTerm = Pred->getTerminator();
3372 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3373 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3376 // If the predecessor has a successor that isn't BB and isn't
3377 // outside the loop, assume the worst.
3378 if (L->contains(PredSucc))
3379 return getCouldNotCompute();
3381 if (Pred == L->getHeader()) {
3388 return getCouldNotCompute();
3391 // Procede to the next level to examine the exit condition expression.
3392 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3393 ExitBr->getSuccessor(0),
3394 ExitBr->getSuccessor(1));
3397 /// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3398 /// backedge of the specified loop will execute if its exit condition
3399 /// were a conditional branch of ExitCond, TBB, and FBB.
3400 ScalarEvolution::BackedgeTakenInfo
3401 ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3405 // Check if the controlling expression for this loop is an And or Or.
3406 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3407 if (BO->getOpcode() == Instruction::And) {
3408 // Recurse on the operands of the and.
3409 BackedgeTakenInfo BTI0 =
3410 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3411 BackedgeTakenInfo BTI1 =
3412 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3413 const SCEV *BECount = getCouldNotCompute();
3414 const SCEV *MaxBECount = getCouldNotCompute();
3415 if (L->contains(TBB)) {
3416 // Both conditions must be true for the loop to continue executing.
3417 // Choose the less conservative count.
3418 if (BTI0.Exact == getCouldNotCompute() ||
3419 BTI1.Exact == getCouldNotCompute())
3420 BECount = getCouldNotCompute();
3422 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3423 if (BTI0.Max == getCouldNotCompute())
3424 MaxBECount = BTI1.Max;
3425 else if (BTI1.Max == getCouldNotCompute())
3426 MaxBECount = BTI0.Max;
3428 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3430 // Both conditions must be true for the loop to exit.
3431 assert(L->contains(FBB) && "Loop block has no successor in loop!");
3432 if (BTI0.Exact != getCouldNotCompute() &&
3433 BTI1.Exact != getCouldNotCompute())
3434 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3435 if (BTI0.Max != getCouldNotCompute() &&
3436 BTI1.Max != getCouldNotCompute())
3437 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3440 return BackedgeTakenInfo(BECount, MaxBECount);
3442 if (BO->getOpcode() == Instruction::Or) {
3443 // Recurse on the operands of the or.
3444 BackedgeTakenInfo BTI0 =
3445 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3446 BackedgeTakenInfo BTI1 =
3447 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3448 const SCEV *BECount = getCouldNotCompute();
3449 const SCEV *MaxBECount = getCouldNotCompute();
3450 if (L->contains(FBB)) {
3451 // Both conditions must be false for the loop to continue executing.
3452 // Choose the less conservative count.
3453 if (BTI0.Exact == getCouldNotCompute() ||
3454 BTI1.Exact == getCouldNotCompute())
3455 BECount = getCouldNotCompute();
3457 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3458 if (BTI0.Max == getCouldNotCompute())
3459 MaxBECount = BTI1.Max;
3460 else if (BTI1.Max == getCouldNotCompute())
3461 MaxBECount = BTI0.Max;
3463 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3465 // Both conditions must be false for the loop to exit.
3466 assert(L->contains(TBB) && "Loop block has no successor in loop!");
3467 if (BTI0.Exact != getCouldNotCompute() &&
3468 BTI1.Exact != getCouldNotCompute())
3469 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3470 if (BTI0.Max != getCouldNotCompute() &&
3471 BTI1.Max != getCouldNotCompute())
3472 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3475 return BackedgeTakenInfo(BECount, MaxBECount);
3479 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3480 // Procede to the next level to examine the icmp.
3481 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3482 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
3484 // If it's not an integer or pointer comparison then compute it the hard way.
3485 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3488 /// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3489 /// backedge of the specified loop will execute if its exit condition
3490 /// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3491 ScalarEvolution::BackedgeTakenInfo
3492 ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3497 // If the condition was exit on true, convert the condition to exit on false
3498 ICmpInst::Predicate Cond;
3499 if (!L->contains(FBB))
3500 Cond = ExitCond->getPredicate();
3502 Cond = ExitCond->getInversePredicate();
3504 // Handle common loops like: for (X = "string"; *X; ++X)
3505 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3506 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
3508 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
3509 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
3510 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
3511 return BackedgeTakenInfo(ItCnt,
3512 isa<SCEVConstant>(ItCnt) ? ItCnt :
3513 getConstant(APInt::getMaxValue(BitWidth)-1));
3517 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3518 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
3520 // Try to evaluate any dependencies out of the loop.
3521 LHS = getSCEVAtScope(LHS, L);
3522 RHS = getSCEVAtScope(RHS, L);
3524 // At this point, we would like to compute how many iterations of the
3525 // loop the predicate will return true for these inputs.
3526 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3527 // If there is a loop-invariant, force it into the RHS.
3528 std::swap(LHS, RHS);
3529 Cond = ICmpInst::getSwappedPredicate(Cond);
3532 // If we have a comparison of a chrec against a constant, try to use value
3533 // ranges to answer this query.
3534 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3535 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
3536 if (AddRec->getLoop() == L) {
3537 // Form the constant range.
3538 ConstantRange CompRange(
3539 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
3541 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
3542 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
3546 case ICmpInst::ICMP_NE: { // while (X != Y)
3547 // Convert to: while (X-Y != 0)
3548 const SCEV *TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
3549 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3552 case ICmpInst::ICMP_EQ: { // while (X == Y)
3553 // Convert to: while (X-Y == 0)
3554 const SCEV *TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
3555 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3558 case ICmpInst::ICMP_SLT: {
3559 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3560 if (BTI.hasAnyInfo()) return BTI;
3563 case ICmpInst::ICMP_SGT: {
3564 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3565 getNotSCEV(RHS), L, true);
3566 if (BTI.hasAnyInfo()) return BTI;
3569 case ICmpInst::ICMP_ULT: {
3570 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3571 if (BTI.hasAnyInfo()) return BTI;
3574 case ICmpInst::ICMP_UGT: {
3575 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3576 getNotSCEV(RHS), L, false);
3577 if (BTI.hasAnyInfo()) return BTI;
3582 errs() << "ComputeBackedgeTakenCount ";
3583 if (ExitCond->getOperand(0)->getType()->isUnsigned())
3584 errs() << "[unsigned] ";
3585 errs() << *LHS << " "
3586 << Instruction::getOpcodeName(Instruction::ICmp)
3587 << " " << *RHS << "\n";
3592 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3595 static ConstantInt *
3596 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3597 ScalarEvolution &SE) {
3598 const SCEV *InVal = SE.getConstant(C);
3599 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
3600 assert(isa<SCEVConstant>(Val) &&
3601 "Evaluation of SCEV at constant didn't fold correctly?");
3602 return cast<SCEVConstant>(Val)->getValue();
3605 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
3606 /// and a GEP expression (missing the pointer index) indexing into it, return
3607 /// the addressed element of the initializer or null if the index expression is
3610 GetAddressedElementFromGlobal(LLVMContext &Context, GlobalVariable *GV,
3611 const std::vector<ConstantInt*> &Indices) {
3612 Constant *Init = GV->getInitializer();
3613 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
3614 uint64_t Idx = Indices[i]->getZExtValue();
3615 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3616 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3617 Init = cast<Constant>(CS->getOperand(Idx));
3618 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3619 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3620 Init = cast<Constant>(CA->getOperand(Idx));
3621 } else if (isa<ConstantAggregateZero>(Init)) {
3622 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3623 assert(Idx < STy->getNumElements() && "Bad struct index!");
3624 Init = Constant::getNullValue(STy->getElementType(Idx));
3625 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3626 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
3627 Init = Constant::getNullValue(ATy->getElementType());
3629 llvm_unreachable("Unknown constant aggregate type!");
3633 return 0; // Unknown initializer type
3639 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3640 /// 'icmp op load X, cst', try to see if we can compute the backedge
3641 /// execution count.
3643 ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3647 ICmpInst::Predicate predicate) {
3648 if (LI->isVolatile()) return getCouldNotCompute();
3650 // Check to see if the loaded pointer is a getelementptr of a global.
3651 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
3652 if (!GEP) return getCouldNotCompute();
3654 // Make sure that it is really a constant global we are gepping, with an
3655 // initializer, and make sure the first IDX is really 0.
3656 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
3657 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
3658 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3659 !cast<Constant>(GEP->getOperand(1))->isNullValue())
3660 return getCouldNotCompute();
3662 // Okay, we allow one non-constant index into the GEP instruction.
3664 std::vector<ConstantInt*> Indexes;
3665 unsigned VarIdxNum = 0;
3666 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3667 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3668 Indexes.push_back(CI);
3669 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
3670 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
3671 VarIdx = GEP->getOperand(i);
3673 Indexes.push_back(0);
3676 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3677 // Check to see if X is a loop variant variable value now.
3678 const SCEV *Idx = getSCEV(VarIdx);
3679 Idx = getSCEVAtScope(Idx, L);
3681 // We can only recognize very limited forms of loop index expressions, in
3682 // particular, only affine AddRec's like {C1,+,C2}.
3683 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
3684 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3685 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3686 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
3687 return getCouldNotCompute();
3689 unsigned MaxSteps = MaxBruteForceIterations;
3690 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
3691 ConstantInt *ItCst = ConstantInt::get(
3692 cast<IntegerType>(IdxExpr->getType()), IterationNum);
3693 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
3695 // Form the GEP offset.
3696 Indexes[VarIdxNum] = Val;
3698 Constant *Result = GetAddressedElementFromGlobal(getContext(), GV, Indexes);
3699 if (Result == 0) break; // Cannot compute!
3701 // Evaluate the condition for this iteration.
3702 Result = ConstantExpr::getICmp(predicate, Result, RHS);
3703 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
3704 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
3706 errs() << "\n***\n*** Computed loop count " << *ItCst
3707 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3710 ++NumArrayLenItCounts;
3711 return getConstant(ItCst); // Found terminating iteration!
3714 return getCouldNotCompute();
3718 /// CanConstantFold - Return true if we can constant fold an instruction of the
3719 /// specified type, assuming that all operands were constants.
3720 static bool CanConstantFold(const Instruction *I) {
3721 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
3722 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3725 if (const CallInst *CI = dyn_cast<CallInst>(I))
3726 if (const Function *F = CI->getCalledFunction())
3727 return canConstantFoldCallTo(F);
3731 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3732 /// in the loop that V is derived from. We allow arbitrary operations along the
3733 /// way, but the operands of an operation must either be constants or a value
3734 /// derived from a constant PHI. If this expression does not fit with these
3735 /// constraints, return null.
3736 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3737 // If this is not an instruction, or if this is an instruction outside of the
3738 // loop, it can't be derived from a loop PHI.
3739 Instruction *I = dyn_cast<Instruction>(V);
3740 if (I == 0 || !L->contains(I->getParent())) return 0;
3742 if (PHINode *PN = dyn_cast<PHINode>(I)) {
3743 if (L->getHeader() == I->getParent())
3746 // We don't currently keep track of the control flow needed to evaluate
3747 // PHIs, so we cannot handle PHIs inside of loops.
3751 // If we won't be able to constant fold this expression even if the operands
3752 // are constants, return early.
3753 if (!CanConstantFold(I)) return 0;
3755 // Otherwise, we can evaluate this instruction if all of its operands are
3756 // constant or derived from a PHI node themselves.
3758 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3759 if (!(isa<Constant>(I->getOperand(Op)) ||
3760 isa<GlobalValue>(I->getOperand(Op)))) {
3761 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3762 if (P == 0) return 0; // Not evolving from PHI
3766 return 0; // Evolving from multiple different PHIs.
3769 // This is a expression evolving from a constant PHI!
3773 /// EvaluateExpression - Given an expression that passes the
3774 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3775 /// in the loop has the value PHIVal. If we can't fold this expression for some
3776 /// reason, return null.
3777 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3778 if (isa<PHINode>(V)) return PHIVal;
3779 if (Constant *C = dyn_cast<Constant>(V)) return C;
3780 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
3781 Instruction *I = cast<Instruction>(V);
3782 LLVMContext &Context = I->getParent()->getContext();
3784 std::vector<Constant*> Operands;
3785 Operands.resize(I->getNumOperands());
3787 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3788 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3789 if (Operands[i] == 0) return 0;
3792 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3793 return ConstantFoldCompareInstOperands(CI->getPredicate(),
3794 &Operands[0], Operands.size(),
3797 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3798 &Operands[0], Operands.size(),
3802 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3803 /// in the header of its containing loop, we know the loop executes a
3804 /// constant number of times, and the PHI node is just a recurrence
3805 /// involving constants, fold it.
3807 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
3810 std::map<PHINode*, Constant*>::iterator I =
3811 ConstantEvolutionLoopExitValue.find(PN);
3812 if (I != ConstantEvolutionLoopExitValue.end())
3815 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
3816 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3818 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3820 // Since the loop is canonicalized, the PHI node must have two entries. One
3821 // entry must be a constant (coming in from outside of the loop), and the
3822 // second must be derived from the same PHI.
3823 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3824 Constant *StartCST =
3825 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3827 return RetVal = 0; // Must be a constant.
3829 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3830 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3832 return RetVal = 0; // Not derived from same PHI.
3834 // Execute the loop symbolically to determine the exit value.
3835 if (BEs.getActiveBits() >= 32)
3836 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
3838 unsigned NumIterations = BEs.getZExtValue(); // must be in range
3839 unsigned IterationNum = 0;
3840 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3841 if (IterationNum == NumIterations)
3842 return RetVal = PHIVal; // Got exit value!
3844 // Compute the value of the PHI node for the next iteration.
3845 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3846 if (NextPHI == PHIVal)
3847 return RetVal = NextPHI; // Stopped evolving!
3849 return 0; // Couldn't evaluate!
3854 /// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
3855 /// constant number of times (the condition evolves only from constants),
3856 /// try to evaluate a few iterations of the loop until we get the exit
3857 /// condition gets a value of ExitWhen (true or false). If we cannot
3858 /// evaluate the trip count of the loop, return getCouldNotCompute().
3860 ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
3863 PHINode *PN = getConstantEvolvingPHI(Cond, L);
3864 if (PN == 0) return getCouldNotCompute();
3866 // Since the loop is canonicalized, the PHI node must have two entries. One
3867 // entry must be a constant (coming in from outside of the loop), and the
3868 // second must be derived from the same PHI.
3869 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3870 Constant *StartCST =
3871 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3872 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
3874 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3875 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3876 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
3878 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3879 // the loop symbolically to determine when the condition gets a value of
3881 unsigned IterationNum = 0;
3882 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3883 for (Constant *PHIVal = StartCST;
3884 IterationNum != MaxIterations; ++IterationNum) {
3885 ConstantInt *CondVal =
3886 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
3888 // Couldn't symbolically evaluate.
3889 if (!CondVal) return getCouldNotCompute();
3891 if (CondVal->getValue() == uint64_t(ExitWhen)) {
3892 ++NumBruteForceTripCountsComputed;
3893 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
3896 // Compute the value of the PHI node for the next iteration.
3897 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3898 if (NextPHI == 0 || NextPHI == PHIVal)
3899 return getCouldNotCompute();// Couldn't evaluate or not making progress...
3903 // Too many iterations were needed to evaluate.
3904 return getCouldNotCompute();
3907 /// getSCEVAtScope - Return a SCEV expression for the specified value
3908 /// at the specified scope in the program. The L value specifies a loop
3909 /// nest to evaluate the expression at, where null is the top-level or a
3910 /// specified loop is immediately inside of the loop.
3912 /// This method can be used to compute the exit value for a variable defined
3913 /// in a loop by querying what the value will hold in the parent loop.
3915 /// In the case that a relevant loop exit value cannot be computed, the
3916 /// original value V is returned.
3917 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
3918 // Check to see if we've folded this expression at this loop before.
3919 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
3920 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
3921 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
3923 return Pair.first->second ? Pair.first->second : V;
3925 // Otherwise compute it.
3926 const SCEV *C = computeSCEVAtScope(V, L);
3927 ValuesAtScopes[V][L] = C;
3931 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
3932 if (isa<SCEVConstant>(V)) return V;
3934 // If this instruction is evolved from a constant-evolving PHI, compute the
3935 // exit value from the loop without using SCEVs.
3936 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
3937 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
3938 const Loop *LI = (*this->LI)[I->getParent()];
3939 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3940 if (PHINode *PN = dyn_cast<PHINode>(I))
3941 if (PN->getParent() == LI->getHeader()) {
3942 // Okay, there is no closed form solution for the PHI node. Check
3943 // to see if the loop that contains it has a known backedge-taken
3944 // count. If so, we may be able to force computation of the exit
3946 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
3947 if (const SCEVConstant *BTCC =
3948 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
3949 // Okay, we know how many times the containing loop executes. If
3950 // this is a constant evolving PHI node, get the final value at
3951 // the specified iteration number.
3952 Constant *RV = getConstantEvolutionLoopExitValue(PN,
3953 BTCC->getValue()->getValue(),
3955 if (RV) return getSCEV(RV);
3959 // Okay, this is an expression that we cannot symbolically evaluate
3960 // into a SCEV. Check to see if it's possible to symbolically evaluate
3961 // the arguments into constants, and if so, try to constant propagate the
3962 // result. This is particularly useful for computing loop exit values.
3963 if (CanConstantFold(I)) {
3964 std::vector<Constant*> Operands;
3965 Operands.reserve(I->getNumOperands());
3966 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3967 Value *Op = I->getOperand(i);
3968 if (Constant *C = dyn_cast<Constant>(Op)) {
3969 Operands.push_back(C);
3971 // If any of the operands is non-constant and if they are
3972 // non-integer and non-pointer, don't even try to analyze them
3973 // with scev techniques.
3974 if (!isSCEVable(Op->getType()))
3977 const SCEV* OpV = getSCEVAtScope(Op, L);
3978 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
3979 Constant *C = SC->getValue();
3980 if (C->getType() != Op->getType())
3981 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3985 Operands.push_back(C);
3986 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
3987 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3988 if (C->getType() != Op->getType())
3990 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3994 Operands.push_back(C);
4004 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4005 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
4006 &Operands[0], Operands.size(),
4009 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4010 &Operands[0], Operands.size(),
4016 // This is some other type of SCEVUnknown, just return it.
4020 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
4021 // Avoid performing the look-up in the common case where the specified
4022 // expression has no loop-variant portions.
4023 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
4024 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
4025 if (OpAtScope != Comm->getOperand(i)) {
4026 // Okay, at least one of these operands is loop variant but might be
4027 // foldable. Build a new instance of the folded commutative expression.
4028 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4029 Comm->op_begin()+i);
4030 NewOps.push_back(OpAtScope);
4032 for (++i; i != e; ++i) {
4033 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
4034 NewOps.push_back(OpAtScope);
4036 if (isa<SCEVAddExpr>(Comm))
4037 return getAddExpr(NewOps);
4038 if (isa<SCEVMulExpr>(Comm))
4039 return getMulExpr(NewOps);
4040 if (isa<SCEVSMaxExpr>(Comm))
4041 return getSMaxExpr(NewOps);
4042 if (isa<SCEVUMaxExpr>(Comm))
4043 return getUMaxExpr(NewOps);
4044 llvm_unreachable("Unknown commutative SCEV type!");
4047 // If we got here, all operands are loop invariant.
4051 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
4052 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4053 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
4054 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4055 return Div; // must be loop invariant
4056 return getUDivExpr(LHS, RHS);
4059 // If this is a loop recurrence for a loop that does not contain L, then we
4060 // are dealing with the final value computed by the loop.
4061 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4062 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
4063 // To evaluate this recurrence, we need to know how many times the AddRec
4064 // loop iterates. Compute this now.
4065 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
4066 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
4068 // Then, evaluate the AddRec.
4069 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
4074 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
4075 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4076 if (Op == Cast->getOperand())
4077 return Cast; // must be loop invariant
4078 return getZeroExtendExpr(Op, Cast->getType());
4081 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
4082 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4083 if (Op == Cast->getOperand())
4084 return Cast; // must be loop invariant
4085 return getSignExtendExpr(Op, Cast->getType());
4088 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
4089 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4090 if (Op == Cast->getOperand())
4091 return Cast; // must be loop invariant
4092 return getTruncateExpr(Op, Cast->getType());
4095 if (isa<SCEVTargetDataConstant>(V))
4098 llvm_unreachable("Unknown SCEV type!");
4102 /// getSCEVAtScope - This is a convenience function which does
4103 /// getSCEVAtScope(getSCEV(V), L).
4104 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
4105 return getSCEVAtScope(getSCEV(V), L);
4108 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4109 /// following equation:
4111 /// A * X = B (mod N)
4113 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4114 /// A and B isn't important.
4116 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
4117 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
4118 ScalarEvolution &SE) {
4119 uint32_t BW = A.getBitWidth();
4120 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4121 assert(A != 0 && "A must be non-zero.");
4125 // The gcd of A and N may have only one prime factor: 2. The number of
4126 // trailing zeros in A is its multiplicity
4127 uint32_t Mult2 = A.countTrailingZeros();
4130 // 2. Check if B is divisible by D.
4132 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4133 // is not less than multiplicity of this prime factor for D.
4134 if (B.countTrailingZeros() < Mult2)
4135 return SE.getCouldNotCompute();
4137 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4140 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4141 // bit width during computations.
4142 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4143 APInt Mod(BW + 1, 0);
4144 Mod.set(BW - Mult2); // Mod = N / D
4145 APInt I = AD.multiplicativeInverse(Mod);
4147 // 4. Compute the minimum unsigned root of the equation:
4148 // I * (B / D) mod (N / D)
4149 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4151 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4153 return SE.getConstant(Result.trunc(BW));
4156 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4157 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4158 /// might be the same) or two SCEVCouldNotCompute objects.
4160 static std::pair<const SCEV *,const SCEV *>
4161 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
4162 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
4163 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4164 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4165 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
4167 // We currently can only solve this if the coefficients are constants.
4168 if (!LC || !MC || !NC) {
4169 const SCEV *CNC = SE.getCouldNotCompute();
4170 return std::make_pair(CNC, CNC);
4173 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
4174 const APInt &L = LC->getValue()->getValue();
4175 const APInt &M = MC->getValue()->getValue();
4176 const APInt &N = NC->getValue()->getValue();
4177 APInt Two(BitWidth, 2);
4178 APInt Four(BitWidth, 4);
4181 using namespace APIntOps;
4183 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4184 // The B coefficient is M-N/2
4188 // The A coefficient is N/2
4189 APInt A(N.sdiv(Two));
4191 // Compute the B^2-4ac term.
4194 SqrtTerm -= Four * (A * C);
4196 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4197 // integer value or else APInt::sqrt() will assert.
4198 APInt SqrtVal(SqrtTerm.sqrt());
4200 // Compute the two solutions for the quadratic formula.
4201 // The divisions must be performed as signed divisions.
4203 APInt TwoA( A << 1 );
4204 if (TwoA.isMinValue()) {
4205 const SCEV *CNC = SE.getCouldNotCompute();
4206 return std::make_pair(CNC, CNC);
4209 LLVMContext &Context = SE.getContext();
4211 ConstantInt *Solution1 =
4212 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
4213 ConstantInt *Solution2 =
4214 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
4216 return std::make_pair(SE.getConstant(Solution1),
4217 SE.getConstant(Solution2));
4218 } // end APIntOps namespace
4221 /// HowFarToZero - Return the number of times a backedge comparing the specified
4222 /// value to zero will execute. If not computable, return CouldNotCompute.
4223 const SCEV *ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
4224 // If the value is a constant
4225 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
4226 // If the value is already zero, the branch will execute zero times.
4227 if (C->getValue()->isZero()) return C;
4228 return getCouldNotCompute(); // Otherwise it will loop infinitely.
4231 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
4232 if (!AddRec || AddRec->getLoop() != L)
4233 return getCouldNotCompute();
4235 if (AddRec->isAffine()) {
4236 // If this is an affine expression, the execution count of this branch is
4237 // the minimum unsigned root of the following equation:
4239 // Start + Step*N = 0 (mod 2^BW)
4243 // Step*N = -Start (mod 2^BW)
4245 // where BW is the common bit width of Start and Step.
4247 // Get the initial value for the loop.
4248 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4249 L->getParentLoop());
4250 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4251 L->getParentLoop());
4253 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
4254 // For now we handle only constant steps.
4256 // First, handle unitary steps.
4257 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
4258 return getNegativeSCEV(Start); // N = -Start (as unsigned)
4259 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4260 return Start; // N = Start (as unsigned)
4262 // Then, try to solve the above equation provided that Start is constant.
4263 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
4264 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
4265 -StartC->getValue()->getValue(),
4268 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
4269 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4270 // the quadratic equation to solve it.
4271 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
4273 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4274 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
4277 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
4278 << " sol#2: " << *R2 << "\n";
4280 // Pick the smallest positive root value.
4281 if (ConstantInt *CB =
4282 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
4283 R1->getValue(), R2->getValue()))) {
4284 if (CB->getZExtValue() == false)
4285 std::swap(R1, R2); // R1 is the minimum root now.
4287 // We can only use this value if the chrec ends up with an exact zero
4288 // value at this index. When solving for "X*X != 5", for example, we
4289 // should not accept a root of 2.
4290 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
4292 return R1; // We found a quadratic root!
4297 return getCouldNotCompute();
4300 /// HowFarToNonZero - Return the number of times a backedge checking the
4301 /// specified value for nonzero will execute. If not computable, return
4303 const SCEV *ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
4304 // Loops that look like: while (X == 0) are very strange indeed. We don't
4305 // handle them yet except for the trivial case. This could be expanded in the
4306 // future as needed.
4308 // If the value is a constant, check to see if it is known to be non-zero
4309 // already. If so, the backedge will execute zero times.
4310 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
4311 if (!C->getValue()->isNullValue())
4312 return getIntegerSCEV(0, C->getType());
4313 return getCouldNotCompute(); // Otherwise it will loop infinitely.
4316 // We could implement others, but I really doubt anyone writes loops like
4317 // this, and if they did, they would already be constant folded.
4318 return getCouldNotCompute();
4321 /// getLoopPredecessor - If the given loop's header has exactly one unique
4322 /// predecessor outside the loop, return it. Otherwise return null.
4324 BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
4325 BasicBlock *Header = L->getHeader();
4326 BasicBlock *Pred = 0;
4327 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
4329 if (!L->contains(*PI)) {
4330 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
4336 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4337 /// (which may not be an immediate predecessor) which has exactly one
4338 /// successor from which BB is reachable, or null if no such block is
4342 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
4343 // If the block has a unique predecessor, then there is no path from the
4344 // predecessor to the block that does not go through the direct edge
4345 // from the predecessor to the block.
4346 if (BasicBlock *Pred = BB->getSinglePredecessor())
4349 // A loop's header is defined to be a block that dominates the loop.
4350 // If the header has a unique predecessor outside the loop, it must be
4351 // a block that has exactly one successor that can reach the loop.
4352 if (Loop *L = LI->getLoopFor(BB))
4353 return getLoopPredecessor(L);
4358 /// HasSameValue - SCEV structural equivalence is usually sufficient for
4359 /// testing whether two expressions are equal, however for the purposes of
4360 /// looking for a condition guarding a loop, it can be useful to be a little
4361 /// more general, since a front-end may have replicated the controlling
4364 static bool HasSameValue(const SCEV *A, const SCEV *B) {
4365 // Quick check to see if they are the same SCEV.
4366 if (A == B) return true;
4368 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4369 // two different instructions with the same value. Check for this case.
4370 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4371 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4372 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4373 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
4374 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
4377 // Otherwise assume they may have a different value.
4381 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
4382 return getSignedRange(S).getSignedMax().isNegative();
4385 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
4386 return getSignedRange(S).getSignedMin().isStrictlyPositive();
4389 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
4390 return !getSignedRange(S).getSignedMin().isNegative();
4393 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
4394 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
4397 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
4398 return isKnownNegative(S) || isKnownPositive(S);
4401 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
4402 const SCEV *LHS, const SCEV *RHS) {
4404 if (HasSameValue(LHS, RHS))
4405 return ICmpInst::isTrueWhenEqual(Pred);
4409 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4411 case ICmpInst::ICMP_SGT:
4412 Pred = ICmpInst::ICMP_SLT;
4413 std::swap(LHS, RHS);
4414 case ICmpInst::ICMP_SLT: {
4415 ConstantRange LHSRange = getSignedRange(LHS);
4416 ConstantRange RHSRange = getSignedRange(RHS);
4417 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
4419 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
4423 case ICmpInst::ICMP_SGE:
4424 Pred = ICmpInst::ICMP_SLE;
4425 std::swap(LHS, RHS);
4426 case ICmpInst::ICMP_SLE: {
4427 ConstantRange LHSRange = getSignedRange(LHS);
4428 ConstantRange RHSRange = getSignedRange(RHS);
4429 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
4431 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
4435 case ICmpInst::ICMP_UGT:
4436 Pred = ICmpInst::ICMP_ULT;
4437 std::swap(LHS, RHS);
4438 case ICmpInst::ICMP_ULT: {
4439 ConstantRange LHSRange = getUnsignedRange(LHS);
4440 ConstantRange RHSRange = getUnsignedRange(RHS);
4441 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
4443 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
4447 case ICmpInst::ICMP_UGE:
4448 Pred = ICmpInst::ICMP_ULE;
4449 std::swap(LHS, RHS);
4450 case ICmpInst::ICMP_ULE: {
4451 ConstantRange LHSRange = getUnsignedRange(LHS);
4452 ConstantRange RHSRange = getUnsignedRange(RHS);
4453 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
4455 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
4459 case ICmpInst::ICMP_NE: {
4460 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
4462 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
4465 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4466 if (isKnownNonZero(Diff))
4470 case ICmpInst::ICMP_EQ:
4471 // The check at the top of the function catches the case where
4472 // the values are known to be equal.
4478 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
4479 /// protected by a conditional between LHS and RHS. This is used to
4480 /// to eliminate casts.
4482 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
4483 ICmpInst::Predicate Pred,
4484 const SCEV *LHS, const SCEV *RHS) {
4485 // Interpret a null as meaning no loop, where there is obviously no guard
4486 // (interprocedural conditions notwithstanding).
4487 if (!L) return true;
4489 BasicBlock *Latch = L->getLoopLatch();
4493 BranchInst *LoopContinuePredicate =
4494 dyn_cast<BranchInst>(Latch->getTerminator());
4495 if (!LoopContinuePredicate ||
4496 LoopContinuePredicate->isUnconditional())
4499 return isImpliedCond(LoopContinuePredicate->getCondition(), Pred, LHS, RHS,
4500 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
4503 /// isLoopGuardedByCond - Test whether entry to the loop is protected
4504 /// by a conditional between LHS and RHS. This is used to help avoid max
4505 /// expressions in loop trip counts, and to eliminate casts.
4507 ScalarEvolution::isLoopGuardedByCond(const Loop *L,
4508 ICmpInst::Predicate Pred,
4509 const SCEV *LHS, const SCEV *RHS) {
4510 // Interpret a null as meaning no loop, where there is obviously no guard
4511 // (interprocedural conditions notwithstanding).
4512 if (!L) return false;
4514 BasicBlock *Predecessor = getLoopPredecessor(L);
4515 BasicBlock *PredecessorDest = L->getHeader();
4517 // Starting at the loop predecessor, climb up the predecessor chain, as long
4518 // as there are predecessors that can be found that have unique successors
4519 // leading to the original header.
4521 PredecessorDest = Predecessor,
4522 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
4524 BranchInst *LoopEntryPredicate =
4525 dyn_cast<BranchInst>(Predecessor->getTerminator());
4526 if (!LoopEntryPredicate ||
4527 LoopEntryPredicate->isUnconditional())
4530 if (isImpliedCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
4531 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
4538 /// isImpliedCond - Test whether the condition described by Pred, LHS,
4539 /// and RHS is true whenever the given Cond value evaluates to true.
4540 bool ScalarEvolution::isImpliedCond(Value *CondValue,
4541 ICmpInst::Predicate Pred,
4542 const SCEV *LHS, const SCEV *RHS,
4544 // Recursivly handle And and Or conditions.
4545 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
4546 if (BO->getOpcode() == Instruction::And) {
4548 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4549 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4550 } else if (BO->getOpcode() == Instruction::Or) {
4552 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4553 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4557 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
4558 if (!ICI) return false;
4560 // Bail if the ICmp's operands' types are wider than the needed type
4561 // before attempting to call getSCEV on them. This avoids infinite
4562 // recursion, since the analysis of widening casts can require loop
4563 // exit condition information for overflow checking, which would
4565 if (getTypeSizeInBits(LHS->getType()) <
4566 getTypeSizeInBits(ICI->getOperand(0)->getType()))
4569 // Now that we found a conditional branch that dominates the loop, check to
4570 // see if it is the comparison we are looking for.
4571 ICmpInst::Predicate FoundPred;
4573 FoundPred = ICI->getInversePredicate();
4575 FoundPred = ICI->getPredicate();
4577 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
4578 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
4580 // Balance the types. The case where FoundLHS' type is wider than
4581 // LHS' type is checked for above.
4582 if (getTypeSizeInBits(LHS->getType()) >
4583 getTypeSizeInBits(FoundLHS->getType())) {
4584 if (CmpInst::isSigned(Pred)) {
4585 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
4586 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
4588 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
4589 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
4593 // Canonicalize the query to match the way instcombine will have
4594 // canonicalized the comparison.
4595 // First, put a constant operand on the right.
4596 if (isa<SCEVConstant>(LHS)) {
4597 std::swap(LHS, RHS);
4598 Pred = ICmpInst::getSwappedPredicate(Pred);
4600 // Then, canonicalize comparisons with boundary cases.
4601 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4602 const APInt &RA = RC->getValue()->getValue();
4604 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4605 case ICmpInst::ICMP_EQ:
4606 case ICmpInst::ICMP_NE:
4608 case ICmpInst::ICMP_UGE:
4609 if ((RA - 1).isMinValue()) {
4610 Pred = ICmpInst::ICMP_NE;
4611 RHS = getConstant(RA - 1);
4614 if (RA.isMaxValue()) {
4615 Pred = ICmpInst::ICMP_EQ;
4618 if (RA.isMinValue()) return true;
4620 case ICmpInst::ICMP_ULE:
4621 if ((RA + 1).isMaxValue()) {
4622 Pred = ICmpInst::ICMP_NE;
4623 RHS = getConstant(RA + 1);
4626 if (RA.isMinValue()) {
4627 Pred = ICmpInst::ICMP_EQ;
4630 if (RA.isMaxValue()) return true;
4632 case ICmpInst::ICMP_SGE:
4633 if ((RA - 1).isMinSignedValue()) {
4634 Pred = ICmpInst::ICMP_NE;
4635 RHS = getConstant(RA - 1);
4638 if (RA.isMaxSignedValue()) {
4639 Pred = ICmpInst::ICMP_EQ;
4642 if (RA.isMinSignedValue()) return true;
4644 case ICmpInst::ICMP_SLE:
4645 if ((RA + 1).isMaxSignedValue()) {
4646 Pred = ICmpInst::ICMP_NE;
4647 RHS = getConstant(RA + 1);
4650 if (RA.isMinSignedValue()) {
4651 Pred = ICmpInst::ICMP_EQ;
4654 if (RA.isMaxSignedValue()) return true;
4656 case ICmpInst::ICMP_UGT:
4657 if (RA.isMinValue()) {
4658 Pred = ICmpInst::ICMP_NE;
4661 if ((RA + 1).isMaxValue()) {
4662 Pred = ICmpInst::ICMP_EQ;
4663 RHS = getConstant(RA + 1);
4666 if (RA.isMaxValue()) return false;
4668 case ICmpInst::ICMP_ULT:
4669 if (RA.isMaxValue()) {
4670 Pred = ICmpInst::ICMP_NE;
4673 if ((RA - 1).isMinValue()) {
4674 Pred = ICmpInst::ICMP_EQ;
4675 RHS = getConstant(RA - 1);
4678 if (RA.isMinValue()) return false;
4680 case ICmpInst::ICMP_SGT:
4681 if (RA.isMinSignedValue()) {
4682 Pred = ICmpInst::ICMP_NE;
4685 if ((RA + 1).isMaxSignedValue()) {
4686 Pred = ICmpInst::ICMP_EQ;
4687 RHS = getConstant(RA + 1);
4690 if (RA.isMaxSignedValue()) return false;
4692 case ICmpInst::ICMP_SLT:
4693 if (RA.isMaxSignedValue()) {
4694 Pred = ICmpInst::ICMP_NE;
4697 if ((RA - 1).isMinSignedValue()) {
4698 Pred = ICmpInst::ICMP_EQ;
4699 RHS = getConstant(RA - 1);
4702 if (RA.isMinSignedValue()) return false;
4707 // Check to see if we can make the LHS or RHS match.
4708 if (LHS == FoundRHS || RHS == FoundLHS) {
4709 if (isa<SCEVConstant>(RHS)) {
4710 std::swap(FoundLHS, FoundRHS);
4711 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
4713 std::swap(LHS, RHS);
4714 Pred = ICmpInst::getSwappedPredicate(Pred);
4718 // Check whether the found predicate is the same as the desired predicate.
4719 if (FoundPred == Pred)
4720 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
4722 // Check whether swapping the found predicate makes it the same as the
4723 // desired predicate.
4724 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
4725 if (isa<SCEVConstant>(RHS))
4726 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
4728 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
4729 RHS, LHS, FoundLHS, FoundRHS);
4732 // Check whether the actual condition is beyond sufficient.
4733 if (FoundPred == ICmpInst::ICMP_EQ)
4734 if (ICmpInst::isTrueWhenEqual(Pred))
4735 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
4737 if (Pred == ICmpInst::ICMP_NE)
4738 if (!ICmpInst::isTrueWhenEqual(FoundPred))
4739 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
4742 // Otherwise assume the worst.
4746 /// isImpliedCondOperands - Test whether the condition described by Pred,
4747 /// LHS, and RHS is true whenever the condition desribed by Pred, FoundLHS,
4748 /// and FoundRHS is true.
4749 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
4750 const SCEV *LHS, const SCEV *RHS,
4751 const SCEV *FoundLHS,
4752 const SCEV *FoundRHS) {
4753 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
4754 FoundLHS, FoundRHS) ||
4755 // ~x < ~y --> x > y
4756 isImpliedCondOperandsHelper(Pred, LHS, RHS,
4757 getNotSCEV(FoundRHS),
4758 getNotSCEV(FoundLHS));
4761 /// isImpliedCondOperandsHelper - Test whether the condition described by
4762 /// Pred, LHS, and RHS is true whenever the condition desribed by Pred,
4763 /// FoundLHS, and FoundRHS is true.
4765 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
4766 const SCEV *LHS, const SCEV *RHS,
4767 const SCEV *FoundLHS,
4768 const SCEV *FoundRHS) {
4770 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4771 case ICmpInst::ICMP_EQ:
4772 case ICmpInst::ICMP_NE:
4773 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
4776 case ICmpInst::ICMP_SLT:
4777 case ICmpInst::ICMP_SLE:
4778 if (isKnownPredicate(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
4779 isKnownPredicate(ICmpInst::ICMP_SGE, RHS, FoundRHS))
4782 case ICmpInst::ICMP_SGT:
4783 case ICmpInst::ICMP_SGE:
4784 if (isKnownPredicate(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
4785 isKnownPredicate(ICmpInst::ICMP_SLE, RHS, FoundRHS))
4788 case ICmpInst::ICMP_ULT:
4789 case ICmpInst::ICMP_ULE:
4790 if (isKnownPredicate(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
4791 isKnownPredicate(ICmpInst::ICMP_UGE, RHS, FoundRHS))
4794 case ICmpInst::ICMP_UGT:
4795 case ICmpInst::ICMP_UGE:
4796 if (isKnownPredicate(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
4797 isKnownPredicate(ICmpInst::ICMP_ULE, RHS, FoundRHS))
4805 /// getBECount - Subtract the end and start values and divide by the step,
4806 /// rounding up, to get the number of times the backedge is executed. Return
4807 /// CouldNotCompute if an intermediate computation overflows.
4808 const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
4812 const Type *Ty = Start->getType();
4813 const SCEV *NegOne = getIntegerSCEV(-1, Ty);
4814 const SCEV *Diff = getMinusSCEV(End, Start);
4815 const SCEV *RoundUp = getAddExpr(Step, NegOne);
4817 // Add an adjustment to the difference between End and Start so that
4818 // the division will effectively round up.
4819 const SCEV *Add = getAddExpr(Diff, RoundUp);
4822 // Check Add for unsigned overflow.
4823 // TODO: More sophisticated things could be done here.
4824 const Type *WideTy = IntegerType::get(getContext(),
4825 getTypeSizeInBits(Ty) + 1);
4826 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
4827 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
4828 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
4829 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
4830 return getCouldNotCompute();
4833 return getUDivExpr(Add, Step);
4836 /// HowManyLessThans - Return the number of times a backedge containing the
4837 /// specified less-than comparison will execute. If not computable, return
4838 /// CouldNotCompute.
4839 ScalarEvolution::BackedgeTakenInfo
4840 ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
4841 const Loop *L, bool isSigned) {
4842 // Only handle: "ADDREC < LoopInvariant".
4843 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
4845 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
4846 if (!AddRec || AddRec->getLoop() != L)
4847 return getCouldNotCompute();
4849 // Check to see if we have a flag which makes analysis easy.
4850 bool NoWrap = isSigned ? AddRec->hasNoSignedWrap() :
4851 AddRec->hasNoUnsignedWrap();
4853 if (AddRec->isAffine()) {
4854 // FORNOW: We only support unit strides.
4855 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
4856 const SCEV *Step = AddRec->getStepRecurrence(*this);
4858 // TODO: handle non-constant strides.
4859 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
4860 if (!CStep || CStep->isZero())
4861 return getCouldNotCompute();
4862 if (CStep->isOne()) {
4863 // With unit stride, the iteration never steps past the limit value.
4864 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
4866 // We know the iteration won't step past the maximum value for its type.
4868 } else if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
4869 // Test whether a positive iteration iteration can step past the limit
4870 // value and past the maximum value for its type in a single step.
4872 APInt Max = APInt::getSignedMaxValue(BitWidth);
4873 if ((Max - CStep->getValue()->getValue())
4874 .slt(CLimit->getValue()->getValue()))
4875 return getCouldNotCompute();
4877 APInt Max = APInt::getMaxValue(BitWidth);
4878 if ((Max - CStep->getValue()->getValue())
4879 .ult(CLimit->getValue()->getValue()))
4880 return getCouldNotCompute();
4883 // TODO: handle non-constant limit values below.
4884 return getCouldNotCompute();
4886 // TODO: handle negative strides below.
4887 return getCouldNotCompute();
4889 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
4890 // m. So, we count the number of iterations in which {n,+,s} < m is true.
4891 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
4892 // treat m-n as signed nor unsigned due to overflow possibility.
4894 // First, we get the value of the LHS in the first iteration: n
4895 const SCEV *Start = AddRec->getOperand(0);
4897 // Determine the minimum constant start value.
4898 const SCEV *MinStart = getConstant(isSigned ?
4899 getSignedRange(Start).getSignedMin() :
4900 getUnsignedRange(Start).getUnsignedMin());
4902 // If we know that the condition is true in order to enter the loop,
4903 // then we know that it will run exactly (m-n)/s times. Otherwise, we
4904 // only know that it will execute (max(m,n)-n)/s times. In both cases,
4905 // the division must round up.
4906 const SCEV *End = RHS;
4907 if (!isLoopGuardedByCond(L,
4908 isSigned ? ICmpInst::ICMP_SLT :
4910 getMinusSCEV(Start, Step), RHS))
4911 End = isSigned ? getSMaxExpr(RHS, Start)
4912 : getUMaxExpr(RHS, Start);
4914 // Determine the maximum constant end value.
4915 const SCEV *MaxEnd = getConstant(isSigned ?
4916 getSignedRange(End).getSignedMax() :
4917 getUnsignedRange(End).getUnsignedMax());
4919 // Finally, we subtract these two values and divide, rounding up, to get
4920 // the number of times the backedge is executed.
4921 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
4923 // The maximum backedge count is similar, except using the minimum start
4924 // value and the maximum end value.
4925 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step, NoWrap);
4927 return BackedgeTakenInfo(BECount, MaxBECount);
4930 return getCouldNotCompute();
4933 /// getNumIterationsInRange - Return the number of iterations of this loop that
4934 /// produce values in the specified constant range. Another way of looking at
4935 /// this is that it returns the first iteration number where the value is not in
4936 /// the condition, thus computing the exit count. If the iteration count can't
4937 /// be computed, an instance of SCEVCouldNotCompute is returned.
4938 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
4939 ScalarEvolution &SE) const {
4940 if (Range.isFullSet()) // Infinite loop.
4941 return SE.getCouldNotCompute();
4943 // If the start is a non-zero constant, shift the range to simplify things.
4944 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
4945 if (!SC->getValue()->isZero()) {
4946 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
4947 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
4948 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
4949 if (const SCEVAddRecExpr *ShiftedAddRec =
4950 dyn_cast<SCEVAddRecExpr>(Shifted))
4951 return ShiftedAddRec->getNumIterationsInRange(
4952 Range.subtract(SC->getValue()->getValue()), SE);
4953 // This is strange and shouldn't happen.
4954 return SE.getCouldNotCompute();
4957 // The only time we can solve this is when we have all constant indices.
4958 // Otherwise, we cannot determine the overflow conditions.
4959 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4960 if (!isa<SCEVConstant>(getOperand(i)))
4961 return SE.getCouldNotCompute();
4964 // Okay at this point we know that all elements of the chrec are constants and
4965 // that the start element is zero.
4967 // First check to see if the range contains zero. If not, the first
4969 unsigned BitWidth = SE.getTypeSizeInBits(getType());
4970 if (!Range.contains(APInt(BitWidth, 0)))
4971 return SE.getIntegerSCEV(0, getType());
4974 // If this is an affine expression then we have this situation:
4975 // Solve {0,+,A} in Range === Ax in Range
4977 // We know that zero is in the range. If A is positive then we know that
4978 // the upper value of the range must be the first possible exit value.
4979 // If A is negative then the lower of the range is the last possible loop
4980 // value. Also note that we already checked for a full range.
4981 APInt One(BitWidth,1);
4982 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
4983 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
4985 // The exit value should be (End+A)/A.
4986 APInt ExitVal = (End + A).udiv(A);
4987 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
4989 // Evaluate at the exit value. If we really did fall out of the valid
4990 // range, then we computed our trip count, otherwise wrap around or other
4991 // things must have happened.
4992 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
4993 if (Range.contains(Val->getValue()))
4994 return SE.getCouldNotCompute(); // Something strange happened
4996 // Ensure that the previous value is in the range. This is a sanity check.
4997 assert(Range.contains(
4998 EvaluateConstantChrecAtConstant(this,
4999 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
5000 "Linear scev computation is off in a bad way!");
5001 return SE.getConstant(ExitValue);
5002 } else if (isQuadratic()) {
5003 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5004 // quadratic equation to solve it. To do this, we must frame our problem in
5005 // terms of figuring out when zero is crossed, instead of when
5006 // Range.getUpper() is crossed.
5007 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
5008 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
5009 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
5011 // Next, solve the constructed addrec
5012 std::pair<const SCEV *,const SCEV *> Roots =
5013 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
5014 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5015 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
5017 // Pick the smallest positive root value.
5018 if (ConstantInt *CB =
5019 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
5020 R1->getValue(), R2->getValue()))) {
5021 if (CB->getZExtValue() == false)
5022 std::swap(R1, R2); // R1 is the minimum root now.
5024 // Make sure the root is not off by one. The returned iteration should
5025 // not be in the range, but the previous one should be. When solving
5026 // for "X*X < 5", for example, we should not return a root of 2.
5027 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
5030 if (Range.contains(R1Val->getValue())) {
5031 // The next iteration must be out of the range...
5032 ConstantInt *NextVal =
5033 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
5035 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
5036 if (!Range.contains(R1Val->getValue()))
5037 return SE.getConstant(NextVal);
5038 return SE.getCouldNotCompute(); // Something strange happened
5041 // If R1 was not in the range, then it is a good return value. Make
5042 // sure that R1-1 WAS in the range though, just in case.
5043 ConstantInt *NextVal =
5044 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
5045 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
5046 if (Range.contains(R1Val->getValue()))
5048 return SE.getCouldNotCompute(); // Something strange happened
5053 return SE.getCouldNotCompute();
5058 //===----------------------------------------------------------------------===//
5059 // SCEVCallbackVH Class Implementation
5060 //===----------------------------------------------------------------------===//
5062 void ScalarEvolution::SCEVCallbackVH::deleted() {
5063 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
5064 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5065 SE->ConstantEvolutionLoopExitValue.erase(PN);
5066 SE->Scalars.erase(getValPtr());
5067 // this now dangles!
5070 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
5071 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
5073 // Forget all the expressions associated with users of the old value,
5074 // so that future queries will recompute the expressions using the new
5076 SmallVector<User *, 16> Worklist;
5077 SmallPtrSet<User *, 8> Visited;
5078 Value *Old = getValPtr();
5079 bool DeleteOld = false;
5080 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5082 Worklist.push_back(*UI);
5083 while (!Worklist.empty()) {
5084 User *U = Worklist.pop_back_val();
5085 // Deleting the Old value will cause this to dangle. Postpone
5086 // that until everything else is done.
5091 if (!Visited.insert(U))
5093 if (PHINode *PN = dyn_cast<PHINode>(U))
5094 SE->ConstantEvolutionLoopExitValue.erase(PN);
5095 SE->Scalars.erase(U);
5096 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5098 Worklist.push_back(*UI);
5100 // Delete the Old value if it (indirectly) references itself.
5102 if (PHINode *PN = dyn_cast<PHINode>(Old))
5103 SE->ConstantEvolutionLoopExitValue.erase(PN);
5104 SE->Scalars.erase(Old);
5105 // this now dangles!
5110 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
5111 : CallbackVH(V), SE(se) {}
5113 //===----------------------------------------------------------------------===//
5114 // ScalarEvolution Class Implementation
5115 //===----------------------------------------------------------------------===//
5117 ScalarEvolution::ScalarEvolution()
5118 : FunctionPass(&ID) {
5121 bool ScalarEvolution::runOnFunction(Function &F) {
5123 LI = &getAnalysis<LoopInfo>();
5124 TD = getAnalysisIfAvailable<TargetData>();
5128 void ScalarEvolution::releaseMemory() {
5130 BackedgeTakenCounts.clear();
5131 ConstantEvolutionLoopExitValue.clear();
5132 ValuesAtScopes.clear();
5133 UniqueSCEVs.clear();
5134 SCEVAllocator.Reset();
5137 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5138 AU.setPreservesAll();
5139 AU.addRequiredTransitive<LoopInfo>();
5142 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
5143 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
5146 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
5148 // Print all inner loops first
5149 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5150 PrintLoopInfo(OS, SE, *I);
5152 OS << "Loop " << L->getHeader()->getName() << ": ";
5154 SmallVector<BasicBlock*, 8> ExitBlocks;
5155 L->getExitBlocks(ExitBlocks);
5156 if (ExitBlocks.size() != 1)
5157 OS << "<multiple exits> ";
5159 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5160 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
5162 OS << "Unpredictable backedge-taken count. ";
5166 OS << "Loop " << L->getHeader()->getName() << ": ";
5168 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5169 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5171 OS << "Unpredictable max backedge-taken count. ";
5177 void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
5178 // ScalarEvolution's implementaiton of the print method is to print
5179 // out SCEV values of all instructions that are interesting. Doing
5180 // this potentially causes it to create new SCEV objects though,
5181 // which technically conflicts with the const qualifier. This isn't
5182 // observable from outside the class though, so casting away the
5183 // const isn't dangerous.
5184 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
5186 OS << "Classifying expressions for: " << F->getName() << "\n";
5187 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
5188 if (isSCEVable(I->getType())) {
5191 const SCEV *SV = SE.getSCEV(&*I);
5194 const Loop *L = LI->getLoopFor((*I).getParent());
5196 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
5203 OS << "\t\t" "Exits: ";
5204 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
5205 if (!ExitValue->isLoopInvariant(L)) {
5206 OS << "<<Unknown>>";
5215 OS << "Determining loop execution counts for: " << F->getName() << "\n";
5216 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5217 PrintLoopInfo(OS, &SE, *I);