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/Dominators.h"
70 #include "llvm/Analysis/LoopInfo.h"
71 #include "llvm/Assembly/Writer.h"
72 #include "llvm/Target/TargetData.h"
73 #include "llvm/Transforms/Scalar.h"
74 #include "llvm/Support/CFG.h"
75 #include "llvm/Support/CommandLine.h"
76 #include "llvm/Support/Compiler.h"
77 #include "llvm/Support/ConstantRange.h"
78 #include "llvm/Support/GetElementPtrTypeIterator.h"
79 #include "llvm/Support/InstIterator.h"
80 #include "llvm/Support/ManagedStatic.h"
81 #include "llvm/Support/MathExtras.h"
82 #include "llvm/Support/Streams.h"
83 #include "llvm/ADT/Statistic.h"
84 #include "llvm/ADT/STLExtras.h"
90 STATISTIC(NumArrayLenItCounts,
91 "Number of trip counts computed with array length");
92 STATISTIC(NumTripCountsComputed,
93 "Number of loops with predictable loop counts");
94 STATISTIC(NumTripCountsNotComputed,
95 "Number of loops without predictable loop counts");
96 STATISTIC(NumBruteForceTripCountsComputed,
97 "Number of loops with trip counts computed by force");
99 static cl::opt<unsigned>
100 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
101 cl::desc("Maximum number of iterations SCEV will "
102 "symbolically execute a constant derived loop"),
105 static RegisterPass<ScalarEvolution>
106 R("scalar-evolution", "Scalar Evolution Analysis", false, true);
107 char ScalarEvolution::ID = 0;
109 //===----------------------------------------------------------------------===//
110 // SCEV class definitions
111 //===----------------------------------------------------------------------===//
113 //===----------------------------------------------------------------------===//
114 // Implementation of the SCEV class.
117 void SCEV::dump() const {
122 bool SCEV::isZero() const {
123 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
124 return SC->getValue()->isZero();
129 SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
131 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
132 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
136 const Type *SCEVCouldNotCompute::getType() const {
137 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
141 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
142 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
146 SCEVHandle SCEVCouldNotCompute::
147 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
148 const SCEVHandle &Conc,
149 ScalarEvolution &SE) 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 ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
168 SCEVConstant::~SCEVConstant() {
169 SCEVConstants->erase(V);
172 SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
173 SCEVConstant *&R = (*SCEVConstants)[V];
174 if (R == 0) R = new SCEVConstant(V);
178 SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
179 return getConstant(ConstantInt::get(Val));
182 const Type *SCEVConstant::getType() const { return V->getType(); }
184 void SCEVConstant::print(std::ostream &OS) const {
185 WriteAsOperand(OS, V, false);
188 // SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
189 // particular input. Don't use a SCEVHandle here, or else the object will
191 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
192 SCEVTruncateExpr*> > SCEVTruncates;
194 SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
195 : SCEV(scTruncate), Op(op), Ty(ty) {
196 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
197 (Ty->isInteger() || isa<PointerType>(Ty)) &&
198 "Cannot truncate non-integer value!");
199 assert((!Op->getType()->isInteger() || !Ty->isInteger() ||
200 Op->getType()->getPrimitiveSizeInBits() >
201 Ty->getPrimitiveSizeInBits()) &&
202 "This is not a truncating conversion!");
205 SCEVTruncateExpr::~SCEVTruncateExpr() {
206 SCEVTruncates->erase(std::make_pair(Op, Ty));
209 bool SCEVTruncateExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
210 return Op->dominates(BB, DT);
213 void SCEVTruncateExpr::print(std::ostream &OS) const {
214 OS << "(truncate " << *Op << " to " << *Ty << ")";
217 // SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
218 // particular input. Don't use a SCEVHandle here, or else the object will never
220 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
221 SCEVZeroExtendExpr*> > SCEVZeroExtends;
223 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
224 : SCEV(scZeroExtend), Op(op), Ty(ty) {
225 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
226 (Ty->isInteger() || isa<PointerType>(Ty)) &&
227 "Cannot zero extend non-integer value!");
228 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
229 && "This is not an extending conversion!");
232 SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
233 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
236 bool SCEVZeroExtendExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
237 return Op->dominates(BB, DT);
240 void SCEVZeroExtendExpr::print(std::ostream &OS) const {
241 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
244 // SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
245 // particular input. Don't use a SCEVHandle here, or else the object will never
247 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
248 SCEVSignExtendExpr*> > SCEVSignExtends;
250 SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
251 : SCEV(scSignExtend), Op(op), Ty(ty) {
252 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
253 (Ty->isInteger() || isa<PointerType>(Ty)) &&
254 "Cannot sign extend non-integer value!");
255 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
256 && "This is not an extending conversion!");
259 SCEVSignExtendExpr::~SCEVSignExtendExpr() {
260 SCEVSignExtends->erase(std::make_pair(Op, Ty));
263 bool SCEVSignExtendExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
264 return Op->dominates(BB, DT);
267 void SCEVSignExtendExpr::print(std::ostream &OS) const {
268 OS << "(signextend " << *Op << " to " << *Ty << ")";
271 // SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
272 // particular input. Don't use a SCEVHandle here, or else the object will never
274 static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
275 SCEVCommutativeExpr*> > SCEVCommExprs;
277 SCEVCommutativeExpr::~SCEVCommutativeExpr() {
278 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
279 std::vector<SCEV*>(Operands.begin(),
283 void SCEVCommutativeExpr::print(std::ostream &OS) const {
284 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
285 const char *OpStr = getOperationStr();
286 OS << "(" << *Operands[0];
287 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
288 OS << OpStr << *Operands[i];
292 SCEVHandle SCEVCommutativeExpr::
293 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
294 const SCEVHandle &Conc,
295 ScalarEvolution &SE) const {
296 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
298 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
299 if (H != getOperand(i)) {
300 std::vector<SCEVHandle> NewOps;
301 NewOps.reserve(getNumOperands());
302 for (unsigned j = 0; j != i; ++j)
303 NewOps.push_back(getOperand(j));
305 for (++i; i != e; ++i)
306 NewOps.push_back(getOperand(i)->
307 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
309 if (isa<SCEVAddExpr>(this))
310 return SE.getAddExpr(NewOps);
311 else if (isa<SCEVMulExpr>(this))
312 return SE.getMulExpr(NewOps);
313 else if (isa<SCEVSMaxExpr>(this))
314 return SE.getSMaxExpr(NewOps);
315 else if (isa<SCEVUMaxExpr>(this))
316 return SE.getUMaxExpr(NewOps);
318 assert(0 && "Unknown commutative expr!");
324 bool SCEVCommutativeExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
325 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
326 if (!getOperand(i)->dominates(BB, DT))
333 // SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
334 // input. Don't use a SCEVHandle here, or else the object will never be
336 static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
337 SCEVUDivExpr*> > SCEVUDivs;
339 SCEVUDivExpr::~SCEVUDivExpr() {
340 SCEVUDivs->erase(std::make_pair(LHS, RHS));
343 bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
344 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
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 bool SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
368 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
369 if (!getOperand(i)->dominates(BB, DT))
376 SCEVHandle SCEVAddRecExpr::
377 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
378 const SCEVHandle &Conc,
379 ScalarEvolution &SE) const {
380 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
382 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
383 if (H != getOperand(i)) {
384 std::vector<SCEVHandle> NewOps;
385 NewOps.reserve(getNumOperands());
386 for (unsigned j = 0; j != i; ++j)
387 NewOps.push_back(getOperand(j));
389 for (++i; i != e; ++i)
390 NewOps.push_back(getOperand(i)->
391 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
393 return SE.getAddRecExpr(NewOps, L);
400 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
401 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
402 // contain L and if the start is invariant.
403 return !QueryLoop->contains(L->getHeader()) &&
404 getOperand(0)->isLoopInvariant(QueryLoop);
408 void SCEVAddRecExpr::print(std::ostream &OS) const {
409 OS << "{" << *Operands[0];
410 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
411 OS << ",+," << *Operands[i];
412 OS << "}<" << L->getHeader()->getName() + ">";
415 // SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
416 // value. Don't use a SCEVHandle here, or else the object will never be
418 static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
420 SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
422 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
423 // All non-instruction values are loop invariant. All instructions are loop
424 // invariant if they are not contained in the specified loop.
425 if (Instruction *I = dyn_cast<Instruction>(V))
426 return !L->contains(I->getParent());
430 bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
431 if (Instruction *I = dyn_cast<Instruction>(getValue()))
432 return DT->dominates(I->getParent(), BB);
436 const Type *SCEVUnknown::getType() const {
440 void SCEVUnknown::print(std::ostream &OS) const {
441 if (isa<PointerType>(V->getType()))
442 OS << "(ptrtoint " << *V->getType() << " ";
443 WriteAsOperand(OS, V, false);
444 if (isa<PointerType>(V->getType()))
448 //===----------------------------------------------------------------------===//
450 //===----------------------------------------------------------------------===//
453 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
454 /// than the complexity of the RHS. This comparator is used to canonicalize
456 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
457 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
458 return LHS->getSCEVType() < RHS->getSCEVType();
463 /// GroupByComplexity - Given a list of SCEV objects, order them by their
464 /// complexity, and group objects of the same complexity together by value.
465 /// When this routine is finished, we know that any duplicates in the vector are
466 /// consecutive and that complexity is monotonically increasing.
468 /// Note that we go take special precautions to ensure that we get determinstic
469 /// results from this routine. In other words, we don't want the results of
470 /// this to depend on where the addresses of various SCEV objects happened to
473 static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
474 if (Ops.size() < 2) return; // Noop
475 if (Ops.size() == 2) {
476 // This is the common case, which also happens to be trivially simple.
478 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
479 std::swap(Ops[0], Ops[1]);
483 // Do the rough sort by complexity.
484 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
486 // Now that we are sorted by complexity, group elements of the same
487 // complexity. Note that this is, at worst, N^2, but the vector is likely to
488 // be extremely short in practice. Note that we take this approach because we
489 // do not want to depend on the addresses of the objects we are grouping.
490 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
492 unsigned Complexity = S->getSCEVType();
494 // If there are any objects of the same complexity and same value as this
496 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
497 if (Ops[j] == S) { // Found a duplicate.
498 // Move it to immediately after i'th element.
499 std::swap(Ops[i+1], Ops[j]);
500 ++i; // no need to rescan it.
501 if (i == e-2) return; // Done!
509 //===----------------------------------------------------------------------===//
510 // Simple SCEV method implementations
511 //===----------------------------------------------------------------------===//
513 /// BinomialCoefficient - Compute BC(It, K). The result has width W.
515 static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
517 const Type* ResultTy) {
518 // Handle the simplest case efficiently.
520 return SE.getTruncateOrZeroExtend(It, ResultTy);
522 // We are using the following formula for BC(It, K):
524 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
526 // Suppose, W is the bitwidth of the return value. We must be prepared for
527 // overflow. Hence, we must assure that the result of our computation is
528 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
529 // safe in modular arithmetic.
531 // However, this code doesn't use exactly that formula; the formula it uses
532 // is something like the following, where T is the number of factors of 2 in
533 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
536 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
538 // This formula is trivially equivalent to the previous formula. However,
539 // this formula can be implemented much more efficiently. The trick is that
540 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
541 // arithmetic. To do exact division in modular arithmetic, all we have
542 // to do is multiply by the inverse. Therefore, this step can be done at
545 // The next issue is how to safely do the division by 2^T. The way this
546 // is done is by doing the multiplication step at a width of at least W + T
547 // bits. This way, the bottom W+T bits of the product are accurate. Then,
548 // when we perform the division by 2^T (which is equivalent to a right shift
549 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
550 // truncated out after the division by 2^T.
552 // In comparison to just directly using the first formula, this technique
553 // is much more efficient; using the first formula requires W * K bits,
554 // but this formula less than W + K bits. Also, the first formula requires
555 // a division step, whereas this formula only requires multiplies and shifts.
557 // It doesn't matter whether the subtraction step is done in the calculation
558 // width or the input iteration count's width; if the subtraction overflows,
559 // the result must be zero anyway. We prefer here to do it in the width of
560 // the induction variable because it helps a lot for certain cases; CodeGen
561 // isn't smart enough to ignore the overflow, which leads to much less
562 // efficient code if the width of the subtraction is wider than the native
565 // (It's possible to not widen at all by pulling out factors of 2 before
566 // the multiplication; for example, K=2 can be calculated as
567 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
568 // extra arithmetic, so it's not an obvious win, and it gets
569 // much more complicated for K > 3.)
571 // Protection from insane SCEVs; this bound is conservative,
572 // but it probably doesn't matter.
574 return new SCEVCouldNotCompute();
576 unsigned W = SE.getTargetData().getTypeSizeInBits(ResultTy);
578 // Calculate K! / 2^T and T; we divide out the factors of two before
579 // multiplying for calculating K! / 2^T to avoid overflow.
580 // Other overflow doesn't matter because we only care about the bottom
581 // W bits of the result.
582 APInt OddFactorial(W, 1);
584 for (unsigned i = 3; i <= K; ++i) {
586 unsigned TwoFactors = Mult.countTrailingZeros();
588 Mult = Mult.lshr(TwoFactors);
589 OddFactorial *= Mult;
592 // We need at least W + T bits for the multiplication step
593 unsigned CalculationBits = W + T;
595 // Calcuate 2^T, at width T+W.
596 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
598 // Calculate the multiplicative inverse of K! / 2^T;
599 // this multiplication factor will perform the exact division by
601 APInt Mod = APInt::getSignedMinValue(W+1);
602 APInt MultiplyFactor = OddFactorial.zext(W+1);
603 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
604 MultiplyFactor = MultiplyFactor.trunc(W);
606 // Calculate the product, at width T+W
607 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
608 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
609 for (unsigned i = 1; i != K; ++i) {
610 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
611 Dividend = SE.getMulExpr(Dividend,
612 SE.getTruncateOrZeroExtend(S, CalculationTy));
616 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
618 // Truncate the result, and divide by K! / 2^T.
620 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
621 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
624 /// evaluateAtIteration - Return the value of this chain of recurrences at
625 /// the specified iteration number. We can evaluate this recurrence by
626 /// multiplying each element in the chain by the binomial coefficient
627 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
629 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
631 /// where BC(It, k) stands for binomial coefficient.
633 SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
634 ScalarEvolution &SE) const {
635 SCEVHandle Result = getStart();
636 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
637 // The computation is correct in the face of overflow provided that the
638 // multiplication is performed _after_ the evaluation of the binomial
640 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
641 if (isa<SCEVCouldNotCompute>(Coeff))
644 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
649 //===----------------------------------------------------------------------===//
650 // SCEV Expression folder implementations
651 //===----------------------------------------------------------------------===//
653 SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
654 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
656 ConstantExpr::getTrunc(SC->getValue(), Ty));
658 // If the input value is a chrec scev made out of constants, truncate
659 // all of the constants.
660 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
661 std::vector<SCEVHandle> Operands;
662 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
663 // FIXME: This should allow truncation of other expression types!
664 if (isa<SCEVConstant>(AddRec->getOperand(i)))
665 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
668 if (Operands.size() == AddRec->getNumOperands())
669 return getAddRecExpr(Operands, AddRec->getLoop());
672 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
673 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
677 SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty) {
678 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
679 const Type *IntTy = Ty;
680 if (isa<PointerType>(IntTy)) IntTy = getTargetData().getIntPtrType();
681 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
682 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
683 return getUnknown(C);
686 // FIXME: If the input value is a chrec scev, and we can prove that the value
687 // did not overflow the old, smaller, value, we can zero extend all of the
688 // operands (often constants). This would allow analysis of something like
689 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
691 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
692 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
696 SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
697 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
698 const Type *IntTy = Ty;
699 if (isa<PointerType>(IntTy)) IntTy = getTargetData().getIntPtrType();
700 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
701 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
702 return getUnknown(C);
705 // FIXME: If the input value is a chrec scev, and we can prove that the value
706 // did not overflow the old, smaller, value, we can sign extend all of the
707 // operands (often constants). This would allow analysis of something like
708 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
710 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
711 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
715 // get - Get a canonical add expression, or something simpler if possible.
716 SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
717 assert(!Ops.empty() && "Cannot get empty add!");
718 if (Ops.size() == 1) return Ops[0];
720 // Sort by complexity, this groups all similar expression types together.
721 GroupByComplexity(Ops);
723 // If there are any constants, fold them together.
725 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
727 assert(Idx < Ops.size());
728 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
729 // We found two constants, fold them together!
730 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
731 RHSC->getValue()->getValue());
732 Ops[0] = getConstant(Fold);
733 Ops.erase(Ops.begin()+1); // Erase the folded element
734 if (Ops.size() == 1) return Ops[0];
735 LHSC = cast<SCEVConstant>(Ops[0]);
738 // If we are left with a constant zero being added, strip it off.
739 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
740 Ops.erase(Ops.begin());
745 if (Ops.size() == 1) return Ops[0];
747 // Okay, check to see if the same value occurs in the operand list twice. If
748 // so, merge them together into an multiply expression. Since we sorted the
749 // list, these values are required to be adjacent.
750 const Type *Ty = Ops[0]->getType();
751 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
752 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
753 // Found a match, merge the two values into a multiply, and add any
754 // remaining values to the result.
755 SCEVHandle Two = getIntegerSCEV(2, Ty);
756 SCEVHandle Mul = getMulExpr(Ops[i], Two);
759 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
761 return getAddExpr(Ops);
764 // Now we know the first non-constant operand. Skip past any cast SCEVs.
765 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
768 // If there are add operands they would be next.
769 if (Idx < Ops.size()) {
770 bool DeletedAdd = false;
771 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
772 // If we have an add, expand the add operands onto the end of the operands
774 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
775 Ops.erase(Ops.begin()+Idx);
779 // If we deleted at least one add, we added operands to the end of the list,
780 // and they are not necessarily sorted. Recurse to resort and resimplify
781 // any operands we just aquired.
783 return getAddExpr(Ops);
786 // Skip over the add expression until we get to a multiply.
787 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
790 // If we are adding something to a multiply expression, make sure the
791 // something is not already an operand of the multiply. If so, merge it into
793 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
794 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
795 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
796 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
797 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
798 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
799 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
800 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
801 if (Mul->getNumOperands() != 2) {
802 // If the multiply has more than two operands, we must get the
804 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
805 MulOps.erase(MulOps.begin()+MulOp);
806 InnerMul = getMulExpr(MulOps);
808 SCEVHandle One = getIntegerSCEV(1, Ty);
809 SCEVHandle AddOne = getAddExpr(InnerMul, One);
810 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
811 if (Ops.size() == 2) return OuterMul;
813 Ops.erase(Ops.begin()+AddOp);
814 Ops.erase(Ops.begin()+Idx-1);
816 Ops.erase(Ops.begin()+Idx);
817 Ops.erase(Ops.begin()+AddOp-1);
819 Ops.push_back(OuterMul);
820 return getAddExpr(Ops);
823 // Check this multiply against other multiplies being added together.
824 for (unsigned OtherMulIdx = Idx+1;
825 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
827 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
828 // If MulOp occurs in OtherMul, we can fold the two multiplies
830 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
831 OMulOp != e; ++OMulOp)
832 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
833 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
834 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
835 if (Mul->getNumOperands() != 2) {
836 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
837 MulOps.erase(MulOps.begin()+MulOp);
838 InnerMul1 = getMulExpr(MulOps);
840 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
841 if (OtherMul->getNumOperands() != 2) {
842 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
844 MulOps.erase(MulOps.begin()+OMulOp);
845 InnerMul2 = getMulExpr(MulOps);
847 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
848 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
849 if (Ops.size() == 2) return OuterMul;
850 Ops.erase(Ops.begin()+Idx);
851 Ops.erase(Ops.begin()+OtherMulIdx-1);
852 Ops.push_back(OuterMul);
853 return getAddExpr(Ops);
859 // If there are any add recurrences in the operands list, see if any other
860 // added values are loop invariant. If so, we can fold them into the
862 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
865 // Scan over all recurrences, trying to fold loop invariants into them.
866 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
867 // Scan all of the other operands to this add and add them to the vector if
868 // they are loop invariant w.r.t. the recurrence.
869 std::vector<SCEVHandle> LIOps;
870 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
871 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
872 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
873 LIOps.push_back(Ops[i]);
874 Ops.erase(Ops.begin()+i);
878 // If we found some loop invariants, fold them into the recurrence.
879 if (!LIOps.empty()) {
880 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
881 LIOps.push_back(AddRec->getStart());
883 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
884 AddRecOps[0] = getAddExpr(LIOps);
886 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
887 // If all of the other operands were loop invariant, we are done.
888 if (Ops.size() == 1) return NewRec;
890 // Otherwise, add the folded AddRec by the non-liv parts.
891 for (unsigned i = 0;; ++i)
892 if (Ops[i] == AddRec) {
896 return getAddExpr(Ops);
899 // Okay, if there weren't any loop invariants to be folded, check to see if
900 // there are multiple AddRec's with the same loop induction variable being
901 // added together. If so, we can fold them.
902 for (unsigned OtherIdx = Idx+1;
903 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
904 if (OtherIdx != Idx) {
905 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
906 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
907 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
908 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
909 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
910 if (i >= NewOps.size()) {
911 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
912 OtherAddRec->op_end());
915 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
917 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
919 if (Ops.size() == 2) return NewAddRec;
921 Ops.erase(Ops.begin()+Idx);
922 Ops.erase(Ops.begin()+OtherIdx-1);
923 Ops.push_back(NewAddRec);
924 return getAddExpr(Ops);
928 // Otherwise couldn't fold anything into this recurrence. Move onto the
932 // Okay, it looks like we really DO need an add expr. Check to see if we
933 // already have one, otherwise create a new one.
934 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
935 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
937 if (Result == 0) Result = new SCEVAddExpr(Ops);
942 SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
943 assert(!Ops.empty() && "Cannot get empty mul!");
945 // Sort by complexity, this groups all similar expression types together.
946 GroupByComplexity(Ops);
948 // If there are any constants, fold them together.
950 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
952 // C1*(C2+V) -> C1*C2 + C1*V
954 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
955 if (Add->getNumOperands() == 2 &&
956 isa<SCEVConstant>(Add->getOperand(0)))
957 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
958 getMulExpr(LHSC, Add->getOperand(1)));
962 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
963 // We found two constants, fold them together!
964 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
965 RHSC->getValue()->getValue());
966 Ops[0] = getConstant(Fold);
967 Ops.erase(Ops.begin()+1); // Erase the folded element
968 if (Ops.size() == 1) return Ops[0];
969 LHSC = cast<SCEVConstant>(Ops[0]);
972 // If we are left with a constant one being multiplied, strip it off.
973 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
974 Ops.erase(Ops.begin());
976 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
977 // If we have a multiply of zero, it will always be zero.
982 // Skip over the add expression until we get to a multiply.
983 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
989 // If there are mul operands inline them all into this expression.
990 if (Idx < Ops.size()) {
991 bool DeletedMul = false;
992 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
993 // If we have an mul, expand the mul operands onto the end of the operands
995 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
996 Ops.erase(Ops.begin()+Idx);
1000 // If we deleted at least one mul, we added operands to the end of the list,
1001 // and they are not necessarily sorted. Recurse to resort and resimplify
1002 // any operands we just aquired.
1004 return getMulExpr(Ops);
1007 // If there are any add recurrences in the operands list, see if any other
1008 // added values are loop invariant. If so, we can fold them into the
1010 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1013 // Scan over all recurrences, trying to fold loop invariants into them.
1014 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1015 // Scan all of the other operands to this mul and add them to the vector if
1016 // they are loop invariant w.r.t. the recurrence.
1017 std::vector<SCEVHandle> LIOps;
1018 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1019 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1020 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1021 LIOps.push_back(Ops[i]);
1022 Ops.erase(Ops.begin()+i);
1026 // If we found some loop invariants, fold them into the recurrence.
1027 if (!LIOps.empty()) {
1028 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
1029 std::vector<SCEVHandle> NewOps;
1030 NewOps.reserve(AddRec->getNumOperands());
1031 if (LIOps.size() == 1) {
1032 SCEV *Scale = LIOps[0];
1033 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1034 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1036 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1037 std::vector<SCEVHandle> MulOps(LIOps);
1038 MulOps.push_back(AddRec->getOperand(i));
1039 NewOps.push_back(getMulExpr(MulOps));
1043 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
1045 // If all of the other operands were loop invariant, we are done.
1046 if (Ops.size() == 1) return NewRec;
1048 // Otherwise, multiply the folded AddRec by the non-liv parts.
1049 for (unsigned i = 0;; ++i)
1050 if (Ops[i] == AddRec) {
1054 return getMulExpr(Ops);
1057 // Okay, if there weren't any loop invariants to be folded, check to see if
1058 // there are multiple AddRec's with the same loop induction variable being
1059 // multiplied together. If so, we can fold them.
1060 for (unsigned OtherIdx = Idx+1;
1061 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1062 if (OtherIdx != Idx) {
1063 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1064 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1065 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1066 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1067 SCEVHandle NewStart = getMulExpr(F->getStart(),
1069 SCEVHandle B = F->getStepRecurrence(*this);
1070 SCEVHandle D = G->getStepRecurrence(*this);
1071 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1074 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1076 if (Ops.size() == 2) return NewAddRec;
1078 Ops.erase(Ops.begin()+Idx);
1079 Ops.erase(Ops.begin()+OtherIdx-1);
1080 Ops.push_back(NewAddRec);
1081 return getMulExpr(Ops);
1085 // Otherwise couldn't fold anything into this recurrence. Move onto the
1089 // Okay, it looks like we really DO need an mul expr. Check to see if we
1090 // already have one, otherwise create a new one.
1091 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1092 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1095 Result = new SCEVMulExpr(Ops);
1099 SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1100 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1101 if (RHSC->getValue()->equalsInt(1))
1102 return LHS; // X udiv 1 --> x
1104 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1105 Constant *LHSCV = LHSC->getValue();
1106 Constant *RHSCV = RHSC->getValue();
1107 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
1111 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1113 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1114 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
1119 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1120 /// specified loop. Simplify the expression as much as possible.
1121 SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
1122 const SCEVHandle &Step, const Loop *L) {
1123 std::vector<SCEVHandle> Operands;
1124 Operands.push_back(Start);
1125 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1126 if (StepChrec->getLoop() == L) {
1127 Operands.insert(Operands.end(), StepChrec->op_begin(),
1128 StepChrec->op_end());
1129 return getAddRecExpr(Operands, L);
1132 Operands.push_back(Step);
1133 return getAddRecExpr(Operands, L);
1136 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1137 /// specified loop. Simplify the expression as much as possible.
1138 SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
1140 if (Operands.size() == 1) return Operands[0];
1142 if (Operands.back()->isZero()) {
1143 Operands.pop_back();
1144 return getAddRecExpr(Operands, L); // {X,+,0} --> X
1147 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1148 if (SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1149 const Loop* NestedLoop = NestedAR->getLoop();
1150 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1151 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1152 NestedAR->op_end());
1153 SCEVHandle NestedARHandle(NestedAR);
1154 Operands[0] = NestedAR->getStart();
1155 NestedOperands[0] = getAddRecExpr(Operands, L);
1156 return getAddRecExpr(NestedOperands, NestedLoop);
1160 SCEVAddRecExpr *&Result =
1161 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1163 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1167 SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1168 const SCEVHandle &RHS) {
1169 std::vector<SCEVHandle> Ops;
1172 return getSMaxExpr(Ops);
1175 SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1176 assert(!Ops.empty() && "Cannot get empty smax!");
1177 if (Ops.size() == 1) return Ops[0];
1179 // Sort by complexity, this groups all similar expression types together.
1180 GroupByComplexity(Ops);
1182 // If there are any constants, fold them together.
1184 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1186 assert(Idx < Ops.size());
1187 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1188 // We found two constants, fold them together!
1189 ConstantInt *Fold = ConstantInt::get(
1190 APIntOps::smax(LHSC->getValue()->getValue(),
1191 RHSC->getValue()->getValue()));
1192 Ops[0] = getConstant(Fold);
1193 Ops.erase(Ops.begin()+1); // Erase the folded element
1194 if (Ops.size() == 1) return Ops[0];
1195 LHSC = cast<SCEVConstant>(Ops[0]);
1198 // If we are left with a constant -inf, strip it off.
1199 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1200 Ops.erase(Ops.begin());
1205 if (Ops.size() == 1) return Ops[0];
1207 // Find the first SMax
1208 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1211 // Check to see if one of the operands is an SMax. If so, expand its operands
1212 // onto our operand list, and recurse to simplify.
1213 if (Idx < Ops.size()) {
1214 bool DeletedSMax = false;
1215 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1216 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1217 Ops.erase(Ops.begin()+Idx);
1222 return getSMaxExpr(Ops);
1225 // Okay, check to see if the same value occurs in the operand list twice. If
1226 // so, delete one. Since we sorted the list, these values are required to
1228 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1229 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1230 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1234 if (Ops.size() == 1) return Ops[0];
1236 assert(!Ops.empty() && "Reduced smax down to nothing!");
1238 // Okay, it looks like we really DO need an smax expr. Check to see if we
1239 // already have one, otherwise create a new one.
1240 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1241 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1243 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1247 SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1248 const SCEVHandle &RHS) {
1249 std::vector<SCEVHandle> Ops;
1252 return getUMaxExpr(Ops);
1255 SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1256 assert(!Ops.empty() && "Cannot get empty umax!");
1257 if (Ops.size() == 1) return Ops[0];
1259 // Sort by complexity, this groups all similar expression types together.
1260 GroupByComplexity(Ops);
1262 // If there are any constants, fold them together.
1264 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1266 assert(Idx < Ops.size());
1267 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1268 // We found two constants, fold them together!
1269 ConstantInt *Fold = ConstantInt::get(
1270 APIntOps::umax(LHSC->getValue()->getValue(),
1271 RHSC->getValue()->getValue()));
1272 Ops[0] = getConstant(Fold);
1273 Ops.erase(Ops.begin()+1); // Erase the folded element
1274 if (Ops.size() == 1) return Ops[0];
1275 LHSC = cast<SCEVConstant>(Ops[0]);
1278 // If we are left with a constant zero, strip it off.
1279 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1280 Ops.erase(Ops.begin());
1285 if (Ops.size() == 1) return Ops[0];
1287 // Find the first UMax
1288 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1291 // Check to see if one of the operands is a UMax. If so, expand its operands
1292 // onto our operand list, and recurse to simplify.
1293 if (Idx < Ops.size()) {
1294 bool DeletedUMax = false;
1295 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1296 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1297 Ops.erase(Ops.begin()+Idx);
1302 return getUMaxExpr(Ops);
1305 // Okay, check to see if the same value occurs in the operand list twice. If
1306 // so, delete one. Since we sorted the list, these values are required to
1308 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1309 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1310 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1314 if (Ops.size() == 1) return Ops[0];
1316 assert(!Ops.empty() && "Reduced umax down to nothing!");
1318 // Okay, it looks like we really DO need a umax expr. Check to see if we
1319 // already have one, otherwise create a new one.
1320 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1321 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1323 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1327 SCEVHandle ScalarEvolution::getUnknown(Value *V) {
1328 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1329 return getConstant(CI);
1330 if (isa<ConstantPointerNull>(V))
1331 return getIntegerSCEV(0, V->getType());
1332 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1333 if (Result == 0) Result = new SCEVUnknown(V);
1338 //===----------------------------------------------------------------------===//
1339 // ScalarEvolutionsImpl Definition and Implementation
1340 //===----------------------------------------------------------------------===//
1342 /// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1346 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
1347 /// SE - A reference to the public ScalarEvolution object.
1348 ScalarEvolution &SE;
1350 /// F - The function we are analyzing.
1354 /// LI - The loop information for the function we are currently analyzing.
1358 /// TD - The target data information for the target we are targetting.
1362 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1364 SCEVHandle UnknownValue;
1366 /// Scalars - This is a cache of the scalars we have analyzed so far.
1368 std::map<Value*, SCEVHandle> Scalars;
1370 /// BackedgeTakenCounts - Cache the backedge-taken count of the loops for
1371 /// this function as they are computed.
1372 std::map<const Loop*, SCEVHandle> BackedgeTakenCounts;
1374 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1375 /// the PHI instructions that we attempt to compute constant evolutions for.
1376 /// This allows us to avoid potentially expensive recomputation of these
1377 /// properties. An instruction maps to null if we are unable to compute its
1379 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
1382 ScalarEvolutionsImpl(ScalarEvolution &se, Function &f, LoopInfo &li,
1384 : SE(se), F(f), LI(li), TD(td), UnknownValue(new SCEVCouldNotCompute()) {}
1386 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
1387 /// specified signed integer value and return a SCEV for the constant.
1388 SCEVHandle getIntegerSCEV(int Val, const Type *Ty);
1390 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1392 SCEVHandle getNegativeSCEV(const SCEVHandle &V);
1394 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
1396 SCEVHandle getNotSCEV(const SCEVHandle &V);
1398 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1400 SCEVHandle getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS);
1402 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
1403 /// of the input value to the specified type. If the type must be extended,
1404 /// it is zero extended.
1405 SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty);
1407 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
1408 /// of the input value to the specified type. If the type must be extended,
1409 /// it is sign extended.
1410 SCEVHandle getTruncateOrSignExtend(const SCEVHandle &V, const Type *Ty);
1412 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1413 /// expression and create a new one.
1414 SCEVHandle getSCEV(Value *V);
1416 /// hasSCEV - Return true if the SCEV for this value has already been
1418 bool hasSCEV(Value *V) const {
1419 return Scalars.count(V);
1422 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1423 /// the specified value.
1424 void setSCEV(Value *V, const SCEVHandle &H) {
1425 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1426 assert(isNew && "This entry already existed!");
1431 /// getSCEVAtScope - Compute the value of the specified expression within
1432 /// the indicated loop (which may be null to indicate in no loop). If the
1433 /// expression cannot be evaluated, return UnknownValue itself.
1434 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1437 /// isLoopGuardedByCond - Test whether entry to the loop is protected by
1438 /// a conditional between LHS and RHS.
1439 bool isLoopGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
1440 SCEV *LHS, SCEV *RHS);
1442 /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop
1443 /// has an analyzable loop-invariant backedge-taken count.
1444 bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
1446 /// forgetLoopBackedgeTakenCount - This method should be called by the
1447 /// client when it has changed a loop in a way that may effect
1448 /// ScalarEvolution's ability to compute a trip count, or if the loop
1450 void forgetLoopBackedgeTakenCount(const Loop *L);
1452 /// getBackedgeTakenCount - If the specified loop has a predictable
1453 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
1454 /// object. The backedge-taken count is the number of times the loop header
1455 /// will be branched to from within the loop. This is one less than the
1456 /// trip count of the loop, since it doesn't count the first iteration,
1457 /// when the header is branched to from outside the loop.
1459 /// Note that it is not valid to call this method on a loop without a
1460 /// loop-invariant backedge-taken count (see
1461 /// hasLoopInvariantBackedgeTakenCount).
1463 SCEVHandle getBackedgeTakenCount(const Loop *L);
1465 /// deleteValueFromRecords - This method should be called by the
1466 /// client before it removes a value from the program, to make sure
1467 /// that no dangling references are left around.
1468 void deleteValueFromRecords(Value *V);
1470 /// getTargetData - Return the TargetData.
1471 const TargetData &getTargetData() const;
1474 /// createSCEV - We know that there is no SCEV for the specified value.
1475 /// Analyze the expression.
1476 SCEVHandle createSCEV(Value *V);
1478 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1480 SCEVHandle createNodeForPHI(PHINode *PN);
1482 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1483 /// for the specified instruction and replaces any references to the
1484 /// symbolic value SymName with the specified value. This is used during
1486 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1487 const SCEVHandle &SymName,
1488 const SCEVHandle &NewVal);
1490 /// ComputeBackedgeTakenCount - Compute the number of times the specified
1491 /// loop will iterate.
1492 SCEVHandle ComputeBackedgeTakenCount(const Loop *L);
1494 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition
1495 /// of 'icmp op load X, cst', try to see if we can compute the trip count.
1497 ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI,
1500 ICmpInst::Predicate p);
1502 /// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute
1503 /// a constant number of times (the condition evolves only from constants),
1504 /// try to evaluate a few iterations of the loop until we get the exit
1505 /// condition gets a value of ExitWhen (true or false). If we cannot
1506 /// evaluate the trip count of the loop, return UnknownValue.
1507 SCEVHandle ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond,
1510 /// HowFarToZero - Return the number of times a backedge comparing the
1511 /// specified value to zero will execute. If not computable, return
1513 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1515 /// HowFarToNonZero - Return the number of times a backedge checking the
1516 /// specified value for nonzero will execute. If not computable, return
1518 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
1520 /// HowManyLessThans - Return the number of times a backedge containing the
1521 /// specified less-than comparison will execute. If not computable, return
1522 /// UnknownValue. isSigned specifies whether the less-than is signed.
1523 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
1526 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
1527 /// (which may not be an immediate predecessor) which has exactly one
1528 /// successor from which BB is reachable, or null if no such block is
1530 BasicBlock* getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
1532 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1533 /// in the header of its containing loop, we know the loop executes a
1534 /// constant number of times, and the PHI node is just a recurrence
1535 /// involving constants, fold it.
1536 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs,
1541 //===----------------------------------------------------------------------===//
1542 // Basic SCEV Analysis and PHI Idiom Recognition Code
1545 /// deleteValueFromRecords - This method should be called by the
1546 /// client before it removes an instruction from the program, to make sure
1547 /// that no dangling references are left around.
1548 void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) {
1549 SmallVector<Value *, 16> Worklist;
1551 if (Scalars.erase(V)) {
1552 if (PHINode *PN = dyn_cast<PHINode>(V))
1553 ConstantEvolutionLoopExitValue.erase(PN);
1554 Worklist.push_back(V);
1557 while (!Worklist.empty()) {
1558 Value *VV = Worklist.back();
1559 Worklist.pop_back();
1561 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
1563 Instruction *Inst = cast<Instruction>(*UI);
1564 if (Scalars.erase(Inst)) {
1565 if (PHINode *PN = dyn_cast<PHINode>(VV))
1566 ConstantEvolutionLoopExitValue.erase(PN);
1567 Worklist.push_back(Inst);
1573 const TargetData &ScalarEvolutionsImpl::getTargetData() const {
1577 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1578 /// expression and create a new one.
1579 SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1580 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1582 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1583 if (I != Scalars.end()) return I->second;
1584 SCEVHandle S = createSCEV(V);
1585 Scalars.insert(std::make_pair(V, S));
1589 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
1590 /// specified signed integer value and return a SCEV for the constant.
1591 SCEVHandle ScalarEvolutionsImpl::getIntegerSCEV(int Val, const Type *Ty) {
1592 if (isa<PointerType>(Ty))
1593 Ty = TD.getIntPtrType();
1596 C = Constant::getNullValue(Ty);
1597 else if (Ty->isFloatingPoint())
1598 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1599 APFloat::IEEEdouble, Val));
1601 C = ConstantInt::get(Ty, Val);
1602 return SE.getUnknown(C);
1605 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1607 SCEVHandle ScalarEvolutionsImpl::getNegativeSCEV(const SCEVHandle &V) {
1608 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
1609 return SE.getUnknown(ConstantExpr::getNeg(VC->getValue()));
1611 const Type *Ty = V->getType();
1612 if (isa<PointerType>(Ty))
1613 Ty = TD.getIntPtrType();
1614 return SE.getMulExpr(V, SE.getConstant(ConstantInt::getAllOnesValue(Ty)));
1617 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
1618 SCEVHandle ScalarEvolutionsImpl::getNotSCEV(const SCEVHandle &V) {
1619 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
1620 return SE.getUnknown(ConstantExpr::getNot(VC->getValue()));
1622 const Type *Ty = V->getType();
1623 if (isa<PointerType>(Ty))
1624 Ty = TD.getIntPtrType();
1625 SCEVHandle AllOnes = SE.getConstant(ConstantInt::getAllOnesValue(Ty));
1626 return getMinusSCEV(AllOnes, V);
1629 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1631 SCEVHandle ScalarEvolutionsImpl::getMinusSCEV(const SCEVHandle &LHS,
1632 const SCEVHandle &RHS) {
1634 return SE.getAddExpr(LHS, SE.getNegativeSCEV(RHS));
1637 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1638 /// input value to the specified type. If the type must be extended, it is zero
1641 ScalarEvolutionsImpl::getTruncateOrZeroExtend(const SCEVHandle &V,
1643 const Type *SrcTy = V->getType();
1644 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
1645 (Ty->isInteger() || isa<PointerType>(Ty)) &&
1646 "Cannot truncate or zero extend with non-integer arguments!");
1647 if (TD.getTypeSizeInBits(SrcTy) == TD.getTypeSizeInBits(Ty))
1648 return V; // No conversion
1649 if (TD.getTypeSizeInBits(SrcTy) > TD.getTypeSizeInBits(Ty))
1650 return SE.getTruncateExpr(V, Ty);
1651 return SE.getZeroExtendExpr(V, Ty);
1654 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1655 /// input value to the specified type. If the type must be extended, it is sign
1658 ScalarEvolutionsImpl::getTruncateOrSignExtend(const SCEVHandle &V,
1660 const Type *SrcTy = V->getType();
1661 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
1662 (Ty->isInteger() || isa<PointerType>(Ty)) &&
1663 "Cannot truncate or zero extend with non-integer arguments!");
1664 if (TD.getTypeSizeInBits(SrcTy) == TD.getTypeSizeInBits(Ty))
1665 return V; // No conversion
1666 if (TD.getTypeSizeInBits(SrcTy) > TD.getTypeSizeInBits(Ty))
1667 return SE.getTruncateExpr(V, Ty);
1668 return SE.getSignExtendExpr(V, Ty);
1671 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1672 /// the specified instruction and replaces any references to the symbolic value
1673 /// SymName with the specified value. This is used during PHI resolution.
1674 void ScalarEvolutionsImpl::
1675 ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1676 const SCEVHandle &NewVal) {
1677 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1678 if (SI == Scalars.end()) return;
1681 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, SE);
1682 if (NV == SI->second) return; // No change.
1684 SI->second = NV; // Update the scalars map!
1686 // Any instruction values that use this instruction might also need to be
1688 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1690 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1693 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1694 /// a loop header, making it a potential recurrence, or it doesn't.
1696 SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1697 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1698 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1699 if (L->getHeader() == PN->getParent()) {
1700 // If it lives in the loop header, it has two incoming values, one
1701 // from outside the loop, and one from inside.
1702 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1703 unsigned BackEdge = IncomingEdge^1;
1705 // While we are analyzing this PHI node, handle its value symbolically.
1706 SCEVHandle SymbolicName = SE.getUnknown(PN);
1707 assert(Scalars.find(PN) == Scalars.end() &&
1708 "PHI node already processed?");
1709 Scalars.insert(std::make_pair(PN, SymbolicName));
1711 // Using this symbolic name for the PHI, analyze the value coming around
1713 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1715 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1716 // has a special value for the first iteration of the loop.
1718 // If the value coming around the backedge is an add with the symbolic
1719 // value we just inserted, then we found a simple induction variable!
1720 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1721 // If there is a single occurrence of the symbolic value, replace it
1722 // with a recurrence.
1723 unsigned FoundIndex = Add->getNumOperands();
1724 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1725 if (Add->getOperand(i) == SymbolicName)
1726 if (FoundIndex == e) {
1731 if (FoundIndex != Add->getNumOperands()) {
1732 // Create an add with everything but the specified operand.
1733 std::vector<SCEVHandle> Ops;
1734 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1735 if (i != FoundIndex)
1736 Ops.push_back(Add->getOperand(i));
1737 SCEVHandle Accum = SE.getAddExpr(Ops);
1739 // This is not a valid addrec if the step amount is varying each
1740 // loop iteration, but is not itself an addrec in this loop.
1741 if (Accum->isLoopInvariant(L) ||
1742 (isa<SCEVAddRecExpr>(Accum) &&
1743 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1744 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1745 SCEVHandle PHISCEV = SE.getAddRecExpr(StartVal, Accum, L);
1747 // Okay, for the entire analysis of this edge we assumed the PHI
1748 // to be symbolic. We now need to go back and update all of the
1749 // entries for the scalars that use the PHI (except for the PHI
1750 // itself) to use the new analyzed value instead of the "symbolic"
1752 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1756 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1757 // Otherwise, this could be a loop like this:
1758 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1759 // In this case, j = {1,+,1} and BEValue is j.
1760 // Because the other in-value of i (0) fits the evolution of BEValue
1761 // i really is an addrec evolution.
1762 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1763 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1765 // If StartVal = j.start - j.stride, we can use StartVal as the
1766 // initial step of the addrec evolution.
1767 if (StartVal == SE.getMinusSCEV(AddRec->getOperand(0),
1768 AddRec->getOperand(1))) {
1769 SCEVHandle PHISCEV =
1770 SE.getAddRecExpr(StartVal, AddRec->getOperand(1), L);
1772 // Okay, for the entire analysis of this edge we assumed the PHI
1773 // to be symbolic. We now need to go back and update all of the
1774 // entries for the scalars that use the PHI (except for the PHI
1775 // itself) to use the new analyzed value instead of the "symbolic"
1777 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1783 return SymbolicName;
1786 // If it's not a loop phi, we can't handle it yet.
1787 return SE.getUnknown(PN);
1790 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1791 /// guaranteed to end in (at every loop iteration). It is, at the same time,
1792 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1793 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
1794 static uint32_t GetMinTrailingZeros(SCEVHandle S, const TargetData &TD) {
1795 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
1796 return C->getValue()->getValue().countTrailingZeros();
1798 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
1799 return std::min(GetMinTrailingZeros(T->getOperand(), TD),
1800 (uint32_t)TD.getTypeSizeInBits(T->getType()));
1802 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
1803 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), TD);
1804 return OpRes == TD.getTypeSizeInBits(E->getOperand()->getType()) ?
1805 TD.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
1808 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
1809 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), TD);
1810 return OpRes == TD.getTypeSizeInBits(E->getOperand()->getType()) ?
1811 TD.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
1814 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
1815 // The result is the min of all operands results.
1816 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), TD);
1817 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1818 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), TD));
1822 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
1823 // The result is the sum of all operands results.
1824 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), TD);
1825 uint32_t BitWidth = TD.getTypeSizeInBits(M->getType());
1826 for (unsigned i = 1, e = M->getNumOperands();
1827 SumOpRes != BitWidth && i != e; ++i)
1828 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), TD),
1833 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
1834 // The result is the min of all operands results.
1835 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), TD);
1836 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1837 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), TD));
1841 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1842 // The result is the min of all operands results.
1843 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), TD);
1844 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1845 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), TD));
1849 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1850 // The result is the min of all operands results.
1851 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), TD);
1852 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1853 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), TD));
1857 // SCEVUDivExpr, SCEVUnknown
1861 /// createSCEV - We know that there is no SCEV for the specified value.
1862 /// Analyze the expression.
1864 SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1865 if (!isa<IntegerType>(V->getType()) &&
1866 !isa<PointerType>(V->getType()))
1867 return SE.getUnknown(V);
1869 unsigned Opcode = Instruction::UserOp1;
1870 if (Instruction *I = dyn_cast<Instruction>(V))
1871 Opcode = I->getOpcode();
1872 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1873 Opcode = CE->getOpcode();
1875 return SE.getUnknown(V);
1877 User *U = cast<User>(V);
1879 case Instruction::Add:
1880 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1881 getSCEV(U->getOperand(1)));
1882 case Instruction::Mul:
1883 return SE.getMulExpr(getSCEV(U->getOperand(0)),
1884 getSCEV(U->getOperand(1)));
1885 case Instruction::UDiv:
1886 return SE.getUDivExpr(getSCEV(U->getOperand(0)),
1887 getSCEV(U->getOperand(1)));
1888 case Instruction::Sub:
1889 return SE.getMinusSCEV(getSCEV(U->getOperand(0)),
1890 getSCEV(U->getOperand(1)));
1891 case Instruction::Or:
1892 // If the RHS of the Or is a constant, we may have something like:
1893 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1894 // optimizations will transparently handle this case.
1896 // In order for this transformation to be safe, the LHS must be of the
1897 // form X*(2^n) and the Or constant must be less than 2^n.
1898 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1899 SCEVHandle LHS = getSCEV(U->getOperand(0));
1900 const APInt &CIVal = CI->getValue();
1901 if (GetMinTrailingZeros(LHS, TD) >=
1902 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
1903 return SE.getAddExpr(LHS, getSCEV(U->getOperand(1)));
1906 case Instruction::Xor:
1907 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1908 // If the RHS of the xor is a signbit, then this is just an add.
1909 // Instcombine turns add of signbit into xor as a strength reduction step.
1910 if (CI->getValue().isSignBit())
1911 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1912 getSCEV(U->getOperand(1)));
1914 // If the RHS of xor is -1, then this is a not operation.
1915 else if (CI->isAllOnesValue())
1916 return SE.getNotSCEV(getSCEV(U->getOperand(0)));
1920 case Instruction::Shl:
1921 // Turn shift left of a constant amount into a multiply.
1922 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1923 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1924 Constant *X = ConstantInt::get(
1925 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1926 return SE.getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1930 case Instruction::LShr:
1931 // Turn logical shift right of a constant into a unsigned divide.
1932 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1933 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1934 Constant *X = ConstantInt::get(
1935 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1936 return SE.getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1940 case Instruction::Trunc:
1941 return SE.getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
1943 case Instruction::ZExt:
1944 return SE.getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1946 case Instruction::SExt:
1947 return SE.getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1949 case Instruction::BitCast:
1950 // BitCasts are no-op casts so we just eliminate the cast.
1951 if ((U->getType()->isInteger() ||
1952 isa<PointerType>(U->getType())) &&
1953 (U->getOperand(0)->getType()->isInteger() ||
1954 isa<PointerType>(U->getOperand(0)->getType())))
1955 return getSCEV(U->getOperand(0));
1958 case Instruction::IntToPtr:
1959 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
1960 TD.getIntPtrType());
1962 case Instruction::PtrToInt:
1963 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
1966 case Instruction::GetElementPtr: {
1967 const Type *IntPtrTy = TD.getIntPtrType();
1968 Value *Base = U->getOperand(0);
1969 SCEVHandle TotalOffset = SE.getIntegerSCEV(0, IntPtrTy);
1970 gep_type_iterator GTI = gep_type_begin(U);
1971 for (GetElementPtrInst::op_iterator I = next(U->op_begin()),
1975 // Compute the (potentially symbolic) offset in bytes for this index.
1976 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
1977 // For a struct, add the member offset.
1978 const StructLayout &SL = *TD.getStructLayout(STy);
1979 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
1980 uint64_t Offset = SL.getElementOffset(FieldNo);
1981 TotalOffset = SE.getAddExpr(TotalOffset,
1982 SE.getIntegerSCEV(Offset, IntPtrTy));
1984 // For an array, add the element offset, explicitly scaled.
1985 SCEVHandle LocalOffset = getSCEV(Index);
1986 if (!isa<PointerType>(LocalOffset->getType()))
1987 // Getelementptr indicies are signed.
1988 LocalOffset = getTruncateOrSignExtend(LocalOffset,
1991 SE.getMulExpr(LocalOffset,
1992 SE.getIntegerSCEV(TD.getTypePaddedSize(*GTI),
1994 TotalOffset = SE.getAddExpr(TotalOffset, LocalOffset);
1997 return SE.getAddExpr(getSCEV(Base), TotalOffset);
2000 case Instruction::PHI:
2001 return createNodeForPHI(cast<PHINode>(U));
2003 case Instruction::Select:
2004 // This could be a smax or umax that was lowered earlier.
2005 // Try to recover it.
2006 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2007 Value *LHS = ICI->getOperand(0);
2008 Value *RHS = ICI->getOperand(1);
2009 switch (ICI->getPredicate()) {
2010 case ICmpInst::ICMP_SLT:
2011 case ICmpInst::ICMP_SLE:
2012 std::swap(LHS, RHS);
2014 case ICmpInst::ICMP_SGT:
2015 case ICmpInst::ICMP_SGE:
2016 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2017 return SE.getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
2018 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2019 // ~smax(~x, ~y) == smin(x, y).
2020 return SE.getNotSCEV(SE.getSMaxExpr(
2021 SE.getNotSCEV(getSCEV(LHS)),
2022 SE.getNotSCEV(getSCEV(RHS))));
2024 case ICmpInst::ICMP_ULT:
2025 case ICmpInst::ICMP_ULE:
2026 std::swap(LHS, RHS);
2028 case ICmpInst::ICMP_UGT:
2029 case ICmpInst::ICMP_UGE:
2030 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2031 return SE.getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
2032 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2033 // ~umax(~x, ~y) == umin(x, y)
2034 return SE.getNotSCEV(SE.getUMaxExpr(SE.getNotSCEV(getSCEV(LHS)),
2035 SE.getNotSCEV(getSCEV(RHS))));
2042 default: // We cannot analyze this expression.
2046 return SE.getUnknown(V);
2051 //===----------------------------------------------------------------------===//
2052 // Iteration Count Computation Code
2055 /// getBackedgeTakenCount - If the specified loop has a predictable
2056 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2057 /// object. The backedge-taken count is the number of times the loop header
2058 /// will be branched to from within the loop. This is one less than the
2059 /// trip count of the loop, since it doesn't count the first iteration,
2060 /// when the header is branched to from outside the loop.
2062 /// Note that it is not valid to call this method on a loop without a
2063 /// loop-invariant backedge-taken count (see
2064 /// hasLoopInvariantBackedgeTakenCount).
2066 SCEVHandle ScalarEvolutionsImpl::getBackedgeTakenCount(const Loop *L) {
2067 std::map<const Loop*, SCEVHandle>::iterator I = BackedgeTakenCounts.find(L);
2068 if (I == BackedgeTakenCounts.end()) {
2069 SCEVHandle ItCount = ComputeBackedgeTakenCount(L);
2070 I = BackedgeTakenCounts.insert(std::make_pair(L, ItCount)).first;
2071 if (ItCount != UnknownValue) {
2072 assert(ItCount->isLoopInvariant(L) &&
2073 "Computed trip count isn't loop invariant for loop!");
2074 ++NumTripCountsComputed;
2075 } else if (isa<PHINode>(L->getHeader()->begin())) {
2076 // Only count loops that have phi nodes as not being computable.
2077 ++NumTripCountsNotComputed;
2083 /// forgetLoopBackedgeTakenCount - This method should be called by the
2084 /// client when it has changed a loop in a way that may effect
2085 /// ScalarEvolution's ability to compute a trip count, or if the loop
2087 void ScalarEvolutionsImpl::forgetLoopBackedgeTakenCount(const Loop *L) {
2088 BackedgeTakenCounts.erase(L);
2091 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
2092 /// of the specified loop will execute.
2093 SCEVHandle ScalarEvolutionsImpl::ComputeBackedgeTakenCount(const Loop *L) {
2094 // If the loop has a non-one exit block count, we can't analyze it.
2095 SmallVector<BasicBlock*, 8> ExitBlocks;
2096 L->getExitBlocks(ExitBlocks);
2097 if (ExitBlocks.size() != 1) return UnknownValue;
2099 // Okay, there is one exit block. Try to find the condition that causes the
2100 // loop to be exited.
2101 BasicBlock *ExitBlock = ExitBlocks[0];
2103 BasicBlock *ExitingBlock = 0;
2104 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
2106 if (L->contains(*PI)) {
2107 if (ExitingBlock == 0)
2110 return UnknownValue; // More than one block exiting!
2112 assert(ExitingBlock && "No exits from loop, something is broken!");
2114 // Okay, we've computed the exiting block. See what condition causes us to
2117 // FIXME: we should be able to handle switch instructions (with a single exit)
2118 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2119 if (ExitBr == 0) return UnknownValue;
2120 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2122 // At this point, we know we have a conditional branch that determines whether
2123 // the loop is exited. However, we don't know if the branch is executed each
2124 // time through the loop. If not, then the execution count of the branch will
2125 // not be equal to the trip count of the loop.
2127 // Currently we check for this by checking to see if the Exit branch goes to
2128 // the loop header. If so, we know it will always execute the same number of
2129 // times as the loop. We also handle the case where the exit block *is* the
2130 // loop header. This is common for un-rotated loops. More extensive analysis
2131 // could be done to handle more cases here.
2132 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2133 ExitBr->getSuccessor(1) != L->getHeader() &&
2134 ExitBr->getParent() != L->getHeader())
2135 return UnknownValue;
2137 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2139 // If it's not an integer comparison then compute it the hard way.
2140 // Note that ICmpInst deals with pointer comparisons too so we must check
2141 // the type of the operand.
2142 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
2143 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
2144 ExitBr->getSuccessor(0) == ExitBlock);
2146 // If the condition was exit on true, convert the condition to exit on false
2147 ICmpInst::Predicate Cond;
2148 if (ExitBr->getSuccessor(1) == ExitBlock)
2149 Cond = ExitCond->getPredicate();
2151 Cond = ExitCond->getInversePredicate();
2153 // Handle common loops like: for (X = "string"; *X; ++X)
2154 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2155 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2157 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
2158 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2161 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2162 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2164 // Try to evaluate any dependencies out of the loop.
2165 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2166 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2167 Tmp = getSCEVAtScope(RHS, L);
2168 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2170 // At this point, we would like to compute how many iterations of the
2171 // loop the predicate will return true for these inputs.
2172 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2173 // If there is a loop-invariant, force it into the RHS.
2174 std::swap(LHS, RHS);
2175 Cond = ICmpInst::getSwappedPredicate(Cond);
2178 // FIXME: think about handling pointer comparisons! i.e.:
2179 // while (P != P+100) ++P;
2181 // If we have a comparison of a chrec against a constant, try to use value
2182 // ranges to answer this query.
2183 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2184 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
2185 if (AddRec->getLoop() == L) {
2186 // Form the comparison range using the constant of the correct type so
2187 // that the ConstantRange class knows to do a signed or unsigned
2189 ConstantInt *CompVal = RHSC->getValue();
2190 const Type *RealTy = ExitCond->getOperand(0)->getType();
2191 CompVal = dyn_cast<ConstantInt>(
2192 ConstantExpr::getBitCast(CompVal, RealTy));
2194 // Form the constant range.
2195 ConstantRange CompRange(
2196 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
2198 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE);
2199 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2204 case ICmpInst::ICMP_NE: { // while (X != Y)
2205 // Convert to: while (X-Y != 0)
2206 SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
2207 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2210 case ICmpInst::ICMP_EQ: {
2211 // Convert to: while (X-Y == 0) // while (X == Y)
2212 SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L);
2213 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2216 case ICmpInst::ICMP_SLT: {
2217 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
2218 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2221 case ICmpInst::ICMP_SGT: {
2222 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
2223 SE.getNotSCEV(RHS), L, true);
2224 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2227 case ICmpInst::ICMP_ULT: {
2228 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
2229 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2232 case ICmpInst::ICMP_UGT: {
2233 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
2234 SE.getNotSCEV(RHS), L, false);
2235 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2240 cerr << "ComputeBackedgeTakenCount ";
2241 if (ExitCond->getOperand(0)->getType()->isUnsigned())
2242 cerr << "[unsigned] ";
2244 << Instruction::getOpcodeName(Instruction::ICmp)
2245 << " " << *RHS << "\n";
2250 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2251 ExitBr->getSuccessor(0) == ExitBlock);
2254 static ConstantInt *
2255 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2256 ScalarEvolution &SE) {
2257 SCEVHandle InVal = SE.getConstant(C);
2258 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
2259 assert(isa<SCEVConstant>(Val) &&
2260 "Evaluation of SCEV at constant didn't fold correctly?");
2261 return cast<SCEVConstant>(Val)->getValue();
2264 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
2265 /// and a GEP expression (missing the pointer index) indexing into it, return
2266 /// the addressed element of the initializer or null if the index expression is
2269 GetAddressedElementFromGlobal(GlobalVariable *GV,
2270 const std::vector<ConstantInt*> &Indices) {
2271 Constant *Init = GV->getInitializer();
2272 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2273 uint64_t Idx = Indices[i]->getZExtValue();
2274 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2275 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2276 Init = cast<Constant>(CS->getOperand(Idx));
2277 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2278 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2279 Init = cast<Constant>(CA->getOperand(Idx));
2280 } else if (isa<ConstantAggregateZero>(Init)) {
2281 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2282 assert(Idx < STy->getNumElements() && "Bad struct index!");
2283 Init = Constant::getNullValue(STy->getElementType(Idx));
2284 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2285 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2286 Init = Constant::getNullValue(ATy->getElementType());
2288 assert(0 && "Unknown constant aggregate type!");
2292 return 0; // Unknown initializer type
2298 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2299 /// 'icmp op load X, cst', try to see if we can compute the backedge
2300 /// execution count.
2301 SCEVHandle ScalarEvolutionsImpl::
2302 ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2304 ICmpInst::Predicate predicate) {
2305 if (LI->isVolatile()) return UnknownValue;
2307 // Check to see if the loaded pointer is a getelementptr of a global.
2308 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2309 if (!GEP) return UnknownValue;
2311 // Make sure that it is really a constant global we are gepping, with an
2312 // initializer, and make sure the first IDX is really 0.
2313 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2314 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2315 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2316 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2317 return UnknownValue;
2319 // Okay, we allow one non-constant index into the GEP instruction.
2321 std::vector<ConstantInt*> Indexes;
2322 unsigned VarIdxNum = 0;
2323 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2324 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2325 Indexes.push_back(CI);
2326 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2327 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2328 VarIdx = GEP->getOperand(i);
2330 Indexes.push_back(0);
2333 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2334 // Check to see if X is a loop variant variable value now.
2335 SCEVHandle Idx = getSCEV(VarIdx);
2336 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2337 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2339 // We can only recognize very limited forms of loop index expressions, in
2340 // particular, only affine AddRec's like {C1,+,C2}.
2341 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2342 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2343 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2344 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2345 return UnknownValue;
2347 unsigned MaxSteps = MaxBruteForceIterations;
2348 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2349 ConstantInt *ItCst =
2350 ConstantInt::get(IdxExpr->getType(), IterationNum);
2351 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE);
2353 // Form the GEP offset.
2354 Indexes[VarIdxNum] = Val;
2356 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2357 if (Result == 0) break; // Cannot compute!
2359 // Evaluate the condition for this iteration.
2360 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2361 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2362 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2364 cerr << "\n***\n*** Computed loop count " << *ItCst
2365 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2368 ++NumArrayLenItCounts;
2369 return SE.getConstant(ItCst); // Found terminating iteration!
2372 return UnknownValue;
2376 /// CanConstantFold - Return true if we can constant fold an instruction of the
2377 /// specified type, assuming that all operands were constants.
2378 static bool CanConstantFold(const Instruction *I) {
2379 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2380 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2383 if (const CallInst *CI = dyn_cast<CallInst>(I))
2384 if (const Function *F = CI->getCalledFunction())
2385 return canConstantFoldCallTo(F);
2389 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2390 /// in the loop that V is derived from. We allow arbitrary operations along the
2391 /// way, but the operands of an operation must either be constants or a value
2392 /// derived from a constant PHI. If this expression does not fit with these
2393 /// constraints, return null.
2394 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2395 // If this is not an instruction, or if this is an instruction outside of the
2396 // loop, it can't be derived from a loop PHI.
2397 Instruction *I = dyn_cast<Instruction>(V);
2398 if (I == 0 || !L->contains(I->getParent())) return 0;
2400 if (PHINode *PN = dyn_cast<PHINode>(I)) {
2401 if (L->getHeader() == I->getParent())
2404 // We don't currently keep track of the control flow needed to evaluate
2405 // PHIs, so we cannot handle PHIs inside of loops.
2409 // If we won't be able to constant fold this expression even if the operands
2410 // are constants, return early.
2411 if (!CanConstantFold(I)) return 0;
2413 // Otherwise, we can evaluate this instruction if all of its operands are
2414 // constant or derived from a PHI node themselves.
2416 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2417 if (!(isa<Constant>(I->getOperand(Op)) ||
2418 isa<GlobalValue>(I->getOperand(Op)))) {
2419 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2420 if (P == 0) return 0; // Not evolving from PHI
2424 return 0; // Evolving from multiple different PHIs.
2427 // This is a expression evolving from a constant PHI!
2431 /// EvaluateExpression - Given an expression that passes the
2432 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2433 /// in the loop has the value PHIVal. If we can't fold this expression for some
2434 /// reason, return null.
2435 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2436 if (isa<PHINode>(V)) return PHIVal;
2437 if (Constant *C = dyn_cast<Constant>(V)) return C;
2438 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
2439 Instruction *I = cast<Instruction>(V);
2441 std::vector<Constant*> Operands;
2442 Operands.resize(I->getNumOperands());
2444 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2445 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2446 if (Operands[i] == 0) return 0;
2449 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2450 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2451 &Operands[0], Operands.size());
2453 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2454 &Operands[0], Operands.size());
2457 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2458 /// in the header of its containing loop, we know the loop executes a
2459 /// constant number of times, and the PHI node is just a recurrence
2460 /// involving constants, fold it.
2461 Constant *ScalarEvolutionsImpl::
2462 getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
2463 std::map<PHINode*, Constant*>::iterator I =
2464 ConstantEvolutionLoopExitValue.find(PN);
2465 if (I != ConstantEvolutionLoopExitValue.end())
2468 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
2469 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2471 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2473 // Since the loop is canonicalized, the PHI node must have two entries. One
2474 // entry must be a constant (coming in from outside of the loop), and the
2475 // second must be derived from the same PHI.
2476 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2477 Constant *StartCST =
2478 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2480 return RetVal = 0; // Must be a constant.
2482 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2483 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2485 return RetVal = 0; // Not derived from same PHI.
2487 // Execute the loop symbolically to determine the exit value.
2488 if (BEs.getActiveBits() >= 32)
2489 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2491 unsigned NumIterations = BEs.getZExtValue(); // must be in range
2492 unsigned IterationNum = 0;
2493 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2494 if (IterationNum == NumIterations)
2495 return RetVal = PHIVal; // Got exit value!
2497 // Compute the value of the PHI node for the next iteration.
2498 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2499 if (NextPHI == PHIVal)
2500 return RetVal = NextPHI; // Stopped evolving!
2502 return 0; // Couldn't evaluate!
2507 /// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
2508 /// constant number of times (the condition evolves only from constants),
2509 /// try to evaluate a few iterations of the loop until we get the exit
2510 /// condition gets a value of ExitWhen (true or false). If we cannot
2511 /// evaluate the trip count of the loop, return UnknownValue.
2512 SCEVHandle ScalarEvolutionsImpl::
2513 ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
2514 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2515 if (PN == 0) return UnknownValue;
2517 // Since the loop is canonicalized, the PHI node must have two entries. One
2518 // entry must be a constant (coming in from outside of the loop), and the
2519 // second must be derived from the same PHI.
2520 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2521 Constant *StartCST =
2522 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2523 if (StartCST == 0) return UnknownValue; // Must be a constant.
2525 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2526 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2527 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2529 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2530 // the loop symbolically to determine when the condition gets a value of
2532 unsigned IterationNum = 0;
2533 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2534 for (Constant *PHIVal = StartCST;
2535 IterationNum != MaxIterations; ++IterationNum) {
2536 ConstantInt *CondVal =
2537 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2539 // Couldn't symbolically evaluate.
2540 if (!CondVal) return UnknownValue;
2542 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2543 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2544 ++NumBruteForceTripCountsComputed;
2545 return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
2548 // Compute the value of the PHI node for the next iteration.
2549 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2550 if (NextPHI == 0 || NextPHI == PHIVal)
2551 return UnknownValue; // Couldn't evaluate or not making progress...
2555 // Too many iterations were needed to evaluate.
2556 return UnknownValue;
2559 /// getSCEVAtScope - Compute the value of the specified expression within the
2560 /// indicated loop (which may be null to indicate in no loop). If the
2561 /// expression cannot be evaluated, return UnknownValue.
2562 SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2563 // FIXME: this should be turned into a virtual method on SCEV!
2565 if (isa<SCEVConstant>(V)) return V;
2567 // If this instruction is evolved from a constant-evolving PHI, compute the
2568 // exit value from the loop without using SCEVs.
2569 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2570 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2571 const Loop *LI = this->LI[I->getParent()];
2572 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2573 if (PHINode *PN = dyn_cast<PHINode>(I))
2574 if (PN->getParent() == LI->getHeader()) {
2575 // Okay, there is no closed form solution for the PHI node. Check
2576 // to see if the loop that contains it has a known backedge-taken
2577 // count. If so, we may be able to force computation of the exit
2579 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
2580 if (SCEVConstant *BTCC =
2581 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
2582 // Okay, we know how many times the containing loop executes. If
2583 // this is a constant evolving PHI node, get the final value at
2584 // the specified iteration number.
2585 Constant *RV = getConstantEvolutionLoopExitValue(PN,
2586 BTCC->getValue()->getValue(),
2588 if (RV) return SE.getUnknown(RV);
2592 // Okay, this is an expression that we cannot symbolically evaluate
2593 // into a SCEV. Check to see if it's possible to symbolically evaluate
2594 // the arguments into constants, and if so, try to constant propagate the
2595 // result. This is particularly useful for computing loop exit values.
2596 if (CanConstantFold(I)) {
2597 std::vector<Constant*> Operands;
2598 Operands.reserve(I->getNumOperands());
2599 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2600 Value *Op = I->getOperand(i);
2601 if (Constant *C = dyn_cast<Constant>(Op)) {
2602 Operands.push_back(C);
2604 // If any of the operands is non-constant and if they are
2605 // non-integer and non-pointer, don't even try to analyze them
2606 // with scev techniques.
2607 if (!isa<IntegerType>(Op->getType()) &&
2608 !isa<PointerType>(Op->getType()))
2611 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2612 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
2613 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2616 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2617 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
2618 Operands.push_back(ConstantExpr::getIntegerCast(C,
2630 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2631 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2632 &Operands[0], Operands.size());
2634 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2635 &Operands[0], Operands.size());
2636 return SE.getUnknown(C);
2640 // This is some other type of SCEVUnknown, just return it.
2644 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2645 // Avoid performing the look-up in the common case where the specified
2646 // expression has no loop-variant portions.
2647 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2648 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2649 if (OpAtScope != Comm->getOperand(i)) {
2650 if (OpAtScope == UnknownValue) return UnknownValue;
2651 // Okay, at least one of these operands is loop variant but might be
2652 // foldable. Build a new instance of the folded commutative expression.
2653 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2654 NewOps.push_back(OpAtScope);
2656 for (++i; i != e; ++i) {
2657 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2658 if (OpAtScope == UnknownValue) return UnknownValue;
2659 NewOps.push_back(OpAtScope);
2661 if (isa<SCEVAddExpr>(Comm))
2662 return SE.getAddExpr(NewOps);
2663 if (isa<SCEVMulExpr>(Comm))
2664 return SE.getMulExpr(NewOps);
2665 if (isa<SCEVSMaxExpr>(Comm))
2666 return SE.getSMaxExpr(NewOps);
2667 if (isa<SCEVUMaxExpr>(Comm))
2668 return SE.getUMaxExpr(NewOps);
2669 assert(0 && "Unknown commutative SCEV type!");
2672 // If we got here, all operands are loop invariant.
2676 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
2677 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
2678 if (LHS == UnknownValue) return LHS;
2679 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
2680 if (RHS == UnknownValue) return RHS;
2681 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2682 return Div; // must be loop invariant
2683 return SE.getUDivExpr(LHS, RHS);
2686 // If this is a loop recurrence for a loop that does not contain L, then we
2687 // are dealing with the final value computed by the loop.
2688 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2689 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2690 // To evaluate this recurrence, we need to know how many times the AddRec
2691 // loop iterates. Compute this now.
2692 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
2693 if (BackedgeTakenCount == UnknownValue) return UnknownValue;
2695 // Then, evaluate the AddRec.
2696 return AddRec->evaluateAtIteration(BackedgeTakenCount, SE);
2698 return UnknownValue;
2701 //assert(0 && "Unknown SCEV type!");
2702 return UnknownValue;
2705 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2706 /// following equation:
2708 /// A * X = B (mod N)
2710 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2711 /// A and B isn't important.
2713 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2714 static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2715 ScalarEvolution &SE) {
2716 uint32_t BW = A.getBitWidth();
2717 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2718 assert(A != 0 && "A must be non-zero.");
2722 // The gcd of A and N may have only one prime factor: 2. The number of
2723 // trailing zeros in A is its multiplicity
2724 uint32_t Mult2 = A.countTrailingZeros();
2727 // 2. Check if B is divisible by D.
2729 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2730 // is not less than multiplicity of this prime factor for D.
2731 if (B.countTrailingZeros() < Mult2)
2732 return new SCEVCouldNotCompute();
2734 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2737 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2738 // bit width during computations.
2739 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2740 APInt Mod(BW + 1, 0);
2741 Mod.set(BW - Mult2); // Mod = N / D
2742 APInt I = AD.multiplicativeInverse(Mod);
2744 // 4. Compute the minimum unsigned root of the equation:
2745 // I * (B / D) mod (N / D)
2746 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2748 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2750 return SE.getConstant(Result.trunc(BW));
2753 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2754 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2755 /// might be the same) or two SCEVCouldNotCompute objects.
2757 static std::pair<SCEVHandle,SCEVHandle>
2758 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
2759 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2760 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2761 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2762 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2764 // We currently can only solve this if the coefficients are constants.
2765 if (!LC || !MC || !NC) {
2766 SCEV *CNC = new SCEVCouldNotCompute();
2767 return std::make_pair(CNC, CNC);
2770 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2771 const APInt &L = LC->getValue()->getValue();
2772 const APInt &M = MC->getValue()->getValue();
2773 const APInt &N = NC->getValue()->getValue();
2774 APInt Two(BitWidth, 2);
2775 APInt Four(BitWidth, 4);
2778 using namespace APIntOps;
2780 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2781 // The B coefficient is M-N/2
2785 // The A coefficient is N/2
2786 APInt A(N.sdiv(Two));
2788 // Compute the B^2-4ac term.
2791 SqrtTerm -= Four * (A * C);
2793 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2794 // integer value or else APInt::sqrt() will assert.
2795 APInt SqrtVal(SqrtTerm.sqrt());
2797 // Compute the two solutions for the quadratic formula.
2798 // The divisions must be performed as signed divisions.
2800 APInt TwoA( A << 1 );
2801 if (TwoA.isMinValue()) {
2802 SCEV *CNC = new SCEVCouldNotCompute();
2803 return std::make_pair(CNC, CNC);
2806 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2807 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2809 return std::make_pair(SE.getConstant(Solution1),
2810 SE.getConstant(Solution2));
2811 } // end APIntOps namespace
2814 /// HowFarToZero - Return the number of times a backedge comparing the specified
2815 /// value to zero will execute. If not computable, return UnknownValue
2816 SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2817 // If the value is a constant
2818 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2819 // If the value is already zero, the branch will execute zero times.
2820 if (C->getValue()->isZero()) return C;
2821 return UnknownValue; // Otherwise it will loop infinitely.
2824 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2825 if (!AddRec || AddRec->getLoop() != L)
2826 return UnknownValue;
2828 if (AddRec->isAffine()) {
2829 // If this is an affine expression, the execution count of this branch is
2830 // the minimum unsigned root of the following equation:
2832 // Start + Step*N = 0 (mod 2^BW)
2836 // Step*N = -Start (mod 2^BW)
2838 // where BW is the common bit width of Start and Step.
2840 // Get the initial value for the loop.
2841 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2842 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
2844 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
2846 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2847 // For now we handle only constant steps.
2849 // First, handle unitary steps.
2850 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
2851 return SE.getNegativeSCEV(Start); // N = -Start (as unsigned)
2852 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2853 return Start; // N = Start (as unsigned)
2855 // Then, try to solve the above equation provided that Start is constant.
2856 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
2857 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
2858 -StartC->getValue()->getValue(),SE);
2860 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2861 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2862 // the quadratic equation to solve it.
2863 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE);
2864 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2865 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2868 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2869 << " sol#2: " << *R2 << "\n";
2871 // Pick the smallest positive root value.
2872 if (ConstantInt *CB =
2873 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2874 R1->getValue(), R2->getValue()))) {
2875 if (CB->getZExtValue() == false)
2876 std::swap(R1, R2); // R1 is the minimum root now.
2878 // We can only use this value if the chrec ends up with an exact zero
2879 // value at this index. When solving for "X*X != 5", for example, we
2880 // should not accept a root of 2.
2881 SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE);
2883 return R1; // We found a quadratic root!
2888 return UnknownValue;
2891 /// HowFarToNonZero - Return the number of times a backedge checking the
2892 /// specified value for nonzero will execute. If not computable, return
2894 SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2895 // Loops that look like: while (X == 0) are very strange indeed. We don't
2896 // handle them yet except for the trivial case. This could be expanded in the
2897 // future as needed.
2899 // If the value is a constant, check to see if it is known to be non-zero
2900 // already. If so, the backedge will execute zero times.
2901 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2902 if (!C->getValue()->isNullValue())
2903 return SE.getIntegerSCEV(0, C->getType());
2904 return UnknownValue; // Otherwise it will loop infinitely.
2907 // We could implement others, but I really doubt anyone writes loops like
2908 // this, and if they did, they would already be constant folded.
2909 return UnknownValue;
2912 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
2913 /// (which may not be an immediate predecessor) which has exactly one
2914 /// successor from which BB is reachable, or null if no such block is
2918 ScalarEvolutionsImpl::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
2919 // If the block has a unique predecessor, the predecessor must have
2920 // no other successors from which BB is reachable.
2921 if (BasicBlock *Pred = BB->getSinglePredecessor())
2924 // A loop's header is defined to be a block that dominates the loop.
2925 // If the loop has a preheader, it must be a block that has exactly
2926 // one successor that can reach BB. This is slightly more strict
2927 // than necessary, but works if critical edges are split.
2928 if (Loop *L = LI.getLoopFor(BB))
2929 return L->getLoopPreheader();
2934 /// isLoopGuardedByCond - Test whether entry to the loop is protected by
2935 /// a conditional between LHS and RHS.
2936 bool ScalarEvolutionsImpl::isLoopGuardedByCond(const Loop *L,
2937 ICmpInst::Predicate Pred,
2938 SCEV *LHS, SCEV *RHS) {
2939 BasicBlock *Preheader = L->getLoopPreheader();
2940 BasicBlock *PreheaderDest = L->getHeader();
2942 // Starting at the preheader, climb up the predecessor chain, as long as
2943 // there are predecessors that can be found that have unique successors
2944 // leading to the original header.
2946 PreheaderDest = Preheader,
2947 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
2949 BranchInst *LoopEntryPredicate =
2950 dyn_cast<BranchInst>(Preheader->getTerminator());
2951 if (!LoopEntryPredicate ||
2952 LoopEntryPredicate->isUnconditional())
2955 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
2958 // Now that we found a conditional branch that dominates the loop, check to
2959 // see if it is the comparison we are looking for.
2960 Value *PreCondLHS = ICI->getOperand(0);
2961 Value *PreCondRHS = ICI->getOperand(1);
2962 ICmpInst::Predicate Cond;
2963 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2964 Cond = ICI->getPredicate();
2966 Cond = ICI->getInversePredicate();
2969 ; // An exact match.
2970 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
2971 ; // The actual condition is beyond sufficient.
2973 // Check a few special cases.
2975 case ICmpInst::ICMP_UGT:
2976 if (Pred == ICmpInst::ICMP_ULT) {
2977 std::swap(PreCondLHS, PreCondRHS);
2978 Cond = ICmpInst::ICMP_ULT;
2982 case ICmpInst::ICMP_SGT:
2983 if (Pred == ICmpInst::ICMP_SLT) {
2984 std::swap(PreCondLHS, PreCondRHS);
2985 Cond = ICmpInst::ICMP_SLT;
2989 case ICmpInst::ICMP_NE:
2990 // Expressions like (x >u 0) are often canonicalized to (x != 0),
2991 // so check for this case by checking if the NE is comparing against
2992 // a minimum or maximum constant.
2993 if (!ICmpInst::isTrueWhenEqual(Pred))
2994 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
2995 const APInt &A = CI->getValue();
2997 case ICmpInst::ICMP_SLT:
2998 if (A.isMaxSignedValue()) break;
3000 case ICmpInst::ICMP_SGT:
3001 if (A.isMinSignedValue()) break;
3003 case ICmpInst::ICMP_ULT:
3004 if (A.isMaxValue()) break;
3006 case ICmpInst::ICMP_UGT:
3007 if (A.isMinValue()) break;
3012 Cond = ICmpInst::ICMP_NE;
3013 // NE is symmetric but the original comparison may not be. Swap
3014 // the operands if necessary so that they match below.
3015 if (isa<SCEVConstant>(LHS))
3016 std::swap(PreCondLHS, PreCondRHS);
3021 // We weren't able to reconcile the condition.
3025 if (!PreCondLHS->getType()->isInteger()) continue;
3027 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3028 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3029 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
3030 (LHS == SE.getNotSCEV(PreCondRHSSCEV) &&
3031 RHS == SE.getNotSCEV(PreCondLHSSCEV)))
3038 /// HowManyLessThans - Return the number of times a backedge containing the
3039 /// specified less-than comparison will execute. If not computable, return
3041 SCEVHandle ScalarEvolutionsImpl::
3042 HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
3043 // Only handle: "ADDREC < LoopInvariant".
3044 if (!RHS->isLoopInvariant(L)) return UnknownValue;
3046 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
3047 if (!AddRec || AddRec->getLoop() != L)
3048 return UnknownValue;
3050 if (AddRec->isAffine()) {
3051 // FORNOW: We only support unit strides.
3052 SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType());
3053 if (AddRec->getOperand(1) != One)
3054 return UnknownValue;
3056 // We know the LHS is of the form {n,+,1} and the RHS is some loop-invariant
3057 // m. So, we count the number of iterations in which {n,+,1} < m is true.
3058 // Note that we cannot simply return max(m-n,0) because it's not safe to
3059 // treat m-n as signed nor unsigned due to overflow possibility.
3061 // First, we get the value of the LHS in the first iteration: n
3062 SCEVHandle Start = AddRec->getOperand(0);
3064 if (isLoopGuardedByCond(L,
3065 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3066 SE.getMinusSCEV(AddRec->getOperand(0), One), RHS)) {
3067 // Since we know that the condition is true in order to enter the loop,
3068 // we know that it will run exactly m-n times.
3069 return SE.getMinusSCEV(RHS, Start);
3071 // Then, we get the value of the LHS in the first iteration in which the
3072 // above condition doesn't hold. This equals to max(m,n).
3073 SCEVHandle End = isSigned ? SE.getSMaxExpr(RHS, Start)
3074 : SE.getUMaxExpr(RHS, Start);
3076 // Finally, we subtract these two values to get the number of times the
3077 // backedge is executed: max(m,n)-n.
3078 return SE.getMinusSCEV(End, Start);
3082 return UnknownValue;
3085 /// getNumIterationsInRange - Return the number of iterations of this loop that
3086 /// produce values in the specified constant range. Another way of looking at
3087 /// this is that it returns the first iteration number where the value is not in
3088 /// the condition, thus computing the exit count. If the iteration count can't
3089 /// be computed, an instance of SCEVCouldNotCompute is returned.
3090 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3091 ScalarEvolution &SE) const {
3092 if (Range.isFullSet()) // Infinite loop.
3093 return new SCEVCouldNotCompute();
3095 // If the start is a non-zero constant, shift the range to simplify things.
3096 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
3097 if (!SC->getValue()->isZero()) {
3098 std::vector<SCEVHandle> Operands(op_begin(), op_end());
3099 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3100 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
3101 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
3102 return ShiftedAddRec->getNumIterationsInRange(
3103 Range.subtract(SC->getValue()->getValue()), SE);
3104 // This is strange and shouldn't happen.
3105 return new SCEVCouldNotCompute();
3108 // The only time we can solve this is when we have all constant indices.
3109 // Otherwise, we cannot determine the overflow conditions.
3110 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3111 if (!isa<SCEVConstant>(getOperand(i)))
3112 return new SCEVCouldNotCompute();
3115 // Okay at this point we know that all elements of the chrec are constants and
3116 // that the start element is zero.
3118 // First check to see if the range contains zero. If not, the first
3120 unsigned BitWidth = SE.getTargetData().getTypeSizeInBits(getType());
3121 if (!Range.contains(APInt(BitWidth, 0)))
3122 return SE.getConstant(ConstantInt::get(getType(),0));
3125 // If this is an affine expression then we have this situation:
3126 // Solve {0,+,A} in Range === Ax in Range
3128 // We know that zero is in the range. If A is positive then we know that
3129 // the upper value of the range must be the first possible exit value.
3130 // If A is negative then the lower of the range is the last possible loop
3131 // value. Also note that we already checked for a full range.
3132 APInt One(BitWidth,1);
3133 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3134 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3136 // The exit value should be (End+A)/A.
3137 APInt ExitVal = (End + A).udiv(A);
3138 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3140 // Evaluate at the exit value. If we really did fall out of the valid
3141 // range, then we computed our trip count, otherwise wrap around or other
3142 // things must have happened.
3143 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
3144 if (Range.contains(Val->getValue()))
3145 return new SCEVCouldNotCompute(); // Something strange happened
3147 // Ensure that the previous value is in the range. This is a sanity check.
3148 assert(Range.contains(
3149 EvaluateConstantChrecAtConstant(this,
3150 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
3151 "Linear scev computation is off in a bad way!");
3152 return SE.getConstant(ExitValue);
3153 } else if (isQuadratic()) {
3154 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3155 // quadratic equation to solve it. To do this, we must frame our problem in
3156 // terms of figuring out when zero is crossed, instead of when
3157 // Range.getUpper() is crossed.
3158 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
3159 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3160 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
3162 // Next, solve the constructed addrec
3163 std::pair<SCEVHandle,SCEVHandle> Roots =
3164 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
3165 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3166 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3168 // Pick the smallest positive root value.
3169 if (ConstantInt *CB =
3170 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3171 R1->getValue(), R2->getValue()))) {
3172 if (CB->getZExtValue() == false)
3173 std::swap(R1, R2); // R1 is the minimum root now.
3175 // Make sure the root is not off by one. The returned iteration should
3176 // not be in the range, but the previous one should be. When solving
3177 // for "X*X < 5", for example, we should not return a root of 2.
3178 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
3181 if (Range.contains(R1Val->getValue())) {
3182 // The next iteration must be out of the range...
3183 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3185 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
3186 if (!Range.contains(R1Val->getValue()))
3187 return SE.getConstant(NextVal);
3188 return new SCEVCouldNotCompute(); // Something strange happened
3191 // If R1 was not in the range, then it is a good return value. Make
3192 // sure that R1-1 WAS in the range though, just in case.
3193 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
3194 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
3195 if (Range.contains(R1Val->getValue()))
3197 return new SCEVCouldNotCompute(); // Something strange happened
3202 return new SCEVCouldNotCompute();
3207 //===----------------------------------------------------------------------===//
3208 // ScalarEvolution Class Implementation
3209 //===----------------------------------------------------------------------===//
3211 bool ScalarEvolution::runOnFunction(Function &F) {
3212 Impl = new ScalarEvolutionsImpl(*this, F,
3213 getAnalysis<LoopInfo>(),
3214 getAnalysis<TargetData>());
3218 void ScalarEvolution::releaseMemory() {
3219 delete (ScalarEvolutionsImpl*)Impl;
3223 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3224 AU.setPreservesAll();
3225 AU.addRequiredTransitive<LoopInfo>();
3226 AU.addRequiredTransitive<TargetData>();
3229 const TargetData &ScalarEvolution::getTargetData() const {
3230 return ((ScalarEvolutionsImpl*)Impl)->getTargetData();
3233 SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
3234 return ((ScalarEvolutionsImpl*)Impl)->getIntegerSCEV(Val, Ty);
3237 SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
3238 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
3241 /// hasSCEV - Return true if the SCEV for this value has already been
3243 bool ScalarEvolution::hasSCEV(Value *V) const {
3244 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
3248 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
3249 /// the specified value.
3250 void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
3251 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
3254 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
3256 SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
3257 return ((ScalarEvolutionsImpl*)Impl)->getNegativeSCEV(V);
3260 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
3262 SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
3263 return ((ScalarEvolutionsImpl*)Impl)->getNotSCEV(V);
3266 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
3268 SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
3269 const SCEVHandle &RHS) {
3270 return ((ScalarEvolutionsImpl*)Impl)->getMinusSCEV(LHS, RHS);
3273 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
3274 /// of the input value to the specified type. If the type must be
3275 /// extended, it is zero extended.
3276 SCEVHandle ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
3278 return ((ScalarEvolutionsImpl*)Impl)->getTruncateOrZeroExtend(V, Ty);
3281 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
3282 /// of the input value to the specified type. If the type must be
3283 /// extended, it is sign extended.
3284 SCEVHandle ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
3286 return ((ScalarEvolutionsImpl*)Impl)->getTruncateOrSignExtend(V, Ty);
3290 bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
3291 ICmpInst::Predicate Pred,
3292 SCEV *LHS, SCEV *RHS) {
3293 return ((ScalarEvolutionsImpl*)Impl)->isLoopGuardedByCond(L, Pred,
3297 SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) const {
3298 return ((ScalarEvolutionsImpl*)Impl)->getBackedgeTakenCount(L);
3301 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) const {
3302 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
3305 void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
3306 return ((ScalarEvolutionsImpl*)Impl)->forgetLoopBackedgeTakenCount(L);
3309 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
3310 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
3313 void ScalarEvolution::deleteValueFromRecords(Value *V) const {
3314 return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
3317 static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
3319 // Print all inner loops first
3320 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3321 PrintLoopInfo(OS, SE, *I);
3323 OS << "Loop " << L->getHeader()->getName() << ": ";
3325 SmallVector<BasicBlock*, 8> ExitBlocks;
3326 L->getExitBlocks(ExitBlocks);
3327 if (ExitBlocks.size() != 1)
3328 OS << "<multiple exits> ";
3330 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3331 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
3333 OS << "Unpredictable backedge-taken count. ";
3339 void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
3340 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
3341 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
3343 OS << "Classifying expressions for: " << F.getName() << "\n";
3344 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
3345 if (I->getType()->isInteger()) {
3348 SCEVHandle SV = getSCEV(&*I);
3352 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
3354 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
3355 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3356 OS << "<<Unknown>>";
3366 OS << "Determining loop execution counts for: " << F.getName() << "\n";
3367 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
3368 PrintLoopInfo(OS, this, *I);