1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
63 #include "llvm/Constants.h"
64 #include "llvm/DerivedTypes.h"
65 #include "llvm/GlobalVariable.h"
66 #include "llvm/Instructions.h"
67 #include "llvm/Analysis/LoopInfo.h"
68 #include "llvm/Assembly/Writer.h"
69 #include "llvm/Transforms/Scalar.h"
70 #include "llvm/Transforms/Utils/Local.h"
71 #include "llvm/Support/CFG.h"
72 #include "llvm/Support/ConstantRange.h"
73 #include "llvm/Support/InstIterator.h"
74 #include "llvm/Support/CommandLine.h"
75 #include "llvm/ADT/Statistic.h"
81 RegisterAnalysis<ScalarEvolution>
82 R("scalar-evolution", "Scalar Evolution Analysis");
85 NumBruteForceEvaluations("scalar-evolution",
86 "Number of brute force evaluations needed to "
87 "calculate high-order polynomial exit values");
89 NumArrayLenItCounts("scalar-evolution",
90 "Number of trip counts computed with array length");
92 NumTripCountsComputed("scalar-evolution",
93 "Number of loops with predictable loop counts");
95 NumTripCountsNotComputed("scalar-evolution",
96 "Number of loops without predictable loop counts");
98 NumBruteForceTripCountsComputed("scalar-evolution",
99 "Number of loops with trip counts computed by force");
102 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
103 cl::desc("Maximum number of iterations SCEV will symbolically execute a constant derived loop"),
107 //===----------------------------------------------------------------------===//
108 // SCEV class definitions
109 //===----------------------------------------------------------------------===//
111 //===----------------------------------------------------------------------===//
112 // Implementation of the SCEV class.
115 void SCEV::dump() const {
119 /// getValueRange - Return the tightest constant bounds that this value is
120 /// known to have. This method is only valid on integer SCEV objects.
121 ConstantRange SCEV::getValueRange() const {
122 const Type *Ty = getType();
123 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
124 Ty = Ty->getUnsignedVersion();
125 // Default to a full range if no better information is available.
126 return ConstantRange(getType());
130 SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
132 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
133 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
137 const Type *SCEVCouldNotCompute::getType() const {
138 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
142 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
143 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
147 SCEVHandle SCEVCouldNotCompute::
148 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
149 const SCEVHandle &Conc) const {
153 void SCEVCouldNotCompute::print(std::ostream &OS) const {
154 OS << "***COULDNOTCOMPUTE***";
157 bool SCEVCouldNotCompute::classof(const SCEV *S) {
158 return S->getSCEVType() == scCouldNotCompute;
162 // SCEVConstants - Only allow the creation of one SCEVConstant for any
163 // particular value. Don't use a SCEVHandle here, or else the object will
165 static std::map<ConstantInt*, SCEVConstant*> SCEVConstants;
168 SCEVConstant::~SCEVConstant() {
169 SCEVConstants.erase(V);
172 SCEVHandle SCEVConstant::get(ConstantInt *V) {
173 // Make sure that SCEVConstant instances are all unsigned.
174 if (V->getType()->isSigned()) {
175 const Type *NewTy = V->getType()->getUnsignedVersion();
176 V = cast<ConstantUInt>(ConstantExpr::getCast(V, NewTy));
179 SCEVConstant *&R = SCEVConstants[V];
180 if (R == 0) R = new SCEVConstant(V);
184 ConstantRange SCEVConstant::getValueRange() const {
185 return ConstantRange(V);
188 const Type *SCEVConstant::getType() const { return V->getType(); }
190 void SCEVConstant::print(std::ostream &OS) const {
191 WriteAsOperand(OS, V, false);
194 // SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
195 // particular input. Don't use a SCEVHandle here, or else the object will
197 static std::map<std::pair<SCEV*, const Type*>, SCEVTruncateExpr*> SCEVTruncates;
199 SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
200 : SCEV(scTruncate), Op(op), Ty(ty) {
201 assert(Op->getType()->isInteger() && Ty->isInteger() &&
203 "Cannot truncate non-integer value!");
204 assert(Op->getType()->getPrimitiveSize() > Ty->getPrimitiveSize() &&
205 "This is not a truncating conversion!");
208 SCEVTruncateExpr::~SCEVTruncateExpr() {
209 SCEVTruncates.erase(std::make_pair(Op, Ty));
212 ConstantRange SCEVTruncateExpr::getValueRange() const {
213 return getOperand()->getValueRange().truncate(getType());
216 void SCEVTruncateExpr::print(std::ostream &OS) const {
217 OS << "(truncate " << *Op << " to " << *Ty << ")";
220 // SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
221 // particular input. Don't use a SCEVHandle here, or else the object will never
223 static std::map<std::pair<SCEV*, const Type*>,
224 SCEVZeroExtendExpr*> SCEVZeroExtends;
226 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
227 : SCEV(scTruncate), Op(op), Ty(ty) {
228 assert(Op->getType()->isInteger() && Ty->isInteger() &&
230 "Cannot zero extend non-integer value!");
231 assert(Op->getType()->getPrimitiveSize() < Ty->getPrimitiveSize() &&
232 "This is not an extending conversion!");
235 SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
236 SCEVZeroExtends.erase(std::make_pair(Op, Ty));
239 ConstantRange SCEVZeroExtendExpr::getValueRange() const {
240 return getOperand()->getValueRange().zeroExtend(getType());
243 void SCEVZeroExtendExpr::print(std::ostream &OS) const {
244 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
247 // SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
248 // particular input. Don't use a SCEVHandle here, or else the object will never
250 static std::map<std::pair<unsigned, std::vector<SCEV*> >,
251 SCEVCommutativeExpr*> SCEVCommExprs;
253 SCEVCommutativeExpr::~SCEVCommutativeExpr() {
254 SCEVCommExprs.erase(std::make_pair(getSCEVType(),
255 std::vector<SCEV*>(Operands.begin(),
259 void SCEVCommutativeExpr::print(std::ostream &OS) const {
260 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
261 const char *OpStr = getOperationStr();
262 OS << "(" << *Operands[0];
263 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
264 OS << OpStr << *Operands[i];
268 SCEVHandle SCEVCommutativeExpr::
269 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
270 const SCEVHandle &Conc) const {
271 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
272 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
273 if (H != getOperand(i)) {
274 std::vector<SCEVHandle> NewOps;
275 NewOps.reserve(getNumOperands());
276 for (unsigned j = 0; j != i; ++j)
277 NewOps.push_back(getOperand(j));
279 for (++i; i != e; ++i)
280 NewOps.push_back(getOperand(i)->
281 replaceSymbolicValuesWithConcrete(Sym, Conc));
283 if (isa<SCEVAddExpr>(this))
284 return SCEVAddExpr::get(NewOps);
285 else if (isa<SCEVMulExpr>(this))
286 return SCEVMulExpr::get(NewOps);
288 assert(0 && "Unknown commutative expr!");
295 // SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
296 // input. Don't use a SCEVHandle here, or else the object will never be
298 static std::map<std::pair<SCEV*, SCEV*>, SCEVUDivExpr*> SCEVUDivs;
300 SCEVUDivExpr::~SCEVUDivExpr() {
301 SCEVUDivs.erase(std::make_pair(LHS, RHS));
304 void SCEVUDivExpr::print(std::ostream &OS) const {
305 OS << "(" << *LHS << " /u " << *RHS << ")";
308 const Type *SCEVUDivExpr::getType() const {
309 const Type *Ty = LHS->getType();
310 if (Ty->isSigned()) Ty = Ty->getUnsignedVersion();
314 // SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
315 // particular input. Don't use a SCEVHandle here, or else the object will never
317 static std::map<std::pair<const Loop *, std::vector<SCEV*> >,
318 SCEVAddRecExpr*> SCEVAddRecExprs;
320 SCEVAddRecExpr::~SCEVAddRecExpr() {
321 SCEVAddRecExprs.erase(std::make_pair(L,
322 std::vector<SCEV*>(Operands.begin(),
326 SCEVHandle SCEVAddRecExpr::
327 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
328 const SCEVHandle &Conc) const {
329 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
330 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
331 if (H != getOperand(i)) {
332 std::vector<SCEVHandle> NewOps;
333 NewOps.reserve(getNumOperands());
334 for (unsigned j = 0; j != i; ++j)
335 NewOps.push_back(getOperand(j));
337 for (++i; i != e; ++i)
338 NewOps.push_back(getOperand(i)->
339 replaceSymbolicValuesWithConcrete(Sym, Conc));
341 return get(NewOps, L);
348 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
349 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
351 return !QueryLoop->contains(L->getHeader());
355 void SCEVAddRecExpr::print(std::ostream &OS) const {
356 OS << "{" << *Operands[0];
357 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
358 OS << ",+," << *Operands[i];
359 OS << "}<" << L->getHeader()->getName() + ">";
362 // SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
363 // value. Don't use a SCEVHandle here, or else the object will never be
365 static std::map<Value*, SCEVUnknown*> SCEVUnknowns;
367 SCEVUnknown::~SCEVUnknown() { SCEVUnknowns.erase(V); }
369 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
370 // All non-instruction values are loop invariant. All instructions are loop
371 // invariant if they are not contained in the specified loop.
372 if (Instruction *I = dyn_cast<Instruction>(V))
373 return !L->contains(I->getParent());
377 const Type *SCEVUnknown::getType() const {
381 void SCEVUnknown::print(std::ostream &OS) const {
382 WriteAsOperand(OS, V, false);
385 //===----------------------------------------------------------------------===//
387 //===----------------------------------------------------------------------===//
390 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
391 /// than the complexity of the RHS. This comparator is used to canonicalize
393 struct SCEVComplexityCompare {
394 bool operator()(SCEV *LHS, SCEV *RHS) {
395 return LHS->getSCEVType() < RHS->getSCEVType();
400 /// GroupByComplexity - Given a list of SCEV objects, order them by their
401 /// complexity, and group objects of the same complexity together by value.
402 /// When this routine is finished, we know that any duplicates in the vector are
403 /// consecutive and that complexity is monotonically increasing.
405 /// Note that we go take special precautions to ensure that we get determinstic
406 /// results from this routine. In other words, we don't want the results of
407 /// this to depend on where the addresses of various SCEV objects happened to
410 static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
411 if (Ops.size() < 2) return; // Noop
412 if (Ops.size() == 2) {
413 // This is the common case, which also happens to be trivially simple.
415 if (Ops[0]->getSCEVType() > Ops[1]->getSCEVType())
416 std::swap(Ops[0], Ops[1]);
420 // Do the rough sort by complexity.
421 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
423 // Now that we are sorted by complexity, group elements of the same
424 // complexity. Note that this is, at worst, N^2, but the vector is likely to
425 // be extremely short in practice. Note that we take this approach because we
426 // do not want to depend on the addresses of the objects we are grouping.
427 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
429 unsigned Complexity = S->getSCEVType();
431 // If there are any objects of the same complexity and same value as this
433 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
434 if (Ops[j] == S) { // Found a duplicate.
435 // Move it to immediately after i'th element.
436 std::swap(Ops[i+1], Ops[j]);
437 ++i; // no need to rescan it.
438 if (i == e-2) return; // Done!
446 //===----------------------------------------------------------------------===//
447 // Simple SCEV method implementations
448 //===----------------------------------------------------------------------===//
450 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
451 /// specified signed integer value and return a SCEV for the constant.
452 SCEVHandle SCEVUnknown::getIntegerSCEV(int Val, const Type *Ty) {
455 C = Constant::getNullValue(Ty);
456 else if (Ty->isFloatingPoint())
457 C = ConstantFP::get(Ty, Val);
458 else if (Ty->isSigned())
459 C = ConstantSInt::get(Ty, Val);
461 C = ConstantSInt::get(Ty->getSignedVersion(), Val);
462 C = ConstantExpr::getCast(C, Ty);
464 return SCEVUnknown::get(C);
467 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
468 /// input value to the specified type. If the type must be extended, it is zero
470 static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
471 const Type *SrcTy = V->getType();
472 assert(SrcTy->isInteger() && Ty->isInteger() &&
473 "Cannot truncate or zero extend with non-integer arguments!");
474 if (SrcTy->getPrimitiveSize() == Ty->getPrimitiveSize())
475 return V; // No conversion
476 if (SrcTy->getPrimitiveSize() > Ty->getPrimitiveSize())
477 return SCEVTruncateExpr::get(V, Ty);
478 return SCEVZeroExtendExpr::get(V, Ty);
481 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
483 static SCEVHandle getNegativeSCEV(const SCEVHandle &V) {
484 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
485 return SCEVUnknown::get(ConstantExpr::getNeg(VC->getValue()));
487 return SCEVMulExpr::get(V, SCEVUnknown::getIntegerSCEV(-1, V->getType()));
490 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
492 static SCEVHandle getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS) {
494 return SCEVAddExpr::get(LHS, getNegativeSCEV(RHS));
498 /// Binomial - Evaluate N!/((N-M)!*M!) . Note that N is often large and M is
499 /// often very small, so we try to reduce the number of N! terms we need to
500 /// evaluate by evaluating this as (N!/(N-M)!)/M!
501 static ConstantInt *Binomial(ConstantInt *N, unsigned M) {
502 uint64_t NVal = N->getRawValue();
503 uint64_t FirstTerm = 1;
504 for (unsigned i = 0; i != M; ++i)
507 unsigned MFactorial = 1;
511 Constant *Result = ConstantUInt::get(Type::ULongTy, FirstTerm/MFactorial);
512 Result = ConstantExpr::getCast(Result, N->getType());
513 assert(isa<ConstantInt>(Result) && "Cast of integer not folded??");
514 return cast<ConstantInt>(Result);
517 /// PartialFact - Compute V!/(V-NumSteps)!
518 static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps) {
519 // Handle this case efficiently, it is common to have constant iteration
520 // counts while computing loop exit values.
521 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
522 uint64_t Val = SC->getValue()->getRawValue();
524 for (; NumSteps; --NumSteps)
525 Result *= Val-(NumSteps-1);
526 Constant *Res = ConstantUInt::get(Type::ULongTy, Result);
527 return SCEVUnknown::get(ConstantExpr::getCast(Res, V->getType()));
530 const Type *Ty = V->getType();
532 return SCEVUnknown::getIntegerSCEV(1, Ty);
534 SCEVHandle Result = V;
535 for (unsigned i = 1; i != NumSteps; ++i)
536 Result = SCEVMulExpr::get(Result, getMinusSCEV(V,
537 SCEVUnknown::getIntegerSCEV(i, Ty)));
542 /// evaluateAtIteration - Return the value of this chain of recurrences at
543 /// the specified iteration number. We can evaluate this recurrence by
544 /// multiplying each element in the chain by the binomial coefficient
545 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
547 /// A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3)
549 /// FIXME/VERIFY: I don't trust that this is correct in the face of overflow.
550 /// Is the binomial equation safe using modular arithmetic??
552 SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It) const {
553 SCEVHandle Result = getStart();
555 const Type *Ty = It->getType();
556 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
557 SCEVHandle BC = PartialFact(It, i);
559 SCEVHandle Val = SCEVUDivExpr::get(SCEVMulExpr::get(BC, getOperand(i)),
560 SCEVUnknown::getIntegerSCEV(Divisor,Ty));
561 Result = SCEVAddExpr::get(Result, Val);
567 //===----------------------------------------------------------------------===//
568 // SCEV Expression folder implementations
569 //===----------------------------------------------------------------------===//
571 SCEVHandle SCEVTruncateExpr::get(const SCEVHandle &Op, const Type *Ty) {
572 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
573 return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty));
575 // If the input value is a chrec scev made out of constants, truncate
576 // all of the constants.
577 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
578 std::vector<SCEVHandle> Operands;
579 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
580 // FIXME: This should allow truncation of other expression types!
581 if (isa<SCEVConstant>(AddRec->getOperand(i)))
582 Operands.push_back(get(AddRec->getOperand(i), Ty));
585 if (Operands.size() == AddRec->getNumOperands())
586 return SCEVAddRecExpr::get(Operands, AddRec->getLoop());
589 SCEVTruncateExpr *&Result = SCEVTruncates[std::make_pair(Op, Ty)];
590 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
594 SCEVHandle SCEVZeroExtendExpr::get(const SCEVHandle &Op, const Type *Ty) {
595 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
596 return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty));
598 // FIXME: If the input value is a chrec scev, and we can prove that the value
599 // did not overflow the old, smaller, value, we can zero extend all of the
600 // operands (often constants). This would allow analysis of something like
601 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
603 SCEVZeroExtendExpr *&Result = SCEVZeroExtends[std::make_pair(Op, Ty)];
604 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
608 // get - Get a canonical add expression, or something simpler if possible.
609 SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) {
610 assert(!Ops.empty() && "Cannot get empty add!");
611 if (Ops.size() == 1) return Ops[0];
613 // Sort by complexity, this groups all similar expression types together.
614 GroupByComplexity(Ops);
616 // If there are any constants, fold them together.
618 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
620 assert(Idx < Ops.size());
621 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
622 // We found two constants, fold them together!
623 Constant *Fold = ConstantExpr::getAdd(LHSC->getValue(), RHSC->getValue());
624 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
625 Ops[0] = SCEVConstant::get(CI);
626 Ops.erase(Ops.begin()+1); // Erase the folded element
627 if (Ops.size() == 1) return Ops[0];
629 // If we couldn't fold the expression, move to the next constant. Note
630 // that this is impossible to happen in practice because we always
631 // constant fold constant ints to constant ints.
636 // If we are left with a constant zero being added, strip it off.
637 if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
638 Ops.erase(Ops.begin());
643 if (Ops.size() == 1) return Ops[0];
645 // Okay, check to see if the same value occurs in the operand list twice. If
646 // so, merge them together into an multiply expression. Since we sorted the
647 // list, these values are required to be adjacent.
648 const Type *Ty = Ops[0]->getType();
649 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
650 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
651 // Found a match, merge the two values into a multiply, and add any
652 // remaining values to the result.
653 SCEVHandle Two = SCEVUnknown::getIntegerSCEV(2, Ty);
654 SCEVHandle Mul = SCEVMulExpr::get(Ops[i], Two);
657 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
659 return SCEVAddExpr::get(Ops);
662 // Okay, now we know the first non-constant operand. If there are add
663 // operands they would be next.
664 if (Idx < Ops.size()) {
665 bool DeletedAdd = false;
666 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
667 // If we have an add, expand the add operands onto the end of the operands
669 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
670 Ops.erase(Ops.begin()+Idx);
674 // If we deleted at least one add, we added operands to the end of the list,
675 // and they are not necessarily sorted. Recurse to resort and resimplify
676 // any operands we just aquired.
681 // Skip over the add expression until we get to a multiply.
682 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
685 // If we are adding something to a multiply expression, make sure the
686 // something is not already an operand of the multiply. If so, merge it into
688 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
689 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
690 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
691 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
692 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
693 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
694 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
695 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
696 if (Mul->getNumOperands() != 2) {
697 // If the multiply has more than two operands, we must get the
699 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
700 MulOps.erase(MulOps.begin()+MulOp);
701 InnerMul = SCEVMulExpr::get(MulOps);
703 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, Ty);
704 SCEVHandle AddOne = SCEVAddExpr::get(InnerMul, One);
705 SCEVHandle OuterMul = SCEVMulExpr::get(AddOne, Ops[AddOp]);
706 if (Ops.size() == 2) return OuterMul;
708 Ops.erase(Ops.begin()+AddOp);
709 Ops.erase(Ops.begin()+Idx-1);
711 Ops.erase(Ops.begin()+Idx);
712 Ops.erase(Ops.begin()+AddOp-1);
714 Ops.push_back(OuterMul);
715 return SCEVAddExpr::get(Ops);
718 // Check this multiply against other multiplies being added together.
719 for (unsigned OtherMulIdx = Idx+1;
720 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
722 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
723 // If MulOp occurs in OtherMul, we can fold the two multiplies
725 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
726 OMulOp != e; ++OMulOp)
727 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
728 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
729 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
730 if (Mul->getNumOperands() != 2) {
731 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
732 MulOps.erase(MulOps.begin()+MulOp);
733 InnerMul1 = SCEVMulExpr::get(MulOps);
735 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
736 if (OtherMul->getNumOperands() != 2) {
737 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
739 MulOps.erase(MulOps.begin()+OMulOp);
740 InnerMul2 = SCEVMulExpr::get(MulOps);
742 SCEVHandle InnerMulSum = SCEVAddExpr::get(InnerMul1,InnerMul2);
743 SCEVHandle OuterMul = SCEVMulExpr::get(MulOpSCEV, InnerMulSum);
744 if (Ops.size() == 2) return OuterMul;
745 Ops.erase(Ops.begin()+Idx);
746 Ops.erase(Ops.begin()+OtherMulIdx-1);
747 Ops.push_back(OuterMul);
748 return SCEVAddExpr::get(Ops);
754 // If there are any add recurrences in the operands list, see if any other
755 // added values are loop invariant. If so, we can fold them into the
757 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
760 // Scan over all recurrences, trying to fold loop invariants into them.
761 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
762 // Scan all of the other operands to this add and add them to the vector if
763 // they are loop invariant w.r.t. the recurrence.
764 std::vector<SCEVHandle> LIOps;
765 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
766 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
767 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
768 LIOps.push_back(Ops[i]);
769 Ops.erase(Ops.begin()+i);
773 // If we found some loop invariants, fold them into the recurrence.
774 if (!LIOps.empty()) {
775 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
776 LIOps.push_back(AddRec->getStart());
778 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
779 AddRecOps[0] = SCEVAddExpr::get(LIOps);
781 SCEVHandle NewRec = SCEVAddRecExpr::get(AddRecOps, AddRec->getLoop());
782 // If all of the other operands were loop invariant, we are done.
783 if (Ops.size() == 1) return NewRec;
785 // Otherwise, add the folded AddRec by the non-liv parts.
786 for (unsigned i = 0;; ++i)
787 if (Ops[i] == AddRec) {
791 return SCEVAddExpr::get(Ops);
794 // Okay, if there weren't any loop invariants to be folded, check to see if
795 // there are multiple AddRec's with the same loop induction variable being
796 // added together. If so, we can fold them.
797 for (unsigned OtherIdx = Idx+1;
798 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
799 if (OtherIdx != Idx) {
800 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
801 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
802 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
803 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
804 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
805 if (i >= NewOps.size()) {
806 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
807 OtherAddRec->op_end());
810 NewOps[i] = SCEVAddExpr::get(NewOps[i], OtherAddRec->getOperand(i));
812 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
814 if (Ops.size() == 2) return NewAddRec;
816 Ops.erase(Ops.begin()+Idx);
817 Ops.erase(Ops.begin()+OtherIdx-1);
818 Ops.push_back(NewAddRec);
819 return SCEVAddExpr::get(Ops);
823 // Otherwise couldn't fold anything into this recurrence. Move onto the
827 // Okay, it looks like we really DO need an add expr. Check to see if we
828 // already have one, otherwise create a new one.
829 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
830 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scAddExpr,
832 if (Result == 0) Result = new SCEVAddExpr(Ops);
837 SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) {
838 assert(!Ops.empty() && "Cannot get empty mul!");
840 // Sort by complexity, this groups all similar expression types together.
841 GroupByComplexity(Ops);
843 // If there are any constants, fold them together.
845 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
847 // C1*(C2+V) -> C1*C2 + C1*V
849 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
850 if (Add->getNumOperands() == 2 &&
851 isa<SCEVConstant>(Add->getOperand(0)))
852 return SCEVAddExpr::get(SCEVMulExpr::get(LHSC, Add->getOperand(0)),
853 SCEVMulExpr::get(LHSC, Add->getOperand(1)));
857 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
858 // We found two constants, fold them together!
859 Constant *Fold = ConstantExpr::getMul(LHSC->getValue(), RHSC->getValue());
860 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
861 Ops[0] = SCEVConstant::get(CI);
862 Ops.erase(Ops.begin()+1); // Erase the folded element
863 if (Ops.size() == 1) return Ops[0];
865 // If we couldn't fold the expression, move to the next constant. Note
866 // that this is impossible to happen in practice because we always
867 // constant fold constant ints to constant ints.
872 // If we are left with a constant one being multiplied, strip it off.
873 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
874 Ops.erase(Ops.begin());
876 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
877 // If we have a multiply of zero, it will always be zero.
882 // Skip over the add expression until we get to a multiply.
883 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
889 // If there are mul operands inline them all into this expression.
890 if (Idx < Ops.size()) {
891 bool DeletedMul = false;
892 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
893 // If we have an mul, expand the mul operands onto the end of the operands
895 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
896 Ops.erase(Ops.begin()+Idx);
900 // If we deleted at least one mul, we added operands to the end of the list,
901 // and they are not necessarily sorted. Recurse to resort and resimplify
902 // any operands we just aquired.
907 // If there are any add recurrences in the operands list, see if any other
908 // added values are loop invariant. If so, we can fold them into the
910 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
913 // Scan over all recurrences, trying to fold loop invariants into them.
914 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
915 // Scan all of the other operands to this mul and add them to the vector if
916 // they are loop invariant w.r.t. the recurrence.
917 std::vector<SCEVHandle> LIOps;
918 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
919 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
920 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
921 LIOps.push_back(Ops[i]);
922 Ops.erase(Ops.begin()+i);
926 // If we found some loop invariants, fold them into the recurrence.
927 if (!LIOps.empty()) {
928 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
929 std::vector<SCEVHandle> NewOps;
930 NewOps.reserve(AddRec->getNumOperands());
931 if (LIOps.size() == 1) {
932 SCEV *Scale = LIOps[0];
933 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
934 NewOps.push_back(SCEVMulExpr::get(Scale, AddRec->getOperand(i)));
936 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
937 std::vector<SCEVHandle> MulOps(LIOps);
938 MulOps.push_back(AddRec->getOperand(i));
939 NewOps.push_back(SCEVMulExpr::get(MulOps));
943 SCEVHandle NewRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
945 // If all of the other operands were loop invariant, we are done.
946 if (Ops.size() == 1) return NewRec;
948 // Otherwise, multiply the folded AddRec by the non-liv parts.
949 for (unsigned i = 0;; ++i)
950 if (Ops[i] == AddRec) {
954 return SCEVMulExpr::get(Ops);
957 // Okay, if there weren't any loop invariants to be folded, check to see if
958 // there are multiple AddRec's with the same loop induction variable being
959 // multiplied together. If so, we can fold them.
960 for (unsigned OtherIdx = Idx+1;
961 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
962 if (OtherIdx != Idx) {
963 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
964 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
965 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
966 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
967 SCEVHandle NewStart = SCEVMulExpr::get(F->getStart(),
969 SCEVHandle B = F->getStepRecurrence();
970 SCEVHandle D = G->getStepRecurrence();
971 SCEVHandle NewStep = SCEVAddExpr::get(SCEVMulExpr::get(F, D),
972 SCEVMulExpr::get(G, B),
973 SCEVMulExpr::get(B, D));
974 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewStart, NewStep,
976 if (Ops.size() == 2) return NewAddRec;
978 Ops.erase(Ops.begin()+Idx);
979 Ops.erase(Ops.begin()+OtherIdx-1);
980 Ops.push_back(NewAddRec);
981 return SCEVMulExpr::get(Ops);
985 // Otherwise couldn't fold anything into this recurrence. Move onto the
989 // Okay, it looks like we really DO need an mul expr. Check to see if we
990 // already have one, otherwise create a new one.
991 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
992 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scMulExpr,
995 Result = new SCEVMulExpr(Ops);
999 SCEVHandle SCEVUDivExpr::get(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1000 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1001 if (RHSC->getValue()->equalsInt(1))
1002 return LHS; // X /u 1 --> x
1003 if (RHSC->getValue()->isAllOnesValue())
1004 return getNegativeSCEV(LHS); // X /u -1 --> -x
1006 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1007 Constant *LHSCV = LHSC->getValue();
1008 Constant *RHSCV = RHSC->getValue();
1009 if (LHSCV->getType()->isSigned())
1010 LHSCV = ConstantExpr::getCast(LHSCV,
1011 LHSCV->getType()->getUnsignedVersion());
1012 if (RHSCV->getType()->isSigned())
1013 RHSCV = ConstantExpr::getCast(RHSCV, LHSCV->getType());
1014 return SCEVUnknown::get(ConstantExpr::getDiv(LHSCV, RHSCV));
1018 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1020 SCEVUDivExpr *&Result = SCEVUDivs[std::make_pair(LHS, RHS)];
1021 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
1026 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1027 /// specified loop. Simplify the expression as much as possible.
1028 SCEVHandle SCEVAddRecExpr::get(const SCEVHandle &Start,
1029 const SCEVHandle &Step, const Loop *L) {
1030 std::vector<SCEVHandle> Operands;
1031 Operands.push_back(Start);
1032 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1033 if (StepChrec->getLoop() == L) {
1034 Operands.insert(Operands.end(), StepChrec->op_begin(),
1035 StepChrec->op_end());
1036 return get(Operands, L);
1039 Operands.push_back(Step);
1040 return get(Operands, L);
1043 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1044 /// specified loop. Simplify the expression as much as possible.
1045 SCEVHandle SCEVAddRecExpr::get(std::vector<SCEVHandle> &Operands,
1047 if (Operands.size() == 1) return Operands[0];
1049 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
1050 if (StepC->getValue()->isNullValue()) {
1051 Operands.pop_back();
1052 return get(Operands, L); // { X,+,0 } --> X
1055 SCEVAddRecExpr *&Result =
1056 SCEVAddRecExprs[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1058 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1062 SCEVHandle SCEVUnknown::get(Value *V) {
1063 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1064 return SCEVConstant::get(CI);
1065 SCEVUnknown *&Result = SCEVUnknowns[V];
1066 if (Result == 0) Result = new SCEVUnknown(V);
1071 //===----------------------------------------------------------------------===//
1072 // ScalarEvolutionsImpl Definition and Implementation
1073 //===----------------------------------------------------------------------===//
1075 /// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1079 struct ScalarEvolutionsImpl {
1080 /// F - The function we are analyzing.
1084 /// LI - The loop information for the function we are currently analyzing.
1088 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1090 SCEVHandle UnknownValue;
1092 /// Scalars - This is a cache of the scalars we have analyzed so far.
1094 std::map<Value*, SCEVHandle> Scalars;
1096 /// IterationCounts - Cache the iteration count of the loops for this
1097 /// function as they are computed.
1098 std::map<const Loop*, SCEVHandle> IterationCounts;
1100 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1101 /// the PHI instructions that we attempt to compute constant evolutions for.
1102 /// This allows us to avoid potentially expensive recomputation of these
1103 /// properties. An instruction maps to null if we are unable to compute its
1105 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
1108 ScalarEvolutionsImpl(Function &f, LoopInfo &li)
1109 : F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1111 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1112 /// expression and create a new one.
1113 SCEVHandle getSCEV(Value *V);
1115 /// getSCEVAtScope - Compute the value of the specified expression within
1116 /// the indicated loop (which may be null to indicate in no loop). If the
1117 /// expression cannot be evaluated, return UnknownValue itself.
1118 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1121 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1122 /// an analyzable loop-invariant iteration count.
1123 bool hasLoopInvariantIterationCount(const Loop *L);
1125 /// getIterationCount - If the specified loop has a predictable iteration
1126 /// count, return it. Note that it is not valid to call this method on a
1127 /// loop without a loop-invariant iteration count.
1128 SCEVHandle getIterationCount(const Loop *L);
1130 /// deleteInstructionFromRecords - This method should be called by the
1131 /// client before it removes an instruction from the program, to make sure
1132 /// that no dangling references are left around.
1133 void deleteInstructionFromRecords(Instruction *I);
1136 /// createSCEV - We know that there is no SCEV for the specified value.
1137 /// Analyze the expression.
1138 SCEVHandle createSCEV(Value *V);
1139 SCEVHandle createNodeForCast(CastInst *CI);
1141 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1143 SCEVHandle createNodeForPHI(PHINode *PN);
1145 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1146 /// for the specified instruction and replaces any references to the
1147 /// symbolic value SymName with the specified value. This is used during
1149 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1150 const SCEVHandle &SymName,
1151 const SCEVHandle &NewVal);
1153 /// ComputeIterationCount - Compute the number of times the specified loop
1155 SCEVHandle ComputeIterationCount(const Loop *L);
1157 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1158 /// 'setcc load X, cst', try to se if we can compute the trip count.
1159 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1162 unsigned SetCCOpcode);
1164 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1165 /// constant number of times (the condition evolves only from constants),
1166 /// try to evaluate a few iterations of the loop until we get the exit
1167 /// condition gets a value of ExitWhen (true or false). If we cannot
1168 /// evaluate the trip count of the loop, return UnknownValue.
1169 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1172 /// HowFarToZero - Return the number of times a backedge comparing the
1173 /// specified value to zero will execute. If not computable, return
1175 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1177 /// HowFarToNonZero - Return the number of times a backedge checking the
1178 /// specified value for nonzero will execute. If not computable, return
1180 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
1182 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1183 /// in the header of its containing loop, we know the loop executes a
1184 /// constant number of times, and the PHI node is just a recurrence
1185 /// involving constants, fold it.
1186 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its,
1191 //===----------------------------------------------------------------------===//
1192 // Basic SCEV Analysis and PHI Idiom Recognition Code
1195 /// deleteInstructionFromRecords - This method should be called by the
1196 /// client before it removes an instruction from the program, to make sure
1197 /// that no dangling references are left around.
1198 void ScalarEvolutionsImpl::deleteInstructionFromRecords(Instruction *I) {
1200 if (PHINode *PN = dyn_cast<PHINode>(I))
1201 ConstantEvolutionLoopExitValue.erase(PN);
1205 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1206 /// expression and create a new one.
1207 SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1208 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1210 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1211 if (I != Scalars.end()) return I->second;
1212 SCEVHandle S = createSCEV(V);
1213 Scalars.insert(std::make_pair(V, S));
1217 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1218 /// the specified instruction and replaces any references to the symbolic value
1219 /// SymName with the specified value. This is used during PHI resolution.
1220 void ScalarEvolutionsImpl::
1221 ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1222 const SCEVHandle &NewVal) {
1223 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1224 if (SI == Scalars.end()) return;
1227 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal);
1228 if (NV == SI->second) return; // No change.
1230 SI->second = NV; // Update the scalars map!
1232 // Any instruction values that use this instruction might also need to be
1234 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1236 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1239 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1240 /// a loop header, making it a potential recurrence, or it doesn't.
1242 SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1243 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1244 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1245 if (L->getHeader() == PN->getParent()) {
1246 // If it lives in the loop header, it has two incoming values, one
1247 // from outside the loop, and one from inside.
1248 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1249 unsigned BackEdge = IncomingEdge^1;
1251 // While we are analyzing this PHI node, handle its value symbolically.
1252 SCEVHandle SymbolicName = SCEVUnknown::get(PN);
1253 assert(Scalars.find(PN) == Scalars.end() &&
1254 "PHI node already processed?");
1255 Scalars.insert(std::make_pair(PN, SymbolicName));
1257 // Using this symbolic name for the PHI, analyze the value coming around
1259 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1261 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1262 // has a special value for the first iteration of the loop.
1264 // If the value coming around the backedge is an add with the symbolic
1265 // value we just inserted, then we found a simple induction variable!
1266 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1267 // If there is a single occurrence of the symbolic value, replace it
1268 // with a recurrence.
1269 unsigned FoundIndex = Add->getNumOperands();
1270 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1271 if (Add->getOperand(i) == SymbolicName)
1272 if (FoundIndex == e) {
1277 if (FoundIndex != Add->getNumOperands()) {
1278 // Create an add with everything but the specified operand.
1279 std::vector<SCEVHandle> Ops;
1280 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1281 if (i != FoundIndex)
1282 Ops.push_back(Add->getOperand(i));
1283 SCEVHandle Accum = SCEVAddExpr::get(Ops);
1285 // This is not a valid addrec if the step amount is varying each
1286 // loop iteration, but is not itself an addrec in this loop.
1287 if (Accum->isLoopInvariant(L) ||
1288 (isa<SCEVAddRecExpr>(Accum) &&
1289 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1290 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1291 SCEVHandle PHISCEV = SCEVAddRecExpr::get(StartVal, Accum, L);
1293 // Okay, for the entire analysis of this edge we assumed the PHI
1294 // to be symbolic. We now need to go back and update all of the
1295 // entries for the scalars that use the PHI (except for the PHI
1296 // itself) to use the new analyzed value instead of the "symbolic"
1298 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1304 return SymbolicName;
1307 // If it's not a loop phi, we can't handle it yet.
1308 return SCEVUnknown::get(PN);
1311 /// createNodeForCast - Handle the various forms of casts that we support.
1313 SCEVHandle ScalarEvolutionsImpl::createNodeForCast(CastInst *CI) {
1314 const Type *SrcTy = CI->getOperand(0)->getType();
1315 const Type *DestTy = CI->getType();
1317 // If this is a noop cast (ie, conversion from int to uint), ignore it.
1318 if (SrcTy->isLosslesslyConvertibleTo(DestTy))
1319 return getSCEV(CI->getOperand(0));
1321 if (SrcTy->isInteger() && DestTy->isInteger()) {
1322 // Otherwise, if this is a truncating integer cast, we can represent this
1324 if (SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize())
1325 return SCEVTruncateExpr::get(getSCEV(CI->getOperand(0)),
1326 CI->getType()->getUnsignedVersion());
1327 if (SrcTy->isUnsigned() &&
1328 SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize())
1329 return SCEVZeroExtendExpr::get(getSCEV(CI->getOperand(0)),
1330 CI->getType()->getUnsignedVersion());
1333 // If this is an sign or zero extending cast and we can prove that the value
1334 // will never overflow, we could do similar transformations.
1336 // Otherwise, we can't handle this cast!
1337 return SCEVUnknown::get(CI);
1341 /// createSCEV - We know that there is no SCEV for the specified value.
1342 /// Analyze the expression.
1344 SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1345 if (Instruction *I = dyn_cast<Instruction>(V)) {
1346 switch (I->getOpcode()) {
1347 case Instruction::Add:
1348 return SCEVAddExpr::get(getSCEV(I->getOperand(0)),
1349 getSCEV(I->getOperand(1)));
1350 case Instruction::Mul:
1351 return SCEVMulExpr::get(getSCEV(I->getOperand(0)),
1352 getSCEV(I->getOperand(1)));
1353 case Instruction::Div:
1354 if (V->getType()->isInteger() && V->getType()->isUnsigned())
1355 return SCEVUDivExpr::get(getSCEV(I->getOperand(0)),
1356 getSCEV(I->getOperand(1)));
1359 case Instruction::Sub:
1360 return getMinusSCEV(getSCEV(I->getOperand(0)), getSCEV(I->getOperand(1)));
1362 case Instruction::Shl:
1363 // Turn shift left of a constant amount into a multiply.
1364 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1365 Constant *X = ConstantInt::get(V->getType(), 1);
1366 X = ConstantExpr::getShl(X, SA);
1367 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1371 case Instruction::Shr:
1372 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
1373 if (V->getType()->isUnsigned()) {
1374 Constant *X = ConstantInt::get(V->getType(), 1);
1375 X = ConstantExpr::getShl(X, SA);
1376 return SCEVUDivExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1380 case Instruction::Cast:
1381 return createNodeForCast(cast<CastInst>(I));
1383 case Instruction::PHI:
1384 return createNodeForPHI(cast<PHINode>(I));
1386 default: // We cannot analyze this expression.
1391 return SCEVUnknown::get(V);
1396 //===----------------------------------------------------------------------===//
1397 // Iteration Count Computation Code
1400 /// getIterationCount - If the specified loop has a predictable iteration
1401 /// count, return it. Note that it is not valid to call this method on a
1402 /// loop without a loop-invariant iteration count.
1403 SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1404 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1405 if (I == IterationCounts.end()) {
1406 SCEVHandle ItCount = ComputeIterationCount(L);
1407 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1408 if (ItCount != UnknownValue) {
1409 assert(ItCount->isLoopInvariant(L) &&
1410 "Computed trip count isn't loop invariant for loop!");
1411 ++NumTripCountsComputed;
1412 } else if (isa<PHINode>(L->getHeader()->begin())) {
1413 // Only count loops that have phi nodes as not being computable.
1414 ++NumTripCountsNotComputed;
1420 /// ComputeIterationCount - Compute the number of times the specified loop
1422 SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1423 // If the loop has a non-one exit block count, we can't analyze it.
1424 std::vector<BasicBlock*> ExitBlocks;
1425 L->getExitBlocks(ExitBlocks);
1426 if (ExitBlocks.size() != 1) return UnknownValue;
1428 // Okay, there is one exit block. Try to find the condition that causes the
1429 // loop to be exited.
1430 BasicBlock *ExitBlock = ExitBlocks[0];
1432 BasicBlock *ExitingBlock = 0;
1433 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1435 if (L->contains(*PI)) {
1436 if (ExitingBlock == 0)
1439 return UnknownValue; // More than one block exiting!
1441 assert(ExitingBlock && "No exits from loop, something is broken!");
1443 // Okay, we've computed the exiting block. See what condition causes us to
1446 // FIXME: we should be able to handle switch instructions (with a single exit)
1447 // FIXME: We should handle cast of int to bool as well
1448 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1449 if (ExitBr == 0) return UnknownValue;
1450 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1451 SetCondInst *ExitCond = dyn_cast<SetCondInst>(ExitBr->getCondition());
1452 if (ExitCond == 0) // Not a setcc
1453 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1454 ExitBr->getSuccessor(0) == ExitBlock);
1456 // If the condition was exit on true, convert the condition to exit on false.
1457 Instruction::BinaryOps Cond;
1458 if (ExitBr->getSuccessor(1) == ExitBlock)
1459 Cond = ExitCond->getOpcode();
1461 Cond = ExitCond->getInverseCondition();
1463 // Handle common loops like: for (X = "string"; *X; ++X)
1464 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1465 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1467 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1468 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1471 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1472 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1474 // Try to evaluate any dependencies out of the loop.
1475 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1476 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1477 Tmp = getSCEVAtScope(RHS, L);
1478 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1480 // At this point, we would like to compute how many iterations of the loop the
1481 // predicate will return true for these inputs.
1482 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1483 // If there is a constant, force it into the RHS.
1484 std::swap(LHS, RHS);
1485 Cond = SetCondInst::getSwappedCondition(Cond);
1488 // FIXME: think about handling pointer comparisons! i.e.:
1489 // while (P != P+100) ++P;
1491 // If we have a comparison of a chrec against a constant, try to use value
1492 // ranges to answer this query.
1493 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1494 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1495 if (AddRec->getLoop() == L) {
1496 // Form the comparison range using the constant of the correct type so
1497 // that the ConstantRange class knows to do a signed or unsigned
1499 ConstantInt *CompVal = RHSC->getValue();
1500 const Type *RealTy = ExitCond->getOperand(0)->getType();
1501 CompVal = dyn_cast<ConstantInt>(ConstantExpr::getCast(CompVal, RealTy));
1503 // Form the constant range.
1504 ConstantRange CompRange(Cond, CompVal);
1506 // Now that we have it, if it's signed, convert it to an unsigned
1508 if (CompRange.getLower()->getType()->isSigned()) {
1509 const Type *NewTy = RHSC->getValue()->getType();
1510 Constant *NewL = ConstantExpr::getCast(CompRange.getLower(), NewTy);
1511 Constant *NewU = ConstantExpr::getCast(CompRange.getUpper(), NewTy);
1512 CompRange = ConstantRange(NewL, NewU);
1515 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange);
1516 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1521 case Instruction::SetNE: // while (X != Y)
1522 // Convert to: while (X-Y != 0)
1523 if (LHS->getType()->isInteger()) {
1524 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
1525 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1528 case Instruction::SetEQ:
1529 // Convert to: while (X-Y == 0) // while (X == Y)
1530 if (LHS->getType()->isInteger()) {
1531 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
1532 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1537 std::cerr << "ComputeIterationCount ";
1538 if (ExitCond->getOperand(0)->getType()->isUnsigned())
1539 std::cerr << "[unsigned] ";
1540 std::cerr << *LHS << " "
1541 << Instruction::getOpcodeName(Cond) << " " << *RHS << "\n";
1546 return ComputeIterationCountExhaustively(L, ExitCond,
1547 ExitBr->getSuccessor(0) == ExitBlock);
1550 static ConstantInt *
1551 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) {
1552 SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C));
1553 SCEVHandle Val = AddRec->evaluateAtIteration(InVal);
1554 assert(isa<SCEVConstant>(Val) &&
1555 "Evaluation of SCEV at constant didn't fold correctly?");
1556 return cast<SCEVConstant>(Val)->getValue();
1559 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
1560 /// and a GEP expression (missing the pointer index) indexing into it, return
1561 /// the addressed element of the initializer or null if the index expression is
1564 GetAddressedElementFromGlobal(GlobalVariable *GV,
1565 const std::vector<ConstantInt*> &Indices) {
1566 Constant *Init = GV->getInitializer();
1567 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1568 uint64_t Idx = Indices[i]->getRawValue();
1569 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1570 assert(Idx < CS->getNumOperands() && "Bad struct index!");
1571 Init = cast<Constant>(CS->getOperand(Idx));
1572 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1573 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
1574 Init = cast<Constant>(CA->getOperand(Idx));
1575 } else if (isa<ConstantAggregateZero>(Init)) {
1576 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1577 assert(Idx < STy->getNumElements() && "Bad struct index!");
1578 Init = Constant::getNullValue(STy->getElementType(Idx));
1579 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
1580 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
1581 Init = Constant::getNullValue(ATy->getElementType());
1583 assert(0 && "Unknown constant aggregate type!");
1587 return 0; // Unknown initializer type
1593 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1594 /// 'setcc load X, cst', try to se if we can compute the trip count.
1595 SCEVHandle ScalarEvolutionsImpl::
1596 ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
1597 const Loop *L, unsigned SetCCOpcode) {
1598 if (LI->isVolatile()) return UnknownValue;
1600 // Check to see if the loaded pointer is a getelementptr of a global.
1601 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
1602 if (!GEP) return UnknownValue;
1604 // Make sure that it is really a constant global we are gepping, with an
1605 // initializer, and make sure the first IDX is really 0.
1606 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1607 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1608 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
1609 !cast<Constant>(GEP->getOperand(1))->isNullValue())
1610 return UnknownValue;
1612 // Okay, we allow one non-constant index into the GEP instruction.
1614 std::vector<ConstantInt*> Indexes;
1615 unsigned VarIdxNum = 0;
1616 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
1617 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
1618 Indexes.push_back(CI);
1619 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
1620 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
1621 VarIdx = GEP->getOperand(i);
1623 Indexes.push_back(0);
1626 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
1627 // Check to see if X is a loop variant variable value now.
1628 SCEVHandle Idx = getSCEV(VarIdx);
1629 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
1630 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
1632 // We can only recognize very limited forms of loop index expressions, in
1633 // particular, only affine AddRec's like {C1,+,C2}.
1634 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
1635 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
1636 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
1637 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
1638 return UnknownValue;
1640 unsigned MaxSteps = MaxBruteForceIterations;
1641 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
1642 ConstantUInt *ItCst =
1643 ConstantUInt::get(IdxExpr->getType()->getUnsignedVersion(), IterationNum);
1644 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst);
1646 // Form the GEP offset.
1647 Indexes[VarIdxNum] = Val;
1649 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
1650 if (Result == 0) break; // Cannot compute!
1652 // Evaluate the condition for this iteration.
1653 Result = ConstantExpr::get(SetCCOpcode, Result, RHS);
1654 if (!isa<ConstantBool>(Result)) break; // Couldn't decide for sure
1655 if (Result == ConstantBool::False) {
1657 std::cerr << "\n***\n*** Computed loop count " << *ItCst
1658 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
1661 ++NumArrayLenItCounts;
1662 return SCEVConstant::get(ItCst); // Found terminating iteration!
1665 return UnknownValue;
1669 /// CanConstantFold - Return true if we can constant fold an instruction of the
1670 /// specified type, assuming that all operands were constants.
1671 static bool CanConstantFold(const Instruction *I) {
1672 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I) ||
1673 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
1676 if (const CallInst *CI = dyn_cast<CallInst>(I))
1677 if (const Function *F = CI->getCalledFunction())
1678 return canConstantFoldCallTo((Function*)F); // FIXME: elim cast
1682 /// ConstantFold - Constant fold an instruction of the specified type with the
1683 /// specified constant operands. This function may modify the operands vector.
1684 static Constant *ConstantFold(const Instruction *I,
1685 std::vector<Constant*> &Operands) {
1686 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
1687 return ConstantExpr::get(I->getOpcode(), Operands[0], Operands[1]);
1689 switch (I->getOpcode()) {
1690 case Instruction::Cast:
1691 return ConstantExpr::getCast(Operands[0], I->getType());
1692 case Instruction::Select:
1693 return ConstantExpr::getSelect(Operands[0], Operands[1], Operands[2]);
1694 case Instruction::Call:
1695 if (Function *GV = dyn_cast<Function>(Operands[0])) {
1696 Operands.erase(Operands.begin());
1697 return ConstantFoldCall(cast<Function>(GV), Operands);
1701 case Instruction::GetElementPtr:
1702 Constant *Base = Operands[0];
1703 Operands.erase(Operands.begin());
1704 return ConstantExpr::getGetElementPtr(Base, Operands);
1710 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
1711 /// in the loop that V is derived from. We allow arbitrary operations along the
1712 /// way, but the operands of an operation must either be constants or a value
1713 /// derived from a constant PHI. If this expression does not fit with these
1714 /// constraints, return null.
1715 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
1716 // If this is not an instruction, or if this is an instruction outside of the
1717 // loop, it can't be derived from a loop PHI.
1718 Instruction *I = dyn_cast<Instruction>(V);
1719 if (I == 0 || !L->contains(I->getParent())) return 0;
1721 if (PHINode *PN = dyn_cast<PHINode>(I))
1722 if (L->getHeader() == I->getParent())
1725 // We don't currently keep track of the control flow needed to evaluate
1726 // PHIs, so we cannot handle PHIs inside of loops.
1729 // If we won't be able to constant fold this expression even if the operands
1730 // are constants, return early.
1731 if (!CanConstantFold(I)) return 0;
1733 // Otherwise, we can evaluate this instruction if all of its operands are
1734 // constant or derived from a PHI node themselves.
1736 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
1737 if (!(isa<Constant>(I->getOperand(Op)) ||
1738 isa<GlobalValue>(I->getOperand(Op)))) {
1739 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
1740 if (P == 0) return 0; // Not evolving from PHI
1744 return 0; // Evolving from multiple different PHIs.
1747 // This is a expression evolving from a constant PHI!
1751 /// EvaluateExpression - Given an expression that passes the
1752 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
1753 /// in the loop has the value PHIVal. If we can't fold this expression for some
1754 /// reason, return null.
1755 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
1756 if (isa<PHINode>(V)) return PHIVal;
1757 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
1759 if (Constant *C = dyn_cast<Constant>(V)) return C;
1760 Instruction *I = cast<Instruction>(V);
1762 std::vector<Constant*> Operands;
1763 Operands.resize(I->getNumOperands());
1765 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1766 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
1767 if (Operands[i] == 0) return 0;
1770 return ConstantFold(I, Operands);
1773 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1774 /// in the header of its containing loop, we know the loop executes a
1775 /// constant number of times, and the PHI node is just a recurrence
1776 /// involving constants, fold it.
1777 Constant *ScalarEvolutionsImpl::
1778 getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its, const Loop *L) {
1779 std::map<PHINode*, Constant*>::iterator I =
1780 ConstantEvolutionLoopExitValue.find(PN);
1781 if (I != ConstantEvolutionLoopExitValue.end())
1784 if (Its > MaxBruteForceIterations)
1785 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
1787 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
1789 // Since the loop is canonicalized, the PHI node must have two entries. One
1790 // entry must be a constant (coming in from outside of the loop), and the
1791 // second must be derived from the same PHI.
1792 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1793 Constant *StartCST =
1794 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1796 return RetVal = 0; // Must be a constant.
1798 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1799 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1801 return RetVal = 0; // Not derived from same PHI.
1803 // Execute the loop symbolically to determine the exit value.
1804 unsigned IterationNum = 0;
1805 unsigned NumIterations = Its;
1806 if (NumIterations != Its)
1807 return RetVal = 0; // More than 2^32 iterations??
1809 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
1810 if (IterationNum == NumIterations)
1811 return RetVal = PHIVal; // Got exit value!
1813 // Compute the value of the PHI node for the next iteration.
1814 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1815 if (NextPHI == PHIVal)
1816 return RetVal = NextPHI; // Stopped evolving!
1818 return 0; // Couldn't evaluate!
1823 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1824 /// constant number of times (the condition evolves only from constants),
1825 /// try to evaluate a few iterations of the loop until we get the exit
1826 /// condition gets a value of ExitWhen (true or false). If we cannot
1827 /// evaluate the trip count of the loop, return UnknownValue.
1828 SCEVHandle ScalarEvolutionsImpl::
1829 ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
1830 PHINode *PN = getConstantEvolvingPHI(Cond, L);
1831 if (PN == 0) return UnknownValue;
1833 // Since the loop is canonicalized, the PHI node must have two entries. One
1834 // entry must be a constant (coming in from outside of the loop), and the
1835 // second must be derived from the same PHI.
1836 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1837 Constant *StartCST =
1838 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1839 if (StartCST == 0) return UnknownValue; // Must be a constant.
1841 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1842 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1843 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
1845 // Okay, we find a PHI node that defines the trip count of this loop. Execute
1846 // the loop symbolically to determine when the condition gets a value of
1848 unsigned IterationNum = 0;
1849 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
1850 for (Constant *PHIVal = StartCST;
1851 IterationNum != MaxIterations; ++IterationNum) {
1852 ConstantBool *CondVal =
1853 dyn_cast_or_null<ConstantBool>(EvaluateExpression(Cond, PHIVal));
1854 if (!CondVal) return UnknownValue; // Couldn't symbolically evaluate.
1856 if (CondVal->getValue() == ExitWhen) {
1857 ConstantEvolutionLoopExitValue[PN] = PHIVal;
1858 ++NumBruteForceTripCountsComputed;
1859 return SCEVConstant::get(ConstantUInt::get(Type::UIntTy, IterationNum));
1862 // Compute the value of the PHI node for the next iteration.
1863 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1864 if (NextPHI == 0 || NextPHI == PHIVal)
1865 return UnknownValue; // Couldn't evaluate or not making progress...
1869 // Too many iterations were needed to evaluate.
1870 return UnknownValue;
1873 /// getSCEVAtScope - Compute the value of the specified expression within the
1874 /// indicated loop (which may be null to indicate in no loop). If the
1875 /// expression cannot be evaluated, return UnknownValue.
1876 SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
1877 // FIXME: this should be turned into a virtual method on SCEV!
1879 if (isa<SCEVConstant>(V)) return V;
1881 // If this instruction is evolves from a constant-evolving PHI, compute the
1882 // exit value from the loop without using SCEVs.
1883 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
1884 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
1885 const Loop *LI = this->LI[I->getParent()];
1886 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
1887 if (PHINode *PN = dyn_cast<PHINode>(I))
1888 if (PN->getParent() == LI->getHeader()) {
1889 // Okay, there is no closed form solution for the PHI node. Check
1890 // to see if the loop that contains it has a known iteration count.
1891 // If so, we may be able to force computation of the exit value.
1892 SCEVHandle IterationCount = getIterationCount(LI);
1893 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
1894 // Okay, we know how many times the containing loop executes. If
1895 // this is a constant evolving PHI node, get the final value at
1896 // the specified iteration number.
1897 Constant *RV = getConstantEvolutionLoopExitValue(PN,
1898 ICC->getValue()->getRawValue(),
1900 if (RV) return SCEVUnknown::get(RV);
1904 // Okay, this is a some expression that we cannot symbolically evaluate
1905 // into a SCEV. Check to see if it's possible to symbolically evaluate
1906 // the arguments into constants, and if see, try to constant propagate the
1907 // result. This is particularly useful for computing loop exit values.
1908 if (CanConstantFold(I)) {
1909 std::vector<Constant*> Operands;
1910 Operands.reserve(I->getNumOperands());
1911 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1912 Value *Op = I->getOperand(i);
1913 if (Constant *C = dyn_cast<Constant>(Op)) {
1914 Operands.push_back(C);
1916 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
1917 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
1918 Operands.push_back(ConstantExpr::getCast(SC->getValue(),
1920 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
1921 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
1922 Operands.push_back(ConstantExpr::getCast(C, Op->getType()));
1930 return SCEVUnknown::get(ConstantFold(I, Operands));
1934 // This is some other type of SCEVUnknown, just return it.
1938 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
1939 // Avoid performing the look-up in the common case where the specified
1940 // expression has no loop-variant portions.
1941 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
1942 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1943 if (OpAtScope != Comm->getOperand(i)) {
1944 if (OpAtScope == UnknownValue) return UnknownValue;
1945 // Okay, at least one of these operands is loop variant but might be
1946 // foldable. Build a new instance of the folded commutative expression.
1947 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
1948 NewOps.push_back(OpAtScope);
1950 for (++i; i != e; ++i) {
1951 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1952 if (OpAtScope == UnknownValue) return UnknownValue;
1953 NewOps.push_back(OpAtScope);
1955 if (isa<SCEVAddExpr>(Comm))
1956 return SCEVAddExpr::get(NewOps);
1957 assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
1958 return SCEVMulExpr::get(NewOps);
1961 // If we got here, all operands are loop invariant.
1965 if (SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(V)) {
1966 SCEVHandle LHS = getSCEVAtScope(UDiv->getLHS(), L);
1967 if (LHS == UnknownValue) return LHS;
1968 SCEVHandle RHS = getSCEVAtScope(UDiv->getRHS(), L);
1969 if (RHS == UnknownValue) return RHS;
1970 if (LHS == UDiv->getLHS() && RHS == UDiv->getRHS())
1971 return UDiv; // must be loop invariant
1972 return SCEVUDivExpr::get(LHS, RHS);
1975 // If this is a loop recurrence for a loop that does not contain L, then we
1976 // are dealing with the final value computed by the loop.
1977 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
1978 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
1979 // To evaluate this recurrence, we need to know how many times the AddRec
1980 // loop iterates. Compute this now.
1981 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
1982 if (IterationCount == UnknownValue) return UnknownValue;
1983 IterationCount = getTruncateOrZeroExtend(IterationCount,
1986 // If the value is affine, simplify the expression evaluation to just
1987 // Start + Step*IterationCount.
1988 if (AddRec->isAffine())
1989 return SCEVAddExpr::get(AddRec->getStart(),
1990 SCEVMulExpr::get(IterationCount,
1991 AddRec->getOperand(1)));
1993 // Otherwise, evaluate it the hard way.
1994 return AddRec->evaluateAtIteration(IterationCount);
1996 return UnknownValue;
1999 //assert(0 && "Unknown SCEV type!");
2000 return UnknownValue;
2004 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2005 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2006 /// might be the same) or two SCEVCouldNotCompute objects.
2008 static std::pair<SCEVHandle,SCEVHandle>
2009 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) {
2010 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2011 SCEVConstant *L = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2012 SCEVConstant *M = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2013 SCEVConstant *N = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2015 // We currently can only solve this if the coefficients are constants.
2016 if (!L || !M || !N) {
2017 SCEV *CNC = new SCEVCouldNotCompute();
2018 return std::make_pair(CNC, CNC);
2021 Constant *Two = ConstantInt::get(L->getValue()->getType(), 2);
2023 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2024 Constant *C = L->getValue();
2025 // The B coefficient is M-N/2
2026 Constant *B = ConstantExpr::getSub(M->getValue(),
2027 ConstantExpr::getDiv(N->getValue(),
2029 // The A coefficient is N/2
2030 Constant *A = ConstantExpr::getDiv(N->getValue(), Two);
2032 // Compute the B^2-4ac term.
2033 Constant *SqrtTerm =
2034 ConstantExpr::getMul(ConstantInt::get(C->getType(), 4),
2035 ConstantExpr::getMul(A, C));
2036 SqrtTerm = ConstantExpr::getSub(ConstantExpr::getMul(B, B), SqrtTerm);
2038 // Compute floor(sqrt(B^2-4ac))
2039 ConstantUInt *SqrtVal =
2040 cast<ConstantUInt>(ConstantExpr::getCast(SqrtTerm,
2041 SqrtTerm->getType()->getUnsignedVersion()));
2042 uint64_t SqrtValV = SqrtVal->getValue();
2043 uint64_t SqrtValV2 = (uint64_t)sqrt((double)SqrtValV);
2044 // The square root might not be precise for arbitrary 64-bit integer
2045 // values. Do some sanity checks to ensure it's correct.
2046 if (SqrtValV2*SqrtValV2 > SqrtValV ||
2047 (SqrtValV2+1)*(SqrtValV2+1) <= SqrtValV) {
2048 SCEV *CNC = new SCEVCouldNotCompute();
2049 return std::make_pair(CNC, CNC);
2052 SqrtVal = ConstantUInt::get(Type::ULongTy, SqrtValV2);
2053 SqrtTerm = ConstantExpr::getCast(SqrtVal, SqrtTerm->getType());
2055 Constant *NegB = ConstantExpr::getNeg(B);
2056 Constant *TwoA = ConstantExpr::getMul(A, Two);
2058 // The divisions must be performed as signed divisions.
2059 const Type *SignedTy = NegB->getType()->getSignedVersion();
2060 NegB = ConstantExpr::getCast(NegB, SignedTy);
2061 TwoA = ConstantExpr::getCast(TwoA, SignedTy);
2062 SqrtTerm = ConstantExpr::getCast(SqrtTerm, SignedTy);
2064 Constant *Solution1 =
2065 ConstantExpr::getDiv(ConstantExpr::getAdd(NegB, SqrtTerm), TwoA);
2066 Constant *Solution2 =
2067 ConstantExpr::getDiv(ConstantExpr::getSub(NegB, SqrtTerm), TwoA);
2068 return std::make_pair(SCEVUnknown::get(Solution1),
2069 SCEVUnknown::get(Solution2));
2072 /// HowFarToZero - Return the number of times a backedge comparing the specified
2073 /// value to zero will execute. If not computable, return UnknownValue
2074 SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2075 // If the value is a constant
2076 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2077 // If the value is already zero, the branch will execute zero times.
2078 if (C->getValue()->isNullValue()) return C;
2079 return UnknownValue; // Otherwise it will loop infinitely.
2082 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2083 if (!AddRec || AddRec->getLoop() != L)
2084 return UnknownValue;
2086 if (AddRec->isAffine()) {
2087 // If this is an affine expression the execution count of this branch is
2090 // (0 - Start/Step) iff Start % Step == 0
2092 // Get the initial value for the loop.
2093 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2094 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
2095 SCEVHandle Step = AddRec->getOperand(1);
2097 Step = getSCEVAtScope(Step, L->getParentLoop());
2099 // Figure out if Start % Step == 0.
2100 // FIXME: We should add DivExpr and RemExpr operations to our AST.
2101 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2102 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
2103 return getNegativeSCEV(Start); // 0 - Start/1 == -Start
2104 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
2105 return Start; // 0 - Start/-1 == Start
2107 // Check to see if Start is divisible by SC with no remainder.
2108 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2109 ConstantInt *StartCC = StartC->getValue();
2110 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
2111 Constant *Rem = ConstantExpr::getRem(StartNegC, StepC->getValue());
2112 if (Rem->isNullValue()) {
2113 Constant *Result =ConstantExpr::getDiv(StartNegC,StepC->getValue());
2114 return SCEVUnknown::get(Result);
2118 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2119 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2120 // the quadratic equation to solve it.
2121 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec);
2122 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2123 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2126 std::cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2127 << " sol#2: " << *R2 << "\n";
2129 // Pick the smallest positive root value.
2130 assert(R1->getType()->isUnsigned()&&"Didn't canonicalize to unsigned?");
2131 if (ConstantBool *CB =
2132 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2134 if (CB != ConstantBool::True)
2135 std::swap(R1, R2); // R1 is the minimum root now.
2137 // We can only use this value if the chrec ends up with an exact zero
2138 // value at this index. When solving for "X*X != 5", for example, we
2139 // should not accept a root of 2.
2140 SCEVHandle Val = AddRec->evaluateAtIteration(R1);
2141 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
2142 if (EvalVal->getValue()->isNullValue())
2143 return R1; // We found a quadratic root!
2148 return UnknownValue;
2151 /// HowFarToNonZero - Return the number of times a backedge checking the
2152 /// specified value for nonzero will execute. If not computable, return
2154 SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2155 // Loops that look like: while (X == 0) are very strange indeed. We don't
2156 // handle them yet except for the trivial case. This could be expanded in the
2157 // future as needed.
2159 // If the value is a constant, check to see if it is known to be non-zero
2160 // already. If so, the backedge will execute zero times.
2161 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2162 Constant *Zero = Constant::getNullValue(C->getValue()->getType());
2163 Constant *NonZero = ConstantExpr::getSetNE(C->getValue(), Zero);
2164 if (NonZero == ConstantBool::True)
2165 return getSCEV(Zero);
2166 return UnknownValue; // Otherwise it will loop infinitely.
2169 // We could implement others, but I really doubt anyone writes loops like
2170 // this, and if they did, they would already be constant folded.
2171 return UnknownValue;
2174 /// getNumIterationsInRange - Return the number of iterations of this loop that
2175 /// produce values in the specified constant range. Another way of looking at
2176 /// this is that it returns the first iteration number where the value is not in
2177 /// the condition, thus computing the exit count. If the iteration count can't
2178 /// be computed, an instance of SCEVCouldNotCompute is returned.
2179 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range) const {
2180 if (Range.isFullSet()) // Infinite loop.
2181 return new SCEVCouldNotCompute();
2183 // If the start is a non-zero constant, shift the range to simplify things.
2184 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2185 if (!SC->getValue()->isNullValue()) {
2186 std::vector<SCEVHandle> Operands(op_begin(), op_end());
2187 Operands[0] = SCEVUnknown::getIntegerSCEV(0, SC->getType());
2188 SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop());
2189 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2190 return ShiftedAddRec->getNumIterationsInRange(
2191 Range.subtract(SC->getValue()));
2192 // This is strange and shouldn't happen.
2193 return new SCEVCouldNotCompute();
2196 // The only time we can solve this is when we have all constant indices.
2197 // Otherwise, we cannot determine the overflow conditions.
2198 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2199 if (!isa<SCEVConstant>(getOperand(i)))
2200 return new SCEVCouldNotCompute();
2203 // Okay at this point we know that all elements of the chrec are constants and
2204 // that the start element is zero.
2206 // First check to see if the range contains zero. If not, the first
2208 ConstantInt *Zero = ConstantInt::get(getType(), 0);
2209 if (!Range.contains(Zero)) return SCEVConstant::get(Zero);
2212 // If this is an affine expression then we have this situation:
2213 // Solve {0,+,A} in Range === Ax in Range
2215 // Since we know that zero is in the range, we know that the upper value of
2216 // the range must be the first possible exit value. Also note that we
2217 // already checked for a full range.
2218 ConstantInt *Upper = cast<ConstantInt>(Range.getUpper());
2219 ConstantInt *A = cast<SCEVConstant>(getOperand(1))->getValue();
2220 ConstantInt *One = ConstantInt::get(getType(), 1);
2222 // The exit value should be (Upper+A-1)/A.
2223 Constant *ExitValue = Upper;
2225 ExitValue = ConstantExpr::getSub(ConstantExpr::getAdd(Upper, A), One);
2226 ExitValue = ConstantExpr::getDiv(ExitValue, A);
2228 assert(isa<ConstantInt>(ExitValue) &&
2229 "Constant folding of integers not implemented?");
2231 // Evaluate at the exit value. If we really did fall out of the valid
2232 // range, then we computed our trip count, otherwise wrap around or other
2233 // things must have happened.
2234 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue);
2235 if (Range.contains(Val))
2236 return new SCEVCouldNotCompute(); // Something strange happened
2238 // Ensure that the previous value is in the range. This is a sanity check.
2239 assert(Range.contains(EvaluateConstantChrecAtConstant(this,
2240 ConstantExpr::getSub(ExitValue, One))) &&
2241 "Linear scev computation is off in a bad way!");
2242 return SCEVConstant::get(cast<ConstantInt>(ExitValue));
2243 } else if (isQuadratic()) {
2244 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2245 // quadratic equation to solve it. To do this, we must frame our problem in
2246 // terms of figuring out when zero is crossed, instead of when
2247 // Range.getUpper() is crossed.
2248 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
2249 NewOps[0] = getNegativeSCEV(SCEVUnknown::get(Range.getUpper()));
2250 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop());
2252 // Next, solve the constructed addrec
2253 std::pair<SCEVHandle,SCEVHandle> Roots =
2254 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec));
2255 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2256 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2258 // Pick the smallest positive root value.
2259 assert(R1->getType()->isUnsigned() && "Didn't canonicalize to unsigned?");
2260 if (ConstantBool *CB =
2261 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2263 if (CB != ConstantBool::True)
2264 std::swap(R1, R2); // R1 is the minimum root now.
2266 // Make sure the root is not off by one. The returned iteration should
2267 // not be in the range, but the previous one should be. When solving
2268 // for "X*X < 5", for example, we should not return a root of 2.
2269 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2271 if (Range.contains(R1Val)) {
2272 // The next iteration must be out of the range...
2274 ConstantExpr::getAdd(R1->getValue(),
2275 ConstantInt::get(R1->getType(), 1));
2277 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2278 if (!Range.contains(R1Val))
2279 return SCEVUnknown::get(NextVal);
2280 return new SCEVCouldNotCompute(); // Something strange happened
2283 // If R1 was not in the range, then it is a good return value. Make
2284 // sure that R1-1 WAS in the range though, just in case.
2286 ConstantExpr::getSub(R1->getValue(),
2287 ConstantInt::get(R1->getType(), 1));
2288 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2289 if (Range.contains(R1Val))
2291 return new SCEVCouldNotCompute(); // Something strange happened
2296 // Fallback, if this is a general polynomial, figure out the progression
2297 // through brute force: evaluate until we find an iteration that fails the
2298 // test. This is likely to be slow, but getting an accurate trip count is
2299 // incredibly important, we will be able to simplify the exit test a lot, and
2300 // we are almost guaranteed to get a trip count in this case.
2301 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2302 ConstantInt *One = ConstantInt::get(getType(), 1);
2303 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2305 ++NumBruteForceEvaluations;
2306 SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal));
2307 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2308 return new SCEVCouldNotCompute();
2310 // Check to see if we found the value!
2311 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()))
2312 return SCEVConstant::get(TestVal);
2314 // Increment to test the next index.
2315 TestVal = cast<ConstantInt>(ConstantExpr::getAdd(TestVal, One));
2316 } while (TestVal != EndVal);
2318 return new SCEVCouldNotCompute();
2323 //===----------------------------------------------------------------------===//
2324 // ScalarEvolution Class Implementation
2325 //===----------------------------------------------------------------------===//
2327 bool ScalarEvolution::runOnFunction(Function &F) {
2328 Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>());
2332 void ScalarEvolution::releaseMemory() {
2333 delete (ScalarEvolutionsImpl*)Impl;
2337 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2338 AU.setPreservesAll();
2339 AU.addRequiredID(LoopSimplifyID);
2340 AU.addRequiredTransitive<LoopInfo>();
2343 SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2344 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2347 SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2348 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2351 bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2352 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2355 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2356 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2359 void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const {
2360 return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I);
2363 static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
2365 // Print all inner loops first
2366 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2367 PrintLoopInfo(OS, SE, *I);
2369 std::cerr << "Loop " << L->getHeader()->getName() << ": ";
2371 std::vector<BasicBlock*> ExitBlocks;
2372 L->getExitBlocks(ExitBlocks);
2373 if (ExitBlocks.size() != 1)
2374 std::cerr << "<multiple exits> ";
2376 if (SE->hasLoopInvariantIterationCount(L)) {
2377 std::cerr << *SE->getIterationCount(L) << " iterations! ";
2379 std::cerr << "Unpredictable iteration count. ";
2385 void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
2386 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2387 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2389 OS << "Classifying expressions for: " << F.getName() << "\n";
2390 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
2391 if (I->getType()->isInteger()) {
2394 SCEVHandle SV = getSCEV(&*I);
2398 if ((*I).getType()->isIntegral()) {
2399 ConstantRange Bounds = SV->getValueRange();
2400 if (!Bounds.isFullSet())
2401 OS << "Bounds: " << Bounds << " ";
2404 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
2406 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
2407 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2408 OS << "<<Unknown>>";
2418 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2419 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2420 PrintLoopInfo(OS, this, *I);