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(NumBruteForceEvaluations,
87 "Number of brute force evaluations needed to "
88 "calculate high-order polynomial exit values");
89 STATISTIC(NumArrayLenItCounts,
90 "Number of trip counts computed with array length");
91 STATISTIC(NumTripCountsComputed,
92 "Number of loops with predictable loop counts");
93 STATISTIC(NumTripCountsNotComputed,
94 "Number of loops without predictable loop counts");
95 STATISTIC(NumBruteForceTripCountsComputed,
96 "Number of loops with trip counts computed by force");
98 static cl::opt<unsigned>
99 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
100 cl::desc("Maximum number of iterations SCEV will "
101 "symbolically execute a constant derived loop"),
104 static RegisterPass<ScalarEvolution>
105 R("scalar-evolution", "Scalar Evolution Analysis", false, true);
106 char ScalarEvolution::ID = 0;
108 //===----------------------------------------------------------------------===//
109 // SCEV class definitions
110 //===----------------------------------------------------------------------===//
112 //===----------------------------------------------------------------------===//
113 // Implementation of the SCEV class.
116 void SCEV::dump() const {
120 uint32_t SCEV::getBitWidth() const {
121 if (const IntegerType* ITy = dyn_cast<IntegerType>(getType()))
122 return ITy->getBitWidth();
126 bool SCEV::isZero() const {
127 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
128 return SC->getValue()->isZero();
133 SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
135 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
136 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
140 const Type *SCEVCouldNotCompute::getType() const {
141 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
145 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
146 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
150 SCEVHandle SCEVCouldNotCompute::
151 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
152 const SCEVHandle &Conc,
153 ScalarEvolution &SE) const {
157 void SCEVCouldNotCompute::print(std::ostream &OS) const {
158 OS << "***COULDNOTCOMPUTE***";
161 bool SCEVCouldNotCompute::classof(const SCEV *S) {
162 return S->getSCEVType() == scCouldNotCompute;
166 // SCEVConstants - Only allow the creation of one SCEVConstant for any
167 // particular value. Don't use a SCEVHandle here, or else the object will
169 static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
172 SCEVConstant::~SCEVConstant() {
173 SCEVConstants->erase(V);
176 SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
177 SCEVConstant *&R = (*SCEVConstants)[V];
178 if (R == 0) R = new SCEVConstant(V);
182 SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
183 return getConstant(ConstantInt::get(Val));
186 const Type *SCEVConstant::getType() const { return V->getType(); }
188 void SCEVConstant::print(std::ostream &OS) const {
189 WriteAsOperand(OS, V, false);
192 // SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
193 // particular input. Don't use a SCEVHandle here, or else the object will
195 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
196 SCEVTruncateExpr*> > SCEVTruncates;
198 SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
199 : SCEV(scTruncate), Op(op), Ty(ty) {
200 assert(Op->getType()->isInteger() && Ty->isInteger() &&
201 "Cannot truncate non-integer value!");
202 assert(Op->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()
203 && "This is not a truncating conversion!");
206 SCEVTruncateExpr::~SCEVTruncateExpr() {
207 SCEVTruncates->erase(std::make_pair(Op, Ty));
210 void SCEVTruncateExpr::print(std::ostream &OS) const {
211 OS << "(truncate " << *Op << " to " << *Ty << ")";
214 // SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
215 // particular input. Don't use a SCEVHandle here, or else the object will never
217 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
218 SCEVZeroExtendExpr*> > SCEVZeroExtends;
220 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
221 : SCEV(scZeroExtend), Op(op), Ty(ty) {
222 assert(Op->getType()->isInteger() && Ty->isInteger() &&
223 "Cannot zero extend non-integer value!");
224 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
225 && "This is not an extending conversion!");
228 SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
229 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
232 void SCEVZeroExtendExpr::print(std::ostream &OS) const {
233 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
236 // SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
237 // particular input. Don't use a SCEVHandle here, or else the object will never
239 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
240 SCEVSignExtendExpr*> > SCEVSignExtends;
242 SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
243 : SCEV(scSignExtend), Op(op), Ty(ty) {
244 assert(Op->getType()->isInteger() && Ty->isInteger() &&
245 "Cannot sign extend non-integer value!");
246 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
247 && "This is not an extending conversion!");
250 SCEVSignExtendExpr::~SCEVSignExtendExpr() {
251 SCEVSignExtends->erase(std::make_pair(Op, Ty));
254 void SCEVSignExtendExpr::print(std::ostream &OS) const {
255 OS << "(signextend " << *Op << " to " << *Ty << ")";
258 // SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
259 // particular input. Don't use a SCEVHandle here, or else the object will never
261 static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
262 SCEVCommutativeExpr*> > SCEVCommExprs;
264 SCEVCommutativeExpr::~SCEVCommutativeExpr() {
265 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
266 std::vector<SCEV*>(Operands.begin(),
270 void SCEVCommutativeExpr::print(std::ostream &OS) const {
271 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
272 const char *OpStr = getOperationStr();
273 OS << "(" << *Operands[0];
274 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
275 OS << OpStr << *Operands[i];
279 SCEVHandle SCEVCommutativeExpr::
280 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
281 const SCEVHandle &Conc,
282 ScalarEvolution &SE) const {
283 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
285 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
286 if (H != getOperand(i)) {
287 std::vector<SCEVHandle> NewOps;
288 NewOps.reserve(getNumOperands());
289 for (unsigned j = 0; j != i; ++j)
290 NewOps.push_back(getOperand(j));
292 for (++i; i != e; ++i)
293 NewOps.push_back(getOperand(i)->
294 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
296 if (isa<SCEVAddExpr>(this))
297 return SE.getAddExpr(NewOps);
298 else if (isa<SCEVMulExpr>(this))
299 return SE.getMulExpr(NewOps);
300 else if (isa<SCEVSMaxExpr>(this))
301 return SE.getSMaxExpr(NewOps);
302 else if (isa<SCEVUMaxExpr>(this))
303 return SE.getUMaxExpr(NewOps);
305 assert(0 && "Unknown commutative expr!");
312 // SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
313 // input. Don't use a SCEVHandle here, or else the object will never be
315 static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
316 SCEVUDivExpr*> > SCEVUDivs;
318 SCEVUDivExpr::~SCEVUDivExpr() {
319 SCEVUDivs->erase(std::make_pair(LHS, RHS));
322 void SCEVUDivExpr::print(std::ostream &OS) const {
323 OS << "(" << *LHS << " /u " << *RHS << ")";
326 const Type *SCEVUDivExpr::getType() const {
327 return LHS->getType();
330 // SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
331 // particular input. Don't use a SCEVHandle here, or else the object will never
333 static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
334 SCEVAddRecExpr*> > SCEVAddRecExprs;
336 SCEVAddRecExpr::~SCEVAddRecExpr() {
337 SCEVAddRecExprs->erase(std::make_pair(L,
338 std::vector<SCEV*>(Operands.begin(),
342 SCEVHandle SCEVAddRecExpr::
343 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
344 const SCEVHandle &Conc,
345 ScalarEvolution &SE) const {
346 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
348 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
349 if (H != getOperand(i)) {
350 std::vector<SCEVHandle> NewOps;
351 NewOps.reserve(getNumOperands());
352 for (unsigned j = 0; j != i; ++j)
353 NewOps.push_back(getOperand(j));
355 for (++i; i != e; ++i)
356 NewOps.push_back(getOperand(i)->
357 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
359 return SE.getAddRecExpr(NewOps, L);
366 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
367 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
368 // contain L and if the start is invariant.
369 return !QueryLoop->contains(L->getHeader()) &&
370 getOperand(0)->isLoopInvariant(QueryLoop);
374 void SCEVAddRecExpr::print(std::ostream &OS) const {
375 OS << "{" << *Operands[0];
376 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
377 OS << ",+," << *Operands[i];
378 OS << "}<" << L->getHeader()->getName() + ">";
381 // SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
382 // value. Don't use a SCEVHandle here, or else the object will never be
384 static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
386 SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
388 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
389 // All non-instruction values are loop invariant. All instructions are loop
390 // invariant if they are not contained in the specified loop.
391 if (Instruction *I = dyn_cast<Instruction>(V))
392 return !L->contains(I->getParent());
396 const Type *SCEVUnknown::getType() const {
400 void SCEVUnknown::print(std::ostream &OS) const {
401 WriteAsOperand(OS, V, false);
404 //===----------------------------------------------------------------------===//
406 //===----------------------------------------------------------------------===//
409 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
410 /// than the complexity of the RHS. This comparator is used to canonicalize
412 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
413 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
414 return LHS->getSCEVType() < RHS->getSCEVType();
419 /// GroupByComplexity - Given a list of SCEV objects, order them by their
420 /// complexity, and group objects of the same complexity together by value.
421 /// When this routine is finished, we know that any duplicates in the vector are
422 /// consecutive and that complexity is monotonically increasing.
424 /// Note that we go take special precautions to ensure that we get determinstic
425 /// results from this routine. In other words, we don't want the results of
426 /// this to depend on where the addresses of various SCEV objects happened to
429 static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
430 if (Ops.size() < 2) return; // Noop
431 if (Ops.size() == 2) {
432 // This is the common case, which also happens to be trivially simple.
434 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
435 std::swap(Ops[0], Ops[1]);
439 // Do the rough sort by complexity.
440 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
442 // Now that we are sorted by complexity, group elements of the same
443 // complexity. Note that this is, at worst, N^2, but the vector is likely to
444 // be extremely short in practice. Note that we take this approach because we
445 // do not want to depend on the addresses of the objects we are grouping.
446 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
448 unsigned Complexity = S->getSCEVType();
450 // If there are any objects of the same complexity and same value as this
452 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
453 if (Ops[j] == S) { // Found a duplicate.
454 // Move it to immediately after i'th element.
455 std::swap(Ops[i+1], Ops[j]);
456 ++i; // no need to rescan it.
457 if (i == e-2) return; // Done!
465 //===----------------------------------------------------------------------===//
466 // Simple SCEV method implementations
467 //===----------------------------------------------------------------------===//
469 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
470 /// specified signed integer value and return a SCEV for the constant.
471 SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
474 C = Constant::getNullValue(Ty);
475 else if (Ty->isFloatingPoint())
476 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
477 APFloat::IEEEdouble, Val));
479 C = ConstantInt::get(Ty, Val);
480 return getUnknown(C);
483 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
485 SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
486 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
487 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
489 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(V->getType())));
492 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
493 SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
494 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
495 return getUnknown(ConstantExpr::getNot(VC->getValue()));
497 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(V->getType()));
498 return getMinusSCEV(AllOnes, V);
501 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
503 SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
504 const SCEVHandle &RHS) {
506 return getAddExpr(LHS, getNegativeSCEV(RHS));
510 /// BinomialCoefficient - Compute BC(It, K). The result has width W.
512 static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
514 const IntegerType* ResultTy) {
515 // Handle the simplest case efficiently.
517 return SE.getTruncateOrZeroExtend(It, ResultTy);
519 // We are using the following formula for BC(It, K):
521 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
523 // Suppose, W is the bitwidth of the return value. We must be prepared for
524 // overflow. Hence, we must assure that the result of our computation is
525 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
526 // safe in modular arithmetic.
528 // However, this code doesn't use exactly that formula; the formula it uses
529 // is something like the following, where T is the number of factors of 2 in
530 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
533 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
535 // This formula is trivially equivalent to the previous formula. However,
536 // this formula can be implemented much more efficiently. The trick is that
537 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
538 // arithmetic. To do exact division in modular arithmetic, all we have
539 // to do is multiply by the inverse. Therefore, this step can be done at
542 // The next issue is how to safely do the division by 2^T. The way this
543 // is done is by doing the multiplication step at a width of at least W + T
544 // bits. This way, the bottom W+T bits of the product are accurate. Then,
545 // when we perform the division by 2^T (which is equivalent to a right shift
546 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
547 // truncated out after the division by 2^T.
549 // In comparison to just directly using the first formula, this technique
550 // is much more efficient; using the first formula requires W * K bits,
551 // but this formula less than W + K bits. Also, the first formula requires
552 // a division step, whereas this formula only requires multiplies and shifts.
554 // It doesn't matter whether the subtraction step is done in the calculation
555 // width or the input iteration count's width; if the subtraction overflows,
556 // the result must be zero anyway. We prefer here to do it in the width of
557 // the induction variable because it helps a lot for certain cases; CodeGen
558 // isn't smart enough to ignore the overflow, which leads to much less
559 // efficient code if the width of the subtraction is wider than the native
562 // (It's possible to not widen at all by pulling out factors of 2 before
563 // the multiplication; for example, K=2 can be calculated as
564 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
565 // extra arithmetic, so it's not an obvious win, and it gets
566 // much more complicated for K > 3.)
568 // Protection from insane SCEVs; this bound is conservative,
569 // but it probably doesn't matter.
571 return new SCEVCouldNotCompute();
573 unsigned W = ResultTy->getBitWidth();
575 // Calculate K! / 2^T and T; we divide out the factors of two before
576 // multiplying for calculating K! / 2^T to avoid overflow.
577 // Other overflow doesn't matter because we only care about the bottom
578 // W bits of the result.
579 APInt OddFactorial(W, 1);
581 for (unsigned i = 3; i <= K; ++i) {
583 unsigned TwoFactors = Mult.countTrailingZeros();
585 Mult = Mult.lshr(TwoFactors);
586 OddFactorial *= Mult;
589 // We need at least W + T bits for the multiplication step
590 // FIXME: A temporary hack; we round up the bitwidths
591 // to the nearest power of 2 to be nice to the code generator.
592 unsigned CalculationBits = 1U << Log2_32_Ceil(W + T);
593 // FIXME: Temporary hack to avoid generating integers that are too wide.
594 // Although, it's not completely clear how to determine how much
595 // widening is safe; for example, on X86, we can't really widen
596 // beyond 64 because we need to be able to do multiplication
597 // that's CalculationBits wide, but on X86-64, we can safely widen up to
599 if (CalculationBits > 64)
600 return new SCEVCouldNotCompute();
602 // Calcuate 2^T, at width T+W.
603 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
605 // Calculate the multiplicative inverse of K! / 2^T;
606 // this multiplication factor will perform the exact division by
608 APInt Mod = APInt::getSignedMinValue(W+1);
609 APInt MultiplyFactor = OddFactorial.zext(W+1);
610 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
611 MultiplyFactor = MultiplyFactor.trunc(W);
613 // Calculate the product, at width T+W
614 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
615 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
616 for (unsigned i = 1; i != K; ++i) {
617 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
618 Dividend = SE.getMulExpr(Dividend,
619 SE.getTruncateOrZeroExtend(S, CalculationTy));
623 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
625 // Truncate the result, and divide by K! / 2^T.
627 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
628 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
631 /// evaluateAtIteration - Return the value of this chain of recurrences at
632 /// the specified iteration number. We can evaluate this recurrence by
633 /// multiplying each element in the chain by the binomial coefficient
634 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
636 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
638 /// where BC(It, k) stands for binomial coefficient.
640 SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
641 ScalarEvolution &SE) const {
642 SCEVHandle Result = getStart();
643 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
644 // The computation is correct in the face of overflow provided that the
645 // multiplication is performed _after_ the evaluation of the binomial
648 SE.getMulExpr(getOperand(i),
649 BinomialCoefficient(It, i, SE,
650 cast<IntegerType>(getType())));
651 Result = SE.getAddExpr(Result, Val);
656 //===----------------------------------------------------------------------===//
657 // SCEV Expression folder implementations
658 //===----------------------------------------------------------------------===//
660 SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
661 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
663 ConstantExpr::getTrunc(SC->getValue(), Ty));
665 // If the input value is a chrec scev made out of constants, truncate
666 // all of the constants.
667 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
668 std::vector<SCEVHandle> Operands;
669 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
670 // FIXME: This should allow truncation of other expression types!
671 if (isa<SCEVConstant>(AddRec->getOperand(i)))
672 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
675 if (Operands.size() == AddRec->getNumOperands())
676 return getAddRecExpr(Operands, AddRec->getLoop());
679 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
680 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
684 SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty) {
685 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
687 ConstantExpr::getZExt(SC->getValue(), Ty));
689 // FIXME: If the input value is a chrec scev, and we can prove that the value
690 // did not overflow the old, smaller, value, we can zero extend all of the
691 // operands (often constants). This would allow analysis of something like
692 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
694 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
695 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
699 SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
700 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
702 ConstantExpr::getSExt(SC->getValue(), Ty));
704 // FIXME: If the input value is a chrec scev, and we can prove that the value
705 // did not overflow the old, smaller, value, we can sign extend all of the
706 // operands (often constants). This would allow analysis of something like
707 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
709 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
710 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
714 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
715 /// of the input value to the specified type. If the type must be
716 /// extended, it is zero extended.
717 SCEVHandle ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
719 const Type *SrcTy = V->getType();
720 assert(SrcTy->isInteger() && Ty->isInteger() &&
721 "Cannot truncate or zero extend with non-integer arguments!");
722 if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
723 return V; // No conversion
724 if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits())
725 return getTruncateExpr(V, Ty);
726 return getZeroExtendExpr(V, Ty);
729 // get - Get a canonical add expression, or something simpler if possible.
730 SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
731 assert(!Ops.empty() && "Cannot get empty add!");
732 if (Ops.size() == 1) return Ops[0];
734 // Sort by complexity, this groups all similar expression types together.
735 GroupByComplexity(Ops);
737 // If there are any constants, fold them together.
739 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
741 assert(Idx < Ops.size());
742 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
743 // We found two constants, fold them together!
744 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
745 RHSC->getValue()->getValue());
746 Ops[0] = getConstant(Fold);
747 Ops.erase(Ops.begin()+1); // Erase the folded element
748 if (Ops.size() == 1) return Ops[0];
749 LHSC = cast<SCEVConstant>(Ops[0]);
752 // If we are left with a constant zero being added, strip it off.
753 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
754 Ops.erase(Ops.begin());
759 if (Ops.size() == 1) return Ops[0];
761 // Okay, check to see if the same value occurs in the operand list twice. If
762 // so, merge them together into an multiply expression. Since we sorted the
763 // list, these values are required to be adjacent.
764 const Type *Ty = Ops[0]->getType();
765 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
766 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
767 // Found a match, merge the two values into a multiply, and add any
768 // remaining values to the result.
769 SCEVHandle Two = getIntegerSCEV(2, Ty);
770 SCEVHandle Mul = getMulExpr(Ops[i], Two);
773 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
775 return getAddExpr(Ops);
778 // Now we know the first non-constant operand. Skip past any cast SCEVs.
779 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
782 // If there are add operands they would be next.
783 if (Idx < Ops.size()) {
784 bool DeletedAdd = false;
785 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
786 // If we have an add, expand the add operands onto the end of the operands
788 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
789 Ops.erase(Ops.begin()+Idx);
793 // If we deleted at least one add, we added operands to the end of the list,
794 // and they are not necessarily sorted. Recurse to resort and resimplify
795 // any operands we just aquired.
797 return getAddExpr(Ops);
800 // Skip over the add expression until we get to a multiply.
801 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
804 // If we are adding something to a multiply expression, make sure the
805 // something is not already an operand of the multiply. If so, merge it into
807 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
808 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
809 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
810 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
811 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
812 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
813 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
814 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
815 if (Mul->getNumOperands() != 2) {
816 // If the multiply has more than two operands, we must get the
818 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
819 MulOps.erase(MulOps.begin()+MulOp);
820 InnerMul = getMulExpr(MulOps);
822 SCEVHandle One = getIntegerSCEV(1, Ty);
823 SCEVHandle AddOne = getAddExpr(InnerMul, One);
824 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
825 if (Ops.size() == 2) return OuterMul;
827 Ops.erase(Ops.begin()+AddOp);
828 Ops.erase(Ops.begin()+Idx-1);
830 Ops.erase(Ops.begin()+Idx);
831 Ops.erase(Ops.begin()+AddOp-1);
833 Ops.push_back(OuterMul);
834 return getAddExpr(Ops);
837 // Check this multiply against other multiplies being added together.
838 for (unsigned OtherMulIdx = Idx+1;
839 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
841 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
842 // If MulOp occurs in OtherMul, we can fold the two multiplies
844 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
845 OMulOp != e; ++OMulOp)
846 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
847 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
848 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
849 if (Mul->getNumOperands() != 2) {
850 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
851 MulOps.erase(MulOps.begin()+MulOp);
852 InnerMul1 = getMulExpr(MulOps);
854 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
855 if (OtherMul->getNumOperands() != 2) {
856 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
858 MulOps.erase(MulOps.begin()+OMulOp);
859 InnerMul2 = getMulExpr(MulOps);
861 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
862 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
863 if (Ops.size() == 2) return OuterMul;
864 Ops.erase(Ops.begin()+Idx);
865 Ops.erase(Ops.begin()+OtherMulIdx-1);
866 Ops.push_back(OuterMul);
867 return getAddExpr(Ops);
873 // If there are any add recurrences in the operands list, see if any other
874 // added values are loop invariant. If so, we can fold them into the
876 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
879 // Scan over all recurrences, trying to fold loop invariants into them.
880 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
881 // Scan all of the other operands to this add and add them to the vector if
882 // they are loop invariant w.r.t. the recurrence.
883 std::vector<SCEVHandle> LIOps;
884 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
885 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
886 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
887 LIOps.push_back(Ops[i]);
888 Ops.erase(Ops.begin()+i);
892 // If we found some loop invariants, fold them into the recurrence.
893 if (!LIOps.empty()) {
894 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
895 LIOps.push_back(AddRec->getStart());
897 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
898 AddRecOps[0] = getAddExpr(LIOps);
900 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
901 // If all of the other operands were loop invariant, we are done.
902 if (Ops.size() == 1) return NewRec;
904 // Otherwise, add the folded AddRec by the non-liv parts.
905 for (unsigned i = 0;; ++i)
906 if (Ops[i] == AddRec) {
910 return getAddExpr(Ops);
913 // Okay, if there weren't any loop invariants to be folded, check to see if
914 // there are multiple AddRec's with the same loop induction variable being
915 // added together. If so, we can fold them.
916 for (unsigned OtherIdx = Idx+1;
917 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
918 if (OtherIdx != Idx) {
919 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
920 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
921 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
922 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
923 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
924 if (i >= NewOps.size()) {
925 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
926 OtherAddRec->op_end());
929 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
931 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
933 if (Ops.size() == 2) return NewAddRec;
935 Ops.erase(Ops.begin()+Idx);
936 Ops.erase(Ops.begin()+OtherIdx-1);
937 Ops.push_back(NewAddRec);
938 return getAddExpr(Ops);
942 // Otherwise couldn't fold anything into this recurrence. Move onto the
946 // Okay, it looks like we really DO need an add expr. Check to see if we
947 // already have one, otherwise create a new one.
948 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
949 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
951 if (Result == 0) Result = new SCEVAddExpr(Ops);
956 SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
957 assert(!Ops.empty() && "Cannot get empty mul!");
959 // Sort by complexity, this groups all similar expression types together.
960 GroupByComplexity(Ops);
962 // If there are any constants, fold them together.
964 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
966 // C1*(C2+V) -> C1*C2 + C1*V
968 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
969 if (Add->getNumOperands() == 2 &&
970 isa<SCEVConstant>(Add->getOperand(0)))
971 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
972 getMulExpr(LHSC, Add->getOperand(1)));
976 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
977 // We found two constants, fold them together!
978 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
979 RHSC->getValue()->getValue());
980 Ops[0] = getConstant(Fold);
981 Ops.erase(Ops.begin()+1); // Erase the folded element
982 if (Ops.size() == 1) return Ops[0];
983 LHSC = cast<SCEVConstant>(Ops[0]);
986 // If we are left with a constant one being multiplied, strip it off.
987 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
988 Ops.erase(Ops.begin());
990 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
991 // If we have a multiply of zero, it will always be zero.
996 // Skip over the add expression until we get to a multiply.
997 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1000 if (Ops.size() == 1)
1003 // If there are mul operands inline them all into this expression.
1004 if (Idx < Ops.size()) {
1005 bool DeletedMul = false;
1006 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1007 // If we have an mul, expand the mul operands onto the end of the operands
1009 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1010 Ops.erase(Ops.begin()+Idx);
1014 // If we deleted at least one mul, we added operands to the end of the list,
1015 // and they are not necessarily sorted. Recurse to resort and resimplify
1016 // any operands we just aquired.
1018 return getMulExpr(Ops);
1021 // If there are any add recurrences in the operands list, see if any other
1022 // added values are loop invariant. If so, we can fold them into the
1024 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1027 // Scan over all recurrences, trying to fold loop invariants into them.
1028 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1029 // Scan all of the other operands to this mul and add them to the vector if
1030 // they are loop invariant w.r.t. the recurrence.
1031 std::vector<SCEVHandle> LIOps;
1032 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1033 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1034 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1035 LIOps.push_back(Ops[i]);
1036 Ops.erase(Ops.begin()+i);
1040 // If we found some loop invariants, fold them into the recurrence.
1041 if (!LIOps.empty()) {
1042 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
1043 std::vector<SCEVHandle> NewOps;
1044 NewOps.reserve(AddRec->getNumOperands());
1045 if (LIOps.size() == 1) {
1046 SCEV *Scale = LIOps[0];
1047 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1048 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1050 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1051 std::vector<SCEVHandle> MulOps(LIOps);
1052 MulOps.push_back(AddRec->getOperand(i));
1053 NewOps.push_back(getMulExpr(MulOps));
1057 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
1059 // If all of the other operands were loop invariant, we are done.
1060 if (Ops.size() == 1) return NewRec;
1062 // Otherwise, multiply the folded AddRec by the non-liv parts.
1063 for (unsigned i = 0;; ++i)
1064 if (Ops[i] == AddRec) {
1068 return getMulExpr(Ops);
1071 // Okay, if there weren't any loop invariants to be folded, check to see if
1072 // there are multiple AddRec's with the same loop induction variable being
1073 // multiplied together. If so, we can fold them.
1074 for (unsigned OtherIdx = Idx+1;
1075 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1076 if (OtherIdx != Idx) {
1077 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1078 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1079 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1080 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1081 SCEVHandle NewStart = getMulExpr(F->getStart(),
1083 SCEVHandle B = F->getStepRecurrence(*this);
1084 SCEVHandle D = G->getStepRecurrence(*this);
1085 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1088 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1090 if (Ops.size() == 2) return NewAddRec;
1092 Ops.erase(Ops.begin()+Idx);
1093 Ops.erase(Ops.begin()+OtherIdx-1);
1094 Ops.push_back(NewAddRec);
1095 return getMulExpr(Ops);
1099 // Otherwise couldn't fold anything into this recurrence. Move onto the
1103 // Okay, it looks like we really DO need an mul expr. Check to see if we
1104 // already have one, otherwise create a new one.
1105 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1106 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1109 Result = new SCEVMulExpr(Ops);
1113 SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1114 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1115 if (RHSC->getValue()->equalsInt(1))
1116 return LHS; // X udiv 1 --> x
1118 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1119 Constant *LHSCV = LHSC->getValue();
1120 Constant *RHSCV = RHSC->getValue();
1121 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
1125 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1127 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1128 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
1133 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1134 /// specified loop. Simplify the expression as much as possible.
1135 SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
1136 const SCEVHandle &Step, const Loop *L) {
1137 std::vector<SCEVHandle> Operands;
1138 Operands.push_back(Start);
1139 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1140 if (StepChrec->getLoop() == L) {
1141 Operands.insert(Operands.end(), StepChrec->op_begin(),
1142 StepChrec->op_end());
1143 return getAddRecExpr(Operands, L);
1146 Operands.push_back(Step);
1147 return getAddRecExpr(Operands, L);
1150 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1151 /// specified loop. Simplify the expression as much as possible.
1152 SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
1154 if (Operands.size() == 1) return Operands[0];
1156 if (Operands.back()->isZero()) {
1157 Operands.pop_back();
1158 return getAddRecExpr(Operands, L); // {X,+,0} --> X
1161 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1162 if (SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1163 const Loop* NestedLoop = NestedAR->getLoop();
1164 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1165 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1166 NestedAR->op_end());
1167 SCEVHandle NestedARHandle(NestedAR);
1168 Operands[0] = NestedAR->getStart();
1169 NestedOperands[0] = getAddRecExpr(Operands, L);
1170 return getAddRecExpr(NestedOperands, NestedLoop);
1174 SCEVAddRecExpr *&Result =
1175 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1177 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1181 SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1182 const SCEVHandle &RHS) {
1183 std::vector<SCEVHandle> Ops;
1186 return getSMaxExpr(Ops);
1189 SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1190 assert(!Ops.empty() && "Cannot get empty smax!");
1191 if (Ops.size() == 1) return Ops[0];
1193 // Sort by complexity, this groups all similar expression types together.
1194 GroupByComplexity(Ops);
1196 // If there are any constants, fold them together.
1198 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1200 assert(Idx < Ops.size());
1201 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1202 // We found two constants, fold them together!
1203 ConstantInt *Fold = ConstantInt::get(
1204 APIntOps::smax(LHSC->getValue()->getValue(),
1205 RHSC->getValue()->getValue()));
1206 Ops[0] = getConstant(Fold);
1207 Ops.erase(Ops.begin()+1); // Erase the folded element
1208 if (Ops.size() == 1) return Ops[0];
1209 LHSC = cast<SCEVConstant>(Ops[0]);
1212 // If we are left with a constant -inf, strip it off.
1213 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1214 Ops.erase(Ops.begin());
1219 if (Ops.size() == 1) return Ops[0];
1221 // Find the first SMax
1222 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1225 // Check to see if one of the operands is an SMax. If so, expand its operands
1226 // onto our operand list, and recurse to simplify.
1227 if (Idx < Ops.size()) {
1228 bool DeletedSMax = false;
1229 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1230 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1231 Ops.erase(Ops.begin()+Idx);
1236 return getSMaxExpr(Ops);
1239 // Okay, check to see if the same value occurs in the operand list twice. If
1240 // so, delete one. Since we sorted the list, these values are required to
1242 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1243 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1244 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1248 if (Ops.size() == 1) return Ops[0];
1250 assert(!Ops.empty() && "Reduced smax down to nothing!");
1252 // Okay, it looks like we really DO need an smax expr. Check to see if we
1253 // already have one, otherwise create a new one.
1254 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1255 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1257 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1261 SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1262 const SCEVHandle &RHS) {
1263 std::vector<SCEVHandle> Ops;
1266 return getUMaxExpr(Ops);
1269 SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1270 assert(!Ops.empty() && "Cannot get empty umax!");
1271 if (Ops.size() == 1) return Ops[0];
1273 // Sort by complexity, this groups all similar expression types together.
1274 GroupByComplexity(Ops);
1276 // If there are any constants, fold them together.
1278 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1280 assert(Idx < Ops.size());
1281 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1282 // We found two constants, fold them together!
1283 ConstantInt *Fold = ConstantInt::get(
1284 APIntOps::umax(LHSC->getValue()->getValue(),
1285 RHSC->getValue()->getValue()));
1286 Ops[0] = getConstant(Fold);
1287 Ops.erase(Ops.begin()+1); // Erase the folded element
1288 if (Ops.size() == 1) return Ops[0];
1289 LHSC = cast<SCEVConstant>(Ops[0]);
1292 // If we are left with a constant zero, strip it off.
1293 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1294 Ops.erase(Ops.begin());
1299 if (Ops.size() == 1) return Ops[0];
1301 // Find the first UMax
1302 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1305 // Check to see if one of the operands is a UMax. If so, expand its operands
1306 // onto our operand list, and recurse to simplify.
1307 if (Idx < Ops.size()) {
1308 bool DeletedUMax = false;
1309 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1310 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1311 Ops.erase(Ops.begin()+Idx);
1316 return getUMaxExpr(Ops);
1319 // Okay, check to see if the same value occurs in the operand list twice. If
1320 // so, delete one. Since we sorted the list, these values are required to
1322 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1323 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1324 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1328 if (Ops.size() == 1) return Ops[0];
1330 assert(!Ops.empty() && "Reduced umax down to nothing!");
1332 // Okay, it looks like we really DO need a umax expr. Check to see if we
1333 // already have one, otherwise create a new one.
1334 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1335 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1337 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1341 SCEVHandle ScalarEvolution::getUnknown(Value *V) {
1342 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1343 return getConstant(CI);
1344 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1345 if (Result == 0) Result = new SCEVUnknown(V);
1350 //===----------------------------------------------------------------------===//
1351 // ScalarEvolutionsImpl Definition and Implementation
1352 //===----------------------------------------------------------------------===//
1354 /// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1358 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
1359 /// SE - A reference to the public ScalarEvolution object.
1360 ScalarEvolution &SE;
1362 /// F - The function we are analyzing.
1366 /// LI - The loop information for the function we are currently analyzing.
1370 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1372 SCEVHandle UnknownValue;
1374 /// Scalars - This is a cache of the scalars we have analyzed so far.
1376 std::map<Value*, SCEVHandle> Scalars;
1378 /// IterationCounts - Cache the iteration count of the loops for this
1379 /// function as they are computed.
1380 std::map<const Loop*, SCEVHandle> IterationCounts;
1382 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1383 /// the PHI instructions that we attempt to compute constant evolutions for.
1384 /// This allows us to avoid potentially expensive recomputation of these
1385 /// properties. An instruction maps to null if we are unable to compute its
1387 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
1390 ScalarEvolutionsImpl(ScalarEvolution &se, Function &f, LoopInfo &li)
1391 : SE(se), F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1393 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1394 /// expression and create a new one.
1395 SCEVHandle getSCEV(Value *V);
1397 /// hasSCEV - Return true if the SCEV for this value has already been
1399 bool hasSCEV(Value *V) const {
1400 return Scalars.count(V);
1403 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1404 /// the specified value.
1405 void setSCEV(Value *V, const SCEVHandle &H) {
1406 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1407 assert(isNew && "This entry already existed!");
1411 /// getSCEVAtScope - Compute the value of the specified expression within
1412 /// the indicated loop (which may be null to indicate in no loop). If the
1413 /// expression cannot be evaluated, return UnknownValue itself.
1414 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1417 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1418 /// an analyzable loop-invariant iteration count.
1419 bool hasLoopInvariantIterationCount(const Loop *L);
1421 /// getIterationCount - If the specified loop has a predictable iteration
1422 /// count, return it. Note that it is not valid to call this method on a
1423 /// loop without a loop-invariant iteration count.
1424 SCEVHandle getIterationCount(const Loop *L);
1426 /// deleteValueFromRecords - This method should be called by the
1427 /// client before it removes a value from the program, to make sure
1428 /// that no dangling references are left around.
1429 void deleteValueFromRecords(Value *V);
1432 /// createSCEV - We know that there is no SCEV for the specified value.
1433 /// Analyze the expression.
1434 SCEVHandle createSCEV(Value *V);
1436 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1438 SCEVHandle createNodeForPHI(PHINode *PN);
1440 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1441 /// for the specified instruction and replaces any references to the
1442 /// symbolic value SymName with the specified value. This is used during
1444 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1445 const SCEVHandle &SymName,
1446 const SCEVHandle &NewVal);
1448 /// ComputeIterationCount - Compute the number of times the specified loop
1450 SCEVHandle ComputeIterationCount(const Loop *L);
1452 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1453 /// 'icmp op load X, cst', try to see if we can compute the trip count.
1454 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1457 ICmpInst::Predicate p);
1459 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1460 /// constant number of times (the condition evolves only from constants),
1461 /// try to evaluate a few iterations of the loop until we get the exit
1462 /// condition gets a value of ExitWhen (true or false). If we cannot
1463 /// evaluate the trip count of the loop, return UnknownValue.
1464 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1467 /// HowFarToZero - Return the number of times a backedge comparing the
1468 /// specified value to zero will execute. If not computable, return
1470 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1472 /// HowFarToNonZero - Return the number of times a backedge checking the
1473 /// specified value for nonzero will execute. If not computable, return
1475 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
1477 /// HowManyLessThans - Return the number of times a backedge containing the
1478 /// specified less-than comparison will execute. If not computable, return
1479 /// UnknownValue. isSigned specifies whether the less-than is signed.
1480 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
1483 /// executesAtLeastOnce - Test whether entry to the loop is protected by
1484 /// a conditional between LHS and RHS.
1485 bool executesAtLeastOnce(const Loop *L, bool isSigned, SCEV *LHS, SCEV *RHS);
1487 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1488 /// in the header of its containing loop, we know the loop executes a
1489 /// constant number of times, and the PHI node is just a recurrence
1490 /// involving constants, fold it.
1491 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its,
1496 //===----------------------------------------------------------------------===//
1497 // Basic SCEV Analysis and PHI Idiom Recognition Code
1500 /// deleteValueFromRecords - This method should be called by the
1501 /// client before it removes an instruction from the program, to make sure
1502 /// that no dangling references are left around.
1503 void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) {
1504 SmallVector<Value *, 16> Worklist;
1506 if (Scalars.erase(V)) {
1507 if (PHINode *PN = dyn_cast<PHINode>(V))
1508 ConstantEvolutionLoopExitValue.erase(PN);
1509 Worklist.push_back(V);
1512 while (!Worklist.empty()) {
1513 Value *VV = Worklist.back();
1514 Worklist.pop_back();
1516 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
1518 Instruction *Inst = cast<Instruction>(*UI);
1519 if (Scalars.erase(Inst)) {
1520 if (PHINode *PN = dyn_cast<PHINode>(VV))
1521 ConstantEvolutionLoopExitValue.erase(PN);
1522 Worklist.push_back(Inst);
1529 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1530 /// expression and create a new one.
1531 SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1532 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1534 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1535 if (I != Scalars.end()) return I->second;
1536 SCEVHandle S = createSCEV(V);
1537 Scalars.insert(std::make_pair(V, S));
1541 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1542 /// the specified instruction and replaces any references to the symbolic value
1543 /// SymName with the specified value. This is used during PHI resolution.
1544 void ScalarEvolutionsImpl::
1545 ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1546 const SCEVHandle &NewVal) {
1547 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1548 if (SI == Scalars.end()) return;
1551 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, SE);
1552 if (NV == SI->second) return; // No change.
1554 SI->second = NV; // Update the scalars map!
1556 // Any instruction values that use this instruction might also need to be
1558 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1560 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1563 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1564 /// a loop header, making it a potential recurrence, or it doesn't.
1566 SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1567 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1568 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1569 if (L->getHeader() == PN->getParent()) {
1570 // If it lives in the loop header, it has two incoming values, one
1571 // from outside the loop, and one from inside.
1572 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1573 unsigned BackEdge = IncomingEdge^1;
1575 // While we are analyzing this PHI node, handle its value symbolically.
1576 SCEVHandle SymbolicName = SE.getUnknown(PN);
1577 assert(Scalars.find(PN) == Scalars.end() &&
1578 "PHI node already processed?");
1579 Scalars.insert(std::make_pair(PN, SymbolicName));
1581 // Using this symbolic name for the PHI, analyze the value coming around
1583 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1585 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1586 // has a special value for the first iteration of the loop.
1588 // If the value coming around the backedge is an add with the symbolic
1589 // value we just inserted, then we found a simple induction variable!
1590 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1591 // If there is a single occurrence of the symbolic value, replace it
1592 // with a recurrence.
1593 unsigned FoundIndex = Add->getNumOperands();
1594 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1595 if (Add->getOperand(i) == SymbolicName)
1596 if (FoundIndex == e) {
1601 if (FoundIndex != Add->getNumOperands()) {
1602 // Create an add with everything but the specified operand.
1603 std::vector<SCEVHandle> Ops;
1604 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1605 if (i != FoundIndex)
1606 Ops.push_back(Add->getOperand(i));
1607 SCEVHandle Accum = SE.getAddExpr(Ops);
1609 // This is not a valid addrec if the step amount is varying each
1610 // loop iteration, but is not itself an addrec in this loop.
1611 if (Accum->isLoopInvariant(L) ||
1612 (isa<SCEVAddRecExpr>(Accum) &&
1613 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1614 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1615 SCEVHandle PHISCEV = SE.getAddRecExpr(StartVal, Accum, L);
1617 // Okay, for the entire analysis of this edge we assumed the PHI
1618 // to be symbolic. We now need to go back and update all of the
1619 // entries for the scalars that use the PHI (except for the PHI
1620 // itself) to use the new analyzed value instead of the "symbolic"
1622 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1626 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1627 // Otherwise, this could be a loop like this:
1628 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1629 // In this case, j = {1,+,1} and BEValue is j.
1630 // Because the other in-value of i (0) fits the evolution of BEValue
1631 // i really is an addrec evolution.
1632 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1633 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1635 // If StartVal = j.start - j.stride, we can use StartVal as the
1636 // initial step of the addrec evolution.
1637 if (StartVal == SE.getMinusSCEV(AddRec->getOperand(0),
1638 AddRec->getOperand(1))) {
1639 SCEVHandle PHISCEV =
1640 SE.getAddRecExpr(StartVal, AddRec->getOperand(1), L);
1642 // Okay, for the entire analysis of this edge we assumed the PHI
1643 // to be symbolic. We now need to go back and update all of the
1644 // entries for the scalars that use the PHI (except for the PHI
1645 // itself) to use the new analyzed value instead of the "symbolic"
1647 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1653 return SymbolicName;
1656 // If it's not a loop phi, we can't handle it yet.
1657 return SE.getUnknown(PN);
1660 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1661 /// guaranteed to end in (at every loop iteration). It is, at the same time,
1662 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1663 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
1664 static uint32_t GetMinTrailingZeros(SCEVHandle S) {
1665 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
1666 return C->getValue()->getValue().countTrailingZeros();
1668 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
1669 return std::min(GetMinTrailingZeros(T->getOperand()), T->getBitWidth());
1671 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
1672 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1673 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1676 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
1677 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1678 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1681 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
1682 // The result is the min of all operands results.
1683 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1684 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1685 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1689 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
1690 // The result is the sum of all operands results.
1691 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
1692 uint32_t BitWidth = M->getBitWidth();
1693 for (unsigned i = 1, e = M->getNumOperands();
1694 SumOpRes != BitWidth && i != e; ++i)
1695 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
1700 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
1701 // The result is the min of all operands results.
1702 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1703 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1704 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1708 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1709 // The result is the min of all operands results.
1710 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1711 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1712 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1716 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1717 // The result is the min of all operands results.
1718 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1719 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1720 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1724 // SCEVUDivExpr, SCEVUnknown
1728 /// createSCEV - We know that there is no SCEV for the specified value.
1729 /// Analyze the expression.
1731 SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1732 if (!isa<IntegerType>(V->getType()))
1733 return SE.getUnknown(V);
1735 unsigned Opcode = Instruction::UserOp1;
1736 if (Instruction *I = dyn_cast<Instruction>(V))
1737 Opcode = I->getOpcode();
1738 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1739 Opcode = CE->getOpcode();
1741 return SE.getUnknown(V);
1743 User *U = cast<User>(V);
1745 case Instruction::Add:
1746 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1747 getSCEV(U->getOperand(1)));
1748 case Instruction::Mul:
1749 return SE.getMulExpr(getSCEV(U->getOperand(0)),
1750 getSCEV(U->getOperand(1)));
1751 case Instruction::UDiv:
1752 return SE.getUDivExpr(getSCEV(U->getOperand(0)),
1753 getSCEV(U->getOperand(1)));
1754 case Instruction::Sub:
1755 return SE.getMinusSCEV(getSCEV(U->getOperand(0)),
1756 getSCEV(U->getOperand(1)));
1757 case Instruction::Or:
1758 // If the RHS of the Or is a constant, we may have something like:
1759 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1760 // optimizations will transparently handle this case.
1762 // In order for this transformation to be safe, the LHS must be of the
1763 // form X*(2^n) and the Or constant must be less than 2^n.
1764 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1765 SCEVHandle LHS = getSCEV(U->getOperand(0));
1766 const APInt &CIVal = CI->getValue();
1767 if (GetMinTrailingZeros(LHS) >=
1768 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
1769 return SE.getAddExpr(LHS, getSCEV(U->getOperand(1)));
1772 case Instruction::Xor:
1773 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1774 // If the RHS of the xor is a signbit, then this is just an add.
1775 // Instcombine turns add of signbit into xor as a strength reduction step.
1776 if (CI->getValue().isSignBit())
1777 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1778 getSCEV(U->getOperand(1)));
1780 // If the RHS of xor is -1, then this is a not operation.
1781 else if (CI->isAllOnesValue())
1782 return SE.getNotSCEV(getSCEV(U->getOperand(0)));
1786 case Instruction::Shl:
1787 // Turn shift left of a constant amount into a multiply.
1788 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1789 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1790 Constant *X = ConstantInt::get(
1791 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1792 return SE.getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1796 case Instruction::LShr:
1797 // Turn logical shift right of a constant into a unsigned divide.
1798 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1799 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1800 Constant *X = ConstantInt::get(
1801 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1802 return SE.getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1806 case Instruction::Trunc:
1807 return SE.getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
1809 case Instruction::ZExt:
1810 return SE.getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1812 case Instruction::SExt:
1813 return SE.getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1815 case Instruction::BitCast:
1816 // BitCasts are no-op casts so we just eliminate the cast.
1817 if (U->getType()->isInteger() &&
1818 U->getOperand(0)->getType()->isInteger())
1819 return getSCEV(U->getOperand(0));
1822 case Instruction::PHI:
1823 return createNodeForPHI(cast<PHINode>(U));
1825 case Instruction::Select:
1826 // This could be a smax or umax that was lowered earlier.
1827 // Try to recover it.
1828 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
1829 Value *LHS = ICI->getOperand(0);
1830 Value *RHS = ICI->getOperand(1);
1831 switch (ICI->getPredicate()) {
1832 case ICmpInst::ICMP_SLT:
1833 case ICmpInst::ICMP_SLE:
1834 std::swap(LHS, RHS);
1836 case ICmpInst::ICMP_SGT:
1837 case ICmpInst::ICMP_SGE:
1838 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
1839 return SE.getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
1840 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
1841 // ~smax(~x, ~y) == smin(x, y).
1842 return SE.getNotSCEV(SE.getSMaxExpr(
1843 SE.getNotSCEV(getSCEV(LHS)),
1844 SE.getNotSCEV(getSCEV(RHS))));
1846 case ICmpInst::ICMP_ULT:
1847 case ICmpInst::ICMP_ULE:
1848 std::swap(LHS, RHS);
1850 case ICmpInst::ICMP_UGT:
1851 case ICmpInst::ICMP_UGE:
1852 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
1853 return SE.getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
1854 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
1855 // ~umax(~x, ~y) == umin(x, y)
1856 return SE.getNotSCEV(SE.getUMaxExpr(SE.getNotSCEV(getSCEV(LHS)),
1857 SE.getNotSCEV(getSCEV(RHS))));
1864 default: // We cannot analyze this expression.
1868 return SE.getUnknown(V);
1873 //===----------------------------------------------------------------------===//
1874 // Iteration Count Computation Code
1877 /// getIterationCount - If the specified loop has a predictable iteration
1878 /// count, return it. Note that it is not valid to call this method on a
1879 /// loop without a loop-invariant iteration count.
1880 SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1881 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1882 if (I == IterationCounts.end()) {
1883 SCEVHandle ItCount = ComputeIterationCount(L);
1884 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1885 if (ItCount != UnknownValue) {
1886 assert(ItCount->isLoopInvariant(L) &&
1887 "Computed trip count isn't loop invariant for loop!");
1888 ++NumTripCountsComputed;
1889 } else if (isa<PHINode>(L->getHeader()->begin())) {
1890 // Only count loops that have phi nodes as not being computable.
1891 ++NumTripCountsNotComputed;
1897 /// ComputeIterationCount - Compute the number of times the specified loop
1899 SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1900 // If the loop has a non-one exit block count, we can't analyze it.
1901 SmallVector<BasicBlock*, 8> ExitBlocks;
1902 L->getExitBlocks(ExitBlocks);
1903 if (ExitBlocks.size() != 1) return UnknownValue;
1905 // Okay, there is one exit block. Try to find the condition that causes the
1906 // loop to be exited.
1907 BasicBlock *ExitBlock = ExitBlocks[0];
1909 BasicBlock *ExitingBlock = 0;
1910 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1912 if (L->contains(*PI)) {
1913 if (ExitingBlock == 0)
1916 return UnknownValue; // More than one block exiting!
1918 assert(ExitingBlock && "No exits from loop, something is broken!");
1920 // Okay, we've computed the exiting block. See what condition causes us to
1923 // FIXME: we should be able to handle switch instructions (with a single exit)
1924 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1925 if (ExitBr == 0) return UnknownValue;
1926 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1928 // At this point, we know we have a conditional branch that determines whether
1929 // the loop is exited. However, we don't know if the branch is executed each
1930 // time through the loop. If not, then the execution count of the branch will
1931 // not be equal to the trip count of the loop.
1933 // Currently we check for this by checking to see if the Exit branch goes to
1934 // the loop header. If so, we know it will always execute the same number of
1935 // times as the loop. We also handle the case where the exit block *is* the
1936 // loop header. This is common for un-rotated loops. More extensive analysis
1937 // could be done to handle more cases here.
1938 if (ExitBr->getSuccessor(0) != L->getHeader() &&
1939 ExitBr->getSuccessor(1) != L->getHeader() &&
1940 ExitBr->getParent() != L->getHeader())
1941 return UnknownValue;
1943 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
1945 // If it's not an integer comparison then compute it the hard way.
1946 // Note that ICmpInst deals with pointer comparisons too so we must check
1947 // the type of the operand.
1948 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
1949 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1950 ExitBr->getSuccessor(0) == ExitBlock);
1952 // If the condition was exit on true, convert the condition to exit on false
1953 ICmpInst::Predicate Cond;
1954 if (ExitBr->getSuccessor(1) == ExitBlock)
1955 Cond = ExitCond->getPredicate();
1957 Cond = ExitCond->getInversePredicate();
1959 // Handle common loops like: for (X = "string"; *X; ++X)
1960 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1961 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1963 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1964 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1967 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1968 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1970 // Try to evaluate any dependencies out of the loop.
1971 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1972 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1973 Tmp = getSCEVAtScope(RHS, L);
1974 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1976 // At this point, we would like to compute how many iterations of the
1977 // loop the predicate will return true for these inputs.
1978 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1979 // If there is a constant, force it into the RHS.
1980 std::swap(LHS, RHS);
1981 Cond = ICmpInst::getSwappedPredicate(Cond);
1984 // FIXME: think about handling pointer comparisons! i.e.:
1985 // while (P != P+100) ++P;
1987 // If we have a comparison of a chrec against a constant, try to use value
1988 // ranges to answer this query.
1989 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1990 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1991 if (AddRec->getLoop() == L) {
1992 // Form the comparison range using the constant of the correct type so
1993 // that the ConstantRange class knows to do a signed or unsigned
1995 ConstantInt *CompVal = RHSC->getValue();
1996 const Type *RealTy = ExitCond->getOperand(0)->getType();
1997 CompVal = dyn_cast<ConstantInt>(
1998 ConstantExpr::getBitCast(CompVal, RealTy));
2000 // Form the constant range.
2001 ConstantRange CompRange(
2002 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
2004 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE);
2005 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2010 case ICmpInst::ICMP_NE: { // while (X != Y)
2011 // Convert to: while (X-Y != 0)
2012 SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
2013 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2016 case ICmpInst::ICMP_EQ: {
2017 // Convert to: while (X-Y == 0) // while (X == Y)
2018 SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L);
2019 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2022 case ICmpInst::ICMP_SLT: {
2023 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
2024 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2027 case ICmpInst::ICMP_SGT: {
2028 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
2029 SE.getNotSCEV(RHS), L, true);
2030 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2033 case ICmpInst::ICMP_ULT: {
2034 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
2035 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2038 case ICmpInst::ICMP_UGT: {
2039 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
2040 SE.getNotSCEV(RHS), L, false);
2041 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2046 cerr << "ComputeIterationCount ";
2047 if (ExitCond->getOperand(0)->getType()->isUnsigned())
2048 cerr << "[unsigned] ";
2050 << Instruction::getOpcodeName(Instruction::ICmp)
2051 << " " << *RHS << "\n";
2055 return ComputeIterationCountExhaustively(L, ExitCond,
2056 ExitBr->getSuccessor(0) == ExitBlock);
2059 static ConstantInt *
2060 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2061 ScalarEvolution &SE) {
2062 SCEVHandle InVal = SE.getConstant(C);
2063 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
2064 assert(isa<SCEVConstant>(Val) &&
2065 "Evaluation of SCEV at constant didn't fold correctly?");
2066 return cast<SCEVConstant>(Val)->getValue();
2069 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
2070 /// and a GEP expression (missing the pointer index) indexing into it, return
2071 /// the addressed element of the initializer or null if the index expression is
2074 GetAddressedElementFromGlobal(GlobalVariable *GV,
2075 const std::vector<ConstantInt*> &Indices) {
2076 Constant *Init = GV->getInitializer();
2077 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2078 uint64_t Idx = Indices[i]->getZExtValue();
2079 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2080 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2081 Init = cast<Constant>(CS->getOperand(Idx));
2082 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2083 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2084 Init = cast<Constant>(CA->getOperand(Idx));
2085 } else if (isa<ConstantAggregateZero>(Init)) {
2086 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2087 assert(Idx < STy->getNumElements() && "Bad struct index!");
2088 Init = Constant::getNullValue(STy->getElementType(Idx));
2089 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2090 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2091 Init = Constant::getNullValue(ATy->getElementType());
2093 assert(0 && "Unknown constant aggregate type!");
2097 return 0; // Unknown initializer type
2103 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
2104 /// 'icmp op load X, cst', try to see if we can compute the trip count.
2105 SCEVHandle ScalarEvolutionsImpl::
2106 ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
2108 ICmpInst::Predicate predicate) {
2109 if (LI->isVolatile()) return UnknownValue;
2111 // Check to see if the loaded pointer is a getelementptr of a global.
2112 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2113 if (!GEP) return UnknownValue;
2115 // Make sure that it is really a constant global we are gepping, with an
2116 // initializer, and make sure the first IDX is really 0.
2117 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2118 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2119 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2120 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2121 return UnknownValue;
2123 // Okay, we allow one non-constant index into the GEP instruction.
2125 std::vector<ConstantInt*> Indexes;
2126 unsigned VarIdxNum = 0;
2127 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2128 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2129 Indexes.push_back(CI);
2130 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2131 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2132 VarIdx = GEP->getOperand(i);
2134 Indexes.push_back(0);
2137 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2138 // Check to see if X is a loop variant variable value now.
2139 SCEVHandle Idx = getSCEV(VarIdx);
2140 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2141 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2143 // We can only recognize very limited forms of loop index expressions, in
2144 // particular, only affine AddRec's like {C1,+,C2}.
2145 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2146 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2147 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2148 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2149 return UnknownValue;
2151 unsigned MaxSteps = MaxBruteForceIterations;
2152 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2153 ConstantInt *ItCst =
2154 ConstantInt::get(IdxExpr->getType(), IterationNum);
2155 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE);
2157 // Form the GEP offset.
2158 Indexes[VarIdxNum] = Val;
2160 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2161 if (Result == 0) break; // Cannot compute!
2163 // Evaluate the condition for this iteration.
2164 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2165 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2166 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2168 cerr << "\n***\n*** Computed loop count " << *ItCst
2169 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2172 ++NumArrayLenItCounts;
2173 return SE.getConstant(ItCst); // Found terminating iteration!
2176 return UnknownValue;
2180 /// CanConstantFold - Return true if we can constant fold an instruction of the
2181 /// specified type, assuming that all operands were constants.
2182 static bool CanConstantFold(const Instruction *I) {
2183 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2184 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2187 if (const CallInst *CI = dyn_cast<CallInst>(I))
2188 if (const Function *F = CI->getCalledFunction())
2189 return canConstantFoldCallTo(F);
2193 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2194 /// in the loop that V is derived from. We allow arbitrary operations along the
2195 /// way, but the operands of an operation must either be constants or a value
2196 /// derived from a constant PHI. If this expression does not fit with these
2197 /// constraints, return null.
2198 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2199 // If this is not an instruction, or if this is an instruction outside of the
2200 // loop, it can't be derived from a loop PHI.
2201 Instruction *I = dyn_cast<Instruction>(V);
2202 if (I == 0 || !L->contains(I->getParent())) return 0;
2204 if (PHINode *PN = dyn_cast<PHINode>(I)) {
2205 if (L->getHeader() == I->getParent())
2208 // We don't currently keep track of the control flow needed to evaluate
2209 // PHIs, so we cannot handle PHIs inside of loops.
2213 // If we won't be able to constant fold this expression even if the operands
2214 // are constants, return early.
2215 if (!CanConstantFold(I)) return 0;
2217 // Otherwise, we can evaluate this instruction if all of its operands are
2218 // constant or derived from a PHI node themselves.
2220 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2221 if (!(isa<Constant>(I->getOperand(Op)) ||
2222 isa<GlobalValue>(I->getOperand(Op)))) {
2223 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2224 if (P == 0) return 0; // Not evolving from PHI
2228 return 0; // Evolving from multiple different PHIs.
2231 // This is a expression evolving from a constant PHI!
2235 /// EvaluateExpression - Given an expression that passes the
2236 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2237 /// in the loop has the value PHIVal. If we can't fold this expression for some
2238 /// reason, return null.
2239 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2240 if (isa<PHINode>(V)) return PHIVal;
2241 if (Constant *C = dyn_cast<Constant>(V)) return C;
2242 Instruction *I = cast<Instruction>(V);
2244 std::vector<Constant*> Operands;
2245 Operands.resize(I->getNumOperands());
2247 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2248 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2249 if (Operands[i] == 0) return 0;
2252 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2253 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2254 &Operands[0], Operands.size());
2256 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2257 &Operands[0], Operands.size());
2260 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2261 /// in the header of its containing loop, we know the loop executes a
2262 /// constant number of times, and the PHI node is just a recurrence
2263 /// involving constants, fold it.
2264 Constant *ScalarEvolutionsImpl::
2265 getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, const Loop *L){
2266 std::map<PHINode*, Constant*>::iterator I =
2267 ConstantEvolutionLoopExitValue.find(PN);
2268 if (I != ConstantEvolutionLoopExitValue.end())
2271 if (Its.ugt(APInt(Its.getBitWidth(),MaxBruteForceIterations)))
2272 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2274 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2276 // Since the loop is canonicalized, the PHI node must have two entries. One
2277 // entry must be a constant (coming in from outside of the loop), and the
2278 // second must be derived from the same PHI.
2279 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2280 Constant *StartCST =
2281 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2283 return RetVal = 0; // Must be a constant.
2285 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2286 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2288 return RetVal = 0; // Not derived from same PHI.
2290 // Execute the loop symbolically to determine the exit value.
2291 if (Its.getActiveBits() >= 32)
2292 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2294 unsigned NumIterations = Its.getZExtValue(); // must be in range
2295 unsigned IterationNum = 0;
2296 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2297 if (IterationNum == NumIterations)
2298 return RetVal = PHIVal; // Got exit value!
2300 // Compute the value of the PHI node for the next iteration.
2301 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2302 if (NextPHI == PHIVal)
2303 return RetVal = NextPHI; // Stopped evolving!
2305 return 0; // Couldn't evaluate!
2310 /// ComputeIterationCountExhaustively - If the trip is known to execute a
2311 /// constant number of times (the condition evolves only from constants),
2312 /// try to evaluate a few iterations of the loop until we get the exit
2313 /// condition gets a value of ExitWhen (true or false). If we cannot
2314 /// evaluate the trip count of the loop, return UnknownValue.
2315 SCEVHandle ScalarEvolutionsImpl::
2316 ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
2317 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2318 if (PN == 0) return UnknownValue;
2320 // Since the loop is canonicalized, the PHI node must have two entries. One
2321 // entry must be a constant (coming in from outside of the loop), and the
2322 // second must be derived from the same PHI.
2323 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2324 Constant *StartCST =
2325 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2326 if (StartCST == 0) return UnknownValue; // Must be a constant.
2328 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2329 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2330 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2332 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2333 // the loop symbolically to determine when the condition gets a value of
2335 unsigned IterationNum = 0;
2336 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2337 for (Constant *PHIVal = StartCST;
2338 IterationNum != MaxIterations; ++IterationNum) {
2339 ConstantInt *CondVal =
2340 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2342 // Couldn't symbolically evaluate.
2343 if (!CondVal) return UnknownValue;
2345 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2346 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2347 ++NumBruteForceTripCountsComputed;
2348 return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
2351 // Compute the value of the PHI node for the next iteration.
2352 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2353 if (NextPHI == 0 || NextPHI == PHIVal)
2354 return UnknownValue; // Couldn't evaluate or not making progress...
2358 // Too many iterations were needed to evaluate.
2359 return UnknownValue;
2362 /// getSCEVAtScope - Compute the value of the specified expression within the
2363 /// indicated loop (which may be null to indicate in no loop). If the
2364 /// expression cannot be evaluated, return UnknownValue.
2365 SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2366 // FIXME: this should be turned into a virtual method on SCEV!
2368 if (isa<SCEVConstant>(V)) return V;
2370 // If this instruction is evolved from a constant-evolving PHI, compute the
2371 // exit value from the loop without using SCEVs.
2372 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2373 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2374 const Loop *LI = this->LI[I->getParent()];
2375 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2376 if (PHINode *PN = dyn_cast<PHINode>(I))
2377 if (PN->getParent() == LI->getHeader()) {
2378 // Okay, there is no closed form solution for the PHI node. Check
2379 // to see if the loop that contains it has a known iteration count.
2380 // If so, we may be able to force computation of the exit value.
2381 SCEVHandle IterationCount = getIterationCount(LI);
2382 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
2383 // Okay, we know how many times the containing loop executes. If
2384 // this is a constant evolving PHI node, get the final value at
2385 // the specified iteration number.
2386 Constant *RV = getConstantEvolutionLoopExitValue(PN,
2387 ICC->getValue()->getValue(),
2389 if (RV) return SE.getUnknown(RV);
2393 // Okay, this is an expression that we cannot symbolically evaluate
2394 // into a SCEV. Check to see if it's possible to symbolically evaluate
2395 // the arguments into constants, and if so, try to constant propagate the
2396 // result. This is particularly useful for computing loop exit values.
2397 if (CanConstantFold(I)) {
2398 std::vector<Constant*> Operands;
2399 Operands.reserve(I->getNumOperands());
2400 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2401 Value *Op = I->getOperand(i);
2402 if (Constant *C = dyn_cast<Constant>(Op)) {
2403 Operands.push_back(C);
2405 // If any of the operands is non-constant and if they are
2406 // non-integer, don't even try to analyze them with scev techniques.
2407 if (!isa<IntegerType>(Op->getType()))
2410 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2411 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
2412 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2415 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2416 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
2417 Operands.push_back(ConstantExpr::getIntegerCast(C,
2429 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2430 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2431 &Operands[0], Operands.size());
2433 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2434 &Operands[0], Operands.size());
2435 return SE.getUnknown(C);
2439 // This is some other type of SCEVUnknown, just return it.
2443 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2444 // Avoid performing the look-up in the common case where the specified
2445 // expression has no loop-variant portions.
2446 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2447 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2448 if (OpAtScope != Comm->getOperand(i)) {
2449 if (OpAtScope == UnknownValue) return UnknownValue;
2450 // Okay, at least one of these operands is loop variant but might be
2451 // foldable. Build a new instance of the folded commutative expression.
2452 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2453 NewOps.push_back(OpAtScope);
2455 for (++i; i != e; ++i) {
2456 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2457 if (OpAtScope == UnknownValue) return UnknownValue;
2458 NewOps.push_back(OpAtScope);
2460 if (isa<SCEVAddExpr>(Comm))
2461 return SE.getAddExpr(NewOps);
2462 if (isa<SCEVMulExpr>(Comm))
2463 return SE.getMulExpr(NewOps);
2464 if (isa<SCEVSMaxExpr>(Comm))
2465 return SE.getSMaxExpr(NewOps);
2466 if (isa<SCEVUMaxExpr>(Comm))
2467 return SE.getUMaxExpr(NewOps);
2468 assert(0 && "Unknown commutative SCEV type!");
2471 // If we got here, all operands are loop invariant.
2475 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
2476 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
2477 if (LHS == UnknownValue) return LHS;
2478 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
2479 if (RHS == UnknownValue) return RHS;
2480 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2481 return Div; // must be loop invariant
2482 return SE.getUDivExpr(LHS, RHS);
2485 // If this is a loop recurrence for a loop that does not contain L, then we
2486 // are dealing with the final value computed by the loop.
2487 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2488 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2489 // To evaluate this recurrence, we need to know how many times the AddRec
2490 // loop iterates. Compute this now.
2491 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2492 if (IterationCount == UnknownValue) return UnknownValue;
2494 // Then, evaluate the AddRec.
2495 return AddRec->evaluateAtIteration(IterationCount, SE);
2497 return UnknownValue;
2500 //assert(0 && "Unknown SCEV type!");
2501 return UnknownValue;
2504 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2505 /// following equation:
2507 /// A * X = B (mod N)
2509 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2510 /// A and B isn't important.
2512 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2513 static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2514 ScalarEvolution &SE) {
2515 uint32_t BW = A.getBitWidth();
2516 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2517 assert(A != 0 && "A must be non-zero.");
2521 // The gcd of A and N may have only one prime factor: 2. The number of
2522 // trailing zeros in A is its multiplicity
2523 uint32_t Mult2 = A.countTrailingZeros();
2526 // 2. Check if B is divisible by D.
2528 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2529 // is not less than multiplicity of this prime factor for D.
2530 if (B.countTrailingZeros() < Mult2)
2531 return new SCEVCouldNotCompute();
2533 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2536 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2537 // bit width during computations.
2538 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2539 APInt Mod(BW + 1, 0);
2540 Mod.set(BW - Mult2); // Mod = N / D
2541 APInt I = AD.multiplicativeInverse(Mod);
2543 // 4. Compute the minimum unsigned root of the equation:
2544 // I * (B / D) mod (N / D)
2545 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2547 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2549 return SE.getConstant(Result.trunc(BW));
2552 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2553 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2554 /// might be the same) or two SCEVCouldNotCompute objects.
2556 static std::pair<SCEVHandle,SCEVHandle>
2557 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
2558 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2559 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2560 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2561 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2563 // We currently can only solve this if the coefficients are constants.
2564 if (!LC || !MC || !NC) {
2565 SCEV *CNC = new SCEVCouldNotCompute();
2566 return std::make_pair(CNC, CNC);
2569 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2570 const APInt &L = LC->getValue()->getValue();
2571 const APInt &M = MC->getValue()->getValue();
2572 const APInt &N = NC->getValue()->getValue();
2573 APInt Two(BitWidth, 2);
2574 APInt Four(BitWidth, 4);
2577 using namespace APIntOps;
2579 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2580 // The B coefficient is M-N/2
2584 // The A coefficient is N/2
2585 APInt A(N.sdiv(Two));
2587 // Compute the B^2-4ac term.
2590 SqrtTerm -= Four * (A * C);
2592 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2593 // integer value or else APInt::sqrt() will assert.
2594 APInt SqrtVal(SqrtTerm.sqrt());
2596 // Compute the two solutions for the quadratic formula.
2597 // The divisions must be performed as signed divisions.
2599 APInt TwoA( A << 1 );
2600 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2601 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2603 return std::make_pair(SE.getConstant(Solution1),
2604 SE.getConstant(Solution2));
2605 } // end APIntOps namespace
2608 /// HowFarToZero - Return the number of times a backedge comparing the specified
2609 /// value to zero will execute. If not computable, return UnknownValue
2610 SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2611 // If the value is a constant
2612 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2613 // If the value is already zero, the branch will execute zero times.
2614 if (C->getValue()->isZero()) return C;
2615 return UnknownValue; // Otherwise it will loop infinitely.
2618 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2619 if (!AddRec || AddRec->getLoop() != L)
2620 return UnknownValue;
2622 if (AddRec->isAffine()) {
2623 // If this is an affine expression, the execution count of this branch is
2624 // the minimum unsigned root of the following equation:
2626 // Start + Step*N = 0 (mod 2^BW)
2630 // Step*N = -Start (mod 2^BW)
2632 // where BW is the common bit width of Start and Step.
2634 // Get the initial value for the loop.
2635 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2636 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
2638 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
2640 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2641 // For now we handle only constant steps.
2643 // First, handle unitary steps.
2644 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
2645 return SE.getNegativeSCEV(Start); // N = -Start (as unsigned)
2646 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2647 return Start; // N = Start (as unsigned)
2649 // Then, try to solve the above equation provided that Start is constant.
2650 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
2651 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
2652 -StartC->getValue()->getValue(),SE);
2654 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2655 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2656 // the quadratic equation to solve it.
2657 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE);
2658 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2659 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2662 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2663 << " sol#2: " << *R2 << "\n";
2665 // Pick the smallest positive root value.
2666 if (ConstantInt *CB =
2667 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2668 R1->getValue(), R2->getValue()))) {
2669 if (CB->getZExtValue() == false)
2670 std::swap(R1, R2); // R1 is the minimum root now.
2672 // We can only use this value if the chrec ends up with an exact zero
2673 // value at this index. When solving for "X*X != 5", for example, we
2674 // should not accept a root of 2.
2675 SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE);
2677 return R1; // We found a quadratic root!
2682 return UnknownValue;
2685 /// HowFarToNonZero - Return the number of times a backedge checking the
2686 /// specified value for nonzero will execute. If not computable, return
2688 SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2689 // Loops that look like: while (X == 0) are very strange indeed. We don't
2690 // handle them yet except for the trivial case. This could be expanded in the
2691 // future as needed.
2693 // If the value is a constant, check to see if it is known to be non-zero
2694 // already. If so, the backedge will execute zero times.
2695 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2696 if (!C->getValue()->isNullValue())
2697 return SE.getIntegerSCEV(0, C->getType());
2698 return UnknownValue; // Otherwise it will loop infinitely.
2701 // We could implement others, but I really doubt anyone writes loops like
2702 // this, and if they did, they would already be constant folded.
2703 return UnknownValue;
2706 /// executesAtLeastOnce - Test whether entry to the loop is protected by
2707 /// a conditional between LHS and RHS.
2708 bool ScalarEvolutionsImpl::executesAtLeastOnce(const Loop *L, bool isSigned,
2709 SCEV *LHS, SCEV *RHS) {
2710 BasicBlock *Preheader = L->getLoopPreheader();
2711 BasicBlock *PreheaderDest = L->getHeader();
2713 // Starting at the preheader, climb up the predecessor chain, as long as
2714 // there are unique predecessors, looking for a conditional branch that
2715 // protects the loop.
2717 // This is a conservative apporoximation of a climb of the
2718 // control-dependence predecessors.
2720 for (; Preheader; PreheaderDest = Preheader,
2721 Preheader = Preheader->getSinglePredecessor()) {
2723 BranchInst *LoopEntryPredicate =
2724 dyn_cast<BranchInst>(Preheader->getTerminator());
2725 if (!LoopEntryPredicate ||
2726 LoopEntryPredicate->isUnconditional())
2729 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
2732 // Now that we found a conditional branch that dominates the loop, check to
2733 // see if it is the comparison we are looking for.
2734 Value *PreCondLHS = ICI->getOperand(0);
2735 Value *PreCondRHS = ICI->getOperand(1);
2736 ICmpInst::Predicate Cond;
2737 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2738 Cond = ICI->getPredicate();
2740 Cond = ICI->getInversePredicate();
2743 case ICmpInst::ICMP_UGT:
2744 if (isSigned) continue;
2745 std::swap(PreCondLHS, PreCondRHS);
2746 Cond = ICmpInst::ICMP_ULT;
2748 case ICmpInst::ICMP_SGT:
2749 if (!isSigned) continue;
2750 std::swap(PreCondLHS, PreCondRHS);
2751 Cond = ICmpInst::ICMP_SLT;
2753 case ICmpInst::ICMP_ULT:
2754 if (isSigned) continue;
2756 case ICmpInst::ICMP_SLT:
2757 if (!isSigned) continue;
2763 if (!PreCondLHS->getType()->isInteger()) continue;
2765 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
2766 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
2767 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
2768 (LHS == SE.getNotSCEV(PreCondRHSSCEV) &&
2769 RHS == SE.getNotSCEV(PreCondLHSSCEV)))
2776 /// HowManyLessThans - Return the number of times a backedge containing the
2777 /// specified less-than comparison will execute. If not computable, return
2779 SCEVHandle ScalarEvolutionsImpl::
2780 HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
2781 // Only handle: "ADDREC < LoopInvariant".
2782 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2784 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2785 if (!AddRec || AddRec->getLoop() != L)
2786 return UnknownValue;
2788 if (AddRec->isAffine()) {
2789 // FORNOW: We only support unit strides.
2790 SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType());
2791 if (AddRec->getOperand(1) != One)
2792 return UnknownValue;
2794 // We know the LHS is of the form {n,+,1} and the RHS is some loop-invariant
2795 // m. So, we count the number of iterations in which {n,+,1} < m is true.
2796 // Note that we cannot simply return max(m-n,0) because it's not safe to
2797 // treat m-n as signed nor unsigned due to overflow possibility.
2799 // First, we get the value of the LHS in the first iteration: n
2800 SCEVHandle Start = AddRec->getOperand(0);
2802 if (executesAtLeastOnce(L, isSigned,
2803 SE.getMinusSCEV(AddRec->getOperand(0), One), RHS)) {
2804 // Since we know that the condition is true in order to enter the loop,
2805 // we know that it will run exactly m-n times.
2806 return SE.getMinusSCEV(RHS, Start);
2808 // Then, we get the value of the LHS in the first iteration in which the
2809 // above condition doesn't hold. This equals to max(m,n).
2810 SCEVHandle End = isSigned ? SE.getSMaxExpr(RHS, Start)
2811 : SE.getUMaxExpr(RHS, Start);
2813 // Finally, we subtract these two values to get the number of times the
2814 // backedge is executed: max(m,n)-n.
2815 return SE.getMinusSCEV(End, Start);
2819 return UnknownValue;
2822 /// getNumIterationsInRange - Return the number of iterations of this loop that
2823 /// produce values in the specified constant range. Another way of looking at
2824 /// this is that it returns the first iteration number where the value is not in
2825 /// the condition, thus computing the exit count. If the iteration count can't
2826 /// be computed, an instance of SCEVCouldNotCompute is returned.
2827 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
2828 ScalarEvolution &SE) const {
2829 if (Range.isFullSet()) // Infinite loop.
2830 return new SCEVCouldNotCompute();
2832 // If the start is a non-zero constant, shift the range to simplify things.
2833 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2834 if (!SC->getValue()->isZero()) {
2835 std::vector<SCEVHandle> Operands(op_begin(), op_end());
2836 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
2837 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
2838 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2839 return ShiftedAddRec->getNumIterationsInRange(
2840 Range.subtract(SC->getValue()->getValue()), SE);
2841 // This is strange and shouldn't happen.
2842 return new SCEVCouldNotCompute();
2845 // The only time we can solve this is when we have all constant indices.
2846 // Otherwise, we cannot determine the overflow conditions.
2847 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2848 if (!isa<SCEVConstant>(getOperand(i)))
2849 return new SCEVCouldNotCompute();
2852 // Okay at this point we know that all elements of the chrec are constants and
2853 // that the start element is zero.
2855 // First check to see if the range contains zero. If not, the first
2857 if (!Range.contains(APInt(getBitWidth(),0)))
2858 return SE.getConstant(ConstantInt::get(getType(),0));
2861 // If this is an affine expression then we have this situation:
2862 // Solve {0,+,A} in Range === Ax in Range
2864 // We know that zero is in the range. If A is positive then we know that
2865 // the upper value of the range must be the first possible exit value.
2866 // If A is negative then the lower of the range is the last possible loop
2867 // value. Also note that we already checked for a full range.
2868 APInt One(getBitWidth(),1);
2869 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
2870 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
2872 // The exit value should be (End+A)/A.
2873 APInt ExitVal = (End + A).udiv(A);
2874 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
2876 // Evaluate at the exit value. If we really did fall out of the valid
2877 // range, then we computed our trip count, otherwise wrap around or other
2878 // things must have happened.
2879 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
2880 if (Range.contains(Val->getValue()))
2881 return new SCEVCouldNotCompute(); // Something strange happened
2883 // Ensure that the previous value is in the range. This is a sanity check.
2884 assert(Range.contains(
2885 EvaluateConstantChrecAtConstant(this,
2886 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
2887 "Linear scev computation is off in a bad way!");
2888 return SE.getConstant(ExitValue);
2889 } else if (isQuadratic()) {
2890 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2891 // quadratic equation to solve it. To do this, we must frame our problem in
2892 // terms of figuring out when zero is crossed, instead of when
2893 // Range.getUpper() is crossed.
2894 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
2895 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
2896 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
2898 // Next, solve the constructed addrec
2899 std::pair<SCEVHandle,SCEVHandle> Roots =
2900 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
2901 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2902 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2904 // Pick the smallest positive root value.
2905 if (ConstantInt *CB =
2906 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2907 R1->getValue(), R2->getValue()))) {
2908 if (CB->getZExtValue() == false)
2909 std::swap(R1, R2); // R1 is the minimum root now.
2911 // Make sure the root is not off by one. The returned iteration should
2912 // not be in the range, but the previous one should be. When solving
2913 // for "X*X < 5", for example, we should not return a root of 2.
2914 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2917 if (Range.contains(R1Val->getValue())) {
2918 // The next iteration must be out of the range...
2919 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
2921 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
2922 if (!Range.contains(R1Val->getValue()))
2923 return SE.getConstant(NextVal);
2924 return new SCEVCouldNotCompute(); // Something strange happened
2927 // If R1 was not in the range, then it is a good return value. Make
2928 // sure that R1-1 WAS in the range though, just in case.
2929 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
2930 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
2931 if (Range.contains(R1Val->getValue()))
2933 return new SCEVCouldNotCompute(); // Something strange happened
2938 // Fallback, if this is a general polynomial, figure out the progression
2939 // through brute force: evaluate until we find an iteration that fails the
2940 // test. This is likely to be slow, but getting an accurate trip count is
2941 // incredibly important, we will be able to simplify the exit test a lot, and
2942 // we are almost guaranteed to get a trip count in this case.
2943 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2944 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2946 ++NumBruteForceEvaluations;
2947 SCEVHandle Val = evaluateAtIteration(SE.getConstant(TestVal), SE);
2948 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2949 return new SCEVCouldNotCompute();
2951 // Check to see if we found the value!
2952 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()->getValue()))
2953 return SE.getConstant(TestVal);
2955 // Increment to test the next index.
2956 TestVal = ConstantInt::get(TestVal->getValue()+1);
2957 } while (TestVal != EndVal);
2959 return new SCEVCouldNotCompute();
2964 //===----------------------------------------------------------------------===//
2965 // ScalarEvolution Class Implementation
2966 //===----------------------------------------------------------------------===//
2968 bool ScalarEvolution::runOnFunction(Function &F) {
2969 Impl = new ScalarEvolutionsImpl(*this, F, getAnalysis<LoopInfo>());
2973 void ScalarEvolution::releaseMemory() {
2974 delete (ScalarEvolutionsImpl*)Impl;
2978 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2979 AU.setPreservesAll();
2980 AU.addRequiredTransitive<LoopInfo>();
2983 SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2984 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2987 /// hasSCEV - Return true if the SCEV for this value has already been
2989 bool ScalarEvolution::hasSCEV(Value *V) const {
2990 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
2994 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
2995 /// the specified value.
2996 void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
2997 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
3001 SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
3002 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
3005 bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
3006 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
3009 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
3010 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
3013 void ScalarEvolution::deleteValueFromRecords(Value *V) const {
3014 return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
3017 static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
3019 // Print all inner loops first
3020 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3021 PrintLoopInfo(OS, SE, *I);
3023 OS << "Loop " << L->getHeader()->getName() << ": ";
3025 SmallVector<BasicBlock*, 8> ExitBlocks;
3026 L->getExitBlocks(ExitBlocks);
3027 if (ExitBlocks.size() != 1)
3028 OS << "<multiple exits> ";
3030 if (SE->hasLoopInvariantIterationCount(L)) {
3031 OS << *SE->getIterationCount(L) << " iterations! ";
3033 OS << "Unpredictable iteration count. ";
3039 void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
3040 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
3041 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
3043 OS << "Classifying expressions for: " << F.getName() << "\n";
3044 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
3045 if (I->getType()->isInteger()) {
3048 SCEVHandle SV = getSCEV(&*I);
3052 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
3054 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
3055 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3056 OS << "<<Unknown>>";
3066 OS << "Determining loop execution counts for: " << F.getName() << "\n";
3067 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
3068 PrintLoopInfo(OS, this, *I);