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");
99 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
100 cl::desc("Maximum number of iterations SCEV will "
101 "symbolically execute a constant derived loop"),
105 RegisterPass<ScalarEvolution>
106 R("scalar-evolution", "Scalar Evolution Analysis");
108 char ScalarEvolution::ID = 0;
110 //===----------------------------------------------------------------------===//
111 // SCEV class definitions
112 //===----------------------------------------------------------------------===//
114 //===----------------------------------------------------------------------===//
115 // Implementation of the SCEV class.
118 void SCEV::dump() const {
122 /// getValueRange - Return the tightest constant bounds that this value is
123 /// known to have. This method is only valid on integer SCEV objects.
124 ConstantRange SCEV::getValueRange() const {
125 const Type *Ty = getType();
126 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
127 // Default to a full range if no better information is available.
128 return ConstantRange(getBitWidth());
131 uint32_t SCEV::getBitWidth() const {
132 if (const IntegerType* ITy = dyn_cast<IntegerType>(getType()))
133 return ITy->getBitWidth();
138 SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
140 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
141 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
145 const Type *SCEVCouldNotCompute::getType() const {
146 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
150 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
151 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
155 SCEVHandle SCEVCouldNotCompute::
156 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
157 const SCEVHandle &Conc,
158 ScalarEvolution &SE) const {
162 void SCEVCouldNotCompute::print(std::ostream &OS) const {
163 OS << "***COULDNOTCOMPUTE***";
166 bool SCEVCouldNotCompute::classof(const SCEV *S) {
167 return S->getSCEVType() == scCouldNotCompute;
171 // SCEVConstants - Only allow the creation of one SCEVConstant for any
172 // particular value. Don't use a SCEVHandle here, or else the object will
174 static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
177 SCEVConstant::~SCEVConstant() {
178 SCEVConstants->erase(V);
181 SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
182 SCEVConstant *&R = (*SCEVConstants)[V];
183 if (R == 0) R = new SCEVConstant(V);
187 SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
188 return getConstant(ConstantInt::get(Val));
191 ConstantRange SCEVConstant::getValueRange() const {
192 return ConstantRange(V->getValue());
195 const Type *SCEVConstant::getType() const { return V->getType(); }
197 void SCEVConstant::print(std::ostream &OS) const {
198 WriteAsOperand(OS, V, false);
201 // SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
202 // particular input. Don't use a SCEVHandle here, or else the object will
204 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
205 SCEVTruncateExpr*> > SCEVTruncates;
207 SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
208 : SCEV(scTruncate), Op(op), Ty(ty) {
209 assert(Op->getType()->isInteger() && Ty->isInteger() &&
210 "Cannot truncate non-integer value!");
211 assert(Op->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()
212 && "This is not a truncating conversion!");
215 SCEVTruncateExpr::~SCEVTruncateExpr() {
216 SCEVTruncates->erase(std::make_pair(Op, Ty));
219 ConstantRange SCEVTruncateExpr::getValueRange() const {
220 return getOperand()->getValueRange().truncate(getBitWidth());
223 void SCEVTruncateExpr::print(std::ostream &OS) const {
224 OS << "(truncate " << *Op << " to " << *Ty << ")";
227 // SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
228 // particular input. Don't use a SCEVHandle here, or else the object will never
230 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
231 SCEVZeroExtendExpr*> > SCEVZeroExtends;
233 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
234 : SCEV(scZeroExtend), Op(op), Ty(ty) {
235 assert(Op->getType()->isInteger() && Ty->isInteger() &&
236 "Cannot zero extend non-integer value!");
237 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
238 && "This is not an extending conversion!");
241 SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
242 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
245 ConstantRange SCEVZeroExtendExpr::getValueRange() const {
246 return getOperand()->getValueRange().zeroExtend(getBitWidth());
249 void SCEVZeroExtendExpr::print(std::ostream &OS) const {
250 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
253 // SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
254 // particular input. Don't use a SCEVHandle here, or else the object will never
256 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
257 SCEVSignExtendExpr*> > SCEVSignExtends;
259 SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
260 : SCEV(scSignExtend), Op(op), Ty(ty) {
261 assert(Op->getType()->isInteger() && Ty->isInteger() &&
262 "Cannot sign extend non-integer value!");
263 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
264 && "This is not an extending conversion!");
267 SCEVSignExtendExpr::~SCEVSignExtendExpr() {
268 SCEVSignExtends->erase(std::make_pair(Op, Ty));
271 ConstantRange SCEVSignExtendExpr::getValueRange() const {
272 return getOperand()->getValueRange().signExtend(getBitWidth());
275 void SCEVSignExtendExpr::print(std::ostream &OS) const {
276 OS << "(signextend " << *Op << " to " << *Ty << ")";
279 // SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
280 // particular input. Don't use a SCEVHandle here, or else the object will never
282 static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
283 SCEVCommutativeExpr*> > SCEVCommExprs;
285 SCEVCommutativeExpr::~SCEVCommutativeExpr() {
286 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
287 std::vector<SCEV*>(Operands.begin(),
291 void SCEVCommutativeExpr::print(std::ostream &OS) const {
292 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
293 const char *OpStr = getOperationStr();
294 OS << "(" << *Operands[0];
295 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
296 OS << OpStr << *Operands[i];
300 SCEVHandle SCEVCommutativeExpr::
301 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
302 const SCEVHandle &Conc,
303 ScalarEvolution &SE) const {
304 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
306 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
307 if (H != getOperand(i)) {
308 std::vector<SCEVHandle> NewOps;
309 NewOps.reserve(getNumOperands());
310 for (unsigned j = 0; j != i; ++j)
311 NewOps.push_back(getOperand(j));
313 for (++i; i != e; ++i)
314 NewOps.push_back(getOperand(i)->
315 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
317 if (isa<SCEVAddExpr>(this))
318 return SE.getAddExpr(NewOps);
319 else if (isa<SCEVMulExpr>(this))
320 return SE.getMulExpr(NewOps);
321 else if (isa<SCEVSMaxExpr>(this))
322 return SE.getSMaxExpr(NewOps);
324 assert(0 && "Unknown commutative expr!");
331 // SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
332 // input. Don't use a SCEVHandle here, or else the object will never be
334 static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
335 SCEVUDivExpr*> > SCEVUDivs;
337 SCEVUDivExpr::~SCEVUDivExpr() {
338 SCEVUDivs->erase(std::make_pair(LHS, RHS));
341 void SCEVUDivExpr::print(std::ostream &OS) const {
342 OS << "(" << *LHS << " /u " << *RHS << ")";
345 const Type *SCEVUDivExpr::getType() const {
346 return LHS->getType();
349 // SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
350 // particular input. Don't use a SCEVHandle here, or else the object will never
352 static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
353 SCEVAddRecExpr*> > SCEVAddRecExprs;
355 SCEVAddRecExpr::~SCEVAddRecExpr() {
356 SCEVAddRecExprs->erase(std::make_pair(L,
357 std::vector<SCEV*>(Operands.begin(),
361 SCEVHandle SCEVAddRecExpr::
362 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
363 const SCEVHandle &Conc,
364 ScalarEvolution &SE) const {
365 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
367 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
368 if (H != getOperand(i)) {
369 std::vector<SCEVHandle> NewOps;
370 NewOps.reserve(getNumOperands());
371 for (unsigned j = 0; j != i; ++j)
372 NewOps.push_back(getOperand(j));
374 for (++i; i != e; ++i)
375 NewOps.push_back(getOperand(i)->
376 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
378 return SE.getAddRecExpr(NewOps, L);
385 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
386 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
387 // contain L and if the start is invariant.
388 return !QueryLoop->contains(L->getHeader()) &&
389 getOperand(0)->isLoopInvariant(QueryLoop);
393 void SCEVAddRecExpr::print(std::ostream &OS) const {
394 OS << "{" << *Operands[0];
395 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
396 OS << ",+," << *Operands[i];
397 OS << "}<" << L->getHeader()->getName() + ">";
400 // SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
401 // value. Don't use a SCEVHandle here, or else the object will never be
403 static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
405 SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
407 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
408 // All non-instruction values are loop invariant. All instructions are loop
409 // invariant if they are not contained in the specified loop.
410 if (Instruction *I = dyn_cast<Instruction>(V))
411 return !L->contains(I->getParent());
415 const Type *SCEVUnknown::getType() const {
419 void SCEVUnknown::print(std::ostream &OS) const {
420 WriteAsOperand(OS, V, false);
423 //===----------------------------------------------------------------------===//
425 //===----------------------------------------------------------------------===//
428 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
429 /// than the complexity of the RHS. This comparator is used to canonicalize
431 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
432 bool operator()(SCEV *LHS, SCEV *RHS) {
433 return LHS->getSCEVType() < RHS->getSCEVType();
438 /// GroupByComplexity - Given a list of SCEV objects, order them by their
439 /// complexity, and group objects of the same complexity together by value.
440 /// When this routine is finished, we know that any duplicates in the vector are
441 /// consecutive and that complexity is monotonically increasing.
443 /// Note that we go take special precautions to ensure that we get determinstic
444 /// results from this routine. In other words, we don't want the results of
445 /// this to depend on where the addresses of various SCEV objects happened to
448 static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
449 if (Ops.size() < 2) return; // Noop
450 if (Ops.size() == 2) {
451 // This is the common case, which also happens to be trivially simple.
453 if (Ops[0]->getSCEVType() > Ops[1]->getSCEVType())
454 std::swap(Ops[0], Ops[1]);
458 // Do the rough sort by complexity.
459 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
461 // Now that we are sorted by complexity, group elements of the same
462 // complexity. Note that this is, at worst, N^2, but the vector is likely to
463 // be extremely short in practice. Note that we take this approach because we
464 // do not want to depend on the addresses of the objects we are grouping.
465 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
467 unsigned Complexity = S->getSCEVType();
469 // If there are any objects of the same complexity and same value as this
471 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
472 if (Ops[j] == S) { // Found a duplicate.
473 // Move it to immediately after i'th element.
474 std::swap(Ops[i+1], Ops[j]);
475 ++i; // no need to rescan it.
476 if (i == e-2) return; // Done!
484 //===----------------------------------------------------------------------===//
485 // Simple SCEV method implementations
486 //===----------------------------------------------------------------------===//
488 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
489 /// specified signed integer value and return a SCEV for the constant.
490 SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
493 C = Constant::getNullValue(Ty);
494 else if (Ty->isFloatingPoint())
495 C = ConstantFP::get(Ty, APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
496 APFloat::IEEEdouble, Val));
498 C = ConstantInt::get(Ty, Val);
499 return getUnknown(C);
502 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
503 /// input value to the specified type. If the type must be extended, it is zero
505 static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty,
506 ScalarEvolution &SE) {
507 const Type *SrcTy = V->getType();
508 assert(SrcTy->isInteger() && Ty->isInteger() &&
509 "Cannot truncate or zero extend with non-integer arguments!");
510 if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
511 return V; // No conversion
512 if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits())
513 return SE.getTruncateExpr(V, Ty);
514 return SE.getZeroExtendExpr(V, Ty);
517 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
519 SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
520 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
521 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
523 return getMulExpr(V, getIntegerSCEV(-1, V->getType()));
526 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
528 SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
529 const SCEVHandle &RHS) {
531 return getAddExpr(LHS, getNegativeSCEV(RHS));
535 /// BinomialCoefficient - Compute BC(It, K). The result is of the same type as
536 /// It. Assume, K > 0.
537 static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
538 ScalarEvolution &SE) {
539 // We are using the following formula for BC(It, K):
541 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
543 // Suppose, W is the bitwidth of It (and of the return value as well). We
544 // must be prepared for overflow. Hence, we must assure that the result of
545 // our computation is equal to the accurate one modulo 2^W. Unfortunately,
546 // division isn't safe in modular arithmetic. This means we must perform the
547 // whole computation accurately and then truncate the result to W bits.
549 // The dividend of the formula is a multiplication of K integers of bitwidth
550 // W. K*W bits suffice to compute it accurately.
552 // FIXME: We assume the divisor can be accurately computed using 16-bit
553 // unsigned integer type. It is true up to K = 8 (AddRecs of length 9). In
554 // future we may use APInt to use the minimum number of bits necessary to
555 // compute it accurately.
557 // It is safe to use unsigned division here: the dividend is nonnegative and
558 // the divisor is positive.
560 // Handle the simplest case efficiently.
564 assert(K < 9 && "We cannot handle such long AddRecs yet.");
566 // FIXME: A temporary hack to remove in future. Arbitrary precision integers
567 // aren't supported by the code generator yet. For the dividend, the bitwidth
568 // we use is the smallest power of 2 greater or equal to K*W and less or equal
569 // to 64. Note that setting the upper bound for bitwidth may still lead to
570 // miscompilation in some cases.
571 unsigned DividendBits = 1U << Log2_32_Ceil(K * It->getBitWidth());
572 if (DividendBits > 64)
574 #if 0 // Waiting for the APInt support in the code generator...
575 unsigned DividendBits = K * It->getBitWidth();
578 const IntegerType *DividendTy = IntegerType::get(DividendBits);
579 const SCEVHandle ExIt = SE.getZeroExtendExpr(It, DividendTy);
581 // The final number of bits we need to perform the division is the maximum of
582 // dividend and divisor bitwidths.
583 const IntegerType *DivisionTy =
584 IntegerType::get(std::max(DividendBits, 16U));
586 // Compute K! We know K >= 2 here.
588 for (unsigned i = 3; i <= K; ++i)
590 APInt Divisor(DivisionTy->getBitWidth(), F);
592 // Handle this case efficiently, it is common to have constant iteration
593 // counts while computing loop exit values.
594 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(ExIt)) {
595 const APInt& N = SC->getValue()->getValue();
596 APInt Dividend(N.getBitWidth(), 1);
599 if (DividendTy != DivisionTy)
600 Dividend = Dividend.zext(DivisionTy->getBitWidth());
601 return SE.getConstant(Dividend.udiv(Divisor).trunc(It->getBitWidth()));
604 SCEVHandle Dividend = ExIt;
605 for (unsigned i = 1; i != K; ++i)
607 SE.getMulExpr(Dividend,
608 SE.getMinusSCEV(ExIt, SE.getIntegerSCEV(i, DividendTy)));
609 if (DividendTy != DivisionTy)
610 Dividend = SE.getZeroExtendExpr(Dividend, DivisionTy);
612 SE.getTruncateExpr(SE.getUDivExpr(Dividend, SE.getConstant(Divisor)),
616 /// evaluateAtIteration - Return the value of this chain of recurrences at
617 /// the specified iteration number. We can evaluate this recurrence by
618 /// multiplying each element in the chain by the binomial coefficient
619 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
621 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
623 /// where BC(It, k) stands for binomial coefficient.
625 SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
626 ScalarEvolution &SE) const {
627 SCEVHandle Result = getStart();
628 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
629 // The computation is correct in the face of overflow provided that the
630 // multiplication is performed _after_ the evaluation of the binomial
632 SCEVHandle Val = SE.getMulExpr(getOperand(i),
633 BinomialCoefficient(It, i, SE));
634 Result = SE.getAddExpr(Result, Val);
639 //===----------------------------------------------------------------------===//
640 // SCEV Expression folder implementations
641 //===----------------------------------------------------------------------===//
643 SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
644 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
646 ConstantExpr::getTrunc(SC->getValue(), Ty));
648 // If the input value is a chrec scev made out of constants, truncate
649 // all of the constants.
650 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
651 std::vector<SCEVHandle> Operands;
652 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
653 // FIXME: This should allow truncation of other expression types!
654 if (isa<SCEVConstant>(AddRec->getOperand(i)))
655 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
658 if (Operands.size() == AddRec->getNumOperands())
659 return getAddRecExpr(Operands, AddRec->getLoop());
662 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
663 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
667 SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty) {
668 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
670 ConstantExpr::getZExt(SC->getValue(), Ty));
672 // FIXME: If the input value is a chrec scev, and we can prove that the value
673 // did not overflow the old, smaller, value, we can zero extend all of the
674 // operands (often constants). This would allow analysis of something like
675 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
677 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
678 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
682 SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
683 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
685 ConstantExpr::getSExt(SC->getValue(), Ty));
687 // FIXME: If the input value is a chrec scev, and we can prove that the value
688 // did not overflow the old, smaller, value, we can sign extend all of the
689 // operands (often constants). This would allow analysis of something like
690 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
692 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
693 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
697 // get - Get a canonical add expression, or something simpler if possible.
698 SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
699 assert(!Ops.empty() && "Cannot get empty add!");
700 if (Ops.size() == 1) return Ops[0];
702 // Sort by complexity, this groups all similar expression types together.
703 GroupByComplexity(Ops);
705 // If there are any constants, fold them together.
707 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
709 assert(Idx < Ops.size());
710 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
711 // We found two constants, fold them together!
712 Constant *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
713 RHSC->getValue()->getValue());
714 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
715 Ops[0] = getConstant(CI);
716 Ops.erase(Ops.begin()+1); // Erase the folded element
717 if (Ops.size() == 1) return Ops[0];
718 LHSC = cast<SCEVConstant>(Ops[0]);
720 // If we couldn't fold the expression, move to the next constant. Note
721 // that this is impossible to happen in practice because we always
722 // constant fold constant ints to constant ints.
727 // If we are left with a constant zero being added, strip it off.
728 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
729 Ops.erase(Ops.begin());
734 if (Ops.size() == 1) return Ops[0];
736 // Okay, check to see if the same value occurs in the operand list twice. If
737 // so, merge them together into an multiply expression. Since we sorted the
738 // list, these values are required to be adjacent.
739 const Type *Ty = Ops[0]->getType();
740 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
741 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
742 // Found a match, merge the two values into a multiply, and add any
743 // remaining values to the result.
744 SCEVHandle Two = getIntegerSCEV(2, Ty);
745 SCEVHandle Mul = getMulExpr(Ops[i], Two);
748 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
750 return getAddExpr(Ops);
753 // Now we know the first non-constant operand. Skip past any cast SCEVs.
754 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
757 // If there are add operands they would be next.
758 if (Idx < Ops.size()) {
759 bool DeletedAdd = false;
760 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
761 // If we have an add, expand the add operands onto the end of the operands
763 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
764 Ops.erase(Ops.begin()+Idx);
768 // If we deleted at least one add, we added operands to the end of the list,
769 // and they are not necessarily sorted. Recurse to resort and resimplify
770 // any operands we just aquired.
772 return getAddExpr(Ops);
775 // Skip over the add expression until we get to a multiply.
776 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
779 // If we are adding something to a multiply expression, make sure the
780 // something is not already an operand of the multiply. If so, merge it into
782 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
783 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
784 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
785 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
786 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
787 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
788 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
789 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
790 if (Mul->getNumOperands() != 2) {
791 // If the multiply has more than two operands, we must get the
793 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
794 MulOps.erase(MulOps.begin()+MulOp);
795 InnerMul = getMulExpr(MulOps);
797 SCEVHandle One = getIntegerSCEV(1, Ty);
798 SCEVHandle AddOne = getAddExpr(InnerMul, One);
799 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
800 if (Ops.size() == 2) return OuterMul;
802 Ops.erase(Ops.begin()+AddOp);
803 Ops.erase(Ops.begin()+Idx-1);
805 Ops.erase(Ops.begin()+Idx);
806 Ops.erase(Ops.begin()+AddOp-1);
808 Ops.push_back(OuterMul);
809 return getAddExpr(Ops);
812 // Check this multiply against other multiplies being added together.
813 for (unsigned OtherMulIdx = Idx+1;
814 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
816 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
817 // If MulOp occurs in OtherMul, we can fold the two multiplies
819 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
820 OMulOp != e; ++OMulOp)
821 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
822 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
823 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
824 if (Mul->getNumOperands() != 2) {
825 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
826 MulOps.erase(MulOps.begin()+MulOp);
827 InnerMul1 = getMulExpr(MulOps);
829 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
830 if (OtherMul->getNumOperands() != 2) {
831 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
833 MulOps.erase(MulOps.begin()+OMulOp);
834 InnerMul2 = getMulExpr(MulOps);
836 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
837 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
838 if (Ops.size() == 2) return OuterMul;
839 Ops.erase(Ops.begin()+Idx);
840 Ops.erase(Ops.begin()+OtherMulIdx-1);
841 Ops.push_back(OuterMul);
842 return getAddExpr(Ops);
848 // If there are any add recurrences in the operands list, see if any other
849 // added values are loop invariant. If so, we can fold them into the
851 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
854 // Scan over all recurrences, trying to fold loop invariants into them.
855 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
856 // Scan all of the other operands to this add and add them to the vector if
857 // they are loop invariant w.r.t. the recurrence.
858 std::vector<SCEVHandle> LIOps;
859 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
860 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
861 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
862 LIOps.push_back(Ops[i]);
863 Ops.erase(Ops.begin()+i);
867 // If we found some loop invariants, fold them into the recurrence.
868 if (!LIOps.empty()) {
869 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
870 LIOps.push_back(AddRec->getStart());
872 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
873 AddRecOps[0] = getAddExpr(LIOps);
875 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
876 // If all of the other operands were loop invariant, we are done.
877 if (Ops.size() == 1) return NewRec;
879 // Otherwise, add the folded AddRec by the non-liv parts.
880 for (unsigned i = 0;; ++i)
881 if (Ops[i] == AddRec) {
885 return getAddExpr(Ops);
888 // Okay, if there weren't any loop invariants to be folded, check to see if
889 // there are multiple AddRec's with the same loop induction variable being
890 // added together. If so, we can fold them.
891 for (unsigned OtherIdx = Idx+1;
892 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
893 if (OtherIdx != Idx) {
894 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
895 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
896 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
897 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
898 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
899 if (i >= NewOps.size()) {
900 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
901 OtherAddRec->op_end());
904 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
906 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
908 if (Ops.size() == 2) return NewAddRec;
910 Ops.erase(Ops.begin()+Idx);
911 Ops.erase(Ops.begin()+OtherIdx-1);
912 Ops.push_back(NewAddRec);
913 return getAddExpr(Ops);
917 // Otherwise couldn't fold anything into this recurrence. Move onto the
921 // Okay, it looks like we really DO need an add expr. Check to see if we
922 // already have one, otherwise create a new one.
923 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
924 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
926 if (Result == 0) Result = new SCEVAddExpr(Ops);
931 SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
932 assert(!Ops.empty() && "Cannot get empty mul!");
934 // Sort by complexity, this groups all similar expression types together.
935 GroupByComplexity(Ops);
937 // If there are any constants, fold them together.
939 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
941 // C1*(C2+V) -> C1*C2 + C1*V
943 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
944 if (Add->getNumOperands() == 2 &&
945 isa<SCEVConstant>(Add->getOperand(0)))
946 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
947 getMulExpr(LHSC, Add->getOperand(1)));
951 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
952 // We found two constants, fold them together!
953 Constant *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
954 RHSC->getValue()->getValue());
955 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
956 Ops[0] = getConstant(CI);
957 Ops.erase(Ops.begin()+1); // Erase the folded element
958 if (Ops.size() == 1) return Ops[0];
959 LHSC = cast<SCEVConstant>(Ops[0]);
961 // If we couldn't fold the expression, move to the next constant. Note
962 // that this is impossible to happen in practice because we always
963 // constant fold constant ints to constant ints.
968 // If we are left with a constant one being multiplied, strip it off.
969 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
970 Ops.erase(Ops.begin());
972 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
973 // If we have a multiply of zero, it will always be zero.
978 // Skip over the add expression until we get to a multiply.
979 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
985 // If there are mul operands inline them all into this expression.
986 if (Idx < Ops.size()) {
987 bool DeletedMul = false;
988 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
989 // If we have an mul, expand the mul operands onto the end of the operands
991 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
992 Ops.erase(Ops.begin()+Idx);
996 // If we deleted at least one mul, we added operands to the end of the list,
997 // and they are not necessarily sorted. Recurse to resort and resimplify
998 // any operands we just aquired.
1000 return getMulExpr(Ops);
1003 // If there are any add recurrences in the operands list, see if any other
1004 // added values are loop invariant. If so, we can fold them into the
1006 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1009 // Scan over all recurrences, trying to fold loop invariants into them.
1010 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1011 // Scan all of the other operands to this mul and add them to the vector if
1012 // they are loop invariant w.r.t. the recurrence.
1013 std::vector<SCEVHandle> LIOps;
1014 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1015 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1016 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1017 LIOps.push_back(Ops[i]);
1018 Ops.erase(Ops.begin()+i);
1022 // If we found some loop invariants, fold them into the recurrence.
1023 if (!LIOps.empty()) {
1024 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
1025 std::vector<SCEVHandle> NewOps;
1026 NewOps.reserve(AddRec->getNumOperands());
1027 if (LIOps.size() == 1) {
1028 SCEV *Scale = LIOps[0];
1029 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1030 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1032 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1033 std::vector<SCEVHandle> MulOps(LIOps);
1034 MulOps.push_back(AddRec->getOperand(i));
1035 NewOps.push_back(getMulExpr(MulOps));
1039 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
1041 // If all of the other operands were loop invariant, we are done.
1042 if (Ops.size() == 1) return NewRec;
1044 // Otherwise, multiply the folded AddRec by the non-liv parts.
1045 for (unsigned i = 0;; ++i)
1046 if (Ops[i] == AddRec) {
1050 return getMulExpr(Ops);
1053 // Okay, if there weren't any loop invariants to be folded, check to see if
1054 // there are multiple AddRec's with the same loop induction variable being
1055 // multiplied together. If so, we can fold them.
1056 for (unsigned OtherIdx = Idx+1;
1057 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1058 if (OtherIdx != Idx) {
1059 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1060 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1061 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1062 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1063 SCEVHandle NewStart = getMulExpr(F->getStart(),
1065 SCEVHandle B = F->getStepRecurrence(*this);
1066 SCEVHandle D = G->getStepRecurrence(*this);
1067 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1070 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1072 if (Ops.size() == 2) return NewAddRec;
1074 Ops.erase(Ops.begin()+Idx);
1075 Ops.erase(Ops.begin()+OtherIdx-1);
1076 Ops.push_back(NewAddRec);
1077 return getMulExpr(Ops);
1081 // Otherwise couldn't fold anything into this recurrence. Move onto the
1085 // Okay, it looks like we really DO need an mul expr. Check to see if we
1086 // already have one, otherwise create a new one.
1087 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1088 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1091 Result = new SCEVMulExpr(Ops);
1095 SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1096 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1097 if (RHSC->getValue()->equalsInt(1))
1098 return LHS; // X udiv 1 --> x
1100 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1101 Constant *LHSCV = LHSC->getValue();
1102 Constant *RHSCV = RHSC->getValue();
1103 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
1107 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1109 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1110 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
1115 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1116 /// specified loop. Simplify the expression as much as possible.
1117 SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
1118 const SCEVHandle &Step, const Loop *L) {
1119 std::vector<SCEVHandle> Operands;
1120 Operands.push_back(Start);
1121 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1122 if (StepChrec->getLoop() == L) {
1123 Operands.insert(Operands.end(), StepChrec->op_begin(),
1124 StepChrec->op_end());
1125 return getAddRecExpr(Operands, L);
1128 Operands.push_back(Step);
1129 return getAddRecExpr(Operands, L);
1132 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1133 /// specified loop. Simplify the expression as much as possible.
1134 SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
1136 if (Operands.size() == 1) return Operands[0];
1138 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
1139 if (StepC->getValue()->isZero()) {
1140 Operands.pop_back();
1141 return getAddRecExpr(Operands, L); // { X,+,0 } --> X
1144 SCEVAddRecExpr *&Result =
1145 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1147 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1151 SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1152 const SCEVHandle &RHS) {
1153 std::vector<SCEVHandle> Ops;
1156 return getSMaxExpr(Ops);
1159 SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1160 assert(!Ops.empty() && "Cannot get empty smax!");
1161 if (Ops.size() == 1) return Ops[0];
1163 // Sort by complexity, this groups all similar expression types together.
1164 GroupByComplexity(Ops);
1166 // If there are any constants, fold them together.
1168 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1170 assert(Idx < Ops.size());
1171 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1172 // We found two constants, fold them together!
1173 Constant *Fold = ConstantInt::get(
1174 APIntOps::smax(LHSC->getValue()->getValue(),
1175 RHSC->getValue()->getValue()));
1176 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
1177 Ops[0] = getConstant(CI);
1178 Ops.erase(Ops.begin()+1); // Erase the folded element
1179 if (Ops.size() == 1) return Ops[0];
1180 LHSC = cast<SCEVConstant>(Ops[0]);
1182 // If we couldn't fold the expression, move to the next constant. Note
1183 // that this is impossible to happen in practice because we always
1184 // constant fold constant ints to constant ints.
1189 // If we are left with a constant -inf, strip it off.
1190 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1191 Ops.erase(Ops.begin());
1196 if (Ops.size() == 1) return Ops[0];
1198 // Find the first SMax
1199 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1202 // Check to see if one of the operands is an SMax. If so, expand its operands
1203 // onto our operand list, and recurse to simplify.
1204 if (Idx < Ops.size()) {
1205 bool DeletedSMax = false;
1206 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1207 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1208 Ops.erase(Ops.begin()+Idx);
1213 return getSMaxExpr(Ops);
1216 // Okay, check to see if the same value occurs in the operand list twice. If
1217 // so, delete one. Since we sorted the list, these values are required to
1219 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1220 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1221 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1225 if (Ops.size() == 1) return Ops[0];
1227 assert(!Ops.empty() && "Reduced smax down to nothing!");
1229 // Okay, it looks like we really DO need an add expr. Check to see if we
1230 // already have one, otherwise create a new one.
1231 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1232 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1234 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1238 SCEVHandle ScalarEvolution::getUnknown(Value *V) {
1239 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1240 return getConstant(CI);
1241 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1242 if (Result == 0) Result = new SCEVUnknown(V);
1247 //===----------------------------------------------------------------------===//
1248 // ScalarEvolutionsImpl Definition and Implementation
1249 //===----------------------------------------------------------------------===//
1251 /// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1255 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
1256 /// SE - A reference to the public ScalarEvolution object.
1257 ScalarEvolution &SE;
1259 /// F - The function we are analyzing.
1263 /// LI - The loop information for the function we are currently analyzing.
1267 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1269 SCEVHandle UnknownValue;
1271 /// Scalars - This is a cache of the scalars we have analyzed so far.
1273 std::map<Value*, SCEVHandle> Scalars;
1275 /// IterationCounts - Cache the iteration count of the loops for this
1276 /// function as they are computed.
1277 std::map<const Loop*, SCEVHandle> IterationCounts;
1279 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1280 /// the PHI instructions that we attempt to compute constant evolutions for.
1281 /// This allows us to avoid potentially expensive recomputation of these
1282 /// properties. An instruction maps to null if we are unable to compute its
1284 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
1287 ScalarEvolutionsImpl(ScalarEvolution &se, Function &f, LoopInfo &li)
1288 : SE(se), F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1290 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1291 /// expression and create a new one.
1292 SCEVHandle getSCEV(Value *V);
1294 /// hasSCEV - Return true if the SCEV for this value has already been
1296 bool hasSCEV(Value *V) const {
1297 return Scalars.count(V);
1300 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1301 /// the specified value.
1302 void setSCEV(Value *V, const SCEVHandle &H) {
1303 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1304 assert(isNew && "This entry already existed!");
1308 /// getSCEVAtScope - Compute the value of the specified expression within
1309 /// the indicated loop (which may be null to indicate in no loop). If the
1310 /// expression cannot be evaluated, return UnknownValue itself.
1311 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1314 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1315 /// an analyzable loop-invariant iteration count.
1316 bool hasLoopInvariantIterationCount(const Loop *L);
1318 /// getIterationCount - If the specified loop has a predictable iteration
1319 /// count, return it. Note that it is not valid to call this method on a
1320 /// loop without a loop-invariant iteration count.
1321 SCEVHandle getIterationCount(const Loop *L);
1323 /// deleteValueFromRecords - This method should be called by the
1324 /// client before it removes a value from the program, to make sure
1325 /// that no dangling references are left around.
1326 void deleteValueFromRecords(Value *V);
1329 /// createSCEV - We know that there is no SCEV for the specified value.
1330 /// Analyze the expression.
1331 SCEVHandle createSCEV(Value *V);
1333 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1335 SCEVHandle createNodeForPHI(PHINode *PN);
1337 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1338 /// for the specified instruction and replaces any references to the
1339 /// symbolic value SymName with the specified value. This is used during
1341 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1342 const SCEVHandle &SymName,
1343 const SCEVHandle &NewVal);
1345 /// ComputeIterationCount - Compute the number of times the specified loop
1347 SCEVHandle ComputeIterationCount(const Loop *L);
1349 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1350 /// 'icmp op load X, cst', try to see if we can compute the trip count.
1351 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1354 ICmpInst::Predicate p);
1356 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1357 /// constant number of times (the condition evolves only from constants),
1358 /// try to evaluate a few iterations of the loop until we get the exit
1359 /// condition gets a value of ExitWhen (true or false). If we cannot
1360 /// evaluate the trip count of the loop, return UnknownValue.
1361 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1364 /// HowFarToZero - Return the number of times a backedge comparing the
1365 /// specified value to zero will execute. If not computable, return
1367 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1369 /// HowFarToNonZero - Return the number of times a backedge checking the
1370 /// specified value for nonzero will execute. If not computable, return
1372 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
1374 /// HowManyLessThans - Return the number of times a backedge containing the
1375 /// specified less-than comparison will execute. If not computable, return
1376 /// UnknownValue. isSigned specifies whether the less-than is signed.
1377 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
1380 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1381 /// in the header of its containing loop, we know the loop executes a
1382 /// constant number of times, and the PHI node is just a recurrence
1383 /// involving constants, fold it.
1384 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its,
1389 //===----------------------------------------------------------------------===//
1390 // Basic SCEV Analysis and PHI Idiom Recognition Code
1393 /// deleteValueFromRecords - This method should be called by the
1394 /// client before it removes an instruction from the program, to make sure
1395 /// that no dangling references are left around.
1396 void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) {
1397 SmallVector<Value *, 16> Worklist;
1399 if (Scalars.erase(V)) {
1400 if (PHINode *PN = dyn_cast<PHINode>(V))
1401 ConstantEvolutionLoopExitValue.erase(PN);
1402 Worklist.push_back(V);
1405 while (!Worklist.empty()) {
1406 Value *VV = Worklist.back();
1407 Worklist.pop_back();
1409 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
1411 Instruction *Inst = cast<Instruction>(*UI);
1412 if (Scalars.erase(Inst)) {
1413 if (PHINode *PN = dyn_cast<PHINode>(VV))
1414 ConstantEvolutionLoopExitValue.erase(PN);
1415 Worklist.push_back(Inst);
1422 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1423 /// expression and create a new one.
1424 SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1425 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1427 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1428 if (I != Scalars.end()) return I->second;
1429 SCEVHandle S = createSCEV(V);
1430 Scalars.insert(std::make_pair(V, S));
1434 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1435 /// the specified instruction and replaces any references to the symbolic value
1436 /// SymName with the specified value. This is used during PHI resolution.
1437 void ScalarEvolutionsImpl::
1438 ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1439 const SCEVHandle &NewVal) {
1440 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1441 if (SI == Scalars.end()) return;
1444 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, SE);
1445 if (NV == SI->second) return; // No change.
1447 SI->second = NV; // Update the scalars map!
1449 // Any instruction values that use this instruction might also need to be
1451 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1453 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1456 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1457 /// a loop header, making it a potential recurrence, or it doesn't.
1459 SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1460 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1461 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1462 if (L->getHeader() == PN->getParent()) {
1463 // If it lives in the loop header, it has two incoming values, one
1464 // from outside the loop, and one from inside.
1465 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1466 unsigned BackEdge = IncomingEdge^1;
1468 // While we are analyzing this PHI node, handle its value symbolically.
1469 SCEVHandle SymbolicName = SE.getUnknown(PN);
1470 assert(Scalars.find(PN) == Scalars.end() &&
1471 "PHI node already processed?");
1472 Scalars.insert(std::make_pair(PN, SymbolicName));
1474 // Using this symbolic name for the PHI, analyze the value coming around
1476 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1478 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1479 // has a special value for the first iteration of the loop.
1481 // If the value coming around the backedge is an add with the symbolic
1482 // value we just inserted, then we found a simple induction variable!
1483 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1484 // If there is a single occurrence of the symbolic value, replace it
1485 // with a recurrence.
1486 unsigned FoundIndex = Add->getNumOperands();
1487 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1488 if (Add->getOperand(i) == SymbolicName)
1489 if (FoundIndex == e) {
1494 if (FoundIndex != Add->getNumOperands()) {
1495 // Create an add with everything but the specified operand.
1496 std::vector<SCEVHandle> Ops;
1497 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1498 if (i != FoundIndex)
1499 Ops.push_back(Add->getOperand(i));
1500 SCEVHandle Accum = SE.getAddExpr(Ops);
1502 // This is not a valid addrec if the step amount is varying each
1503 // loop iteration, but is not itself an addrec in this loop.
1504 if (Accum->isLoopInvariant(L) ||
1505 (isa<SCEVAddRecExpr>(Accum) &&
1506 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1507 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1508 SCEVHandle PHISCEV = SE.getAddRecExpr(StartVal, Accum, L);
1510 // Okay, for the entire analysis of this edge we assumed the PHI
1511 // to be symbolic. We now need to go back and update all of the
1512 // entries for the scalars that use the PHI (except for the PHI
1513 // itself) to use the new analyzed value instead of the "symbolic"
1515 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1519 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1520 // Otherwise, this could be a loop like this:
1521 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1522 // In this case, j = {1,+,1} and BEValue is j.
1523 // Because the other in-value of i (0) fits the evolution of BEValue
1524 // i really is an addrec evolution.
1525 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1526 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1528 // If StartVal = j.start - j.stride, we can use StartVal as the
1529 // initial step of the addrec evolution.
1530 if (StartVal == SE.getMinusSCEV(AddRec->getOperand(0),
1531 AddRec->getOperand(1))) {
1532 SCEVHandle PHISCEV =
1533 SE.getAddRecExpr(StartVal, AddRec->getOperand(1), L);
1535 // Okay, for the entire analysis of this edge we assumed the PHI
1536 // to be symbolic. We now need to go back and update all of the
1537 // entries for the scalars that use the PHI (except for the PHI
1538 // itself) to use the new analyzed value instead of the "symbolic"
1540 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1546 return SymbolicName;
1549 // If it's not a loop phi, we can't handle it yet.
1550 return SE.getUnknown(PN);
1553 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1554 /// guaranteed to end in (at every loop iteration). It is, at the same time,
1555 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1556 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
1557 static uint32_t GetMinTrailingZeros(SCEVHandle S) {
1558 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
1559 return C->getValue()->getValue().countTrailingZeros();
1561 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
1562 return std::min(GetMinTrailingZeros(T->getOperand()), T->getBitWidth());
1564 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
1565 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1566 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1569 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
1570 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1571 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1574 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
1575 // The result is the min of all operands results.
1576 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1577 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1578 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1582 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
1583 // The result is the sum of all operands results.
1584 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
1585 uint32_t BitWidth = M->getBitWidth();
1586 for (unsigned i = 1, e = M->getNumOperands();
1587 SumOpRes != BitWidth && i != e; ++i)
1588 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
1593 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
1594 // The result is the min of all operands results.
1595 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1596 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1597 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1601 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1602 // The result is the min of all operands results.
1603 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1604 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1605 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1609 // SCEVUDivExpr, SCEVUnknown
1613 /// createSCEV - We know that there is no SCEV for the specified value.
1614 /// Analyze the expression.
1616 SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1617 if (!isa<IntegerType>(V->getType()))
1618 return SE.getUnknown(V);
1620 if (Instruction *I = dyn_cast<Instruction>(V)) {
1621 switch (I->getOpcode()) {
1622 case Instruction::Add:
1623 return SE.getAddExpr(getSCEV(I->getOperand(0)),
1624 getSCEV(I->getOperand(1)));
1625 case Instruction::Mul:
1626 return SE.getMulExpr(getSCEV(I->getOperand(0)),
1627 getSCEV(I->getOperand(1)));
1628 case Instruction::UDiv:
1629 return SE.getUDivExpr(getSCEV(I->getOperand(0)),
1630 getSCEV(I->getOperand(1)));
1631 case Instruction::Sub:
1632 return SE.getMinusSCEV(getSCEV(I->getOperand(0)),
1633 getSCEV(I->getOperand(1)));
1634 case Instruction::Or:
1635 // If the RHS of the Or is a constant, we may have something like:
1636 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1637 // optimizations will transparently handle this case.
1639 // In order for this transformation to be safe, the LHS must be of the
1640 // form X*(2^n) and the Or constant must be less than 2^n.
1641 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1642 SCEVHandle LHS = getSCEV(I->getOperand(0));
1643 const APInt &CIVal = CI->getValue();
1644 if (GetMinTrailingZeros(LHS) >=
1645 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
1646 return SE.getAddExpr(LHS, getSCEV(I->getOperand(1)));
1649 case Instruction::Xor:
1650 // If the RHS of the xor is a signbit, then this is just an add.
1651 // Instcombine turns add of signbit into xor as a strength reduction step.
1652 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1653 if (CI->getValue().isSignBit())
1654 return SE.getAddExpr(getSCEV(I->getOperand(0)),
1655 getSCEV(I->getOperand(1)));
1659 case Instruction::Shl:
1660 // Turn shift left of a constant amount into a multiply.
1661 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1662 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1663 Constant *X = ConstantInt::get(
1664 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1665 return SE.getMulExpr(getSCEV(I->getOperand(0)), getSCEV(X));
1669 case Instruction::Trunc:
1670 return SE.getTruncateExpr(getSCEV(I->getOperand(0)), I->getType());
1672 case Instruction::ZExt:
1673 return SE.getZeroExtendExpr(getSCEV(I->getOperand(0)), I->getType());
1675 case Instruction::SExt:
1676 return SE.getSignExtendExpr(getSCEV(I->getOperand(0)), I->getType());
1678 case Instruction::BitCast:
1679 // BitCasts are no-op casts so we just eliminate the cast.
1680 if (I->getType()->isInteger() &&
1681 I->getOperand(0)->getType()->isInteger())
1682 return getSCEV(I->getOperand(0));
1685 case Instruction::PHI:
1686 return createNodeForPHI(cast<PHINode>(I));
1688 case Instruction::Select:
1689 // This could be an SCEVSMax that was lowered earlier. Try to recover it.
1690 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I->getOperand(0))) {
1691 Value *LHS = ICI->getOperand(0);
1692 Value *RHS = ICI->getOperand(1);
1693 switch (ICI->getPredicate()) {
1694 case ICmpInst::ICMP_SLT:
1695 case ICmpInst::ICMP_SLE:
1696 std::swap(LHS, RHS);
1698 case ICmpInst::ICMP_SGT:
1699 case ICmpInst::ICMP_SGE:
1700 if (LHS == I->getOperand(1) && RHS == I->getOperand(2))
1701 return SE.getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
1707 default: // We cannot analyze this expression.
1712 return SE.getUnknown(V);
1717 //===----------------------------------------------------------------------===//
1718 // Iteration Count Computation Code
1721 /// getIterationCount - If the specified loop has a predictable iteration
1722 /// count, return it. Note that it is not valid to call this method on a
1723 /// loop without a loop-invariant iteration count.
1724 SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1725 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1726 if (I == IterationCounts.end()) {
1727 SCEVHandle ItCount = ComputeIterationCount(L);
1728 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1729 if (ItCount != UnknownValue) {
1730 assert(ItCount->isLoopInvariant(L) &&
1731 "Computed trip count isn't loop invariant for loop!");
1732 ++NumTripCountsComputed;
1733 } else if (isa<PHINode>(L->getHeader()->begin())) {
1734 // Only count loops that have phi nodes as not being computable.
1735 ++NumTripCountsNotComputed;
1741 /// ComputeIterationCount - Compute the number of times the specified loop
1743 SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1744 // If the loop has a non-one exit block count, we can't analyze it.
1745 SmallVector<BasicBlock*, 8> ExitBlocks;
1746 L->getExitBlocks(ExitBlocks);
1747 if (ExitBlocks.size() != 1) return UnknownValue;
1749 // Okay, there is one exit block. Try to find the condition that causes the
1750 // loop to be exited.
1751 BasicBlock *ExitBlock = ExitBlocks[0];
1753 BasicBlock *ExitingBlock = 0;
1754 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1756 if (L->contains(*PI)) {
1757 if (ExitingBlock == 0)
1760 return UnknownValue; // More than one block exiting!
1762 assert(ExitingBlock && "No exits from loop, something is broken!");
1764 // Okay, we've computed the exiting block. See what condition causes us to
1767 // FIXME: we should be able to handle switch instructions (with a single exit)
1768 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1769 if (ExitBr == 0) return UnknownValue;
1770 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1772 // At this point, we know we have a conditional branch that determines whether
1773 // the loop is exited. However, we don't know if the branch is executed each
1774 // time through the loop. If not, then the execution count of the branch will
1775 // not be equal to the trip count of the loop.
1777 // Currently we check for this by checking to see if the Exit branch goes to
1778 // the loop header. If so, we know it will always execute the same number of
1779 // times as the loop. We also handle the case where the exit block *is* the
1780 // loop header. This is common for un-rotated loops. More extensive analysis
1781 // could be done to handle more cases here.
1782 if (ExitBr->getSuccessor(0) != L->getHeader() &&
1783 ExitBr->getSuccessor(1) != L->getHeader() &&
1784 ExitBr->getParent() != L->getHeader())
1785 return UnknownValue;
1787 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
1789 // If its not an integer comparison then compute it the hard way.
1790 // Note that ICmpInst deals with pointer comparisons too so we must check
1791 // the type of the operand.
1792 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
1793 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1794 ExitBr->getSuccessor(0) == ExitBlock);
1796 // If the condition was exit on true, convert the condition to exit on false
1797 ICmpInst::Predicate Cond;
1798 if (ExitBr->getSuccessor(1) == ExitBlock)
1799 Cond = ExitCond->getPredicate();
1801 Cond = ExitCond->getInversePredicate();
1803 // Handle common loops like: for (X = "string"; *X; ++X)
1804 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1805 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1807 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1808 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1811 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1812 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1814 // Try to evaluate any dependencies out of the loop.
1815 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1816 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1817 Tmp = getSCEVAtScope(RHS, L);
1818 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1820 // At this point, we would like to compute how many iterations of the
1821 // loop the predicate will return true for these inputs.
1822 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
1823 // If there is a loop-invariant, force it into the RHS.
1824 std::swap(LHS, RHS);
1825 Cond = ICmpInst::getSwappedPredicate(Cond);
1828 // FIXME: think about handling pointer comparisons! i.e.:
1829 // while (P != P+100) ++P;
1831 // If we have a comparison of a chrec against a constant, try to use value
1832 // ranges to answer this query.
1833 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1834 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1835 if (AddRec->getLoop() == L) {
1836 // Form the comparison range using the constant of the correct type so
1837 // that the ConstantRange class knows to do a signed or unsigned
1839 ConstantInt *CompVal = RHSC->getValue();
1840 const Type *RealTy = ExitCond->getOperand(0)->getType();
1841 CompVal = dyn_cast<ConstantInt>(
1842 ConstantExpr::getBitCast(CompVal, RealTy));
1844 // Form the constant range.
1845 ConstantRange CompRange(
1846 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
1848 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE);
1849 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1854 case ICmpInst::ICMP_NE: { // while (X != Y)
1855 // Convert to: while (X-Y != 0)
1856 SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
1857 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1860 case ICmpInst::ICMP_EQ: {
1861 // Convert to: while (X-Y == 0) // while (X == Y)
1862 SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L);
1863 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1866 case ICmpInst::ICMP_SLT: {
1867 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
1868 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1871 case ICmpInst::ICMP_SGT: {
1872 SCEVHandle TC = HowManyLessThans(SE.getNegativeSCEV(LHS),
1873 SE.getNegativeSCEV(RHS), L, true);
1874 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1877 case ICmpInst::ICMP_ULT: {
1878 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
1879 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1882 case ICmpInst::ICMP_UGT: {
1883 SCEVHandle TC = HowManyLessThans(SE.getNegativeSCEV(LHS),
1884 SE.getNegativeSCEV(RHS), L, false);
1885 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1890 cerr << "ComputeIterationCount ";
1891 if (ExitCond->getOperand(0)->getType()->isUnsigned())
1892 cerr << "[unsigned] ";
1894 << Instruction::getOpcodeName(Instruction::ICmp)
1895 << " " << *RHS << "\n";
1899 return ComputeIterationCountExhaustively(L, ExitCond,
1900 ExitBr->getSuccessor(0) == ExitBlock);
1903 static ConstantInt *
1904 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
1905 ScalarEvolution &SE) {
1906 SCEVHandle InVal = SE.getConstant(C);
1907 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
1908 assert(isa<SCEVConstant>(Val) &&
1909 "Evaluation of SCEV at constant didn't fold correctly?");
1910 return cast<SCEVConstant>(Val)->getValue();
1913 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
1914 /// and a GEP expression (missing the pointer index) indexing into it, return
1915 /// the addressed element of the initializer or null if the index expression is
1918 GetAddressedElementFromGlobal(GlobalVariable *GV,
1919 const std::vector<ConstantInt*> &Indices) {
1920 Constant *Init = GV->getInitializer();
1921 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1922 uint64_t Idx = Indices[i]->getZExtValue();
1923 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1924 assert(Idx < CS->getNumOperands() && "Bad struct index!");
1925 Init = cast<Constant>(CS->getOperand(Idx));
1926 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1927 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
1928 Init = cast<Constant>(CA->getOperand(Idx));
1929 } else if (isa<ConstantAggregateZero>(Init)) {
1930 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1931 assert(Idx < STy->getNumElements() && "Bad struct index!");
1932 Init = Constant::getNullValue(STy->getElementType(Idx));
1933 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
1934 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
1935 Init = Constant::getNullValue(ATy->getElementType());
1937 assert(0 && "Unknown constant aggregate type!");
1941 return 0; // Unknown initializer type
1947 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1948 /// 'icmp op load X, cst', try to se if we can compute the trip count.
1949 SCEVHandle ScalarEvolutionsImpl::
1950 ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
1952 ICmpInst::Predicate predicate) {
1953 if (LI->isVolatile()) return UnknownValue;
1955 // Check to see if the loaded pointer is a getelementptr of a global.
1956 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
1957 if (!GEP) return UnknownValue;
1959 // Make sure that it is really a constant global we are gepping, with an
1960 // initializer, and make sure the first IDX is really 0.
1961 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1962 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1963 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
1964 !cast<Constant>(GEP->getOperand(1))->isNullValue())
1965 return UnknownValue;
1967 // Okay, we allow one non-constant index into the GEP instruction.
1969 std::vector<ConstantInt*> Indexes;
1970 unsigned VarIdxNum = 0;
1971 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
1972 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
1973 Indexes.push_back(CI);
1974 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
1975 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
1976 VarIdx = GEP->getOperand(i);
1978 Indexes.push_back(0);
1981 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
1982 // Check to see if X is a loop variant variable value now.
1983 SCEVHandle Idx = getSCEV(VarIdx);
1984 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
1985 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
1987 // We can only recognize very limited forms of loop index expressions, in
1988 // particular, only affine AddRec's like {C1,+,C2}.
1989 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
1990 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
1991 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
1992 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
1993 return UnknownValue;
1995 unsigned MaxSteps = MaxBruteForceIterations;
1996 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
1997 ConstantInt *ItCst =
1998 ConstantInt::get(IdxExpr->getType(), IterationNum);
1999 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE);
2001 // Form the GEP offset.
2002 Indexes[VarIdxNum] = Val;
2004 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2005 if (Result == 0) break; // Cannot compute!
2007 // Evaluate the condition for this iteration.
2008 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2009 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2010 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2012 cerr << "\n***\n*** Computed loop count " << *ItCst
2013 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2016 ++NumArrayLenItCounts;
2017 return SE.getConstant(ItCst); // Found terminating iteration!
2020 return UnknownValue;
2024 /// CanConstantFold - Return true if we can constant fold an instruction of the
2025 /// specified type, assuming that all operands were constants.
2026 static bool CanConstantFold(const Instruction *I) {
2027 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2028 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2031 if (const CallInst *CI = dyn_cast<CallInst>(I))
2032 if (const Function *F = CI->getCalledFunction())
2033 return canConstantFoldCallTo(F);
2037 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2038 /// in the loop that V is derived from. We allow arbitrary operations along the
2039 /// way, but the operands of an operation must either be constants or a value
2040 /// derived from a constant PHI. If this expression does not fit with these
2041 /// constraints, return null.
2042 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2043 // If this is not an instruction, or if this is an instruction outside of the
2044 // loop, it can't be derived from a loop PHI.
2045 Instruction *I = dyn_cast<Instruction>(V);
2046 if (I == 0 || !L->contains(I->getParent())) return 0;
2048 if (PHINode *PN = dyn_cast<PHINode>(I))
2049 if (L->getHeader() == I->getParent())
2052 // We don't currently keep track of the control flow needed to evaluate
2053 // PHIs, so we cannot handle PHIs inside of loops.
2056 // If we won't be able to constant fold this expression even if the operands
2057 // are constants, return early.
2058 if (!CanConstantFold(I)) return 0;
2060 // Otherwise, we can evaluate this instruction if all of its operands are
2061 // constant or derived from a PHI node themselves.
2063 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2064 if (!(isa<Constant>(I->getOperand(Op)) ||
2065 isa<GlobalValue>(I->getOperand(Op)))) {
2066 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2067 if (P == 0) return 0; // Not evolving from PHI
2071 return 0; // Evolving from multiple different PHIs.
2074 // This is a expression evolving from a constant PHI!
2078 /// EvaluateExpression - Given an expression that passes the
2079 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2080 /// in the loop has the value PHIVal. If we can't fold this expression for some
2081 /// reason, return null.
2082 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2083 if (isa<PHINode>(V)) return PHIVal;
2084 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
2086 if (Constant *C = dyn_cast<Constant>(V)) return C;
2087 Instruction *I = cast<Instruction>(V);
2089 std::vector<Constant*> Operands;
2090 Operands.resize(I->getNumOperands());
2092 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2093 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2094 if (Operands[i] == 0) return 0;
2097 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2098 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2099 &Operands[0], Operands.size());
2101 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2102 &Operands[0], Operands.size());
2105 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2106 /// in the header of its containing loop, we know the loop executes a
2107 /// constant number of times, and the PHI node is just a recurrence
2108 /// involving constants, fold it.
2109 Constant *ScalarEvolutionsImpl::
2110 getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, const Loop *L){
2111 std::map<PHINode*, Constant*>::iterator I =
2112 ConstantEvolutionLoopExitValue.find(PN);
2113 if (I != ConstantEvolutionLoopExitValue.end())
2116 if (Its.ugt(APInt(Its.getBitWidth(),MaxBruteForceIterations)))
2117 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2119 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2121 // Since the loop is canonicalized, the PHI node must have two entries. One
2122 // entry must be a constant (coming in from outside of the loop), and the
2123 // second must be derived from the same PHI.
2124 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2125 Constant *StartCST =
2126 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2128 return RetVal = 0; // Must be a constant.
2130 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2131 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2133 return RetVal = 0; // Not derived from same PHI.
2135 // Execute the loop symbolically to determine the exit value.
2136 if (Its.getActiveBits() >= 32)
2137 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2139 unsigned NumIterations = Its.getZExtValue(); // must be in range
2140 unsigned IterationNum = 0;
2141 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2142 if (IterationNum == NumIterations)
2143 return RetVal = PHIVal; // Got exit value!
2145 // Compute the value of the PHI node for the next iteration.
2146 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2147 if (NextPHI == PHIVal)
2148 return RetVal = NextPHI; // Stopped evolving!
2150 return 0; // Couldn't evaluate!
2155 /// ComputeIterationCountExhaustively - If the trip is known to execute a
2156 /// constant number of times (the condition evolves only from constants),
2157 /// try to evaluate a few iterations of the loop until we get the exit
2158 /// condition gets a value of ExitWhen (true or false). If we cannot
2159 /// evaluate the trip count of the loop, return UnknownValue.
2160 SCEVHandle ScalarEvolutionsImpl::
2161 ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
2162 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2163 if (PN == 0) return UnknownValue;
2165 // Since the loop is canonicalized, the PHI node must have two entries. One
2166 // entry must be a constant (coming in from outside of the loop), and the
2167 // second must be derived from the same PHI.
2168 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2169 Constant *StartCST =
2170 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2171 if (StartCST == 0) return UnknownValue; // Must be a constant.
2173 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2174 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2175 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2177 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2178 // the loop symbolically to determine when the condition gets a value of
2180 unsigned IterationNum = 0;
2181 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2182 for (Constant *PHIVal = StartCST;
2183 IterationNum != MaxIterations; ++IterationNum) {
2184 ConstantInt *CondVal =
2185 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2187 // Couldn't symbolically evaluate.
2188 if (!CondVal) return UnknownValue;
2190 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2191 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2192 ++NumBruteForceTripCountsComputed;
2193 return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
2196 // Compute the value of the PHI node for the next iteration.
2197 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2198 if (NextPHI == 0 || NextPHI == PHIVal)
2199 return UnknownValue; // Couldn't evaluate or not making progress...
2203 // Too many iterations were needed to evaluate.
2204 return UnknownValue;
2207 /// getSCEVAtScope - Compute the value of the specified expression within the
2208 /// indicated loop (which may be null to indicate in no loop). If the
2209 /// expression cannot be evaluated, return UnknownValue.
2210 SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2211 // FIXME: this should be turned into a virtual method on SCEV!
2213 if (isa<SCEVConstant>(V)) return V;
2215 // If this instruction is evolves from a constant-evolving PHI, compute the
2216 // exit value from the loop without using SCEVs.
2217 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2218 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2219 const Loop *LI = this->LI[I->getParent()];
2220 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2221 if (PHINode *PN = dyn_cast<PHINode>(I))
2222 if (PN->getParent() == LI->getHeader()) {
2223 // Okay, there is no closed form solution for the PHI node. Check
2224 // to see if the loop that contains it has a known iteration count.
2225 // If so, we may be able to force computation of the exit value.
2226 SCEVHandle IterationCount = getIterationCount(LI);
2227 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
2228 // Okay, we know how many times the containing loop executes. If
2229 // this is a constant evolving PHI node, get the final value at
2230 // the specified iteration number.
2231 Constant *RV = getConstantEvolutionLoopExitValue(PN,
2232 ICC->getValue()->getValue(),
2234 if (RV) return SE.getUnknown(RV);
2238 // Okay, this is an expression that we cannot symbolically evaluate
2239 // into a SCEV. Check to see if it's possible to symbolically evaluate
2240 // the arguments into constants, and if so, try to constant propagate the
2241 // result. This is particularly useful for computing loop exit values.
2242 if (CanConstantFold(I)) {
2243 std::vector<Constant*> Operands;
2244 Operands.reserve(I->getNumOperands());
2245 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2246 Value *Op = I->getOperand(i);
2247 if (Constant *C = dyn_cast<Constant>(Op)) {
2248 Operands.push_back(C);
2250 // If any of the operands is non-constant and if they are
2251 // non-integer, don't even try to analyze them with scev techniques.
2252 if (!isa<IntegerType>(Op->getType()))
2255 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2256 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
2257 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2260 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2261 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
2262 Operands.push_back(ConstantExpr::getIntegerCast(C,
2274 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2275 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2276 &Operands[0], Operands.size());
2278 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2279 &Operands[0], Operands.size());
2280 return SE.getUnknown(C);
2284 // This is some other type of SCEVUnknown, just return it.
2288 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2289 // Avoid performing the look-up in the common case where the specified
2290 // expression has no loop-variant portions.
2291 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2292 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2293 if (OpAtScope != Comm->getOperand(i)) {
2294 if (OpAtScope == UnknownValue) return UnknownValue;
2295 // Okay, at least one of these operands is loop variant but might be
2296 // foldable. Build a new instance of the folded commutative expression.
2297 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2298 NewOps.push_back(OpAtScope);
2300 for (++i; i != e; ++i) {
2301 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2302 if (OpAtScope == UnknownValue) return UnknownValue;
2303 NewOps.push_back(OpAtScope);
2305 if (isa<SCEVAddExpr>(Comm))
2306 return SE.getAddExpr(NewOps);
2307 if (isa<SCEVMulExpr>(Comm))
2308 return SE.getMulExpr(NewOps);
2309 if (isa<SCEVSMaxExpr>(Comm))
2310 return SE.getSMaxExpr(NewOps);
2311 assert(0 && "Unknown commutative SCEV type!");
2314 // If we got here, all operands are loop invariant.
2318 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
2319 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
2320 if (LHS == UnknownValue) return LHS;
2321 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
2322 if (RHS == UnknownValue) return RHS;
2323 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2324 return Div; // must be loop invariant
2325 return SE.getUDivExpr(LHS, RHS);
2328 // If this is a loop recurrence for a loop that does not contain L, then we
2329 // are dealing with the final value computed by the loop.
2330 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2331 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2332 // To evaluate this recurrence, we need to know how many times the AddRec
2333 // loop iterates. Compute this now.
2334 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2335 if (IterationCount == UnknownValue) return UnknownValue;
2336 IterationCount = getTruncateOrZeroExtend(IterationCount,
2337 AddRec->getType(), SE);
2339 // If the value is affine, simplify the expression evaluation to just
2340 // Start + Step*IterationCount.
2341 if (AddRec->isAffine())
2342 return SE.getAddExpr(AddRec->getStart(),
2343 SE.getMulExpr(IterationCount,
2344 AddRec->getOperand(1)));
2346 // Otherwise, evaluate it the hard way.
2347 return AddRec->evaluateAtIteration(IterationCount, SE);
2349 return UnknownValue;
2352 //assert(0 && "Unknown SCEV type!");
2353 return UnknownValue;
2357 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2358 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2359 /// might be the same) or two SCEVCouldNotCompute objects.
2361 static std::pair<SCEVHandle,SCEVHandle>
2362 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
2363 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2364 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2365 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2366 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2368 // We currently can only solve this if the coefficients are constants.
2369 if (!LC || !MC || !NC) {
2370 SCEV *CNC = new SCEVCouldNotCompute();
2371 return std::make_pair(CNC, CNC);
2374 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2375 const APInt &L = LC->getValue()->getValue();
2376 const APInt &M = MC->getValue()->getValue();
2377 const APInt &N = NC->getValue()->getValue();
2378 APInt Two(BitWidth, 2);
2379 APInt Four(BitWidth, 4);
2382 using namespace APIntOps;
2384 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2385 // The B coefficient is M-N/2
2389 // The A coefficient is N/2
2390 APInt A(N.sdiv(Two));
2392 // Compute the B^2-4ac term.
2395 SqrtTerm -= Four * (A * C);
2397 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2398 // integer value or else APInt::sqrt() will assert.
2399 APInt SqrtVal(SqrtTerm.sqrt());
2401 // Compute the two solutions for the quadratic formula.
2402 // The divisions must be performed as signed divisions.
2404 APInt TwoA( A << 1 );
2405 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2406 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2408 return std::make_pair(SE.getConstant(Solution1),
2409 SE.getConstant(Solution2));
2410 } // end APIntOps namespace
2413 /// HowFarToZero - Return the number of times a backedge comparing the specified
2414 /// value to zero will execute. If not computable, return UnknownValue
2415 SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2416 // If the value is a constant
2417 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2418 // If the value is already zero, the branch will execute zero times.
2419 if (C->getValue()->isZero()) return C;
2420 return UnknownValue; // Otherwise it will loop infinitely.
2423 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2424 if (!AddRec || AddRec->getLoop() != L)
2425 return UnknownValue;
2427 if (AddRec->isAffine()) {
2428 // If this is an affine expression the execution count of this branch is
2431 // (0 - Start/Step) iff Start % Step == 0
2433 // Get the initial value for the loop.
2434 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2435 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
2436 SCEVHandle Step = AddRec->getOperand(1);
2438 Step = getSCEVAtScope(Step, L->getParentLoop());
2440 // Figure out if Start % Step == 0.
2441 // FIXME: We should add DivExpr and RemExpr operations to our AST.
2442 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2443 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
2444 return SE.getNegativeSCEV(Start); // 0 - Start/1 == -Start
2445 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
2446 return Start; // 0 - Start/-1 == Start
2448 // Check to see if Start is divisible by SC with no remainder.
2449 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2450 ConstantInt *StartCC = StartC->getValue();
2451 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
2452 Constant *Rem = ConstantExpr::getSRem(StartNegC, StepC->getValue());
2453 if (Rem->isNullValue()) {
2454 Constant *Result =ConstantExpr::getSDiv(StartNegC,StepC->getValue());
2455 return SE.getUnknown(Result);
2459 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2460 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2461 // the quadratic equation to solve it.
2462 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE);
2463 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2464 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2467 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2468 << " sol#2: " << *R2 << "\n";
2470 // Pick the smallest positive root value.
2471 if (ConstantInt *CB =
2472 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2473 R1->getValue(), R2->getValue()))) {
2474 if (CB->getZExtValue() == false)
2475 std::swap(R1, R2); // R1 is the minimum root now.
2477 // We can only use this value if the chrec ends up with an exact zero
2478 // value at this index. When solving for "X*X != 5", for example, we
2479 // should not accept a root of 2.
2480 SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE);
2481 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
2482 if (EvalVal->getValue()->isZero())
2483 return R1; // We found a quadratic root!
2488 return UnknownValue;
2491 /// HowFarToNonZero - Return the number of times a backedge checking the
2492 /// specified value for nonzero will execute. If not computable, return
2494 SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2495 // Loops that look like: while (X == 0) are very strange indeed. We don't
2496 // handle them yet except for the trivial case. This could be expanded in the
2497 // future as needed.
2499 // If the value is a constant, check to see if it is known to be non-zero
2500 // already. If so, the backedge will execute zero times.
2501 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2502 Constant *Zero = Constant::getNullValue(C->getValue()->getType());
2504 ConstantExpr::getICmp(ICmpInst::ICMP_NE, C->getValue(), Zero);
2505 if (NonZero == ConstantInt::getTrue())
2506 return getSCEV(Zero);
2507 return UnknownValue; // Otherwise it will loop infinitely.
2510 // We could implement others, but I really doubt anyone writes loops like
2511 // this, and if they did, they would already be constant folded.
2512 return UnknownValue;
2515 /// HowManyLessThans - Return the number of times a backedge containing the
2516 /// specified less-than comparison will execute. If not computable, return
2518 SCEVHandle ScalarEvolutionsImpl::
2519 HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
2520 // Only handle: "ADDREC < LoopInvariant".
2521 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2523 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2524 if (!AddRec || AddRec->getLoop() != L)
2525 return UnknownValue;
2527 if (AddRec->isAffine()) {
2528 // The number of iterations for "{n,+,1} < m", is m-n. However, we don't
2529 // know that m is >= n on input to the loop. If it is, the condition
2530 // returns true zero times. To handle both cases, we return SMAX(m, n)-n.
2532 // FORNOW: We only support unit strides.
2533 SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType());
2534 if (AddRec->getOperand(1) != One)
2535 return UnknownValue;
2537 SCEVHandle Start = AddRec->getOperand(0);
2538 SCEVHandle End = isSigned ? SE.getSMaxExpr(RHS, Start) : (SCEVHandle)RHS;
2540 return SE.getMinusSCEV(End, Start);
2543 return UnknownValue;
2546 /// getNumIterationsInRange - Return the number of iterations of this loop that
2547 /// produce values in the specified constant range. Another way of looking at
2548 /// this is that it returns the first iteration number where the value is not in
2549 /// the condition, thus computing the exit count. If the iteration count can't
2550 /// be computed, an instance of SCEVCouldNotCompute is returned.
2551 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
2552 ScalarEvolution &SE) const {
2553 if (Range.isFullSet()) // Infinite loop.
2554 return new SCEVCouldNotCompute();
2556 // If the start is a non-zero constant, shift the range to simplify things.
2557 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2558 if (!SC->getValue()->isZero()) {
2559 std::vector<SCEVHandle> Operands(op_begin(), op_end());
2560 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
2561 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
2562 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2563 return ShiftedAddRec->getNumIterationsInRange(
2564 Range.subtract(SC->getValue()->getValue()), SE);
2565 // This is strange and shouldn't happen.
2566 return new SCEVCouldNotCompute();
2569 // The only time we can solve this is when we have all constant indices.
2570 // Otherwise, we cannot determine the overflow conditions.
2571 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2572 if (!isa<SCEVConstant>(getOperand(i)))
2573 return new SCEVCouldNotCompute();
2576 // Okay at this point we know that all elements of the chrec are constants and
2577 // that the start element is zero.
2579 // First check to see if the range contains zero. If not, the first
2581 if (!Range.contains(APInt(getBitWidth(),0)))
2582 return SE.getConstant(ConstantInt::get(getType(),0));
2585 // If this is an affine expression then we have this situation:
2586 // Solve {0,+,A} in Range === Ax in Range
2588 // We know that zero is in the range. If A is positive then we know that
2589 // the upper value of the range must be the first possible exit value.
2590 // If A is negative then the lower of the range is the last possible loop
2591 // value. Also note that we already checked for a full range.
2592 APInt One(getBitWidth(),1);
2593 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
2594 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
2596 // The exit value should be (End+A)/A.
2597 APInt ExitVal = (End + A).udiv(A);
2598 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
2600 // Evaluate at the exit value. If we really did fall out of the valid
2601 // range, then we computed our trip count, otherwise wrap around or other
2602 // things must have happened.
2603 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
2604 if (Range.contains(Val->getValue()))
2605 return new SCEVCouldNotCompute(); // Something strange happened
2607 // Ensure that the previous value is in the range. This is a sanity check.
2608 assert(Range.contains(
2609 EvaluateConstantChrecAtConstant(this,
2610 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
2611 "Linear scev computation is off in a bad way!");
2612 return SE.getConstant(ExitValue);
2613 } else if (isQuadratic()) {
2614 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2615 // quadratic equation to solve it. To do this, we must frame our problem in
2616 // terms of figuring out when zero is crossed, instead of when
2617 // Range.getUpper() is crossed.
2618 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
2619 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
2620 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
2622 // Next, solve the constructed addrec
2623 std::pair<SCEVHandle,SCEVHandle> Roots =
2624 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
2625 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2626 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2628 // Pick the smallest positive root value.
2629 if (ConstantInt *CB =
2630 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2631 R1->getValue(), R2->getValue()))) {
2632 if (CB->getZExtValue() == false)
2633 std::swap(R1, R2); // R1 is the minimum root now.
2635 // Make sure the root is not off by one. The returned iteration should
2636 // not be in the range, but the previous one should be. When solving
2637 // for "X*X < 5", for example, we should not return a root of 2.
2638 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2641 if (Range.contains(R1Val->getValue())) {
2642 // The next iteration must be out of the range...
2643 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
2645 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
2646 if (!Range.contains(R1Val->getValue()))
2647 return SE.getConstant(NextVal);
2648 return new SCEVCouldNotCompute(); // Something strange happened
2651 // If R1 was not in the range, then it is a good return value. Make
2652 // sure that R1-1 WAS in the range though, just in case.
2653 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
2654 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
2655 if (Range.contains(R1Val->getValue()))
2657 return new SCEVCouldNotCompute(); // Something strange happened
2662 // Fallback, if this is a general polynomial, figure out the progression
2663 // through brute force: evaluate until we find an iteration that fails the
2664 // test. This is likely to be slow, but getting an accurate trip count is
2665 // incredibly important, we will be able to simplify the exit test a lot, and
2666 // we are almost guaranteed to get a trip count in this case.
2667 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2668 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2670 ++NumBruteForceEvaluations;
2671 SCEVHandle Val = evaluateAtIteration(SE.getConstant(TestVal), SE);
2672 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2673 return new SCEVCouldNotCompute();
2675 // Check to see if we found the value!
2676 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()->getValue()))
2677 return SE.getConstant(TestVal);
2679 // Increment to test the next index.
2680 TestVal = ConstantInt::get(TestVal->getValue()+1);
2681 } while (TestVal != EndVal);
2683 return new SCEVCouldNotCompute();
2688 //===----------------------------------------------------------------------===//
2689 // ScalarEvolution Class Implementation
2690 //===----------------------------------------------------------------------===//
2692 bool ScalarEvolution::runOnFunction(Function &F) {
2693 Impl = new ScalarEvolutionsImpl(*this, F, getAnalysis<LoopInfo>());
2697 void ScalarEvolution::releaseMemory() {
2698 delete (ScalarEvolutionsImpl*)Impl;
2702 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2703 AU.setPreservesAll();
2704 AU.addRequiredTransitive<LoopInfo>();
2707 SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2708 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2711 /// hasSCEV - Return true if the SCEV for this value has already been
2713 bool ScalarEvolution::hasSCEV(Value *V) const {
2714 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
2718 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
2719 /// the specified value.
2720 void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
2721 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
2725 SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2726 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2729 bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2730 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2733 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2734 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2737 void ScalarEvolution::deleteValueFromRecords(Value *V) const {
2738 return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
2741 static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
2743 // Print all inner loops first
2744 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2745 PrintLoopInfo(OS, SE, *I);
2747 OS << "Loop " << L->getHeader()->getName() << ": ";
2749 SmallVector<BasicBlock*, 8> ExitBlocks;
2750 L->getExitBlocks(ExitBlocks);
2751 if (ExitBlocks.size() != 1)
2752 OS << "<multiple exits> ";
2754 if (SE->hasLoopInvariantIterationCount(L)) {
2755 OS << *SE->getIterationCount(L) << " iterations! ";
2757 OS << "Unpredictable iteration count. ";
2763 void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
2764 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2765 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2767 OS << "Classifying expressions for: " << F.getName() << "\n";
2768 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
2769 if (I->getType()->isInteger()) {
2772 SCEVHandle SV = getSCEV(&*I);
2776 if ((*I).getType()->isInteger()) {
2777 ConstantRange Bounds = SV->getValueRange();
2778 if (!Bounds.isFullSet())
2779 OS << "Bounds: " << Bounds << " ";
2782 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
2784 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
2785 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2786 OS << "<<Unknown>>";
2796 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2797 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2798 PrintLoopInfo(OS, this, *I);