1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the implementation of the scalar evolution analysis
11 // engine, which is used primarily to analyze expressions involving induction
12 // variables in loops.
14 // There are several aspects to this library. First is the representation of
15 // scalar expressions, which are represented as subclasses of the SCEV class.
16 // These classes are used to represent certain types of subexpressions that we
17 // can handle. These classes are reference counted, managed by the SCEVHandle
18 // class. We only create one SCEV of a particular shape, so pointer-comparisons
19 // for equality are legal.
21 // One important aspect of the SCEV objects is that they are never cyclic, even
22 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If
23 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
24 // recurrence) then we represent it directly as a recurrence node, otherwise we
25 // represent it as a SCEVUnknown node.
27 // In addition to being able to represent expressions of various types, we also
28 // have folders that are used to build the *canonical* representation for a
29 // particular expression. These folders are capable of using a variety of
30 // rewrite rules to simplify the expressions.
32 // Once the folders are defined, we can implement the more interesting
33 // higher-level code, such as the code that recognizes PHI nodes of various
34 // types, computes the execution count of a loop, etc.
36 // TODO: We should use these routines and value representations to implement
37 // dependence analysis!
39 //===----------------------------------------------------------------------===//
41 // There are several good references for the techniques used in this analysis.
43 // Chains of recurrences -- a method to expedite the evaluation
44 // of closed-form functions
45 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima
47 // On computational properties of chains of recurrences
50 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization
51 // Robert A. van Engelen
53 // Efficient Symbolic Analysis for Optimizing Compilers
54 // Robert A. van Engelen
56 // Using the chains of recurrences algebra for data dependence testing and
57 // induction variable substitution
58 // MS Thesis, Johnie Birch
60 //===----------------------------------------------------------------------===//
62 #define DEBUG_TYPE "scalar-evolution"
63 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
64 #include "llvm/Constants.h"
65 #include "llvm/DerivedTypes.h"
66 #include "llvm/GlobalVariable.h"
67 #include "llvm/Instructions.h"
68 #include "llvm/Analysis/ConstantFolding.h"
69 #include "llvm/Analysis/LoopInfo.h"
70 #include "llvm/Assembly/Writer.h"
71 #include "llvm/Transforms/Scalar.h"
72 #include "llvm/Support/CFG.h"
73 #include "llvm/Support/CommandLine.h"
74 #include "llvm/Support/Compiler.h"
75 #include "llvm/Support/ConstantRange.h"
76 #include "llvm/Support/InstIterator.h"
77 #include "llvm/Support/ManagedStatic.h"
78 #include "llvm/Support/MathExtras.h"
79 #include "llvm/Support/Streams.h"
80 #include "llvm/ADT/Statistic.h"
86 STATISTIC(NumBruteForceEvaluations,
87 "Number of brute force evaluations needed to "
88 "calculate high-order polynomial exit values");
89 STATISTIC(NumArrayLenItCounts,
90 "Number of trip counts computed with array length");
91 STATISTIC(NumTripCountsComputed,
92 "Number of loops with predictable loop counts");
93 STATISTIC(NumTripCountsNotComputed,
94 "Number of loops without predictable loop counts");
95 STATISTIC(NumBruteForceTripCountsComputed,
96 "Number of loops with trip counts computed by force");
98 static cl::opt<unsigned>
99 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
100 cl::desc("Maximum number of iterations SCEV will "
101 "symbolically execute a constant derived loop"),
104 static RegisterPass<ScalarEvolution>
105 R("scalar-evolution", "Scalar Evolution Analysis", false, true);
106 char ScalarEvolution::ID = 0;
108 //===----------------------------------------------------------------------===//
109 // SCEV class definitions
110 //===----------------------------------------------------------------------===//
112 //===----------------------------------------------------------------------===//
113 // Implementation of the SCEV class.
116 void SCEV::dump() const {
120 /// getValueRange - Return the tightest constant bounds that this value is
121 /// known to have. This method is only valid on integer SCEV objects.
122 ConstantRange SCEV::getValueRange() const {
123 const Type *Ty = getType();
124 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
125 // Default to a full range if no better information is available.
126 return ConstantRange(getBitWidth());
129 uint32_t SCEV::getBitWidth() const {
130 if (const IntegerType* ITy = dyn_cast<IntegerType>(getType()))
131 return ITy->getBitWidth();
135 bool SCEV::isZero() const {
136 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
137 return SC->getValue()->isZero();
142 SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
144 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
145 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
149 const Type *SCEVCouldNotCompute::getType() const {
150 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
154 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
155 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
159 SCEVHandle SCEVCouldNotCompute::
160 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
161 const SCEVHandle &Conc,
162 ScalarEvolution &SE) const {
166 void SCEVCouldNotCompute::print(std::ostream &OS) const {
167 OS << "***COULDNOTCOMPUTE***";
170 bool SCEVCouldNotCompute::classof(const SCEV *S) {
171 return S->getSCEVType() == scCouldNotCompute;
175 // SCEVConstants - Only allow the creation of one SCEVConstant for any
176 // particular value. Don't use a SCEVHandle here, or else the object will
178 static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
181 SCEVConstant::~SCEVConstant() {
182 SCEVConstants->erase(V);
185 SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
186 SCEVConstant *&R = (*SCEVConstants)[V];
187 if (R == 0) R = new SCEVConstant(V);
191 SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
192 return getConstant(ConstantInt::get(Val));
195 ConstantRange SCEVConstant::getValueRange() const {
196 return ConstantRange(V->getValue());
199 const Type *SCEVConstant::getType() const { return V->getType(); }
201 void SCEVConstant::print(std::ostream &OS) const {
202 WriteAsOperand(OS, V, false);
205 // SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
206 // particular input. Don't use a SCEVHandle here, or else the object will
208 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
209 SCEVTruncateExpr*> > SCEVTruncates;
211 SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
212 : SCEV(scTruncate), Op(op), Ty(ty) {
213 assert(Op->getType()->isInteger() && Ty->isInteger() &&
214 "Cannot truncate non-integer value!");
215 assert(Op->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()
216 && "This is not a truncating conversion!");
219 SCEVTruncateExpr::~SCEVTruncateExpr() {
220 SCEVTruncates->erase(std::make_pair(Op, Ty));
223 ConstantRange SCEVTruncateExpr::getValueRange() const {
224 return getOperand()->getValueRange().truncate(getBitWidth());
227 void SCEVTruncateExpr::print(std::ostream &OS) const {
228 OS << "(truncate " << *Op << " to " << *Ty << ")";
231 // SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
232 // particular input. Don't use a SCEVHandle here, or else the object will never
234 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
235 SCEVZeroExtendExpr*> > SCEVZeroExtends;
237 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
238 : SCEV(scZeroExtend), Op(op), Ty(ty) {
239 assert(Op->getType()->isInteger() && Ty->isInteger() &&
240 "Cannot zero extend non-integer value!");
241 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
242 && "This is not an extending conversion!");
245 SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
246 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
249 ConstantRange SCEVZeroExtendExpr::getValueRange() const {
250 return getOperand()->getValueRange().zeroExtend(getBitWidth());
253 void SCEVZeroExtendExpr::print(std::ostream &OS) const {
254 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
257 // SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
258 // particular input. Don't use a SCEVHandle here, or else the object will never
260 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
261 SCEVSignExtendExpr*> > SCEVSignExtends;
263 SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
264 : SCEV(scSignExtend), Op(op), Ty(ty) {
265 assert(Op->getType()->isInteger() && Ty->isInteger() &&
266 "Cannot sign extend non-integer value!");
267 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
268 && "This is not an extending conversion!");
271 SCEVSignExtendExpr::~SCEVSignExtendExpr() {
272 SCEVSignExtends->erase(std::make_pair(Op, Ty));
275 ConstantRange SCEVSignExtendExpr::getValueRange() const {
276 return getOperand()->getValueRange().signExtend(getBitWidth());
279 void SCEVSignExtendExpr::print(std::ostream &OS) const {
280 OS << "(signextend " << *Op << " to " << *Ty << ")";
283 // SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
284 // particular input. Don't use a SCEVHandle here, or else the object will never
286 static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
287 SCEVCommutativeExpr*> > SCEVCommExprs;
289 SCEVCommutativeExpr::~SCEVCommutativeExpr() {
290 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
291 std::vector<SCEV*>(Operands.begin(),
295 void SCEVCommutativeExpr::print(std::ostream &OS) const {
296 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
297 const char *OpStr = getOperationStr();
298 OS << "(" << *Operands[0];
299 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
300 OS << OpStr << *Operands[i];
304 SCEVHandle SCEVCommutativeExpr::
305 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
306 const SCEVHandle &Conc,
307 ScalarEvolution &SE) const {
308 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
310 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
311 if (H != getOperand(i)) {
312 std::vector<SCEVHandle> NewOps;
313 NewOps.reserve(getNumOperands());
314 for (unsigned j = 0; j != i; ++j)
315 NewOps.push_back(getOperand(j));
317 for (++i; i != e; ++i)
318 NewOps.push_back(getOperand(i)->
319 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
321 if (isa<SCEVAddExpr>(this))
322 return SE.getAddExpr(NewOps);
323 else if (isa<SCEVMulExpr>(this))
324 return SE.getMulExpr(NewOps);
325 else if (isa<SCEVSMaxExpr>(this))
326 return SE.getSMaxExpr(NewOps);
327 else if (isa<SCEVUMaxExpr>(this))
328 return SE.getUMaxExpr(NewOps);
330 assert(0 && "Unknown commutative expr!");
337 // SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
338 // input. Don't use a SCEVHandle here, or else the object will never be
340 static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
341 SCEVUDivExpr*> > SCEVUDivs;
343 SCEVUDivExpr::~SCEVUDivExpr() {
344 SCEVUDivs->erase(std::make_pair(LHS, RHS));
347 void SCEVUDivExpr::print(std::ostream &OS) const {
348 OS << "(" << *LHS << " /u " << *RHS << ")";
351 const Type *SCEVUDivExpr::getType() const {
352 return LHS->getType();
355 // SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
356 // particular input. Don't use a SCEVHandle here, or else the object will never
358 static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
359 SCEVAddRecExpr*> > SCEVAddRecExprs;
361 SCEVAddRecExpr::~SCEVAddRecExpr() {
362 SCEVAddRecExprs->erase(std::make_pair(L,
363 std::vector<SCEV*>(Operands.begin(),
367 SCEVHandle SCEVAddRecExpr::
368 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
369 const SCEVHandle &Conc,
370 ScalarEvolution &SE) const {
371 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
373 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
374 if (H != getOperand(i)) {
375 std::vector<SCEVHandle> NewOps;
376 NewOps.reserve(getNumOperands());
377 for (unsigned j = 0; j != i; ++j)
378 NewOps.push_back(getOperand(j));
380 for (++i; i != e; ++i)
381 NewOps.push_back(getOperand(i)->
382 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
384 return SE.getAddRecExpr(NewOps, L);
391 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
392 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
393 // contain L and if the start is invariant.
394 return !QueryLoop->contains(L->getHeader()) &&
395 getOperand(0)->isLoopInvariant(QueryLoop);
399 void SCEVAddRecExpr::print(std::ostream &OS) const {
400 OS << "{" << *Operands[0];
401 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
402 OS << ",+," << *Operands[i];
403 OS << "}<" << L->getHeader()->getName() + ">";
406 // SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
407 // value. Don't use a SCEVHandle here, or else the object will never be
409 static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
411 SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
413 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
414 // All non-instruction values are loop invariant. All instructions are loop
415 // invariant if they are not contained in the specified loop.
416 if (Instruction *I = dyn_cast<Instruction>(V))
417 return !L->contains(I->getParent());
421 const Type *SCEVUnknown::getType() const {
425 void SCEVUnknown::print(std::ostream &OS) const {
426 WriteAsOperand(OS, V, false);
429 //===----------------------------------------------------------------------===//
431 //===----------------------------------------------------------------------===//
434 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
435 /// than the complexity of the RHS. This comparator is used to canonicalize
437 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
438 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
439 return LHS->getSCEVType() < RHS->getSCEVType();
444 /// GroupByComplexity - Given a list of SCEV objects, order them by their
445 /// complexity, and group objects of the same complexity together by value.
446 /// When this routine is finished, we know that any duplicates in the vector are
447 /// consecutive and that complexity is monotonically increasing.
449 /// Note that we go take special precautions to ensure that we get determinstic
450 /// results from this routine. In other words, we don't want the results of
451 /// this to depend on where the addresses of various SCEV objects happened to
454 static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
455 if (Ops.size() < 2) return; // Noop
456 if (Ops.size() == 2) {
457 // This is the common case, which also happens to be trivially simple.
459 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
460 std::swap(Ops[0], Ops[1]);
464 // Do the rough sort by complexity.
465 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
467 // Now that we are sorted by complexity, group elements of the same
468 // complexity. Note that this is, at worst, N^2, but the vector is likely to
469 // be extremely short in practice. Note that we take this approach because we
470 // do not want to depend on the addresses of the objects we are grouping.
471 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
473 unsigned Complexity = S->getSCEVType();
475 // If there are any objects of the same complexity and same value as this
477 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
478 if (Ops[j] == S) { // Found a duplicate.
479 // Move it to immediately after i'th element.
480 std::swap(Ops[i+1], Ops[j]);
481 ++i; // no need to rescan it.
482 if (i == e-2) return; // Done!
490 //===----------------------------------------------------------------------===//
491 // Simple SCEV method implementations
492 //===----------------------------------------------------------------------===//
494 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
495 /// specified signed integer value and return a SCEV for the constant.
496 SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
499 C = Constant::getNullValue(Ty);
500 else if (Ty->isFloatingPoint())
501 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
502 APFloat::IEEEdouble, Val));
504 C = ConstantInt::get(Ty, Val);
505 return getUnknown(C);
508 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
510 SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
511 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
512 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
514 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(V->getType())));
517 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
518 SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
519 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
520 return getUnknown(ConstantExpr::getNot(VC->getValue()));
522 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(V->getType()));
523 return getMinusSCEV(AllOnes, V);
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.getTruncateOrZeroExtend(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());
602 APInt Result = Dividend.udiv(Divisor);
603 if (Result.getBitWidth() != It->getBitWidth())
604 Result = Result.trunc(It->getBitWidth());
606 return SE.getConstant(Result);
609 SCEVHandle Dividend = ExIt;
610 for (unsigned i = 1; i != K; ++i)
612 SE.getMulExpr(Dividend,
613 SE.getMinusSCEV(ExIt, SE.getIntegerSCEV(i, DividendTy)));
615 return SE.getTruncateOrZeroExtend(
617 SE.getTruncateOrZeroExtend(Dividend, DivisionTy),
618 SE.getConstant(Divisor)
622 /// evaluateAtIteration - Return the value of this chain of recurrences at
623 /// the specified iteration number. We can evaluate this recurrence by
624 /// multiplying each element in the chain by the binomial coefficient
625 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
627 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
629 /// where BC(It, k) stands for binomial coefficient.
631 SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
632 ScalarEvolution &SE) const {
633 SCEVHandle Result = getStart();
634 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
635 // The computation is correct in the face of overflow provided that the
636 // multiplication is performed _after_ the evaluation of the binomial
638 SCEVHandle Val = SE.getMulExpr(getOperand(i),
639 BinomialCoefficient(It, i, SE));
640 Result = SE.getAddExpr(Result, Val);
645 //===----------------------------------------------------------------------===//
646 // SCEV Expression folder implementations
647 //===----------------------------------------------------------------------===//
649 SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
650 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
652 ConstantExpr::getTrunc(SC->getValue(), Ty));
654 // If the input value is a chrec scev made out of constants, truncate
655 // all of the constants.
656 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
657 std::vector<SCEVHandle> Operands;
658 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
659 // FIXME: This should allow truncation of other expression types!
660 if (isa<SCEVConstant>(AddRec->getOperand(i)))
661 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
664 if (Operands.size() == AddRec->getNumOperands())
665 return getAddRecExpr(Operands, AddRec->getLoop());
668 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
669 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
673 SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty) {
674 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
676 ConstantExpr::getZExt(SC->getValue(), Ty));
678 // FIXME: If the input value is a chrec scev, and we can prove that the value
679 // did not overflow the old, smaller, value, we can zero extend all of the
680 // operands (often constants). This would allow analysis of something like
681 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
683 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
684 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
688 SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
689 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
691 ConstantExpr::getSExt(SC->getValue(), Ty));
693 // FIXME: If the input value is a chrec scev, and we can prove that the value
694 // did not overflow the old, smaller, value, we can sign extend all of the
695 // operands (often constants). This would allow analysis of something like
696 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
698 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
699 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
703 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
704 /// of the input value to the specified type. If the type must be
705 /// extended, it is zero extended.
706 SCEVHandle ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
708 const Type *SrcTy = V->getType();
709 assert(SrcTy->isInteger() && Ty->isInteger() &&
710 "Cannot truncate or zero extend with non-integer arguments!");
711 if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
712 return V; // No conversion
713 if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits())
714 return getTruncateExpr(V, Ty);
715 return getZeroExtendExpr(V, Ty);
718 // get - Get a canonical add expression, or something simpler if possible.
719 SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
720 assert(!Ops.empty() && "Cannot get empty add!");
721 if (Ops.size() == 1) return Ops[0];
723 // Sort by complexity, this groups all similar expression types together.
724 GroupByComplexity(Ops);
726 // If there are any constants, fold them together.
728 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
730 assert(Idx < Ops.size());
731 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
732 // We found two constants, fold them together!
733 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
734 RHSC->getValue()->getValue());
735 Ops[0] = getConstant(Fold);
736 Ops.erase(Ops.begin()+1); // Erase the folded element
737 if (Ops.size() == 1) return Ops[0];
738 LHSC = cast<SCEVConstant>(Ops[0]);
741 // If we are left with a constant zero being added, strip it off.
742 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
743 Ops.erase(Ops.begin());
748 if (Ops.size() == 1) return Ops[0];
750 // Okay, check to see if the same value occurs in the operand list twice. If
751 // so, merge them together into an multiply expression. Since we sorted the
752 // list, these values are required to be adjacent.
753 const Type *Ty = Ops[0]->getType();
754 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
755 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
756 // Found a match, merge the two values into a multiply, and add any
757 // remaining values to the result.
758 SCEVHandle Two = getIntegerSCEV(2, Ty);
759 SCEVHandle Mul = getMulExpr(Ops[i], Two);
762 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
764 return getAddExpr(Ops);
767 // Now we know the first non-constant operand. Skip past any cast SCEVs.
768 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
771 // If there are add operands they would be next.
772 if (Idx < Ops.size()) {
773 bool DeletedAdd = false;
774 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
775 // If we have an add, expand the add operands onto the end of the operands
777 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
778 Ops.erase(Ops.begin()+Idx);
782 // If we deleted at least one add, we added operands to the end of the list,
783 // and they are not necessarily sorted. Recurse to resort and resimplify
784 // any operands we just aquired.
786 return getAddExpr(Ops);
789 // Skip over the add expression until we get to a multiply.
790 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
793 // If we are adding something to a multiply expression, make sure the
794 // something is not already an operand of the multiply. If so, merge it into
796 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
797 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
798 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
799 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
800 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
801 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
802 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
803 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
804 if (Mul->getNumOperands() != 2) {
805 // If the multiply has more than two operands, we must get the
807 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
808 MulOps.erase(MulOps.begin()+MulOp);
809 InnerMul = getMulExpr(MulOps);
811 SCEVHandle One = getIntegerSCEV(1, Ty);
812 SCEVHandle AddOne = getAddExpr(InnerMul, One);
813 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
814 if (Ops.size() == 2) return OuterMul;
816 Ops.erase(Ops.begin()+AddOp);
817 Ops.erase(Ops.begin()+Idx-1);
819 Ops.erase(Ops.begin()+Idx);
820 Ops.erase(Ops.begin()+AddOp-1);
822 Ops.push_back(OuterMul);
823 return getAddExpr(Ops);
826 // Check this multiply against other multiplies being added together.
827 for (unsigned OtherMulIdx = Idx+1;
828 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
830 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
831 // If MulOp occurs in OtherMul, we can fold the two multiplies
833 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
834 OMulOp != e; ++OMulOp)
835 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
836 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
837 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
838 if (Mul->getNumOperands() != 2) {
839 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
840 MulOps.erase(MulOps.begin()+MulOp);
841 InnerMul1 = getMulExpr(MulOps);
843 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
844 if (OtherMul->getNumOperands() != 2) {
845 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
847 MulOps.erase(MulOps.begin()+OMulOp);
848 InnerMul2 = getMulExpr(MulOps);
850 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
851 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
852 if (Ops.size() == 2) return OuterMul;
853 Ops.erase(Ops.begin()+Idx);
854 Ops.erase(Ops.begin()+OtherMulIdx-1);
855 Ops.push_back(OuterMul);
856 return getAddExpr(Ops);
862 // If there are any add recurrences in the operands list, see if any other
863 // added values are loop invariant. If so, we can fold them into the
865 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
868 // Scan over all recurrences, trying to fold loop invariants into them.
869 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
870 // Scan all of the other operands to this add and add them to the vector if
871 // they are loop invariant w.r.t. the recurrence.
872 std::vector<SCEVHandle> LIOps;
873 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
874 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
875 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
876 LIOps.push_back(Ops[i]);
877 Ops.erase(Ops.begin()+i);
881 // If we found some loop invariants, fold them into the recurrence.
882 if (!LIOps.empty()) {
883 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
884 LIOps.push_back(AddRec->getStart());
886 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
887 AddRecOps[0] = getAddExpr(LIOps);
889 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
890 // If all of the other operands were loop invariant, we are done.
891 if (Ops.size() == 1) return NewRec;
893 // Otherwise, add the folded AddRec by the non-liv parts.
894 for (unsigned i = 0;; ++i)
895 if (Ops[i] == AddRec) {
899 return getAddExpr(Ops);
902 // Okay, if there weren't any loop invariants to be folded, check to see if
903 // there are multiple AddRec's with the same loop induction variable being
904 // added together. If so, we can fold them.
905 for (unsigned OtherIdx = Idx+1;
906 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
907 if (OtherIdx != Idx) {
908 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
909 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
910 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
911 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
912 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
913 if (i >= NewOps.size()) {
914 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
915 OtherAddRec->op_end());
918 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
920 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
922 if (Ops.size() == 2) return NewAddRec;
924 Ops.erase(Ops.begin()+Idx);
925 Ops.erase(Ops.begin()+OtherIdx-1);
926 Ops.push_back(NewAddRec);
927 return getAddExpr(Ops);
931 // Otherwise couldn't fold anything into this recurrence. Move onto the
935 // Okay, it looks like we really DO need an add expr. Check to see if we
936 // already have one, otherwise create a new one.
937 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
938 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
940 if (Result == 0) Result = new SCEVAddExpr(Ops);
945 SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
946 assert(!Ops.empty() && "Cannot get empty mul!");
948 // Sort by complexity, this groups all similar expression types together.
949 GroupByComplexity(Ops);
951 // If there are any constants, fold them together.
953 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
955 // C1*(C2+V) -> C1*C2 + C1*V
957 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
958 if (Add->getNumOperands() == 2 &&
959 isa<SCEVConstant>(Add->getOperand(0)))
960 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
961 getMulExpr(LHSC, Add->getOperand(1)));
965 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
966 // We found two constants, fold them together!
967 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
968 RHSC->getValue()->getValue());
969 Ops[0] = getConstant(Fold);
970 Ops.erase(Ops.begin()+1); // Erase the folded element
971 if (Ops.size() == 1) return Ops[0];
972 LHSC = cast<SCEVConstant>(Ops[0]);
975 // If we are left with a constant one being multiplied, strip it off.
976 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
977 Ops.erase(Ops.begin());
979 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
980 // If we have a multiply of zero, it will always be zero.
985 // Skip over the add expression until we get to a multiply.
986 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
992 // If there are mul operands inline them all into this expression.
993 if (Idx < Ops.size()) {
994 bool DeletedMul = false;
995 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
996 // If we have an mul, expand the mul operands onto the end of the operands
998 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
999 Ops.erase(Ops.begin()+Idx);
1003 // If we deleted at least one mul, we added operands to the end of the list,
1004 // and they are not necessarily sorted. Recurse to resort and resimplify
1005 // any operands we just aquired.
1007 return getMulExpr(Ops);
1010 // If there are any add recurrences in the operands list, see if any other
1011 // added values are loop invariant. If so, we can fold them into the
1013 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1016 // Scan over all recurrences, trying to fold loop invariants into them.
1017 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1018 // Scan all of the other operands to this mul and add them to the vector if
1019 // they are loop invariant w.r.t. the recurrence.
1020 std::vector<SCEVHandle> LIOps;
1021 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1022 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1023 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1024 LIOps.push_back(Ops[i]);
1025 Ops.erase(Ops.begin()+i);
1029 // If we found some loop invariants, fold them into the recurrence.
1030 if (!LIOps.empty()) {
1031 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
1032 std::vector<SCEVHandle> NewOps;
1033 NewOps.reserve(AddRec->getNumOperands());
1034 if (LIOps.size() == 1) {
1035 SCEV *Scale = LIOps[0];
1036 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1037 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1039 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1040 std::vector<SCEVHandle> MulOps(LIOps);
1041 MulOps.push_back(AddRec->getOperand(i));
1042 NewOps.push_back(getMulExpr(MulOps));
1046 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
1048 // If all of the other operands were loop invariant, we are done.
1049 if (Ops.size() == 1) return NewRec;
1051 // Otherwise, multiply the folded AddRec by the non-liv parts.
1052 for (unsigned i = 0;; ++i)
1053 if (Ops[i] == AddRec) {
1057 return getMulExpr(Ops);
1060 // Okay, if there weren't any loop invariants to be folded, check to see if
1061 // there are multiple AddRec's with the same loop induction variable being
1062 // multiplied together. If so, we can fold them.
1063 for (unsigned OtherIdx = Idx+1;
1064 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1065 if (OtherIdx != Idx) {
1066 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1067 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1068 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1069 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1070 SCEVHandle NewStart = getMulExpr(F->getStart(),
1072 SCEVHandle B = F->getStepRecurrence(*this);
1073 SCEVHandle D = G->getStepRecurrence(*this);
1074 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1077 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1079 if (Ops.size() == 2) return NewAddRec;
1081 Ops.erase(Ops.begin()+Idx);
1082 Ops.erase(Ops.begin()+OtherIdx-1);
1083 Ops.push_back(NewAddRec);
1084 return getMulExpr(Ops);
1088 // Otherwise couldn't fold anything into this recurrence. Move onto the
1092 // Okay, it looks like we really DO need an mul expr. Check to see if we
1093 // already have one, otherwise create a new one.
1094 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1095 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1098 Result = new SCEVMulExpr(Ops);
1102 SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1103 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1104 if (RHSC->getValue()->equalsInt(1))
1105 return LHS; // X udiv 1 --> x
1107 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1108 Constant *LHSCV = LHSC->getValue();
1109 Constant *RHSCV = RHSC->getValue();
1110 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
1114 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1116 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1117 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
1122 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1123 /// specified loop. Simplify the expression as much as possible.
1124 SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
1125 const SCEVHandle &Step, const Loop *L) {
1126 std::vector<SCEVHandle> Operands;
1127 Operands.push_back(Start);
1128 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1129 if (StepChrec->getLoop() == L) {
1130 Operands.insert(Operands.end(), StepChrec->op_begin(),
1131 StepChrec->op_end());
1132 return getAddRecExpr(Operands, L);
1135 Operands.push_back(Step);
1136 return getAddRecExpr(Operands, L);
1139 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1140 /// specified loop. Simplify the expression as much as possible.
1141 SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
1143 if (Operands.size() == 1) return Operands[0];
1145 if (Operands.back()->isZero()) {
1146 Operands.pop_back();
1147 return getAddRecExpr(Operands, L); // { X,+,0 } --> X
1150 SCEVAddRecExpr *&Result =
1151 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1153 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1157 SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1158 const SCEVHandle &RHS) {
1159 std::vector<SCEVHandle> Ops;
1162 return getSMaxExpr(Ops);
1165 SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1166 assert(!Ops.empty() && "Cannot get empty smax!");
1167 if (Ops.size() == 1) return Ops[0];
1169 // Sort by complexity, this groups all similar expression types together.
1170 GroupByComplexity(Ops);
1172 // If there are any constants, fold them together.
1174 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1176 assert(Idx < Ops.size());
1177 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1178 // We found two constants, fold them together!
1179 ConstantInt *Fold = ConstantInt::get(
1180 APIntOps::smax(LHSC->getValue()->getValue(),
1181 RHSC->getValue()->getValue()));
1182 Ops[0] = getConstant(Fold);
1183 Ops.erase(Ops.begin()+1); // Erase the folded element
1184 if (Ops.size() == 1) return Ops[0];
1185 LHSC = cast<SCEVConstant>(Ops[0]);
1188 // If we are left with a constant -inf, strip it off.
1189 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1190 Ops.erase(Ops.begin());
1195 if (Ops.size() == 1) return Ops[0];
1197 // Find the first SMax
1198 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1201 // Check to see if one of the operands is an SMax. If so, expand its operands
1202 // onto our operand list, and recurse to simplify.
1203 if (Idx < Ops.size()) {
1204 bool DeletedSMax = false;
1205 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1206 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1207 Ops.erase(Ops.begin()+Idx);
1212 return getSMaxExpr(Ops);
1215 // Okay, check to see if the same value occurs in the operand list twice. If
1216 // so, delete one. Since we sorted the list, these values are required to
1218 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1219 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1220 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1224 if (Ops.size() == 1) return Ops[0];
1226 assert(!Ops.empty() && "Reduced smax down to nothing!");
1228 // Okay, it looks like we really DO need an smax expr. Check to see if we
1229 // already have one, otherwise create a new one.
1230 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1231 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1233 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1237 SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1238 const SCEVHandle &RHS) {
1239 std::vector<SCEVHandle> Ops;
1242 return getUMaxExpr(Ops);
1245 SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1246 assert(!Ops.empty() && "Cannot get empty umax!");
1247 if (Ops.size() == 1) return Ops[0];
1249 // Sort by complexity, this groups all similar expression types together.
1250 GroupByComplexity(Ops);
1252 // If there are any constants, fold them together.
1254 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1256 assert(Idx < Ops.size());
1257 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1258 // We found two constants, fold them together!
1259 ConstantInt *Fold = ConstantInt::get(
1260 APIntOps::umax(LHSC->getValue()->getValue(),
1261 RHSC->getValue()->getValue()));
1262 Ops[0] = getConstant(Fold);
1263 Ops.erase(Ops.begin()+1); // Erase the folded element
1264 if (Ops.size() == 1) return Ops[0];
1265 LHSC = cast<SCEVConstant>(Ops[0]);
1268 // If we are left with a constant zero, strip it off.
1269 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1270 Ops.erase(Ops.begin());
1275 if (Ops.size() == 1) return Ops[0];
1277 // Find the first UMax
1278 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1281 // Check to see if one of the operands is a UMax. If so, expand its operands
1282 // onto our operand list, and recurse to simplify.
1283 if (Idx < Ops.size()) {
1284 bool DeletedUMax = false;
1285 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1286 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1287 Ops.erase(Ops.begin()+Idx);
1292 return getUMaxExpr(Ops);
1295 // Okay, check to see if the same value occurs in the operand list twice. If
1296 // so, delete one. Since we sorted the list, these values are required to
1298 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1299 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1300 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1304 if (Ops.size() == 1) return Ops[0];
1306 assert(!Ops.empty() && "Reduced umax down to nothing!");
1308 // Okay, it looks like we really DO need a umax expr. Check to see if we
1309 // already have one, otherwise create a new one.
1310 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1311 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1313 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1317 SCEVHandle ScalarEvolution::getUnknown(Value *V) {
1318 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1319 return getConstant(CI);
1320 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1321 if (Result == 0) Result = new SCEVUnknown(V);
1326 //===----------------------------------------------------------------------===//
1327 // ScalarEvolutionsImpl Definition and Implementation
1328 //===----------------------------------------------------------------------===//
1330 /// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1334 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
1335 /// SE - A reference to the public ScalarEvolution object.
1336 ScalarEvolution &SE;
1338 /// F - The function we are analyzing.
1342 /// LI - The loop information for the function we are currently analyzing.
1346 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1348 SCEVHandle UnknownValue;
1350 /// Scalars - This is a cache of the scalars we have analyzed so far.
1352 std::map<Value*, SCEVHandle> Scalars;
1354 /// IterationCounts - Cache the iteration count of the loops for this
1355 /// function as they are computed.
1356 std::map<const Loop*, SCEVHandle> IterationCounts;
1358 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1359 /// the PHI instructions that we attempt to compute constant evolutions for.
1360 /// This allows us to avoid potentially expensive recomputation of these
1361 /// properties. An instruction maps to null if we are unable to compute its
1363 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
1366 ScalarEvolutionsImpl(ScalarEvolution &se, Function &f, LoopInfo &li)
1367 : SE(se), F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1369 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1370 /// expression and create a new one.
1371 SCEVHandle getSCEV(Value *V);
1373 /// hasSCEV - Return true if the SCEV for this value has already been
1375 bool hasSCEV(Value *V) const {
1376 return Scalars.count(V);
1379 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1380 /// the specified value.
1381 void setSCEV(Value *V, const SCEVHandle &H) {
1382 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1383 assert(isNew && "This entry already existed!");
1387 /// getSCEVAtScope - Compute the value of the specified expression within
1388 /// the indicated loop (which may be null to indicate in no loop). If the
1389 /// expression cannot be evaluated, return UnknownValue itself.
1390 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1393 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1394 /// an analyzable loop-invariant iteration count.
1395 bool hasLoopInvariantIterationCount(const Loop *L);
1397 /// getIterationCount - If the specified loop has a predictable iteration
1398 /// count, return it. Note that it is not valid to call this method on a
1399 /// loop without a loop-invariant iteration count.
1400 SCEVHandle getIterationCount(const Loop *L);
1402 /// deleteValueFromRecords - This method should be called by the
1403 /// client before it removes a value from the program, to make sure
1404 /// that no dangling references are left around.
1405 void deleteValueFromRecords(Value *V);
1408 /// createSCEV - We know that there is no SCEV for the specified value.
1409 /// Analyze the expression.
1410 SCEVHandle createSCEV(Value *V);
1412 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1414 SCEVHandle createNodeForPHI(PHINode *PN);
1416 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1417 /// for the specified instruction and replaces any references to the
1418 /// symbolic value SymName with the specified value. This is used during
1420 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1421 const SCEVHandle &SymName,
1422 const SCEVHandle &NewVal);
1424 /// ComputeIterationCount - Compute the number of times the specified loop
1426 SCEVHandle ComputeIterationCount(const Loop *L);
1428 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1429 /// 'icmp op load X, cst', try to see if we can compute the trip count.
1430 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1433 ICmpInst::Predicate p);
1435 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1436 /// constant number of times (the condition evolves only from constants),
1437 /// try to evaluate a few iterations of the loop until we get the exit
1438 /// condition gets a value of ExitWhen (true or false). If we cannot
1439 /// evaluate the trip count of the loop, return UnknownValue.
1440 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1443 /// HowFarToZero - Return the number of times a backedge comparing the
1444 /// specified value to zero will execute. If not computable, return
1446 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1448 /// HowFarToNonZero - Return the number of times a backedge checking the
1449 /// specified value for nonzero will execute. If not computable, return
1451 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
1453 /// HowManyLessThans - Return the number of times a backedge containing the
1454 /// specified less-than comparison will execute. If not computable, return
1455 /// UnknownValue. isSigned specifies whether the less-than is signed.
1456 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
1459 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1460 /// in the header of its containing loop, we know the loop executes a
1461 /// constant number of times, and the PHI node is just a recurrence
1462 /// involving constants, fold it.
1463 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its,
1468 //===----------------------------------------------------------------------===//
1469 // Basic SCEV Analysis and PHI Idiom Recognition Code
1472 /// deleteValueFromRecords - This method should be called by the
1473 /// client before it removes an instruction from the program, to make sure
1474 /// that no dangling references are left around.
1475 void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) {
1476 SmallVector<Value *, 16> Worklist;
1478 if (Scalars.erase(V)) {
1479 if (PHINode *PN = dyn_cast<PHINode>(V))
1480 ConstantEvolutionLoopExitValue.erase(PN);
1481 Worklist.push_back(V);
1484 while (!Worklist.empty()) {
1485 Value *VV = Worklist.back();
1486 Worklist.pop_back();
1488 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
1490 Instruction *Inst = cast<Instruction>(*UI);
1491 if (Scalars.erase(Inst)) {
1492 if (PHINode *PN = dyn_cast<PHINode>(VV))
1493 ConstantEvolutionLoopExitValue.erase(PN);
1494 Worklist.push_back(Inst);
1501 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1502 /// expression and create a new one.
1503 SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1504 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1506 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1507 if (I != Scalars.end()) return I->second;
1508 SCEVHandle S = createSCEV(V);
1509 Scalars.insert(std::make_pair(V, S));
1513 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1514 /// the specified instruction and replaces any references to the symbolic value
1515 /// SymName with the specified value. This is used during PHI resolution.
1516 void ScalarEvolutionsImpl::
1517 ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1518 const SCEVHandle &NewVal) {
1519 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1520 if (SI == Scalars.end()) return;
1523 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, SE);
1524 if (NV == SI->second) return; // No change.
1526 SI->second = NV; // Update the scalars map!
1528 // Any instruction values that use this instruction might also need to be
1530 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1532 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1535 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1536 /// a loop header, making it a potential recurrence, or it doesn't.
1538 SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1539 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1540 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1541 if (L->getHeader() == PN->getParent()) {
1542 // If it lives in the loop header, it has two incoming values, one
1543 // from outside the loop, and one from inside.
1544 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1545 unsigned BackEdge = IncomingEdge^1;
1547 // While we are analyzing this PHI node, handle its value symbolically.
1548 SCEVHandle SymbolicName = SE.getUnknown(PN);
1549 assert(Scalars.find(PN) == Scalars.end() &&
1550 "PHI node already processed?");
1551 Scalars.insert(std::make_pair(PN, SymbolicName));
1553 // Using this symbolic name for the PHI, analyze the value coming around
1555 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1557 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1558 // has a special value for the first iteration of the loop.
1560 // If the value coming around the backedge is an add with the symbolic
1561 // value we just inserted, then we found a simple induction variable!
1562 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1563 // If there is a single occurrence of the symbolic value, replace it
1564 // with a recurrence.
1565 unsigned FoundIndex = Add->getNumOperands();
1566 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1567 if (Add->getOperand(i) == SymbolicName)
1568 if (FoundIndex == e) {
1573 if (FoundIndex != Add->getNumOperands()) {
1574 // Create an add with everything but the specified operand.
1575 std::vector<SCEVHandle> Ops;
1576 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1577 if (i != FoundIndex)
1578 Ops.push_back(Add->getOperand(i));
1579 SCEVHandle Accum = SE.getAddExpr(Ops);
1581 // This is not a valid addrec if the step amount is varying each
1582 // loop iteration, but is not itself an addrec in this loop.
1583 if (Accum->isLoopInvariant(L) ||
1584 (isa<SCEVAddRecExpr>(Accum) &&
1585 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1586 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1587 SCEVHandle PHISCEV = SE.getAddRecExpr(StartVal, Accum, L);
1589 // Okay, for the entire analysis of this edge we assumed the PHI
1590 // to be symbolic. We now need to go back and update all of the
1591 // entries for the scalars that use the PHI (except for the PHI
1592 // itself) to use the new analyzed value instead of the "symbolic"
1594 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1598 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1599 // Otherwise, this could be a loop like this:
1600 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1601 // In this case, j = {1,+,1} and BEValue is j.
1602 // Because the other in-value of i (0) fits the evolution of BEValue
1603 // i really is an addrec evolution.
1604 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1605 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1607 // If StartVal = j.start - j.stride, we can use StartVal as the
1608 // initial step of the addrec evolution.
1609 if (StartVal == SE.getMinusSCEV(AddRec->getOperand(0),
1610 AddRec->getOperand(1))) {
1611 SCEVHandle PHISCEV =
1612 SE.getAddRecExpr(StartVal, AddRec->getOperand(1), L);
1614 // Okay, for the entire analysis of this edge we assumed the PHI
1615 // to be symbolic. We now need to go back and update all of the
1616 // entries for the scalars that use the PHI (except for the PHI
1617 // itself) to use the new analyzed value instead of the "symbolic"
1619 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1625 return SymbolicName;
1628 // If it's not a loop phi, we can't handle it yet.
1629 return SE.getUnknown(PN);
1632 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1633 /// guaranteed to end in (at every loop iteration). It is, at the same time,
1634 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1635 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
1636 static uint32_t GetMinTrailingZeros(SCEVHandle S) {
1637 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
1638 return C->getValue()->getValue().countTrailingZeros();
1640 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
1641 return std::min(GetMinTrailingZeros(T->getOperand()), T->getBitWidth());
1643 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
1644 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1645 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1648 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
1649 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1650 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1653 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
1654 // The result is the min of all operands results.
1655 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1656 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1657 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1661 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
1662 // The result is the sum of all operands results.
1663 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
1664 uint32_t BitWidth = M->getBitWidth();
1665 for (unsigned i = 1, e = M->getNumOperands();
1666 SumOpRes != BitWidth && i != e; ++i)
1667 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
1672 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
1673 // The result is the min of all operands results.
1674 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1675 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1676 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1680 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1681 // The result is the min of all operands results.
1682 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1683 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1684 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1688 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1689 // The result is the min of all operands results.
1690 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1691 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1692 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1696 // SCEVUDivExpr, SCEVUnknown
1700 /// createSCEV - We know that there is no SCEV for the specified value.
1701 /// Analyze the expression.
1703 SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1704 if (!isa<IntegerType>(V->getType()))
1705 return SE.getUnknown(V);
1707 if (Instruction *I = dyn_cast<Instruction>(V)) {
1708 switch (I->getOpcode()) {
1709 case Instruction::Add:
1710 return SE.getAddExpr(getSCEV(I->getOperand(0)),
1711 getSCEV(I->getOperand(1)));
1712 case Instruction::Mul:
1713 return SE.getMulExpr(getSCEV(I->getOperand(0)),
1714 getSCEV(I->getOperand(1)));
1715 case Instruction::UDiv:
1716 return SE.getUDivExpr(getSCEV(I->getOperand(0)),
1717 getSCEV(I->getOperand(1)));
1718 case Instruction::Sub:
1719 return SE.getMinusSCEV(getSCEV(I->getOperand(0)),
1720 getSCEV(I->getOperand(1)));
1721 case Instruction::Or:
1722 // If the RHS of the Or is a constant, we may have something like:
1723 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1724 // optimizations will transparently handle this case.
1726 // In order for this transformation to be safe, the LHS must be of the
1727 // form X*(2^n) and the Or constant must be less than 2^n.
1728 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1729 SCEVHandle LHS = getSCEV(I->getOperand(0));
1730 const APInt &CIVal = CI->getValue();
1731 if (GetMinTrailingZeros(LHS) >=
1732 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
1733 return SE.getAddExpr(LHS, getSCEV(I->getOperand(1)));
1736 case Instruction::Xor:
1737 // If the RHS of the xor is a signbit, then this is just an add.
1738 // Instcombine turns add of signbit into xor as a strength reduction step.
1739 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1740 if (CI->getValue().isSignBit())
1741 return SE.getAddExpr(getSCEV(I->getOperand(0)),
1742 getSCEV(I->getOperand(1)));
1743 else if (CI->isAllOnesValue())
1744 return SE.getNotSCEV(getSCEV(I->getOperand(0)));
1748 case Instruction::Shl:
1749 // Turn shift left of a constant amount into a multiply.
1750 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1751 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1752 Constant *X = ConstantInt::get(
1753 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1754 return SE.getMulExpr(getSCEV(I->getOperand(0)), getSCEV(X));
1758 case Instruction::Trunc:
1759 return SE.getTruncateExpr(getSCEV(I->getOperand(0)), I->getType());
1761 case Instruction::ZExt:
1762 return SE.getZeroExtendExpr(getSCEV(I->getOperand(0)), I->getType());
1764 case Instruction::SExt:
1765 return SE.getSignExtendExpr(getSCEV(I->getOperand(0)), I->getType());
1767 case Instruction::BitCast:
1768 // BitCasts are no-op casts so we just eliminate the cast.
1769 if (I->getType()->isInteger() &&
1770 I->getOperand(0)->getType()->isInteger())
1771 return getSCEV(I->getOperand(0));
1774 case Instruction::PHI:
1775 return createNodeForPHI(cast<PHINode>(I));
1777 case Instruction::Select:
1778 // This could be a smax or umax that was lowered earlier.
1779 // Try to recover it.
1780 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I->getOperand(0))) {
1781 Value *LHS = ICI->getOperand(0);
1782 Value *RHS = ICI->getOperand(1);
1783 switch (ICI->getPredicate()) {
1784 case ICmpInst::ICMP_SLT:
1785 case ICmpInst::ICMP_SLE:
1786 std::swap(LHS, RHS);
1788 case ICmpInst::ICMP_SGT:
1789 case ICmpInst::ICMP_SGE:
1790 if (LHS == I->getOperand(1) && RHS == I->getOperand(2))
1791 return SE.getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
1792 else if (LHS == I->getOperand(2) && RHS == I->getOperand(1))
1793 // -smax(-x, -y) == smin(x, y).
1794 return SE.getNegativeSCEV(SE.getSMaxExpr(
1795 SE.getNegativeSCEV(getSCEV(LHS)),
1796 SE.getNegativeSCEV(getSCEV(RHS))));
1798 case ICmpInst::ICMP_ULT:
1799 case ICmpInst::ICMP_ULE:
1800 std::swap(LHS, RHS);
1802 case ICmpInst::ICMP_UGT:
1803 case ICmpInst::ICMP_UGE:
1804 if (LHS == I->getOperand(1) && RHS == I->getOperand(2))
1805 return SE.getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
1806 else if (LHS == I->getOperand(2) && RHS == I->getOperand(1))
1807 // ~umax(~x, ~y) == umin(x, y)
1808 return SE.getNotSCEV(SE.getUMaxExpr(SE.getNotSCEV(getSCEV(LHS)),
1809 SE.getNotSCEV(getSCEV(RHS))));
1816 default: // We cannot analyze this expression.
1821 return SE.getUnknown(V);
1826 //===----------------------------------------------------------------------===//
1827 // Iteration Count Computation Code
1830 /// getIterationCount - If the specified loop has a predictable iteration
1831 /// count, return it. Note that it is not valid to call this method on a
1832 /// loop without a loop-invariant iteration count.
1833 SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1834 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1835 if (I == IterationCounts.end()) {
1836 SCEVHandle ItCount = ComputeIterationCount(L);
1837 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1838 if (ItCount != UnknownValue) {
1839 assert(ItCount->isLoopInvariant(L) &&
1840 "Computed trip count isn't loop invariant for loop!");
1841 ++NumTripCountsComputed;
1842 } else if (isa<PHINode>(L->getHeader()->begin())) {
1843 // Only count loops that have phi nodes as not being computable.
1844 ++NumTripCountsNotComputed;
1850 /// ComputeIterationCount - Compute the number of times the specified loop
1852 SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1853 // If the loop has a non-one exit block count, we can't analyze it.
1854 SmallVector<BasicBlock*, 8> ExitBlocks;
1855 L->getExitBlocks(ExitBlocks);
1856 if (ExitBlocks.size() != 1) return UnknownValue;
1858 // Okay, there is one exit block. Try to find the condition that causes the
1859 // loop to be exited.
1860 BasicBlock *ExitBlock = ExitBlocks[0];
1862 BasicBlock *ExitingBlock = 0;
1863 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1865 if (L->contains(*PI)) {
1866 if (ExitingBlock == 0)
1869 return UnknownValue; // More than one block exiting!
1871 assert(ExitingBlock && "No exits from loop, something is broken!");
1873 // Okay, we've computed the exiting block. See what condition causes us to
1876 // FIXME: we should be able to handle switch instructions (with a single exit)
1877 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1878 if (ExitBr == 0) return UnknownValue;
1879 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1881 // At this point, we know we have a conditional branch that determines whether
1882 // the loop is exited. However, we don't know if the branch is executed each
1883 // time through the loop. If not, then the execution count of the branch will
1884 // not be equal to the trip count of the loop.
1886 // Currently we check for this by checking to see if the Exit branch goes to
1887 // the loop header. If so, we know it will always execute the same number of
1888 // times as the loop. We also handle the case where the exit block *is* the
1889 // loop header. This is common for un-rotated loops. More extensive analysis
1890 // could be done to handle more cases here.
1891 if (ExitBr->getSuccessor(0) != L->getHeader() &&
1892 ExitBr->getSuccessor(1) != L->getHeader() &&
1893 ExitBr->getParent() != L->getHeader())
1894 return UnknownValue;
1896 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
1898 // If it's not an integer comparison then compute it the hard way.
1899 // Note that ICmpInst deals with pointer comparisons too so we must check
1900 // the type of the operand.
1901 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
1902 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1903 ExitBr->getSuccessor(0) == ExitBlock);
1905 // If the condition was exit on true, convert the condition to exit on false
1906 ICmpInst::Predicate Cond;
1907 if (ExitBr->getSuccessor(1) == ExitBlock)
1908 Cond = ExitCond->getPredicate();
1910 Cond = ExitCond->getInversePredicate();
1912 // Handle common loops like: for (X = "string"; *X; ++X)
1913 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1914 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1916 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1917 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1920 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1921 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1923 // Try to evaluate any dependencies out of the loop.
1924 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1925 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1926 Tmp = getSCEVAtScope(RHS, L);
1927 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1929 // At this point, we would like to compute how many iterations of the
1930 // loop the predicate will return true for these inputs.
1931 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1932 // If there is a constant, force it into the RHS.
1933 std::swap(LHS, RHS);
1934 Cond = ICmpInst::getSwappedPredicate(Cond);
1937 // FIXME: think about handling pointer comparisons! i.e.:
1938 // while (P != P+100) ++P;
1940 // If we have a comparison of a chrec against a constant, try to use value
1941 // ranges to answer this query.
1942 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1943 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1944 if (AddRec->getLoop() == L) {
1945 // Form the comparison range using the constant of the correct type so
1946 // that the ConstantRange class knows to do a signed or unsigned
1948 ConstantInt *CompVal = RHSC->getValue();
1949 const Type *RealTy = ExitCond->getOperand(0)->getType();
1950 CompVal = dyn_cast<ConstantInt>(
1951 ConstantExpr::getBitCast(CompVal, RealTy));
1953 // Form the constant range.
1954 ConstantRange CompRange(
1955 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
1957 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE);
1958 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1963 case ICmpInst::ICMP_NE: { // while (X != Y)
1964 // Convert to: while (X-Y != 0)
1965 SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
1966 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1969 case ICmpInst::ICMP_EQ: {
1970 // Convert to: while (X-Y == 0) // while (X == Y)
1971 SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L);
1972 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1975 case ICmpInst::ICMP_SLT: {
1976 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
1977 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1980 case ICmpInst::ICMP_SGT: {
1981 SCEVHandle TC = HowManyLessThans(SE.getNegativeSCEV(LHS),
1982 SE.getNegativeSCEV(RHS), L, true);
1983 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1986 case ICmpInst::ICMP_ULT: {
1987 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
1988 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1991 case ICmpInst::ICMP_UGT: {
1992 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
1993 SE.getNotSCEV(RHS), L, false);
1994 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1999 cerr << "ComputeIterationCount ";
2000 if (ExitCond->getOperand(0)->getType()->isUnsigned())
2001 cerr << "[unsigned] ";
2003 << Instruction::getOpcodeName(Instruction::ICmp)
2004 << " " << *RHS << "\n";
2008 return ComputeIterationCountExhaustively(L, ExitCond,
2009 ExitBr->getSuccessor(0) == ExitBlock);
2012 static ConstantInt *
2013 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2014 ScalarEvolution &SE) {
2015 SCEVHandle InVal = SE.getConstant(C);
2016 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
2017 assert(isa<SCEVConstant>(Val) &&
2018 "Evaluation of SCEV at constant didn't fold correctly?");
2019 return cast<SCEVConstant>(Val)->getValue();
2022 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
2023 /// and a GEP expression (missing the pointer index) indexing into it, return
2024 /// the addressed element of the initializer or null if the index expression is
2027 GetAddressedElementFromGlobal(GlobalVariable *GV,
2028 const std::vector<ConstantInt*> &Indices) {
2029 Constant *Init = GV->getInitializer();
2030 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2031 uint64_t Idx = Indices[i]->getZExtValue();
2032 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2033 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2034 Init = cast<Constant>(CS->getOperand(Idx));
2035 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2036 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2037 Init = cast<Constant>(CA->getOperand(Idx));
2038 } else if (isa<ConstantAggregateZero>(Init)) {
2039 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2040 assert(Idx < STy->getNumElements() && "Bad struct index!");
2041 Init = Constant::getNullValue(STy->getElementType(Idx));
2042 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2043 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2044 Init = Constant::getNullValue(ATy->getElementType());
2046 assert(0 && "Unknown constant aggregate type!");
2050 return 0; // Unknown initializer type
2056 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
2057 /// 'icmp op load X, cst', try to see if we can compute the trip count.
2058 SCEVHandle ScalarEvolutionsImpl::
2059 ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
2061 ICmpInst::Predicate predicate) {
2062 if (LI->isVolatile()) return UnknownValue;
2064 // Check to see if the loaded pointer is a getelementptr of a global.
2065 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2066 if (!GEP) return UnknownValue;
2068 // Make sure that it is really a constant global we are gepping, with an
2069 // initializer, and make sure the first IDX is really 0.
2070 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2071 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2072 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2073 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2074 return UnknownValue;
2076 // Okay, we allow one non-constant index into the GEP instruction.
2078 std::vector<ConstantInt*> Indexes;
2079 unsigned VarIdxNum = 0;
2080 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2081 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2082 Indexes.push_back(CI);
2083 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2084 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2085 VarIdx = GEP->getOperand(i);
2087 Indexes.push_back(0);
2090 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2091 // Check to see if X is a loop variant variable value now.
2092 SCEVHandle Idx = getSCEV(VarIdx);
2093 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2094 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2096 // We can only recognize very limited forms of loop index expressions, in
2097 // particular, only affine AddRec's like {C1,+,C2}.
2098 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2099 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2100 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2101 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2102 return UnknownValue;
2104 unsigned MaxSteps = MaxBruteForceIterations;
2105 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2106 ConstantInt *ItCst =
2107 ConstantInt::get(IdxExpr->getType(), IterationNum);
2108 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE);
2110 // Form the GEP offset.
2111 Indexes[VarIdxNum] = Val;
2113 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2114 if (Result == 0) break; // Cannot compute!
2116 // Evaluate the condition for this iteration.
2117 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2118 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2119 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2121 cerr << "\n***\n*** Computed loop count " << *ItCst
2122 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2125 ++NumArrayLenItCounts;
2126 return SE.getConstant(ItCst); // Found terminating iteration!
2129 return UnknownValue;
2133 /// CanConstantFold - Return true if we can constant fold an instruction of the
2134 /// specified type, assuming that all operands were constants.
2135 static bool CanConstantFold(const Instruction *I) {
2136 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2137 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2140 if (const CallInst *CI = dyn_cast<CallInst>(I))
2141 if (const Function *F = CI->getCalledFunction())
2142 return canConstantFoldCallTo(F);
2146 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2147 /// in the loop that V is derived from. We allow arbitrary operations along the
2148 /// way, but the operands of an operation must either be constants or a value
2149 /// derived from a constant PHI. If this expression does not fit with these
2150 /// constraints, return null.
2151 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2152 // If this is not an instruction, or if this is an instruction outside of the
2153 // loop, it can't be derived from a loop PHI.
2154 Instruction *I = dyn_cast<Instruction>(V);
2155 if (I == 0 || !L->contains(I->getParent())) return 0;
2157 if (PHINode *PN = dyn_cast<PHINode>(I)) {
2158 if (L->getHeader() == I->getParent())
2161 // We don't currently keep track of the control flow needed to evaluate
2162 // PHIs, so we cannot handle PHIs inside of loops.
2166 // If we won't be able to constant fold this expression even if the operands
2167 // are constants, return early.
2168 if (!CanConstantFold(I)) return 0;
2170 // Otherwise, we can evaluate this instruction if all of its operands are
2171 // constant or derived from a PHI node themselves.
2173 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2174 if (!(isa<Constant>(I->getOperand(Op)) ||
2175 isa<GlobalValue>(I->getOperand(Op)))) {
2176 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2177 if (P == 0) return 0; // Not evolving from PHI
2181 return 0; // Evolving from multiple different PHIs.
2184 // This is a expression evolving from a constant PHI!
2188 /// EvaluateExpression - Given an expression that passes the
2189 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2190 /// in the loop has the value PHIVal. If we can't fold this expression for some
2191 /// reason, return null.
2192 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2193 if (isa<PHINode>(V)) return PHIVal;
2194 if (Constant *C = dyn_cast<Constant>(V)) return C;
2195 Instruction *I = cast<Instruction>(V);
2197 std::vector<Constant*> Operands;
2198 Operands.resize(I->getNumOperands());
2200 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2201 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2202 if (Operands[i] == 0) return 0;
2205 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2206 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2207 &Operands[0], Operands.size());
2209 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2210 &Operands[0], Operands.size());
2213 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2214 /// in the header of its containing loop, we know the loop executes a
2215 /// constant number of times, and the PHI node is just a recurrence
2216 /// involving constants, fold it.
2217 Constant *ScalarEvolutionsImpl::
2218 getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, const Loop *L){
2219 std::map<PHINode*, Constant*>::iterator I =
2220 ConstantEvolutionLoopExitValue.find(PN);
2221 if (I != ConstantEvolutionLoopExitValue.end())
2224 if (Its.ugt(APInt(Its.getBitWidth(),MaxBruteForceIterations)))
2225 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2227 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2229 // Since the loop is canonicalized, the PHI node must have two entries. One
2230 // entry must be a constant (coming in from outside of the loop), and the
2231 // second must be derived from the same PHI.
2232 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2233 Constant *StartCST =
2234 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2236 return RetVal = 0; // Must be a constant.
2238 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2239 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2241 return RetVal = 0; // Not derived from same PHI.
2243 // Execute the loop symbolically to determine the exit value.
2244 if (Its.getActiveBits() >= 32)
2245 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2247 unsigned NumIterations = Its.getZExtValue(); // must be in range
2248 unsigned IterationNum = 0;
2249 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2250 if (IterationNum == NumIterations)
2251 return RetVal = PHIVal; // Got exit value!
2253 // Compute the value of the PHI node for the next iteration.
2254 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2255 if (NextPHI == PHIVal)
2256 return RetVal = NextPHI; // Stopped evolving!
2258 return 0; // Couldn't evaluate!
2263 /// ComputeIterationCountExhaustively - If the trip is known to execute a
2264 /// constant number of times (the condition evolves only from constants),
2265 /// try to evaluate a few iterations of the loop until we get the exit
2266 /// condition gets a value of ExitWhen (true or false). If we cannot
2267 /// evaluate the trip count of the loop, return UnknownValue.
2268 SCEVHandle ScalarEvolutionsImpl::
2269 ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
2270 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2271 if (PN == 0) return UnknownValue;
2273 // Since the loop is canonicalized, the PHI node must have two entries. One
2274 // entry must be a constant (coming in from outside of the loop), and the
2275 // second must be derived from the same PHI.
2276 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2277 Constant *StartCST =
2278 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2279 if (StartCST == 0) return UnknownValue; // Must be a constant.
2281 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2282 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2283 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2285 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2286 // the loop symbolically to determine when the condition gets a value of
2288 unsigned IterationNum = 0;
2289 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2290 for (Constant *PHIVal = StartCST;
2291 IterationNum != MaxIterations; ++IterationNum) {
2292 ConstantInt *CondVal =
2293 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2295 // Couldn't symbolically evaluate.
2296 if (!CondVal) return UnknownValue;
2298 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2299 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2300 ++NumBruteForceTripCountsComputed;
2301 return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
2304 // Compute the value of the PHI node for the next iteration.
2305 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2306 if (NextPHI == 0 || NextPHI == PHIVal)
2307 return UnknownValue; // Couldn't evaluate or not making progress...
2311 // Too many iterations were needed to evaluate.
2312 return UnknownValue;
2315 /// getSCEVAtScope - Compute the value of the specified expression within the
2316 /// indicated loop (which may be null to indicate in no loop). If the
2317 /// expression cannot be evaluated, return UnknownValue.
2318 SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2319 // FIXME: this should be turned into a virtual method on SCEV!
2321 if (isa<SCEVConstant>(V)) return V;
2323 // If this instruction is evolved from a constant-evolving PHI, compute the
2324 // exit value from the loop without using SCEVs.
2325 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2326 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2327 const Loop *LI = this->LI[I->getParent()];
2328 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2329 if (PHINode *PN = dyn_cast<PHINode>(I))
2330 if (PN->getParent() == LI->getHeader()) {
2331 // Okay, there is no closed form solution for the PHI node. Check
2332 // to see if the loop that contains it has a known iteration count.
2333 // If so, we may be able to force computation of the exit value.
2334 SCEVHandle IterationCount = getIterationCount(LI);
2335 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
2336 // Okay, we know how many times the containing loop executes. If
2337 // this is a constant evolving PHI node, get the final value at
2338 // the specified iteration number.
2339 Constant *RV = getConstantEvolutionLoopExitValue(PN,
2340 ICC->getValue()->getValue(),
2342 if (RV) return SE.getUnknown(RV);
2346 // Okay, this is an expression that we cannot symbolically evaluate
2347 // into a SCEV. Check to see if it's possible to symbolically evaluate
2348 // the arguments into constants, and if so, try to constant propagate the
2349 // result. This is particularly useful for computing loop exit values.
2350 if (CanConstantFold(I)) {
2351 std::vector<Constant*> Operands;
2352 Operands.reserve(I->getNumOperands());
2353 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2354 Value *Op = I->getOperand(i);
2355 if (Constant *C = dyn_cast<Constant>(Op)) {
2356 Operands.push_back(C);
2358 // If any of the operands is non-constant and if they are
2359 // non-integer, don't even try to analyze them with scev techniques.
2360 if (!isa<IntegerType>(Op->getType()))
2363 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2364 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
2365 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2368 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2369 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
2370 Operands.push_back(ConstantExpr::getIntegerCast(C,
2382 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2383 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2384 &Operands[0], Operands.size());
2386 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2387 &Operands[0], Operands.size());
2388 return SE.getUnknown(C);
2392 // This is some other type of SCEVUnknown, just return it.
2396 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2397 // Avoid performing the look-up in the common case where the specified
2398 // expression has no loop-variant portions.
2399 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2400 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2401 if (OpAtScope != Comm->getOperand(i)) {
2402 if (OpAtScope == UnknownValue) return UnknownValue;
2403 // Okay, at least one of these operands is loop variant but might be
2404 // foldable. Build a new instance of the folded commutative expression.
2405 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2406 NewOps.push_back(OpAtScope);
2408 for (++i; i != e; ++i) {
2409 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2410 if (OpAtScope == UnknownValue) return UnknownValue;
2411 NewOps.push_back(OpAtScope);
2413 if (isa<SCEVAddExpr>(Comm))
2414 return SE.getAddExpr(NewOps);
2415 if (isa<SCEVMulExpr>(Comm))
2416 return SE.getMulExpr(NewOps);
2417 if (isa<SCEVSMaxExpr>(Comm))
2418 return SE.getSMaxExpr(NewOps);
2419 if (isa<SCEVUMaxExpr>(Comm))
2420 return SE.getUMaxExpr(NewOps);
2421 assert(0 && "Unknown commutative SCEV type!");
2424 // If we got here, all operands are loop invariant.
2428 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
2429 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
2430 if (LHS == UnknownValue) return LHS;
2431 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
2432 if (RHS == UnknownValue) return RHS;
2433 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2434 return Div; // must be loop invariant
2435 return SE.getUDivExpr(LHS, RHS);
2438 // If this is a loop recurrence for a loop that does not contain L, then we
2439 // are dealing with the final value computed by the loop.
2440 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2441 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2442 // To evaluate this recurrence, we need to know how many times the AddRec
2443 // loop iterates. Compute this now.
2444 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2445 if (IterationCount == UnknownValue) return UnknownValue;
2446 IterationCount = SE.getTruncateOrZeroExtend(IterationCount,
2449 // If the value is affine, simplify the expression evaluation to just
2450 // Start + Step*IterationCount.
2451 if (AddRec->isAffine())
2452 return SE.getAddExpr(AddRec->getStart(),
2453 SE.getMulExpr(IterationCount,
2454 AddRec->getOperand(1)));
2456 // Otherwise, evaluate it the hard way.
2457 return AddRec->evaluateAtIteration(IterationCount, SE);
2459 return UnknownValue;
2462 //assert(0 && "Unknown SCEV type!");
2463 return UnknownValue;
2467 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2468 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2469 /// might be the same) or two SCEVCouldNotCompute objects.
2471 static std::pair<SCEVHandle,SCEVHandle>
2472 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
2473 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2474 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2475 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2476 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2478 // We currently can only solve this if the coefficients are constants.
2479 if (!LC || !MC || !NC) {
2480 SCEV *CNC = new SCEVCouldNotCompute();
2481 return std::make_pair(CNC, CNC);
2484 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2485 const APInt &L = LC->getValue()->getValue();
2486 const APInt &M = MC->getValue()->getValue();
2487 const APInt &N = NC->getValue()->getValue();
2488 APInt Two(BitWidth, 2);
2489 APInt Four(BitWidth, 4);
2492 using namespace APIntOps;
2494 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2495 // The B coefficient is M-N/2
2499 // The A coefficient is N/2
2500 APInt A(N.sdiv(Two));
2502 // Compute the B^2-4ac term.
2505 SqrtTerm -= Four * (A * C);
2507 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2508 // integer value or else APInt::sqrt() will assert.
2509 APInt SqrtVal(SqrtTerm.sqrt());
2511 // Compute the two solutions for the quadratic formula.
2512 // The divisions must be performed as signed divisions.
2514 APInt TwoA( A << 1 );
2515 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2516 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2518 return std::make_pair(SE.getConstant(Solution1),
2519 SE.getConstant(Solution2));
2520 } // end APIntOps namespace
2523 /// HowFarToZero - Return the number of times a backedge comparing the specified
2524 /// value to zero will execute. If not computable, return UnknownValue
2525 SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2526 // If the value is a constant
2527 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2528 // If the value is already zero, the branch will execute zero times.
2529 if (C->getValue()->isZero()) return C;
2530 return UnknownValue; // Otherwise it will loop infinitely.
2533 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2534 if (!AddRec || AddRec->getLoop() != L)
2535 return UnknownValue;
2537 if (AddRec->isAffine()) {
2538 // If this is an affine expression the execution count of this branch is
2541 // (0 - Start/Step) iff Start % Step == 0
2543 // Get the initial value for the loop.
2544 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2545 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
2546 SCEVHandle Step = AddRec->getOperand(1);
2548 Step = getSCEVAtScope(Step, L->getParentLoop());
2550 // Figure out if Start % Step == 0.
2551 // FIXME: We should add DivExpr and RemExpr operations to our AST.
2552 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2553 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
2554 return SE.getNegativeSCEV(Start); // 0 - Start/1 == -Start
2555 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
2556 return Start; // 0 - Start/-1 == Start
2558 // Check to see if Start is divisible by SC with no remainder.
2559 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2560 ConstantInt *StartCC = StartC->getValue();
2561 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
2562 Constant *Rem = ConstantExpr::getURem(StartNegC, StepC->getValue());
2563 if (Rem->isNullValue()) {
2564 Constant *Result = ConstantExpr::getUDiv(StartNegC,StepC->getValue());
2565 return SE.getUnknown(Result);
2569 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2570 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2571 // the quadratic equation to solve it.
2572 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE);
2573 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2574 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2577 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2578 << " sol#2: " << *R2 << "\n";
2580 // Pick the smallest positive root value.
2581 if (ConstantInt *CB =
2582 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2583 R1->getValue(), R2->getValue()))) {
2584 if (CB->getZExtValue() == false)
2585 std::swap(R1, R2); // R1 is the minimum root now.
2587 // We can only use this value if the chrec ends up with an exact zero
2588 // value at this index. When solving for "X*X != 5", for example, we
2589 // should not accept a root of 2.
2590 SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE);
2592 return R1; // We found a quadratic root!
2597 return UnknownValue;
2600 /// HowFarToNonZero - Return the number of times a backedge checking the
2601 /// specified value for nonzero will execute. If not computable, return
2603 SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2604 // Loops that look like: while (X == 0) are very strange indeed. We don't
2605 // handle them yet except for the trivial case. This could be expanded in the
2606 // future as needed.
2608 // If the value is a constant, check to see if it is known to be non-zero
2609 // already. If so, the backedge will execute zero times.
2610 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2611 if (!C->getValue()->isNullValue())
2612 return SE.getIntegerSCEV(0, C->getType());
2613 return UnknownValue; // Otherwise it will loop infinitely.
2616 // We could implement others, but I really doubt anyone writes loops like
2617 // this, and if they did, they would already be constant folded.
2618 return UnknownValue;
2621 /// HowManyLessThans - Return the number of times a backedge containing the
2622 /// specified less-than comparison will execute. If not computable, return
2624 SCEVHandle ScalarEvolutionsImpl::
2625 HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
2626 // Only handle: "ADDREC < LoopInvariant".
2627 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2629 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2630 if (!AddRec || AddRec->getLoop() != L)
2631 return UnknownValue;
2633 if (AddRec->isAffine()) {
2634 // FORNOW: We only support unit strides.
2635 SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType());
2636 if (AddRec->getOperand(1) != One)
2637 return UnknownValue;
2639 // We know the LHS is of the form {n,+,1} and the RHS is some loop-invariant
2640 // m. So, we count the number of iterations in which {n,+,1} < m is true.
2641 // Note that we cannot simply return max(m-n,0) because it's not safe to
2642 // treat m-n as signed nor unsigned due to overflow possibility.
2644 // First, we get the value of the LHS in the first iteration: n
2645 SCEVHandle Start = AddRec->getOperand(0);
2647 // Then, we get the value of the LHS in the first iteration in which the
2648 // above condition doesn't hold. This equals to max(m,n).
2649 SCEVHandle End = isSigned ? SE.getSMaxExpr(RHS, Start)
2650 : SE.getUMaxExpr(RHS, Start);
2652 // Finally, we subtract these two values to get the number of times the
2653 // backedge is executed: max(m,n)-n.
2654 return SE.getMinusSCEV(End, Start);
2657 return UnknownValue;
2660 /// getNumIterationsInRange - Return the number of iterations of this loop that
2661 /// produce values in the specified constant range. Another way of looking at
2662 /// this is that it returns the first iteration number where the value is not in
2663 /// the condition, thus computing the exit count. If the iteration count can't
2664 /// be computed, an instance of SCEVCouldNotCompute is returned.
2665 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
2666 ScalarEvolution &SE) const {
2667 if (Range.isFullSet()) // Infinite loop.
2668 return new SCEVCouldNotCompute();
2670 // If the start is a non-zero constant, shift the range to simplify things.
2671 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2672 if (!SC->getValue()->isZero()) {
2673 std::vector<SCEVHandle> Operands(op_begin(), op_end());
2674 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
2675 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
2676 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2677 return ShiftedAddRec->getNumIterationsInRange(
2678 Range.subtract(SC->getValue()->getValue()), SE);
2679 // This is strange and shouldn't happen.
2680 return new SCEVCouldNotCompute();
2683 // The only time we can solve this is when we have all constant indices.
2684 // Otherwise, we cannot determine the overflow conditions.
2685 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2686 if (!isa<SCEVConstant>(getOperand(i)))
2687 return new SCEVCouldNotCompute();
2690 // Okay at this point we know that all elements of the chrec are constants and
2691 // that the start element is zero.
2693 // First check to see if the range contains zero. If not, the first
2695 if (!Range.contains(APInt(getBitWidth(),0)))
2696 return SE.getConstant(ConstantInt::get(getType(),0));
2699 // If this is an affine expression then we have this situation:
2700 // Solve {0,+,A} in Range === Ax in Range
2702 // We know that zero is in the range. If A is positive then we know that
2703 // the upper value of the range must be the first possible exit value.
2704 // If A is negative then the lower of the range is the last possible loop
2705 // value. Also note that we already checked for a full range.
2706 APInt One(getBitWidth(),1);
2707 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
2708 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
2710 // The exit value should be (End+A)/A.
2711 APInt ExitVal = (End + A).udiv(A);
2712 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
2714 // Evaluate at the exit value. If we really did fall out of the valid
2715 // range, then we computed our trip count, otherwise wrap around or other
2716 // things must have happened.
2717 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
2718 if (Range.contains(Val->getValue()))
2719 return new SCEVCouldNotCompute(); // Something strange happened
2721 // Ensure that the previous value is in the range. This is a sanity check.
2722 assert(Range.contains(
2723 EvaluateConstantChrecAtConstant(this,
2724 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
2725 "Linear scev computation is off in a bad way!");
2726 return SE.getConstant(ExitValue);
2727 } else if (isQuadratic()) {
2728 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2729 // quadratic equation to solve it. To do this, we must frame our problem in
2730 // terms of figuring out when zero is crossed, instead of when
2731 // Range.getUpper() is crossed.
2732 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
2733 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
2734 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
2736 // Next, solve the constructed addrec
2737 std::pair<SCEVHandle,SCEVHandle> Roots =
2738 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
2739 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2740 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2742 // Pick the smallest positive root value.
2743 if (ConstantInt *CB =
2744 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2745 R1->getValue(), R2->getValue()))) {
2746 if (CB->getZExtValue() == false)
2747 std::swap(R1, R2); // R1 is the minimum root now.
2749 // Make sure the root is not off by one. The returned iteration should
2750 // not be in the range, but the previous one should be. When solving
2751 // for "X*X < 5", for example, we should not return a root of 2.
2752 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2755 if (Range.contains(R1Val->getValue())) {
2756 // The next iteration must be out of the range...
2757 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
2759 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
2760 if (!Range.contains(R1Val->getValue()))
2761 return SE.getConstant(NextVal);
2762 return new SCEVCouldNotCompute(); // Something strange happened
2765 // If R1 was not in the range, then it is a good return value. Make
2766 // sure that R1-1 WAS in the range though, just in case.
2767 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
2768 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
2769 if (Range.contains(R1Val->getValue()))
2771 return new SCEVCouldNotCompute(); // Something strange happened
2776 // Fallback, if this is a general polynomial, figure out the progression
2777 // through brute force: evaluate until we find an iteration that fails the
2778 // test. This is likely to be slow, but getting an accurate trip count is
2779 // incredibly important, we will be able to simplify the exit test a lot, and
2780 // we are almost guaranteed to get a trip count in this case.
2781 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2782 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2784 ++NumBruteForceEvaluations;
2785 SCEVHandle Val = evaluateAtIteration(SE.getConstant(TestVal), SE);
2786 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2787 return new SCEVCouldNotCompute();
2789 // Check to see if we found the value!
2790 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()->getValue()))
2791 return SE.getConstant(TestVal);
2793 // Increment to test the next index.
2794 TestVal = ConstantInt::get(TestVal->getValue()+1);
2795 } while (TestVal != EndVal);
2797 return new SCEVCouldNotCompute();
2802 //===----------------------------------------------------------------------===//
2803 // ScalarEvolution Class Implementation
2804 //===----------------------------------------------------------------------===//
2806 bool ScalarEvolution::runOnFunction(Function &F) {
2807 Impl = new ScalarEvolutionsImpl(*this, F, getAnalysis<LoopInfo>());
2811 void ScalarEvolution::releaseMemory() {
2812 delete (ScalarEvolutionsImpl*)Impl;
2816 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2817 AU.setPreservesAll();
2818 AU.addRequiredTransitive<LoopInfo>();
2821 SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2822 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2825 /// hasSCEV - Return true if the SCEV for this value has already been
2827 bool ScalarEvolution::hasSCEV(Value *V) const {
2828 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
2832 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
2833 /// the specified value.
2834 void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
2835 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
2839 SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2840 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2843 bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2844 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2847 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2848 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2851 void ScalarEvolution::deleteValueFromRecords(Value *V) const {
2852 return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
2855 static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
2857 // Print all inner loops first
2858 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2859 PrintLoopInfo(OS, SE, *I);
2861 OS << "Loop " << L->getHeader()->getName() << ": ";
2863 SmallVector<BasicBlock*, 8> ExitBlocks;
2864 L->getExitBlocks(ExitBlocks);
2865 if (ExitBlocks.size() != 1)
2866 OS << "<multiple exits> ";
2868 if (SE->hasLoopInvariantIterationCount(L)) {
2869 OS << *SE->getIterationCount(L) << " iterations! ";
2871 OS << "Unpredictable iteration count. ";
2877 void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
2878 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2879 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2881 OS << "Classifying expressions for: " << F.getName() << "\n";
2882 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
2883 if (I->getType()->isInteger()) {
2886 SCEVHandle SV = getSCEV(&*I);
2890 if ((*I).getType()->isInteger()) {
2891 ConstantRange Bounds = SV->getValueRange();
2892 if (!Bounds.isFullSet())
2893 OS << "Bounds: " << Bounds << " ";
2896 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
2898 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
2899 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2900 OS << "<<Unknown>>";
2910 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2911 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2912 PrintLoopInfo(OS, this, *I);