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. These classes are reference counted, managed by the SCEVHandle
18 // class. We only create one SCEV of a particular shape, so pointer-comparisons
19 // for equality are legal.
21 // One important aspect of the SCEV objects is that they are never cyclic, even
22 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If
23 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
24 // recurrence) then we represent it directly as a recurrence node, otherwise we
25 // represent it as a SCEVUnknown node.
27 // In addition to being able to represent expressions of various types, we also
28 // have folders that are used to build the *canonical* representation for a
29 // particular expression. These folders are capable of using a variety of
30 // rewrite rules to simplify the expressions.
32 // Once the folders are defined, we can implement the more interesting
33 // higher-level code, such as the code that recognizes PHI nodes of various
34 // types, computes the execution count of a loop, etc.
36 // TODO: We should use these routines and value representations to implement
37 // dependence analysis!
39 //===----------------------------------------------------------------------===//
41 // There are several good references for the techniques used in this analysis.
43 // Chains of recurrences -- a method to expedite the evaluation
44 // of closed-form functions
45 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima
47 // On computational properties of chains of recurrences
50 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization
51 // Robert A. van Engelen
53 // Efficient Symbolic Analysis for Optimizing Compilers
54 // Robert A. van Engelen
56 // Using the chains of recurrences algebra for data dependence testing and
57 // induction variable substitution
58 // MS Thesis, Johnie Birch
60 //===----------------------------------------------------------------------===//
62 #define DEBUG_TYPE "scalar-evolution"
63 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
64 #include "llvm/Constants.h"
65 #include "llvm/DerivedTypes.h"
66 #include "llvm/GlobalVariable.h"
67 #include "llvm/Instructions.h"
68 #include "llvm/Analysis/ConstantFolding.h"
69 #include "llvm/Analysis/LoopInfo.h"
70 #include "llvm/Assembly/Writer.h"
71 #include "llvm/Transforms/Scalar.h"
72 #include "llvm/Support/CFG.h"
73 #include "llvm/Support/CommandLine.h"
74 #include "llvm/Support/Compiler.h"
75 #include "llvm/Support/ConstantRange.h"
76 #include "llvm/Support/InstIterator.h"
77 #include "llvm/Support/ManagedStatic.h"
78 #include "llvm/Support/MathExtras.h"
79 #include "llvm/Support/Streams.h"
80 #include "llvm/ADT/Statistic.h"
86 STATISTIC(NumArrayLenItCounts,
87 "Number of trip counts computed with array length");
88 STATISTIC(NumTripCountsComputed,
89 "Number of loops with predictable loop counts");
90 STATISTIC(NumTripCountsNotComputed,
91 "Number of loops without predictable loop counts");
92 STATISTIC(NumBruteForceTripCountsComputed,
93 "Number of loops with trip counts computed by force");
95 static cl::opt<unsigned>
96 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
97 cl::desc("Maximum number of iterations SCEV will "
98 "symbolically execute a constant derived loop"),
101 static RegisterPass<ScalarEvolution>
102 R("scalar-evolution", "Scalar Evolution Analysis", false, true);
103 char ScalarEvolution::ID = 0;
105 //===----------------------------------------------------------------------===//
106 // SCEV class definitions
107 //===----------------------------------------------------------------------===//
109 //===----------------------------------------------------------------------===//
110 // Implementation of the SCEV class.
113 void SCEV::dump() const {
118 uint32_t SCEV::getBitWidth() const {
119 if (const IntegerType* ITy = dyn_cast<IntegerType>(getType()))
120 return ITy->getBitWidth();
124 bool SCEV::isZero() const {
125 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
126 return SC->getValue()->isZero();
131 SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
133 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
134 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
138 const Type *SCEVCouldNotCompute::getType() const {
139 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
143 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
144 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
148 SCEVHandle SCEVCouldNotCompute::
149 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
150 const SCEVHandle &Conc,
151 ScalarEvolution &SE) const {
155 void SCEVCouldNotCompute::print(std::ostream &OS) const {
156 OS << "***COULDNOTCOMPUTE***";
159 bool SCEVCouldNotCompute::classof(const SCEV *S) {
160 return S->getSCEVType() == scCouldNotCompute;
164 // SCEVConstants - Only allow the creation of one SCEVConstant for any
165 // particular value. Don't use a SCEVHandle here, or else the object will
167 static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
170 SCEVConstant::~SCEVConstant() {
171 SCEVConstants->erase(V);
174 SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
175 SCEVConstant *&R = (*SCEVConstants)[V];
176 if (R == 0) R = new SCEVConstant(V);
180 SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
181 return getConstant(ConstantInt::get(Val));
184 const Type *SCEVConstant::getType() const { return V->getType(); }
186 void SCEVConstant::print(std::ostream &OS) const {
187 WriteAsOperand(OS, V, false);
190 // SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
191 // particular input. Don't use a SCEVHandle here, or else the object will
193 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
194 SCEVTruncateExpr*> > SCEVTruncates;
196 SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
197 : SCEV(scTruncate), Op(op), Ty(ty) {
198 assert(Op->getType()->isInteger() && Ty->isInteger() &&
199 "Cannot truncate non-integer value!");
200 assert(Op->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()
201 && "This is not a truncating conversion!");
204 SCEVTruncateExpr::~SCEVTruncateExpr() {
205 SCEVTruncates->erase(std::make_pair(Op, Ty));
208 void SCEVTruncateExpr::print(std::ostream &OS) const {
209 OS << "(truncate " << *Op << " to " << *Ty << ")";
212 // SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
213 // particular input. Don't use a SCEVHandle here, or else the object will never
215 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
216 SCEVZeroExtendExpr*> > SCEVZeroExtends;
218 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
219 : SCEV(scZeroExtend), Op(op), Ty(ty) {
220 assert(Op->getType()->isInteger() && Ty->isInteger() &&
221 "Cannot zero extend non-integer value!");
222 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
223 && "This is not an extending conversion!");
226 SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
227 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
230 void SCEVZeroExtendExpr::print(std::ostream &OS) const {
231 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
234 // SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
235 // particular input. Don't use a SCEVHandle here, or else the object will never
237 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
238 SCEVSignExtendExpr*> > SCEVSignExtends;
240 SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
241 : SCEV(scSignExtend), Op(op), Ty(ty) {
242 assert(Op->getType()->isInteger() && Ty->isInteger() &&
243 "Cannot sign extend non-integer value!");
244 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
245 && "This is not an extending conversion!");
248 SCEVSignExtendExpr::~SCEVSignExtendExpr() {
249 SCEVSignExtends->erase(std::make_pair(Op, Ty));
252 void SCEVSignExtendExpr::print(std::ostream &OS) const {
253 OS << "(signextend " << *Op << " to " << *Ty << ")";
256 // SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
257 // particular input. Don't use a SCEVHandle here, or else the object will never
259 static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
260 SCEVCommutativeExpr*> > SCEVCommExprs;
262 SCEVCommutativeExpr::~SCEVCommutativeExpr() {
263 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
264 std::vector<SCEV*>(Operands.begin(),
268 void SCEVCommutativeExpr::print(std::ostream &OS) const {
269 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
270 const char *OpStr = getOperationStr();
271 OS << "(" << *Operands[0];
272 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
273 OS << OpStr << *Operands[i];
277 SCEVHandle SCEVCommutativeExpr::
278 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
279 const SCEVHandle &Conc,
280 ScalarEvolution &SE) const {
281 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
283 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
284 if (H != getOperand(i)) {
285 std::vector<SCEVHandle> NewOps;
286 NewOps.reserve(getNumOperands());
287 for (unsigned j = 0; j != i; ++j)
288 NewOps.push_back(getOperand(j));
290 for (++i; i != e; ++i)
291 NewOps.push_back(getOperand(i)->
292 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
294 if (isa<SCEVAddExpr>(this))
295 return SE.getAddExpr(NewOps);
296 else if (isa<SCEVMulExpr>(this))
297 return SE.getMulExpr(NewOps);
298 else if (isa<SCEVSMaxExpr>(this))
299 return SE.getSMaxExpr(NewOps);
300 else if (isa<SCEVUMaxExpr>(this))
301 return SE.getUMaxExpr(NewOps);
303 assert(0 && "Unknown commutative expr!");
310 // SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
311 // input. Don't use a SCEVHandle here, or else the object will never be
313 static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
314 SCEVUDivExpr*> > SCEVUDivs;
316 SCEVUDivExpr::~SCEVUDivExpr() {
317 SCEVUDivs->erase(std::make_pair(LHS, RHS));
320 void SCEVUDivExpr::print(std::ostream &OS) const {
321 OS << "(" << *LHS << " /u " << *RHS << ")";
324 const Type *SCEVUDivExpr::getType() const {
325 return LHS->getType();
329 // SCEVSDivs - Only allow the creation of one SCEVSDivExpr for any particular
330 // input. Don't use a SCEVHandle here, or else the object will never be
332 static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
333 SCEVSDivExpr*> > SCEVSDivs;
335 SCEVSDivExpr::~SCEVSDivExpr() {
336 SCEVSDivs->erase(std::make_pair(LHS, RHS));
339 void SCEVSDivExpr::print(std::ostream &OS) const {
340 OS << "(" << *LHS << " /s " << *RHS << ")";
343 const Type *SCEVSDivExpr::getType() const {
344 return LHS->getType();
348 // SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
349 // particular input. Don't use a SCEVHandle here, or else the object will never
351 static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
352 SCEVAddRecExpr*> > SCEVAddRecExprs;
354 SCEVAddRecExpr::~SCEVAddRecExpr() {
355 SCEVAddRecExprs->erase(std::make_pair(L,
356 std::vector<SCEV*>(Operands.begin(),
360 SCEVHandle SCEVAddRecExpr::
361 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
362 const SCEVHandle &Conc,
363 ScalarEvolution &SE) const {
364 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
366 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
367 if (H != getOperand(i)) {
368 std::vector<SCEVHandle> NewOps;
369 NewOps.reserve(getNumOperands());
370 for (unsigned j = 0; j != i; ++j)
371 NewOps.push_back(getOperand(j));
373 for (++i; i != e; ++i)
374 NewOps.push_back(getOperand(i)->
375 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
377 return SE.getAddRecExpr(NewOps, L);
384 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
385 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
386 // contain L and if the start is invariant.
387 return !QueryLoop->contains(L->getHeader()) &&
388 getOperand(0)->isLoopInvariant(QueryLoop);
392 void SCEVAddRecExpr::print(std::ostream &OS) const {
393 OS << "{" << *Operands[0];
394 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
395 OS << ",+," << *Operands[i];
396 OS << "}<" << L->getHeader()->getName() + ">";
399 // SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
400 // value. Don't use a SCEVHandle here, or else the object will never be
402 static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
404 SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
406 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
407 // All non-instruction values are loop invariant. All instructions are loop
408 // invariant if they are not contained in the specified loop.
409 if (Instruction *I = dyn_cast<Instruction>(V))
410 return !L->contains(I->getParent());
414 const Type *SCEVUnknown::getType() const {
418 void SCEVUnknown::print(std::ostream &OS) const {
419 WriteAsOperand(OS, V, false);
422 //===----------------------------------------------------------------------===//
424 //===----------------------------------------------------------------------===//
427 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
428 /// than the complexity of the RHS. This comparator is used to canonicalize
430 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
431 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
432 return LHS->getSCEVType() < RHS->getSCEVType();
437 /// GroupByComplexity - Given a list of SCEV objects, order them by their
438 /// complexity, and group objects of the same complexity together by value.
439 /// When this routine is finished, we know that any duplicates in the vector are
440 /// consecutive and that complexity is monotonically increasing.
442 /// Note that we go take special precautions to ensure that we get determinstic
443 /// results from this routine. In other words, we don't want the results of
444 /// this to depend on where the addresses of various SCEV objects happened to
447 static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
448 if (Ops.size() < 2) return; // Noop
449 if (Ops.size() == 2) {
450 // This is the common case, which also happens to be trivially simple.
452 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
453 std::swap(Ops[0], Ops[1]);
457 // Do the rough sort by complexity.
458 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
460 // Now that we are sorted by complexity, group elements of the same
461 // complexity. Note that this is, at worst, N^2, but the vector is likely to
462 // be extremely short in practice. Note that we take this approach because we
463 // do not want to depend on the addresses of the objects we are grouping.
464 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
466 unsigned Complexity = S->getSCEVType();
468 // If there are any objects of the same complexity and same value as this
470 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
471 if (Ops[j] == S) { // Found a duplicate.
472 // Move it to immediately after i'th element.
473 std::swap(Ops[i+1], Ops[j]);
474 ++i; // no need to rescan it.
475 if (i == e-2) return; // Done!
483 //===----------------------------------------------------------------------===//
484 // Simple SCEV method implementations
485 //===----------------------------------------------------------------------===//
487 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
488 /// specified signed integer value and return a SCEV for the constant.
489 SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
492 C = Constant::getNullValue(Ty);
493 else if (Ty->isFloatingPoint())
494 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
495 APFloat::IEEEdouble, Val));
497 C = ConstantInt::get(Ty, Val);
498 return getUnknown(C);
501 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
503 SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
504 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
505 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
507 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(V->getType())));
510 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
511 SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
512 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
513 return getUnknown(ConstantExpr::getNot(VC->getValue()));
515 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(V->getType()));
516 return getMinusSCEV(AllOnes, V);
519 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
521 SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
522 const SCEVHandle &RHS) {
524 return getAddExpr(LHS, getNegativeSCEV(RHS));
528 /// BinomialCoefficient - Compute BC(It, K). The result has width W.
530 static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
532 const IntegerType* ResultTy) {
533 // Handle the simplest case efficiently.
535 return SE.getTruncateOrZeroExtend(It, ResultTy);
537 // We are using the following formula for BC(It, K):
539 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
541 // Suppose, W is the bitwidth of the return value. We must be prepared for
542 // overflow. Hence, we must assure that the result of our computation is
543 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
544 // safe in modular arithmetic.
546 // However, this code doesn't use exactly that formula; the formula it uses
547 // is something like the following, where T is the number of factors of 2 in
548 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
551 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
553 // This formula is trivially equivalent to the previous formula. However,
554 // this formula can be implemented much more efficiently. The trick is that
555 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
556 // arithmetic. To do exact division in modular arithmetic, all we have
557 // to do is multiply by the inverse. Therefore, this step can be done at
560 // The next issue is how to safely do the division by 2^T. The way this
561 // is done is by doing the multiplication step at a width of at least W + T
562 // bits. This way, the bottom W+T bits of the product are accurate. Then,
563 // when we perform the division by 2^T (which is equivalent to a right shift
564 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
565 // truncated out after the division by 2^T.
567 // In comparison to just directly using the first formula, this technique
568 // is much more efficient; using the first formula requires W * K bits,
569 // but this formula less than W + K bits. Also, the first formula requires
570 // a division step, whereas this formula only requires multiplies and shifts.
572 // It doesn't matter whether the subtraction step is done in the calculation
573 // width or the input iteration count's width; if the subtraction overflows,
574 // the result must be zero anyway. We prefer here to do it in the width of
575 // the induction variable because it helps a lot for certain cases; CodeGen
576 // isn't smart enough to ignore the overflow, which leads to much less
577 // efficient code if the width of the subtraction is wider than the native
580 // (It's possible to not widen at all by pulling out factors of 2 before
581 // the multiplication; for example, K=2 can be calculated as
582 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
583 // extra arithmetic, so it's not an obvious win, and it gets
584 // much more complicated for K > 3.)
586 // Protection from insane SCEVs; this bound is conservative,
587 // but it probably doesn't matter.
589 return new SCEVCouldNotCompute();
591 unsigned W = ResultTy->getBitWidth();
593 // Calculate K! / 2^T and T; we divide out the factors of two before
594 // multiplying for calculating K! / 2^T to avoid overflow.
595 // Other overflow doesn't matter because we only care about the bottom
596 // W bits of the result.
597 APInt OddFactorial(W, 1);
599 for (unsigned i = 3; i <= K; ++i) {
601 unsigned TwoFactors = Mult.countTrailingZeros();
603 Mult = Mult.lshr(TwoFactors);
604 OddFactorial *= Mult;
607 // We need at least W + T bits for the multiplication step
608 // FIXME: A temporary hack; we round up the bitwidths
609 // to the nearest power of 2 to be nice to the code generator.
610 unsigned CalculationBits = 1U << Log2_32_Ceil(W + T);
611 // FIXME: Temporary hack to avoid generating integers that are too wide.
612 // Although, it's not completely clear how to determine how much
613 // widening is safe; for example, on X86, we can't really widen
614 // beyond 64 because we need to be able to do multiplication
615 // that's CalculationBits wide, but on X86-64, we can safely widen up to
617 if (CalculationBits > 64)
618 return new SCEVCouldNotCompute();
620 // Calcuate 2^T, at width T+W.
621 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
623 // Calculate the multiplicative inverse of K! / 2^T;
624 // this multiplication factor will perform the exact division by
626 APInt Mod = APInt::getSignedMinValue(W+1);
627 APInt MultiplyFactor = OddFactorial.zext(W+1);
628 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
629 MultiplyFactor = MultiplyFactor.trunc(W);
631 // Calculate the product, at width T+W
632 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
633 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
634 for (unsigned i = 1; i != K; ++i) {
635 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
636 Dividend = SE.getMulExpr(Dividend,
637 SE.getTruncateOrZeroExtend(S, CalculationTy));
641 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
643 // Truncate the result, and divide by K! / 2^T.
645 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
646 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
649 /// evaluateAtIteration - Return the value of this chain of recurrences at
650 /// the specified iteration number. We can evaluate this recurrence by
651 /// multiplying each element in the chain by the binomial coefficient
652 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
654 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
656 /// where BC(It, k) stands for binomial coefficient.
658 SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
659 ScalarEvolution &SE) const {
660 SCEVHandle Result = getStart();
661 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
662 // The computation is correct in the face of overflow provided that the
663 // multiplication is performed _after_ the evaluation of the binomial
665 SCEVHandle Coeff = BinomialCoefficient(It, i, SE,
666 cast<IntegerType>(getType()));
667 if (isa<SCEVCouldNotCompute>(Coeff))
670 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
675 //===----------------------------------------------------------------------===//
676 // SCEV Expression folder implementations
677 //===----------------------------------------------------------------------===//
679 SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
680 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
682 ConstantExpr::getTrunc(SC->getValue(), Ty));
684 // If the input value is a chrec scev made out of constants, truncate
685 // all of the constants.
686 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
687 std::vector<SCEVHandle> Operands;
688 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
689 // FIXME: This should allow truncation of other expression types!
690 if (isa<SCEVConstant>(AddRec->getOperand(i)))
691 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
694 if (Operands.size() == AddRec->getNumOperands())
695 return getAddRecExpr(Operands, AddRec->getLoop());
698 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
699 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
703 SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty) {
704 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
706 ConstantExpr::getZExt(SC->getValue(), Ty));
708 // FIXME: If the input value is a chrec scev, and we can prove that the value
709 // did not overflow the old, smaller, value, we can zero extend all of the
710 // operands (often constants). This would allow analysis of something like
711 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
713 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
714 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
718 SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
719 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
721 ConstantExpr::getSExt(SC->getValue(), Ty));
723 // FIXME: If the input value is a chrec scev, and we can prove that the value
724 // did not overflow the old, smaller, value, we can sign extend all of the
725 // operands (often constants). This would allow analysis of something like
726 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
728 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
729 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
733 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
734 /// of the input value to the specified type. If the type must be
735 /// extended, it is zero extended.
736 SCEVHandle ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
738 const Type *SrcTy = V->getType();
739 assert(SrcTy->isInteger() && Ty->isInteger() &&
740 "Cannot truncate or zero extend with non-integer arguments!");
741 if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
742 return V; // No conversion
743 if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits())
744 return getTruncateExpr(V, Ty);
745 return getZeroExtendExpr(V, Ty);
748 // get - Get a canonical add expression, or something simpler if possible.
749 SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
750 assert(!Ops.empty() && "Cannot get empty add!");
751 if (Ops.size() == 1) return Ops[0];
753 // Sort by complexity, this groups all similar expression types together.
754 GroupByComplexity(Ops);
756 // If there are any constants, fold them together.
758 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
760 assert(Idx < Ops.size());
761 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
762 // We found two constants, fold them together!
763 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
764 RHSC->getValue()->getValue());
765 Ops[0] = getConstant(Fold);
766 Ops.erase(Ops.begin()+1); // Erase the folded element
767 if (Ops.size() == 1) return Ops[0];
768 LHSC = cast<SCEVConstant>(Ops[0]);
771 // If we are left with a constant zero being added, strip it off.
772 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
773 Ops.erase(Ops.begin());
778 if (Ops.size() == 1) return Ops[0];
780 // Okay, check to see if the same value occurs in the operand list twice. If
781 // so, merge them together into an multiply expression. Since we sorted the
782 // list, these values are required to be adjacent.
783 const Type *Ty = Ops[0]->getType();
784 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
785 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
786 // Found a match, merge the two values into a multiply, and add any
787 // remaining values to the result.
788 SCEVHandle Two = getIntegerSCEV(2, Ty);
789 SCEVHandle Mul = getMulExpr(Ops[i], Two);
792 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
794 return getAddExpr(Ops);
797 // Now we know the first non-constant operand. Skip past any cast SCEVs.
798 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
801 // If there are add operands they would be next.
802 if (Idx < Ops.size()) {
803 bool DeletedAdd = false;
804 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
805 // If we have an add, expand the add operands onto the end of the operands
807 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
808 Ops.erase(Ops.begin()+Idx);
812 // If we deleted at least one add, we added operands to the end of the list,
813 // and they are not necessarily sorted. Recurse to resort and resimplify
814 // any operands we just aquired.
816 return getAddExpr(Ops);
819 // Skip over the add expression until we get to a multiply.
820 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
823 // If we are adding something to a multiply expression, make sure the
824 // something is not already an operand of the multiply. If so, merge it into
826 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
827 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
828 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
829 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
830 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
831 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
832 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
833 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
834 if (Mul->getNumOperands() != 2) {
835 // If the multiply has more than two operands, we must get the
837 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
838 MulOps.erase(MulOps.begin()+MulOp);
839 InnerMul = getMulExpr(MulOps);
841 SCEVHandle One = getIntegerSCEV(1, Ty);
842 SCEVHandle AddOne = getAddExpr(InnerMul, One);
843 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
844 if (Ops.size() == 2) return OuterMul;
846 Ops.erase(Ops.begin()+AddOp);
847 Ops.erase(Ops.begin()+Idx-1);
849 Ops.erase(Ops.begin()+Idx);
850 Ops.erase(Ops.begin()+AddOp-1);
852 Ops.push_back(OuterMul);
853 return getAddExpr(Ops);
856 // Check this multiply against other multiplies being added together.
857 for (unsigned OtherMulIdx = Idx+1;
858 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
860 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
861 // If MulOp occurs in OtherMul, we can fold the two multiplies
863 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
864 OMulOp != e; ++OMulOp)
865 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
866 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
867 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
868 if (Mul->getNumOperands() != 2) {
869 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
870 MulOps.erase(MulOps.begin()+MulOp);
871 InnerMul1 = getMulExpr(MulOps);
873 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
874 if (OtherMul->getNumOperands() != 2) {
875 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
877 MulOps.erase(MulOps.begin()+OMulOp);
878 InnerMul2 = getMulExpr(MulOps);
880 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
881 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
882 if (Ops.size() == 2) return OuterMul;
883 Ops.erase(Ops.begin()+Idx);
884 Ops.erase(Ops.begin()+OtherMulIdx-1);
885 Ops.push_back(OuterMul);
886 return getAddExpr(Ops);
892 // If there are any add recurrences in the operands list, see if any other
893 // added values are loop invariant. If so, we can fold them into the
895 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
898 // Scan over all recurrences, trying to fold loop invariants into them.
899 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
900 // Scan all of the other operands to this add and add them to the vector if
901 // they are loop invariant w.r.t. the recurrence.
902 std::vector<SCEVHandle> LIOps;
903 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
904 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
905 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
906 LIOps.push_back(Ops[i]);
907 Ops.erase(Ops.begin()+i);
911 // If we found some loop invariants, fold them into the recurrence.
912 if (!LIOps.empty()) {
913 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
914 LIOps.push_back(AddRec->getStart());
916 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
917 AddRecOps[0] = getAddExpr(LIOps);
919 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
920 // If all of the other operands were loop invariant, we are done.
921 if (Ops.size() == 1) return NewRec;
923 // Otherwise, add the folded AddRec by the non-liv parts.
924 for (unsigned i = 0;; ++i)
925 if (Ops[i] == AddRec) {
929 return getAddExpr(Ops);
932 // Okay, if there weren't any loop invariants to be folded, check to see if
933 // there are multiple AddRec's with the same loop induction variable being
934 // added together. If so, we can fold them.
935 for (unsigned OtherIdx = Idx+1;
936 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
937 if (OtherIdx != Idx) {
938 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
939 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
940 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
941 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
942 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
943 if (i >= NewOps.size()) {
944 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
945 OtherAddRec->op_end());
948 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
950 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
952 if (Ops.size() == 2) return NewAddRec;
954 Ops.erase(Ops.begin()+Idx);
955 Ops.erase(Ops.begin()+OtherIdx-1);
956 Ops.push_back(NewAddRec);
957 return getAddExpr(Ops);
961 // Otherwise couldn't fold anything into this recurrence. Move onto the
965 // Okay, it looks like we really DO need an add expr. Check to see if we
966 // already have one, otherwise create a new one.
967 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
968 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
970 if (Result == 0) Result = new SCEVAddExpr(Ops);
975 SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
976 assert(!Ops.empty() && "Cannot get empty mul!");
978 // Sort by complexity, this groups all similar expression types together.
979 GroupByComplexity(Ops);
981 // If there are any constants, fold them together.
983 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
985 // C1*(C2+V) -> C1*C2 + C1*V
987 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
988 if (Add->getNumOperands() == 2 &&
989 isa<SCEVConstant>(Add->getOperand(0)))
990 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
991 getMulExpr(LHSC, Add->getOperand(1)));
995 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
996 // We found two constants, fold them together!
997 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
998 RHSC->getValue()->getValue());
999 Ops[0] = getConstant(Fold);
1000 Ops.erase(Ops.begin()+1); // Erase the folded element
1001 if (Ops.size() == 1) return Ops[0];
1002 LHSC = cast<SCEVConstant>(Ops[0]);
1005 // If we are left with a constant one being multiplied, strip it off.
1006 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1007 Ops.erase(Ops.begin());
1009 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1010 // If we have a multiply of zero, it will always be zero.
1015 // Skip over the add expression until we get to a multiply.
1016 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1019 if (Ops.size() == 1)
1022 // If there are mul operands inline them all into this expression.
1023 if (Idx < Ops.size()) {
1024 bool DeletedMul = false;
1025 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1026 // If we have an mul, expand the mul operands onto the end of the operands
1028 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1029 Ops.erase(Ops.begin()+Idx);
1033 // If we deleted at least one mul, we added operands to the end of the list,
1034 // and they are not necessarily sorted. Recurse to resort and resimplify
1035 // any operands we just aquired.
1037 return getMulExpr(Ops);
1040 // If there are any add recurrences in the operands list, see if any other
1041 // added values are loop invariant. If so, we can fold them into the
1043 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1046 // Scan over all recurrences, trying to fold loop invariants into them.
1047 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1048 // Scan all of the other operands to this mul and add them to the vector if
1049 // they are loop invariant w.r.t. the recurrence.
1050 std::vector<SCEVHandle> LIOps;
1051 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1052 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1053 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1054 LIOps.push_back(Ops[i]);
1055 Ops.erase(Ops.begin()+i);
1059 // If we found some loop invariants, fold them into the recurrence.
1060 if (!LIOps.empty()) {
1061 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
1062 std::vector<SCEVHandle> NewOps;
1063 NewOps.reserve(AddRec->getNumOperands());
1064 if (LIOps.size() == 1) {
1065 SCEV *Scale = LIOps[0];
1066 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1067 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1069 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1070 std::vector<SCEVHandle> MulOps(LIOps);
1071 MulOps.push_back(AddRec->getOperand(i));
1072 NewOps.push_back(getMulExpr(MulOps));
1076 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
1078 // If all of the other operands were loop invariant, we are done.
1079 if (Ops.size() == 1) return NewRec;
1081 // Otherwise, multiply the folded AddRec by the non-liv parts.
1082 for (unsigned i = 0;; ++i)
1083 if (Ops[i] == AddRec) {
1087 return getMulExpr(Ops);
1090 // Okay, if there weren't any loop invariants to be folded, check to see if
1091 // there are multiple AddRec's with the same loop induction variable being
1092 // multiplied together. If so, we can fold them.
1093 for (unsigned OtherIdx = Idx+1;
1094 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1095 if (OtherIdx != Idx) {
1096 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1097 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1098 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1099 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1100 SCEVHandle NewStart = getMulExpr(F->getStart(),
1102 SCEVHandle B = F->getStepRecurrence(*this);
1103 SCEVHandle D = G->getStepRecurrence(*this);
1104 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1107 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1109 if (Ops.size() == 2) return NewAddRec;
1111 Ops.erase(Ops.begin()+Idx);
1112 Ops.erase(Ops.begin()+OtherIdx-1);
1113 Ops.push_back(NewAddRec);
1114 return getMulExpr(Ops);
1118 // Otherwise couldn't fold anything into this recurrence. Move onto the
1122 // Okay, it looks like we really DO need an mul expr. Check to see if we
1123 // already have one, otherwise create a new one.
1124 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1125 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1128 Result = new SCEVMulExpr(Ops);
1132 SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1134 return getIntegerSCEV(1, LHS->getType()); // X udiv X --> 1
1136 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1137 if (RHSC->getValue()->equalsInt(1))
1138 return LHS; // X udiv 1 --> X
1140 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1141 Constant *LHSCV = LHSC->getValue();
1142 Constant *RHSCV = RHSC->getValue();
1143 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
1147 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1148 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
1152 SCEVHandle ScalarEvolution::getSDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1154 return getIntegerSCEV(1, LHS->getType()); // X sdiv X --> 1
1156 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1157 if (RHSC->getValue()->equalsInt(1))
1158 return LHS; // X sdiv 1 --> X
1160 if (RHSC->getValue()->isAllOnesValue())
1161 return getNegativeSCEV(LHS); // X sdiv -1 --> -X
1163 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1164 Constant *LHSCV = LHSC->getValue();
1165 Constant *RHSCV = RHSC->getValue();
1166 return getUnknown(ConstantExpr::getSDiv(LHSCV, RHSCV));
1170 SCEVSDivExpr *&Result = (*SCEVSDivs)[std::make_pair(LHS, RHS)];
1171 if (Result == 0) Result = new SCEVSDivExpr(LHS, RHS);
1176 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1177 /// specified loop. Simplify the expression as much as possible.
1178 SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
1179 const SCEVHandle &Step, const Loop *L) {
1180 std::vector<SCEVHandle> Operands;
1181 Operands.push_back(Start);
1182 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1183 if (StepChrec->getLoop() == L) {
1184 Operands.insert(Operands.end(), StepChrec->op_begin(),
1185 StepChrec->op_end());
1186 return getAddRecExpr(Operands, L);
1189 Operands.push_back(Step);
1190 return getAddRecExpr(Operands, L);
1193 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1194 /// specified loop. Simplify the expression as much as possible.
1195 SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
1197 if (Operands.size() == 1) return Operands[0];
1199 if (Operands.back()->isZero()) {
1200 Operands.pop_back();
1201 return getAddRecExpr(Operands, L); // {X,+,0} --> X
1204 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1205 if (SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1206 const Loop* NestedLoop = NestedAR->getLoop();
1207 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1208 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1209 NestedAR->op_end());
1210 SCEVHandle NestedARHandle(NestedAR);
1211 Operands[0] = NestedAR->getStart();
1212 NestedOperands[0] = getAddRecExpr(Operands, L);
1213 return getAddRecExpr(NestedOperands, NestedLoop);
1217 SCEVAddRecExpr *&Result =
1218 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1220 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1224 SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1225 const SCEVHandle &RHS) {
1226 std::vector<SCEVHandle> Ops;
1229 return getSMaxExpr(Ops);
1232 SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1233 assert(!Ops.empty() && "Cannot get empty smax!");
1234 if (Ops.size() == 1) return Ops[0];
1236 // Sort by complexity, this groups all similar expression types together.
1237 GroupByComplexity(Ops);
1239 // If there are any constants, fold them together.
1241 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1243 assert(Idx < Ops.size());
1244 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1245 // We found two constants, fold them together!
1246 ConstantInt *Fold = ConstantInt::get(
1247 APIntOps::smax(LHSC->getValue()->getValue(),
1248 RHSC->getValue()->getValue()));
1249 Ops[0] = getConstant(Fold);
1250 Ops.erase(Ops.begin()+1); // Erase the folded element
1251 if (Ops.size() == 1) return Ops[0];
1252 LHSC = cast<SCEVConstant>(Ops[0]);
1255 // If we are left with a constant -inf, strip it off.
1256 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1257 Ops.erase(Ops.begin());
1262 if (Ops.size() == 1) return Ops[0];
1264 // Find the first SMax
1265 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1268 // Check to see if one of the operands is an SMax. If so, expand its operands
1269 // onto our operand list, and recurse to simplify.
1270 if (Idx < Ops.size()) {
1271 bool DeletedSMax = false;
1272 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1273 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1274 Ops.erase(Ops.begin()+Idx);
1279 return getSMaxExpr(Ops);
1282 // Okay, check to see if the same value occurs in the operand list twice. If
1283 // so, delete one. Since we sorted the list, these values are required to
1285 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1286 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1287 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1291 if (Ops.size() == 1) return Ops[0];
1293 assert(!Ops.empty() && "Reduced smax down to nothing!");
1295 // Okay, it looks like we really DO need an smax expr. Check to see if we
1296 // already have one, otherwise create a new one.
1297 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1298 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1300 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1304 SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1305 const SCEVHandle &RHS) {
1306 std::vector<SCEVHandle> Ops;
1309 return getUMaxExpr(Ops);
1312 SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1313 assert(!Ops.empty() && "Cannot get empty umax!");
1314 if (Ops.size() == 1) return Ops[0];
1316 // Sort by complexity, this groups all similar expression types together.
1317 GroupByComplexity(Ops);
1319 // If there are any constants, fold them together.
1321 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1323 assert(Idx < Ops.size());
1324 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1325 // We found two constants, fold them together!
1326 ConstantInt *Fold = ConstantInt::get(
1327 APIntOps::umax(LHSC->getValue()->getValue(),
1328 RHSC->getValue()->getValue()));
1329 Ops[0] = getConstant(Fold);
1330 Ops.erase(Ops.begin()+1); // Erase the folded element
1331 if (Ops.size() == 1) return Ops[0];
1332 LHSC = cast<SCEVConstant>(Ops[0]);
1335 // If we are left with a constant zero, strip it off.
1336 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1337 Ops.erase(Ops.begin());
1342 if (Ops.size() == 1) return Ops[0];
1344 // Find the first UMax
1345 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1348 // Check to see if one of the operands is a UMax. If so, expand its operands
1349 // onto our operand list, and recurse to simplify.
1350 if (Idx < Ops.size()) {
1351 bool DeletedUMax = false;
1352 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1353 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1354 Ops.erase(Ops.begin()+Idx);
1359 return getUMaxExpr(Ops);
1362 // Okay, check to see if the same value occurs in the operand list twice. If
1363 // so, delete one. Since we sorted the list, these values are required to
1365 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1366 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1367 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1371 if (Ops.size() == 1) return Ops[0];
1373 assert(!Ops.empty() && "Reduced umax down to nothing!");
1375 // Okay, it looks like we really DO need a umax expr. Check to see if we
1376 // already have one, otherwise create a new one.
1377 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1378 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1380 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1384 SCEVHandle ScalarEvolution::getUnknown(Value *V) {
1385 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1386 return getConstant(CI);
1387 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1388 if (Result == 0) Result = new SCEVUnknown(V);
1393 //===----------------------------------------------------------------------===//
1394 // ScalarEvolutionsImpl Definition and Implementation
1395 //===----------------------------------------------------------------------===//
1397 /// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1401 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
1402 /// SE - A reference to the public ScalarEvolution object.
1403 ScalarEvolution &SE;
1405 /// F - The function we are analyzing.
1409 /// LI - The loop information for the function we are currently analyzing.
1413 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1415 SCEVHandle UnknownValue;
1417 /// Scalars - This is a cache of the scalars we have analyzed so far.
1419 std::map<Value*, SCEVHandle> Scalars;
1421 /// IterationCounts - Cache the iteration count of the loops for this
1422 /// function as they are computed.
1423 std::map<const Loop*, SCEVHandle> IterationCounts;
1425 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1426 /// the PHI instructions that we attempt to compute constant evolutions for.
1427 /// This allows us to avoid potentially expensive recomputation of these
1428 /// properties. An instruction maps to null if we are unable to compute its
1430 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
1433 ScalarEvolutionsImpl(ScalarEvolution &se, Function &f, LoopInfo &li)
1434 : SE(se), F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1436 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1437 /// expression and create a new one.
1438 SCEVHandle getSCEV(Value *V);
1440 /// hasSCEV - Return true if the SCEV for this value has already been
1442 bool hasSCEV(Value *V) const {
1443 return Scalars.count(V);
1446 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1447 /// the specified value.
1448 void setSCEV(Value *V, const SCEVHandle &H) {
1449 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1450 assert(isNew && "This entry already existed!");
1455 /// getSCEVAtScope - Compute the value of the specified expression within
1456 /// the indicated loop (which may be null to indicate in no loop). If the
1457 /// expression cannot be evaluated, return UnknownValue itself.
1458 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1461 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1462 /// an analyzable loop-invariant iteration count.
1463 bool hasLoopInvariantIterationCount(const Loop *L);
1465 /// getIterationCount - If the specified loop has a predictable iteration
1466 /// count, return it. Note that it is not valid to call this method on a
1467 /// loop without a loop-invariant iteration count.
1468 SCEVHandle getIterationCount(const Loop *L);
1470 /// deleteValueFromRecords - This method should be called by the
1471 /// client before it removes a value from the program, to make sure
1472 /// that no dangling references are left around.
1473 void deleteValueFromRecords(Value *V);
1476 /// createSCEV - We know that there is no SCEV for the specified value.
1477 /// Analyze the expression.
1478 SCEVHandle createSCEV(Value *V);
1480 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1482 SCEVHandle createNodeForPHI(PHINode *PN);
1484 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1485 /// for the specified instruction and replaces any references to the
1486 /// symbolic value SymName with the specified value. This is used during
1488 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1489 const SCEVHandle &SymName,
1490 const SCEVHandle &NewVal);
1492 /// ComputeIterationCount - Compute the number of times the specified loop
1494 SCEVHandle ComputeIterationCount(const Loop *L);
1496 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1497 /// 'icmp op load X, cst', try to see if we can compute the trip count.
1498 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1501 ICmpInst::Predicate p);
1503 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1504 /// constant number of times (the condition evolves only from constants),
1505 /// try to evaluate a few iterations of the loop until we get the exit
1506 /// condition gets a value of ExitWhen (true or false). If we cannot
1507 /// evaluate the trip count of the loop, return UnknownValue.
1508 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1511 /// HowFarToZero - Return the number of times a backedge comparing the
1512 /// specified value to zero will execute. If not computable, return
1514 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1516 /// HowFarToNonZero - Return the number of times a backedge checking the
1517 /// specified value for nonzero will execute. If not computable, return
1519 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
1521 /// HowManyLessThans - Return the number of times a backedge containing the
1522 /// specified less-than comparison will execute. If not computable, return
1523 /// UnknownValue. isSigned specifies whether the less-than is signed.
1524 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
1525 bool isSigned, bool trueWhenEqual);
1527 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
1528 /// (which may not be an immediate predecessor) which has exactly one
1529 /// successor from which BB is reachable, or null if no such block is
1531 BasicBlock* getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
1533 /// executesAtLeastOnce - Test whether entry to the loop is protected by
1534 /// a conditional between LHS and RHS.
1535 bool executesAtLeastOnce(const Loop *L, bool isSigned, bool trueWhenEqual,
1536 SCEV *LHS, SCEV *RHS);
1538 /// potentialInfiniteLoop - Test whether the loop might jump over the exit value
1539 /// due to wrapping.
1540 bool potentialInfiniteLoop(SCEV *Stride, SCEV *RHS, bool isSigned,
1541 bool trueWhenEqual);
1543 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1544 /// in the header of its containing loop, we know the loop executes a
1545 /// constant number of times, and the PHI node is just a recurrence
1546 /// involving constants, fold it.
1547 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its,
1552 //===----------------------------------------------------------------------===//
1553 // Basic SCEV Analysis and PHI Idiom Recognition Code
1556 /// deleteValueFromRecords - This method should be called by the
1557 /// client before it removes an instruction from the program, to make sure
1558 /// that no dangling references are left around.
1559 void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) {
1560 SmallVector<Value *, 16> Worklist;
1562 if (Scalars.erase(V)) {
1563 if (PHINode *PN = dyn_cast<PHINode>(V))
1564 ConstantEvolutionLoopExitValue.erase(PN);
1565 Worklist.push_back(V);
1568 while (!Worklist.empty()) {
1569 Value *VV = Worklist.back();
1570 Worklist.pop_back();
1572 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
1574 Instruction *Inst = cast<Instruction>(*UI);
1575 if (Scalars.erase(Inst)) {
1576 if (PHINode *PN = dyn_cast<PHINode>(VV))
1577 ConstantEvolutionLoopExitValue.erase(PN);
1578 Worklist.push_back(Inst);
1585 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1586 /// expression and create a new one.
1587 SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1588 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1590 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1591 if (I != Scalars.end()) return I->second;
1592 SCEVHandle S = createSCEV(V);
1593 Scalars.insert(std::make_pair(V, S));
1597 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1598 /// the specified instruction and replaces any references to the symbolic value
1599 /// SymName with the specified value. This is used during PHI resolution.
1600 void ScalarEvolutionsImpl::
1601 ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1602 const SCEVHandle &NewVal) {
1603 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1604 if (SI == Scalars.end()) return;
1607 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, SE);
1608 if (NV == SI->second) return; // No change.
1610 SI->second = NV; // Update the scalars map!
1612 // Any instruction values that use this instruction might also need to be
1614 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1616 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1619 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1620 /// a loop header, making it a potential recurrence, or it doesn't.
1622 SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1623 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1624 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1625 if (L->getHeader() == PN->getParent()) {
1626 // If it lives in the loop header, it has two incoming values, one
1627 // from outside the loop, and one from inside.
1628 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1629 unsigned BackEdge = IncomingEdge^1;
1631 // While we are analyzing this PHI node, handle its value symbolically.
1632 SCEVHandle SymbolicName = SE.getUnknown(PN);
1633 assert(Scalars.find(PN) == Scalars.end() &&
1634 "PHI node already processed?");
1635 Scalars.insert(std::make_pair(PN, SymbolicName));
1637 // Using this symbolic name for the PHI, analyze the value coming around
1639 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1641 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1642 // has a special value for the first iteration of the loop.
1644 // If the value coming around the backedge is an add with the symbolic
1645 // value we just inserted, then we found a simple induction variable!
1646 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1647 // If there is a single occurrence of the symbolic value, replace it
1648 // with a recurrence.
1649 unsigned FoundIndex = Add->getNumOperands();
1650 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1651 if (Add->getOperand(i) == SymbolicName)
1652 if (FoundIndex == e) {
1657 if (FoundIndex != Add->getNumOperands()) {
1658 // Create an add with everything but the specified operand.
1659 std::vector<SCEVHandle> Ops;
1660 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1661 if (i != FoundIndex)
1662 Ops.push_back(Add->getOperand(i));
1663 SCEVHandle Accum = SE.getAddExpr(Ops);
1665 // This is not a valid addrec if the step amount is varying each
1666 // loop iteration, but is not itself an addrec in this loop.
1667 if (Accum->isLoopInvariant(L) ||
1668 (isa<SCEVAddRecExpr>(Accum) &&
1669 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1670 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1671 SCEVHandle PHISCEV = SE.getAddRecExpr(StartVal, Accum, L);
1673 // Okay, for the entire analysis of this edge we assumed the PHI
1674 // to be symbolic. We now need to go back and update all of the
1675 // entries for the scalars that use the PHI (except for the PHI
1676 // itself) to use the new analyzed value instead of the "symbolic"
1678 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1682 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1683 // Otherwise, this could be a loop like this:
1684 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1685 // In this case, j = {1,+,1} and BEValue is j.
1686 // Because the other in-value of i (0) fits the evolution of BEValue
1687 // i really is an addrec evolution.
1688 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1689 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1691 // If StartVal = j.start - j.stride, we can use StartVal as the
1692 // initial step of the addrec evolution.
1693 if (StartVal == SE.getMinusSCEV(AddRec->getOperand(0),
1694 AddRec->getOperand(1))) {
1695 SCEVHandle PHISCEV =
1696 SE.getAddRecExpr(StartVal, AddRec->getOperand(1), L);
1698 // Okay, for the entire analysis of this edge we assumed the PHI
1699 // to be symbolic. We now need to go back and update all of the
1700 // entries for the scalars that use the PHI (except for the PHI
1701 // itself) to use the new analyzed value instead of the "symbolic"
1703 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1709 return SymbolicName;
1712 // If it's not a loop phi, we can't handle it yet.
1713 return SE.getUnknown(PN);
1716 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1717 /// guaranteed to end in (at every loop iteration). It is, at the same time,
1718 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1719 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
1720 static uint32_t GetMinTrailingZeros(SCEVHandle S) {
1721 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
1722 return C->getValue()->getValue().countTrailingZeros();
1724 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
1725 return std::min(GetMinTrailingZeros(T->getOperand()), T->getBitWidth());
1727 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
1728 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1729 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1732 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
1733 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1734 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1737 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
1738 // The result is the min of all operands results.
1739 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1740 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1741 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1745 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
1746 // The result is the sum of all operands results.
1747 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
1748 uint32_t BitWidth = M->getBitWidth();
1749 for (unsigned i = 1, e = M->getNumOperands();
1750 SumOpRes != BitWidth && i != e; ++i)
1751 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
1756 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
1757 // The result is the min of all operands results.
1758 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1759 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1760 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1764 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1765 // The result is the min of all operands results.
1766 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1767 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1768 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1772 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1773 // The result is the min of all operands results.
1774 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1775 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1776 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1780 // SCEVUDivExpr, SCEVSDivExpr, SCEVUnknown
1784 /// createSCEV - We know that there is no SCEV for the specified value.
1785 /// Analyze the expression.
1787 SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1788 if (!isa<IntegerType>(V->getType()))
1789 return SE.getUnknown(V);
1791 unsigned Opcode = Instruction::UserOp1;
1792 if (Instruction *I = dyn_cast<Instruction>(V))
1793 Opcode = I->getOpcode();
1794 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1795 Opcode = CE->getOpcode();
1797 return SE.getUnknown(V);
1799 User *U = cast<User>(V);
1801 case Instruction::Add:
1802 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1803 getSCEV(U->getOperand(1)));
1804 case Instruction::Mul:
1805 return SE.getMulExpr(getSCEV(U->getOperand(0)),
1806 getSCEV(U->getOperand(1)));
1807 case Instruction::UDiv:
1808 return SE.getUDivExpr(getSCEV(U->getOperand(0)),
1809 getSCEV(U->getOperand(1)));
1810 case Instruction::SDiv:
1811 return SE.getSDivExpr(getSCEV(U->getOperand(0)),
1812 getSCEV(U->getOperand(1)));
1813 case Instruction::Sub:
1814 return SE.getMinusSCEV(getSCEV(U->getOperand(0)),
1815 getSCEV(U->getOperand(1)));
1816 case Instruction::Or:
1817 // If the RHS of the Or is a constant, we may have something like:
1818 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1819 // optimizations will transparently handle this case.
1821 // In order for this transformation to be safe, the LHS must be of the
1822 // form X*(2^n) and the Or constant must be less than 2^n.
1823 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1824 SCEVHandle LHS = getSCEV(U->getOperand(0));
1825 const APInt &CIVal = CI->getValue();
1826 if (GetMinTrailingZeros(LHS) >=
1827 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
1828 return SE.getAddExpr(LHS, getSCEV(U->getOperand(1)));
1831 case Instruction::Xor:
1832 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1833 // If the RHS of the xor is a signbit, then this is just an add.
1834 // Instcombine turns add of signbit into xor as a strength reduction step.
1835 if (CI->getValue().isSignBit())
1836 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1837 getSCEV(U->getOperand(1)));
1839 // If the RHS of xor is -1, then this is a not operation.
1840 else if (CI->isAllOnesValue())
1841 return SE.getNotSCEV(getSCEV(U->getOperand(0)));
1845 case Instruction::Shl:
1846 // Turn shift left of a constant amount into a multiply.
1847 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1848 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1849 Constant *X = ConstantInt::get(
1850 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1851 return SE.getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1855 case Instruction::LShr:
1856 // Turn logical shift right of a constant into an unsigned divide.
1857 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1858 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1859 Constant *X = ConstantInt::get(
1860 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1861 return SE.getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1865 case Instruction::Trunc:
1866 return SE.getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
1868 case Instruction::ZExt:
1869 return SE.getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1871 case Instruction::SExt:
1872 return SE.getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1874 case Instruction::BitCast:
1875 // BitCasts are no-op casts so we just eliminate the cast.
1876 if (U->getType()->isInteger() &&
1877 U->getOperand(0)->getType()->isInteger())
1878 return getSCEV(U->getOperand(0));
1881 case Instruction::PHI:
1882 return createNodeForPHI(cast<PHINode>(U));
1884 case Instruction::Select:
1885 // This could be a smax or umax that was lowered earlier.
1886 // Try to recover it.
1887 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
1888 Value *LHS = ICI->getOperand(0);
1889 Value *RHS = ICI->getOperand(1);
1890 switch (ICI->getPredicate()) {
1891 case ICmpInst::ICMP_SLT:
1892 case ICmpInst::ICMP_SLE:
1893 std::swap(LHS, RHS);
1895 case ICmpInst::ICMP_SGT:
1896 case ICmpInst::ICMP_SGE:
1897 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
1898 return SE.getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
1899 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
1900 // ~smax(~x, ~y) == smin(x, y).
1901 return SE.getNotSCEV(SE.getSMaxExpr(
1902 SE.getNotSCEV(getSCEV(LHS)),
1903 SE.getNotSCEV(getSCEV(RHS))));
1905 case ICmpInst::ICMP_ULT:
1906 case ICmpInst::ICMP_ULE:
1907 std::swap(LHS, RHS);
1909 case ICmpInst::ICMP_UGT:
1910 case ICmpInst::ICMP_UGE:
1911 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
1912 return SE.getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
1913 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
1914 // ~umax(~x, ~y) == umin(x, y)
1915 return SE.getNotSCEV(SE.getUMaxExpr(SE.getNotSCEV(getSCEV(LHS)),
1916 SE.getNotSCEV(getSCEV(RHS))));
1923 default: // We cannot analyze this expression.
1927 return SE.getUnknown(V);
1932 //===----------------------------------------------------------------------===//
1933 // Iteration Count Computation Code
1936 /// getIterationCount - If the specified loop has a predictable iteration
1937 /// count, return it. Note that it is not valid to call this method on a
1938 /// loop without a loop-invariant iteration count.
1939 SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1940 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1941 if (I == IterationCounts.end()) {
1942 SCEVHandle ItCount = ComputeIterationCount(L);
1943 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1944 if (ItCount != UnknownValue) {
1945 assert(ItCount->isLoopInvariant(L) &&
1946 "Computed trip count isn't loop invariant for loop!");
1947 ++NumTripCountsComputed;
1948 } else if (isa<PHINode>(L->getHeader()->begin())) {
1949 // Only count loops that have phi nodes as not being computable.
1950 ++NumTripCountsNotComputed;
1956 /// ComputeIterationCount - Compute the number of times the specified loop
1958 SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1959 // If the loop has a non-one exit block count, we can't analyze it.
1960 SmallVector<BasicBlock*, 8> ExitBlocks;
1961 L->getExitBlocks(ExitBlocks);
1962 if (ExitBlocks.size() != 1) return UnknownValue;
1964 // Okay, there is one exit block. Try to find the condition that causes the
1965 // loop to be exited.
1966 BasicBlock *ExitBlock = ExitBlocks[0];
1968 BasicBlock *ExitingBlock = 0;
1969 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1971 if (L->contains(*PI)) {
1972 if (ExitingBlock == 0)
1975 return UnknownValue; // More than one block exiting!
1977 assert(ExitingBlock && "No exits from loop, something is broken!");
1979 // Okay, we've computed the exiting block. See what condition causes us to
1982 // FIXME: we should be able to handle switch instructions (with a single exit)
1983 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1984 if (ExitBr == 0) return UnknownValue;
1985 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1987 // At this point, we know we have a conditional branch that determines whether
1988 // the loop is exited. However, we don't know if the branch is executed each
1989 // time through the loop. If not, then the execution count of the branch will
1990 // not be equal to the trip count of the loop.
1992 // Currently we check for this by checking to see if the Exit branch goes to
1993 // the loop header. If so, we know it will always execute the same number of
1994 // times as the loop. We also handle the case where the exit block *is* the
1995 // loop header. This is common for un-rotated loops. More extensive analysis
1996 // could be done to handle more cases here.
1997 if (ExitBr->getSuccessor(0) != L->getHeader() &&
1998 ExitBr->getSuccessor(1) != L->getHeader() &&
1999 ExitBr->getParent() != L->getHeader())
2000 return UnknownValue;
2002 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2004 // If it's not an integer comparison then compute it the hard way.
2005 // Note that ICmpInst deals with pointer comparisons too so we must check
2006 // the type of the operand.
2007 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
2008 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
2009 ExitBr->getSuccessor(0) == ExitBlock);
2011 // If the condition was exit on true, convert the condition to exit on false
2012 ICmpInst::Predicate Cond;
2013 if (ExitBr->getSuccessor(1) == ExitBlock)
2014 Cond = ExitCond->getPredicate();
2016 Cond = ExitCond->getInversePredicate();
2018 // Handle common loops like: for (X = "string"; *X; ++X)
2019 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2020 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2022 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
2023 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2026 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2027 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2029 // Try to evaluate any dependencies out of the loop.
2030 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2031 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2032 Tmp = getSCEVAtScope(RHS, L);
2033 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2035 // At this point, we would like to compute how many iterations of the
2036 // loop the predicate will return true for these inputs.
2037 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2038 // If there is a loop-invariant, force it into the RHS.
2039 std::swap(LHS, RHS);
2040 Cond = ICmpInst::getSwappedPredicate(Cond);
2043 // FIXME: think about handling pointer comparisons! i.e.:
2044 // while (P != P+100) ++P;
2046 // If we have a comparison of a chrec against a constant, try to use value
2047 // ranges to answer this query.
2048 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2049 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
2050 if (AddRec->getLoop() == L) {
2051 // Form the comparison range using the constant of the correct type so
2052 // that the ConstantRange class knows to do a signed or unsigned
2054 ConstantInt *CompVal = RHSC->getValue();
2055 const Type *RealTy = ExitCond->getOperand(0)->getType();
2056 CompVal = dyn_cast<ConstantInt>(
2057 ConstantExpr::getBitCast(CompVal, RealTy));
2059 // Form the constant range.
2060 ConstantRange CompRange(
2061 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
2063 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE);
2064 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2069 case ICmpInst::ICMP_NE: { // while (X != Y)
2070 // Convert to: while (X-Y != 0)
2071 SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
2072 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2075 case ICmpInst::ICMP_EQ: {
2076 // Convert to: while (X-Y == 0) // while (X == Y)
2077 SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L);
2078 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2081 case ICmpInst::ICMP_SLT: {
2082 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true, false);
2083 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2086 case ICmpInst::ICMP_SGT: {
2087 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
2088 SE.getNotSCEV(RHS), L, true, false);
2089 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2092 case ICmpInst::ICMP_ULT: {
2093 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false, false);
2094 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2097 case ICmpInst::ICMP_UGT: {
2098 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
2099 SE.getNotSCEV(RHS), L, false, false);
2100 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2103 case ICmpInst::ICMP_SLE: {
2104 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true, true);
2105 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2108 case ICmpInst::ICMP_SGE: {
2109 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
2110 SE.getNotSCEV(RHS), L, true, true);
2111 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2114 case ICmpInst::ICMP_ULE: {
2115 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false, true);
2116 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2119 case ICmpInst::ICMP_UGE: {
2120 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
2121 SE.getNotSCEV(RHS), L, false, true);
2122 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2127 cerr << "ComputeIterationCount ";
2128 if (ExitCond->getOperand(0)->getType()->isUnsigned())
2129 cerr << "[unsigned] ";
2131 << Instruction::getOpcodeName(Instruction::ICmp)
2132 << " " << *RHS << "\n";
2136 return ComputeIterationCountExhaustively(L, ExitCond,
2137 ExitBr->getSuccessor(0) == ExitBlock);
2140 static ConstantInt *
2141 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2142 ScalarEvolution &SE) {
2143 SCEVHandle InVal = SE.getConstant(C);
2144 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
2145 assert(isa<SCEVConstant>(Val) &&
2146 "Evaluation of SCEV at constant didn't fold correctly?");
2147 return cast<SCEVConstant>(Val)->getValue();
2150 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
2151 /// and a GEP expression (missing the pointer index) indexing into it, return
2152 /// the addressed element of the initializer or null if the index expression is
2155 GetAddressedElementFromGlobal(GlobalVariable *GV,
2156 const std::vector<ConstantInt*> &Indices) {
2157 Constant *Init = GV->getInitializer();
2158 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2159 uint64_t Idx = Indices[i]->getZExtValue();
2160 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2161 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2162 Init = cast<Constant>(CS->getOperand(Idx));
2163 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2164 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2165 Init = cast<Constant>(CA->getOperand(Idx));
2166 } else if (isa<ConstantAggregateZero>(Init)) {
2167 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2168 assert(Idx < STy->getNumElements() && "Bad struct index!");
2169 Init = Constant::getNullValue(STy->getElementType(Idx));
2170 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2171 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2172 Init = Constant::getNullValue(ATy->getElementType());
2174 assert(0 && "Unknown constant aggregate type!");
2178 return 0; // Unknown initializer type
2184 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
2185 /// 'icmp op load X, cst', try to see if we can compute the trip count.
2186 SCEVHandle ScalarEvolutionsImpl::
2187 ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
2189 ICmpInst::Predicate predicate) {
2190 if (LI->isVolatile()) return UnknownValue;
2192 // Check to see if the loaded pointer is a getelementptr of a global.
2193 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2194 if (!GEP) return UnknownValue;
2196 // Make sure that it is really a constant global we are gepping, with an
2197 // initializer, and make sure the first IDX is really 0.
2198 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2199 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2200 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2201 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2202 return UnknownValue;
2204 // Okay, we allow one non-constant index into the GEP instruction.
2206 std::vector<ConstantInt*> Indexes;
2207 unsigned VarIdxNum = 0;
2208 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2209 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2210 Indexes.push_back(CI);
2211 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2212 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2213 VarIdx = GEP->getOperand(i);
2215 Indexes.push_back(0);
2218 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2219 // Check to see if X is a loop variant variable value now.
2220 SCEVHandle Idx = getSCEV(VarIdx);
2221 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2222 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2224 // We can only recognize very limited forms of loop index expressions, in
2225 // particular, only affine AddRec's like {C1,+,C2}.
2226 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2227 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2228 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2229 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2230 return UnknownValue;
2232 unsigned MaxSteps = MaxBruteForceIterations;
2233 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2234 ConstantInt *ItCst =
2235 ConstantInt::get(IdxExpr->getType(), IterationNum);
2236 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE);
2238 // Form the GEP offset.
2239 Indexes[VarIdxNum] = Val;
2241 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2242 if (Result == 0) break; // Cannot compute!
2244 // Evaluate the condition for this iteration.
2245 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2246 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2247 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2249 cerr << "\n***\n*** Computed loop count " << *ItCst
2250 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2253 ++NumArrayLenItCounts;
2254 return SE.getConstant(ItCst); // Found terminating iteration!
2257 return UnknownValue;
2261 /// CanConstantFold - Return true if we can constant fold an instruction of the
2262 /// specified type, assuming that all operands were constants.
2263 static bool CanConstantFold(const Instruction *I) {
2264 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2265 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2268 if (const CallInst *CI = dyn_cast<CallInst>(I))
2269 if (const Function *F = CI->getCalledFunction())
2270 return canConstantFoldCallTo(F);
2274 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2275 /// in the loop that V is derived from. We allow arbitrary operations along the
2276 /// way, but the operands of an operation must either be constants or a value
2277 /// derived from a constant PHI. If this expression does not fit with these
2278 /// constraints, return null.
2279 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2280 // If this is not an instruction, or if this is an instruction outside of the
2281 // loop, it can't be derived from a loop PHI.
2282 Instruction *I = dyn_cast<Instruction>(V);
2283 if (I == 0 || !L->contains(I->getParent())) return 0;
2285 if (PHINode *PN = dyn_cast<PHINode>(I)) {
2286 if (L->getHeader() == I->getParent())
2289 // We don't currently keep track of the control flow needed to evaluate
2290 // PHIs, so we cannot handle PHIs inside of loops.
2294 // If we won't be able to constant fold this expression even if the operands
2295 // are constants, return early.
2296 if (!CanConstantFold(I)) return 0;
2298 // Otherwise, we can evaluate this instruction if all of its operands are
2299 // constant or derived from a PHI node themselves.
2301 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2302 if (!(isa<Constant>(I->getOperand(Op)) ||
2303 isa<GlobalValue>(I->getOperand(Op)))) {
2304 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2305 if (P == 0) return 0; // Not evolving from PHI
2309 return 0; // Evolving from multiple different PHIs.
2312 // This is a expression evolving from a constant PHI!
2316 /// EvaluateExpression - Given an expression that passes the
2317 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2318 /// in the loop has the value PHIVal. If we can't fold this expression for some
2319 /// reason, return null.
2320 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2321 if (isa<PHINode>(V)) return PHIVal;
2322 if (Constant *C = dyn_cast<Constant>(V)) return C;
2323 Instruction *I = cast<Instruction>(V);
2325 std::vector<Constant*> Operands;
2326 Operands.resize(I->getNumOperands());
2328 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2329 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2330 if (Operands[i] == 0) return 0;
2333 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2334 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2335 &Operands[0], Operands.size());
2337 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2338 &Operands[0], Operands.size());
2341 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2342 /// in the header of its containing loop, we know the loop executes a
2343 /// constant number of times, and the PHI node is just a recurrence
2344 /// involving constants, fold it.
2345 Constant *ScalarEvolutionsImpl::
2346 getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, const Loop *L){
2347 std::map<PHINode*, Constant*>::iterator I =
2348 ConstantEvolutionLoopExitValue.find(PN);
2349 if (I != ConstantEvolutionLoopExitValue.end())
2352 if (Its.ugt(APInt(Its.getBitWidth(),MaxBruteForceIterations)))
2353 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2355 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2357 // Since the loop is canonicalized, the PHI node must have two entries. One
2358 // entry must be a constant (coming in from outside of the loop), and the
2359 // second must be derived from the same PHI.
2360 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2361 Constant *StartCST =
2362 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2364 return RetVal = 0; // Must be a constant.
2366 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2367 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2369 return RetVal = 0; // Not derived from same PHI.
2371 // Execute the loop symbolically to determine the exit value.
2372 if (Its.getActiveBits() >= 32)
2373 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2375 unsigned NumIterations = Its.getZExtValue(); // must be in range
2376 unsigned IterationNum = 0;
2377 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2378 if (IterationNum == NumIterations)
2379 return RetVal = PHIVal; // Got exit value!
2381 // Compute the value of the PHI node for the next iteration.
2382 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2383 if (NextPHI == PHIVal)
2384 return RetVal = NextPHI; // Stopped evolving!
2386 return 0; // Couldn't evaluate!
2391 /// ComputeIterationCountExhaustively - If the trip is known to execute a
2392 /// constant number of times (the condition evolves only from constants),
2393 /// try to evaluate a few iterations of the loop until we get the exit
2394 /// condition gets a value of ExitWhen (true or false). If we cannot
2395 /// evaluate the trip count of the loop, return UnknownValue.
2396 SCEVHandle ScalarEvolutionsImpl::
2397 ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
2398 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2399 if (PN == 0) return UnknownValue;
2401 // Since the loop is canonicalized, the PHI node must have two entries. One
2402 // entry must be a constant (coming in from outside of the loop), and the
2403 // second must be derived from the same PHI.
2404 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2405 Constant *StartCST =
2406 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2407 if (StartCST == 0) return UnknownValue; // Must be a constant.
2409 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2410 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2411 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2413 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2414 // the loop symbolically to determine when the condition gets a value of
2416 unsigned IterationNum = 0;
2417 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2418 for (Constant *PHIVal = StartCST;
2419 IterationNum != MaxIterations; ++IterationNum) {
2420 ConstantInt *CondVal =
2421 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2423 // Couldn't symbolically evaluate.
2424 if (!CondVal) return UnknownValue;
2426 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2427 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2428 ++NumBruteForceTripCountsComputed;
2429 return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
2432 // Compute the value of the PHI node for the next iteration.
2433 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2434 if (NextPHI == 0 || NextPHI == PHIVal)
2435 return UnknownValue; // Couldn't evaluate or not making progress...
2439 // Too many iterations were needed to evaluate.
2440 return UnknownValue;
2443 /// getSCEVAtScope - Compute the value of the specified expression within the
2444 /// indicated loop (which may be null to indicate in no loop). If the
2445 /// expression cannot be evaluated, return UnknownValue.
2446 SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2447 // FIXME: this should be turned into a virtual method on SCEV!
2449 if (isa<SCEVConstant>(V)) return V;
2451 // If this instruction is evolved from a constant-evolving PHI, compute the
2452 // exit value from the loop without using SCEVs.
2453 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2454 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2455 const Loop *LI = this->LI[I->getParent()];
2456 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2457 if (PHINode *PN = dyn_cast<PHINode>(I))
2458 if (PN->getParent() == LI->getHeader()) {
2459 // Okay, there is no closed form solution for the PHI node. Check
2460 // to see if the loop that contains it has a known iteration count.
2461 // If so, we may be able to force computation of the exit value.
2462 SCEVHandle IterationCount = getIterationCount(LI);
2463 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
2464 // Okay, we know how many times the containing loop executes. If
2465 // this is a constant evolving PHI node, get the final value at
2466 // the specified iteration number.
2467 Constant *RV = getConstantEvolutionLoopExitValue(PN,
2468 ICC->getValue()->getValue(),
2470 if (RV) return SE.getUnknown(RV);
2474 // Okay, this is an expression that we cannot symbolically evaluate
2475 // into a SCEV. Check to see if it's possible to symbolically evaluate
2476 // the arguments into constants, and if so, try to constant propagate the
2477 // result. This is particularly useful for computing loop exit values.
2478 if (CanConstantFold(I)) {
2479 std::vector<Constant*> Operands;
2480 Operands.reserve(I->getNumOperands());
2481 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2482 Value *Op = I->getOperand(i);
2483 if (Constant *C = dyn_cast<Constant>(Op)) {
2484 Operands.push_back(C);
2486 // If any of the operands is non-constant and if they are
2487 // non-integer, don't even try to analyze them with scev techniques.
2488 if (!isa<IntegerType>(Op->getType()))
2491 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2492 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
2493 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2496 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2497 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
2498 Operands.push_back(ConstantExpr::getIntegerCast(C,
2510 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2511 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2512 &Operands[0], Operands.size());
2514 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2515 &Operands[0], Operands.size());
2516 return SE.getUnknown(C);
2520 // This is some other type of SCEVUnknown, just return it.
2524 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2525 // Avoid performing the look-up in the common case where the specified
2526 // expression has no loop-variant portions.
2527 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2528 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2529 if (OpAtScope != Comm->getOperand(i)) {
2530 if (OpAtScope == UnknownValue) return UnknownValue;
2531 // Okay, at least one of these operands is loop variant but might be
2532 // foldable. Build a new instance of the folded commutative expression.
2533 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2534 NewOps.push_back(OpAtScope);
2536 for (++i; i != e; ++i) {
2537 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2538 if (OpAtScope == UnknownValue) return UnknownValue;
2539 NewOps.push_back(OpAtScope);
2541 if (isa<SCEVAddExpr>(Comm))
2542 return SE.getAddExpr(NewOps);
2543 if (isa<SCEVMulExpr>(Comm))
2544 return SE.getMulExpr(NewOps);
2545 if (isa<SCEVSMaxExpr>(Comm))
2546 return SE.getSMaxExpr(NewOps);
2547 if (isa<SCEVUMaxExpr>(Comm))
2548 return SE.getUMaxExpr(NewOps);
2549 assert(0 && "Unknown commutative SCEV type!");
2552 // If we got here, all operands are loop invariant.
2556 if (SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(V)) {
2557 SCEVHandle LHS = getSCEVAtScope(UDiv->getLHS(), L);
2558 if (LHS == UnknownValue) return LHS;
2559 SCEVHandle RHS = getSCEVAtScope(UDiv->getRHS(), L);
2560 if (RHS == UnknownValue) return RHS;
2561 if (LHS == UDiv->getLHS() && RHS == UDiv->getRHS())
2562 return UDiv; // must be loop invariant
2563 return SE.getUDivExpr(LHS, RHS);
2566 if (SCEVSDivExpr *SDiv = dyn_cast<SCEVSDivExpr>(V)) {
2567 SCEVHandle LHS = getSCEVAtScope(SDiv->getLHS(), L);
2568 if (LHS == UnknownValue) return LHS;
2569 SCEVHandle RHS = getSCEVAtScope(SDiv->getRHS(), L);
2570 if (RHS == UnknownValue) return RHS;
2571 if (LHS == SDiv->getLHS() && RHS == SDiv->getRHS())
2572 return SDiv; // must be loop invariant
2573 return SE.getSDivExpr(LHS, RHS);
2576 // If this is a loop recurrence for a loop that does not contain L, then we
2577 // are dealing with the final value computed by the loop.
2578 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2579 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2580 // To evaluate this recurrence, we need to know how many times the AddRec
2581 // loop iterates. Compute this now.
2582 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2583 if (IterationCount == UnknownValue) return UnknownValue;
2585 // Then, evaluate the AddRec.
2586 return AddRec->evaluateAtIteration(IterationCount, SE);
2588 return UnknownValue;
2591 //assert(0 && "Unknown SCEV type!");
2592 return UnknownValue;
2595 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2596 /// following equation:
2598 /// A * X = B (mod N)
2600 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2601 /// A and B isn't important.
2603 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2604 static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2605 ScalarEvolution &SE) {
2606 uint32_t BW = A.getBitWidth();
2607 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2608 assert(A != 0 && "A must be non-zero.");
2612 // The gcd of A and N may have only one prime factor: 2. The number of
2613 // trailing zeros in A is its multiplicity
2614 uint32_t Mult2 = A.countTrailingZeros();
2617 // 2. Check if B is divisible by D.
2619 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2620 // is not less than multiplicity of this prime factor for D.
2621 if (B.countTrailingZeros() < Mult2)
2622 return new SCEVCouldNotCompute();
2624 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2627 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2628 // bit width during computations.
2629 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2630 APInt Mod(BW + 1, 0);
2631 Mod.set(BW - Mult2); // Mod = N / D
2632 APInt I = AD.multiplicativeInverse(Mod);
2634 // 4. Compute the minimum unsigned root of the equation:
2635 // I * (B / D) mod (N / D)
2636 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2638 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2640 return SE.getConstant(Result.trunc(BW));
2643 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2644 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2645 /// might be the same) or two SCEVCouldNotCompute objects.
2647 static std::pair<SCEVHandle,SCEVHandle>
2648 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
2649 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2650 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2651 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2652 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2654 // We currently can only solve this if the coefficients are constants.
2655 if (!LC || !MC || !NC) {
2656 SCEV *CNC = new SCEVCouldNotCompute();
2657 return std::make_pair(CNC, CNC);
2660 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2661 const APInt &L = LC->getValue()->getValue();
2662 const APInt &M = MC->getValue()->getValue();
2663 const APInt &N = NC->getValue()->getValue();
2664 APInt Two(BitWidth, 2);
2665 APInt Four(BitWidth, 4);
2668 using namespace APIntOps;
2670 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2671 // The B coefficient is M-N/2
2675 // The A coefficient is N/2
2676 APInt A(N.sdiv(Two));
2678 // Compute the B^2-4ac term.
2681 SqrtTerm -= Four * (A * C);
2683 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2684 // integer value or else APInt::sqrt() will assert.
2685 APInt SqrtVal(SqrtTerm.sqrt());
2687 // Compute the two solutions for the quadratic formula.
2688 // The divisions must be performed as signed divisions.
2690 APInt TwoA( A << 1 );
2691 if (TwoA.isMinValue()) {
2692 SCEV *CNC = new SCEVCouldNotCompute();
2693 return std::make_pair(CNC, CNC);
2696 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2697 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2699 return std::make_pair(SE.getConstant(Solution1),
2700 SE.getConstant(Solution2));
2701 } // end APIntOps namespace
2704 /// HowFarToZero - Return the number of times a backedge comparing the specified
2705 /// value to zero will execute. If not computable, return UnknownValue
2706 SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2707 // If the value is a constant
2708 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2709 // If the value is already zero, the branch will execute zero times.
2710 if (C->getValue()->isZero()) return C;
2711 return UnknownValue; // Otherwise it will loop infinitely.
2714 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2715 if (!AddRec || AddRec->getLoop() != L)
2716 return UnknownValue;
2718 if (AddRec->isAffine()) {
2719 // If this is an affine expression, the execution count of this branch is
2720 // the minimum unsigned root of the following equation:
2722 // Start + Step*N = 0 (mod 2^BW)
2726 // Step*N = -Start (mod 2^BW)
2728 // where BW is the common bit width of Start and Step.
2730 // Get the initial value for the loop.
2731 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2732 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
2734 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
2736 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2737 // For now we handle only constant steps.
2739 // First, handle unitary steps.
2740 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
2741 return SE.getNegativeSCEV(Start); // N = -Start (as unsigned)
2742 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2743 return Start; // N = Start (as unsigned)
2745 // Then, try to solve the above equation provided that Start is constant.
2746 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
2747 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
2748 -StartC->getValue()->getValue(),SE);
2750 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2751 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2752 // the quadratic equation to solve it.
2753 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE);
2754 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2755 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2758 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2759 << " sol#2: " << *R2 << "\n";
2761 // Pick the smallest positive root value.
2762 if (ConstantInt *CB =
2763 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2764 R1->getValue(), R2->getValue()))) {
2765 if (CB->getZExtValue() == false)
2766 std::swap(R1, R2); // R1 is the minimum root now.
2768 // We can only use this value if the chrec ends up with an exact zero
2769 // value at this index. When solving for "X*X != 5", for example, we
2770 // should not accept a root of 2.
2771 SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE);
2773 return R1; // We found a quadratic root!
2778 return UnknownValue;
2781 /// HowFarToNonZero - Return the number of times a backedge checking the
2782 /// specified value for nonzero will execute. If not computable, return
2784 SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2785 // Loops that look like: while (X == 0) are very strange indeed. We don't
2786 // handle them yet except for the trivial case. This could be expanded in the
2787 // future as needed.
2789 // If the value is a constant, check to see if it is known to be non-zero
2790 // already. If so, the backedge will execute zero times.
2791 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2792 if (!C->getValue()->isNullValue())
2793 return SE.getIntegerSCEV(0, C->getType());
2794 return UnknownValue; // Otherwise it will loop infinitely.
2797 // We could implement others, but I really doubt anyone writes loops like
2798 // this, and if they did, they would already be constant folded.
2799 return UnknownValue;
2802 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
2803 /// (which may not be an immediate predecessor) which has exactly one
2804 /// successor from which BB is reachable, or null if no such block is
2808 ScalarEvolutionsImpl::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
2809 // If the block has a unique predecessor, the predecessor must have
2810 // no other successors from which BB is reachable.
2811 if (BasicBlock *Pred = BB->getSinglePredecessor())
2814 // A loop's header is defined to be a block that dominates the loop.
2815 // If the loop has a preheader, it must be a block that has exactly
2816 // one successor that can reach BB. This is slightly more strict
2817 // than necessary, but works if critical edges are split.
2818 if (Loop *L = LI.getLoopFor(BB))
2819 return L->getLoopPreheader();
2824 /// executesAtLeastOnce - Test whether entry to the loop is protected by
2825 /// a conditional between LHS and RHS.
2826 bool ScalarEvolutionsImpl::executesAtLeastOnce(const Loop *L, bool isSigned,
2828 SCEV *LHS, SCEV *RHS) {
2829 BasicBlock *Preheader = L->getLoopPreheader();
2830 BasicBlock *PreheaderDest = L->getHeader();
2832 // Starting at the preheader, climb up the predecessor chain, as long as
2833 // there are predecessors that can be found that have unique successors
2834 // leading to the original header.
2836 PreheaderDest = Preheader,
2837 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
2839 BranchInst *LoopEntryPredicate =
2840 dyn_cast<BranchInst>(Preheader->getTerminator());
2841 if (!LoopEntryPredicate ||
2842 LoopEntryPredicate->isUnconditional())
2845 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
2848 // Now that we found a conditional branch that dominates the loop, check to
2849 // see if it is the comparison we are looking for.
2850 Value *PreCondLHS = ICI->getOperand(0);
2851 Value *PreCondRHS = ICI->getOperand(1);
2852 ICmpInst::Predicate Cond;
2853 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2854 Cond = ICI->getPredicate();
2856 Cond = ICI->getInversePredicate();
2859 case ICmpInst::ICMP_UGT:
2860 if (isSigned || trueWhenEqual) continue;
2861 std::swap(PreCondLHS, PreCondRHS);
2862 Cond = ICmpInst::ICMP_ULT;
2864 case ICmpInst::ICMP_SGT:
2865 if (!isSigned || trueWhenEqual) continue;
2866 std::swap(PreCondLHS, PreCondRHS);
2867 Cond = ICmpInst::ICMP_SLT;
2869 case ICmpInst::ICMP_ULT:
2870 if (isSigned || trueWhenEqual) continue;
2872 case ICmpInst::ICMP_SLT:
2873 if (!isSigned || trueWhenEqual) continue;
2875 case ICmpInst::ICMP_UGE:
2876 if (isSigned || !trueWhenEqual) continue;
2877 std::swap(PreCondLHS, PreCondRHS);
2878 Cond = ICmpInst::ICMP_ULE;
2880 case ICmpInst::ICMP_SGE:
2881 if (!isSigned || !trueWhenEqual) continue;
2882 std::swap(PreCondLHS, PreCondRHS);
2883 Cond = ICmpInst::ICMP_SLE;
2885 case ICmpInst::ICMP_ULE:
2886 if (isSigned || !trueWhenEqual) continue;
2888 case ICmpInst::ICMP_SLE:
2889 if (!isSigned || !trueWhenEqual) continue;
2895 if (!PreCondLHS->getType()->isInteger()) continue;
2897 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
2898 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
2899 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
2900 (LHS == SE.getNotSCEV(PreCondRHSSCEV) &&
2901 RHS == SE.getNotSCEV(PreCondLHSSCEV)))
2908 static bool isNegative(SCEVHandle X) {
2909 if (SCEVConstant *C = dyn_cast<SCEVConstant>(X))
2910 return C->getValue()->getValue().isNegative();
2913 /// potentialInfiniteLoop - Test whether the loop might jump over the exit value
2914 /// due to wrapping around 2^n.
2915 bool ScalarEvolutionsImpl::potentialInfiniteLoop(SCEV *Stride, SCEV *RHS,
2916 bool isSigned, bool trueWhenEqual) {
2917 // Return true when the distance from RHS to maxint > Stride.
2919 SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride);
2923 if (SC->getValue()->isZero())
2925 if (!trueWhenEqual && SC->getValue()->isOne())
2928 SCEVConstant *R = dyn_cast<SCEVConstant>(RHS);
2932 // If negative, it wraps around every iteration, but we don't care about that.
2933 APInt S = SC->getValue()->getValue().abs();
2935 uint32_t Width = R->getValue()->getBitWidth();
2936 APInt Dist = (isSigned ? APInt::getSignedMaxValue(Width)
2937 : APInt::getMaxValue(Width))
2938 - R->getValue()->getValue();
2940 // Because we're looking at distance, we perform an unsigned comparison,
2941 // regardless of the sign of the computation.
2943 return !S.ult(Dist);
2945 return !S.ule(Dist);
2948 /// HowManyLessThans - Return the number of times a backedge containing the
2949 /// specified less-than comparison will execute. If not computable, return
2951 SCEVHandle ScalarEvolutionsImpl::
2952 HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
2953 bool isSigned, bool trueWhenEqual) {
2954 // Only handle: "ADDREC < LoopInvariant".
2955 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2957 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2958 if (!AddRec || AddRec->getLoop() != L)
2959 return UnknownValue;
2961 if (AddRec->isAffine()) {
2962 SCEVHandle Stride = AddRec->getOperand(1);
2963 if (potentialInfiniteLoop(Stride, RHS, isSigned, trueWhenEqual))
2964 return UnknownValue;
2966 // We don't handle this correctly at the moment. The problem is that when
2967 // the stride is negative, we're not counting how many times 'less-than' is
2968 // true as we approach it, we're counting how far away we are from wrapping
2969 // around the backside.
2970 if (isSigned && isNegative(Stride))
2971 return UnknownValue;
2973 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
2974 // m. So, we count the number of iterations in which {n,+,s} < m is true.
2975 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
2976 // treat m-n as signed nor unsigned due to overflow possibility.
2978 // Assuming that the loop will run at least once, we know that it will
2979 // run (m-n)/s times.
2981 // First, we get the value of the LHS in the first iteration: n
2982 SCEVHandle Start = AddRec->getOperand(0);
2984 SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType());
2986 // If the expression is less-than-or-equal to, we need to extend the
2987 // loop by one iteration.
2989 // The loop won't actually run (m-n)/s times because the loop iterations
2990 // might not divide cleanly. For example, if you have {2,+,5} u< 10 the
2991 // division would equal one, but the loop runs twice putting the
2992 // induction variable at 12.
2993 SCEVHandle End = SE.getAddExpr(RHS, Stride);
2995 End = SE.getMinusSCEV(End, One);
2997 if (!executesAtLeastOnce(L, isSigned, trueWhenEqual,
2998 SE.getMinusSCEV(Start, One), RHS)) {
2999 // If not, we get the value of the LHS in the first iteration in which
3000 // the above condition doesn't hold. This equals to max(m,n).
3001 End = isSigned ? SE.getSMaxExpr(End, Start)
3002 : SE.getUMaxExpr(End, Start);
3005 // Finally, we subtract these two values to get the number of times the
3006 // backedge is executed: (max(m,n)-n)/s.
3008 // Note that a trip count is always positive. Using SDiv here produces
3009 // wrong answers when Start < End.
3010 return SE.getUDivExpr(SE.getMinusSCEV(End, Start), Stride);
3013 return UnknownValue;
3016 /// getNumIterationsInRange - Return the number of iterations of this loop that
3017 /// produce values in the specified constant range. Another way of looking at
3018 /// this is that it returns the first iteration number where the value is not in
3019 /// the condition, thus computing the exit count. If the iteration count can't
3020 /// be computed, an instance of SCEVCouldNotCompute is returned.
3021 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3022 ScalarEvolution &SE) const {
3023 if (Range.isFullSet()) // Infinite loop.
3024 return new SCEVCouldNotCompute();
3026 // If the start is a non-zero constant, shift the range to simplify things.
3027 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
3028 if (!SC->getValue()->isZero()) {
3029 std::vector<SCEVHandle> Operands(op_begin(), op_end());
3030 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3031 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
3032 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
3033 return ShiftedAddRec->getNumIterationsInRange(
3034 Range.subtract(SC->getValue()->getValue()), SE);
3035 // This is strange and shouldn't happen.
3036 return new SCEVCouldNotCompute();
3039 // The only time we can solve this is when we have all constant indices.
3040 // Otherwise, we cannot determine the overflow conditions.
3041 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3042 if (!isa<SCEVConstant>(getOperand(i)))
3043 return new SCEVCouldNotCompute();
3046 // Okay at this point we know that all elements of the chrec are constants and
3047 // that the start element is zero.
3049 // First check to see if the range contains zero. If not, the first
3051 if (!Range.contains(APInt(getBitWidth(),0)))
3052 return SE.getConstant(ConstantInt::get(getType(),0));
3055 // If this is an affine expression then we have this situation:
3056 // Solve {0,+,A} in Range === Ax in Range
3058 // We know that zero is in the range. If A is positive then we know that
3059 // the upper value of the range must be the first possible exit value.
3060 // If A is negative then the lower of the range is the last possible loop
3061 // value. Also note that we already checked for a full range.
3062 APInt One(getBitWidth(),1);
3063 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3064 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3066 // The exit value should be (End+A)/A.
3067 APInt ExitVal = (End + A).udiv(A);
3068 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3070 // Evaluate at the exit value. If we really did fall out of the valid
3071 // range, then we computed our trip count, otherwise wrap around or other
3072 // things must have happened.
3073 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
3074 if (Range.contains(Val->getValue()))
3075 return new SCEVCouldNotCompute(); // Something strange happened
3077 // Ensure that the previous value is in the range. This is a sanity check.
3078 assert(Range.contains(
3079 EvaluateConstantChrecAtConstant(this,
3080 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
3081 "Linear scev computation is off in a bad way!");
3082 return SE.getConstant(ExitValue);
3083 } else if (isQuadratic()) {
3084 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3085 // quadratic equation to solve it. To do this, we must frame our problem in
3086 // terms of figuring out when zero is crossed, instead of when
3087 // Range.getUpper() is crossed.
3088 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
3089 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3090 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
3092 // Next, solve the constructed addrec
3093 std::pair<SCEVHandle,SCEVHandle> Roots =
3094 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
3095 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3096 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3098 // Pick the smallest positive root value.
3099 if (ConstantInt *CB =
3100 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3101 R1->getValue(), R2->getValue()))) {
3102 if (CB->getZExtValue() == false)
3103 std::swap(R1, R2); // R1 is the minimum root now.
3105 // Make sure the root is not off by one. The returned iteration should
3106 // not be in the range, but the previous one should be. When solving
3107 // for "X*X < 5", for example, we should not return a root of 2.
3108 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
3111 if (Range.contains(R1Val->getValue())) {
3112 // The next iteration must be out of the range...
3113 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3115 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
3116 if (!Range.contains(R1Val->getValue()))
3117 return SE.getConstant(NextVal);
3118 return new SCEVCouldNotCompute(); // Something strange happened
3121 // If R1 was not in the range, then it is a good return value. Make
3122 // sure that R1-1 WAS in the range though, just in case.
3123 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
3124 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
3125 if (Range.contains(R1Val->getValue()))
3127 return new SCEVCouldNotCompute(); // Something strange happened
3132 return new SCEVCouldNotCompute();
3137 //===----------------------------------------------------------------------===//
3138 // ScalarEvolution Class Implementation
3139 //===----------------------------------------------------------------------===//
3141 bool ScalarEvolution::runOnFunction(Function &F) {
3142 Impl = new ScalarEvolutionsImpl(*this, F, getAnalysis<LoopInfo>());
3146 void ScalarEvolution::releaseMemory() {
3147 delete (ScalarEvolutionsImpl*)Impl;
3151 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3152 AU.setPreservesAll();
3153 AU.addRequiredTransitive<LoopInfo>();
3156 SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
3157 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
3160 /// hasSCEV - Return true if the SCEV for this value has already been
3162 bool ScalarEvolution::hasSCEV(Value *V) const {
3163 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
3167 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
3168 /// the specified value.
3169 void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
3170 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
3174 SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
3175 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
3178 bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
3179 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
3182 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
3183 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
3186 void ScalarEvolution::deleteValueFromRecords(Value *V) const {
3187 return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
3190 static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
3192 // Print all inner loops first
3193 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3194 PrintLoopInfo(OS, SE, *I);
3196 OS << "Loop " << L->getHeader()->getName() << ": ";
3198 SmallVector<BasicBlock*, 8> ExitBlocks;
3199 L->getExitBlocks(ExitBlocks);
3200 if (ExitBlocks.size() != 1)
3201 OS << "<multiple exits> ";
3203 if (SE->hasLoopInvariantIterationCount(L)) {
3204 OS << *SE->getIterationCount(L) << " iterations! ";
3206 OS << "Unpredictable iteration count. ";
3212 void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
3213 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
3214 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
3216 OS << "Classifying expressions for: " << F.getName() << "\n";
3217 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
3218 if (I->getType()->isInteger()) {
3221 SCEVHandle SV = getSCEV(&*I);
3225 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
3227 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
3228 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3229 OS << "<<Unknown>>";
3239 OS << "Determining loop execution counts for: " << F.getName() << "\n";
3240 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
3241 PrintLoopInfo(OS, this, *I);