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/raw_ostream.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 void SCEV::print(std::ostream &o) const {
123 raw_os_ostream OS(o);
127 bool SCEV::isZero() const {
128 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
129 return SC->getValue()->isZero();
134 SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
136 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
137 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
141 const Type *SCEVCouldNotCompute::getType() const {
142 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
146 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
147 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
151 SCEVHandle SCEVCouldNotCompute::
152 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
153 const SCEVHandle &Conc,
154 ScalarEvolution &SE) const {
158 void SCEVCouldNotCompute::print(raw_ostream &OS) const {
159 OS << "***COULDNOTCOMPUTE***";
162 bool SCEVCouldNotCompute::classof(const SCEV *S) {
163 return S->getSCEVType() == scCouldNotCompute;
167 // SCEVConstants - Only allow the creation of one SCEVConstant for any
168 // particular value. Don't use a SCEVHandle here, or else the object will
170 static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
173 SCEVConstant::~SCEVConstant() {
174 SCEVConstants->erase(V);
177 SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
178 SCEVConstant *&R = (*SCEVConstants)[V];
179 if (R == 0) R = new SCEVConstant(V);
183 SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
184 return getConstant(ConstantInt::get(Val));
187 const Type *SCEVConstant::getType() const { return V->getType(); }
189 void SCEVConstant::print(raw_ostream &OS) const {
190 WriteAsOperand(OS, V, false);
193 SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
194 const SCEVHandle &op, const Type *ty)
195 : SCEV(SCEVTy), Op(op), Ty(ty) {}
197 SCEVCastExpr::~SCEVCastExpr() {}
199 bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
200 return Op->dominates(BB, DT);
203 // SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
204 // particular input. Don't use a SCEVHandle here, or else the object will
206 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
207 SCEVTruncateExpr*> > SCEVTruncates;
209 SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
210 : SCEVCastExpr(scTruncate, op, ty) {
211 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
212 (Ty->isInteger() || isa<PointerType>(Ty)) &&
213 "Cannot truncate non-integer value!");
216 SCEVTruncateExpr::~SCEVTruncateExpr() {
217 SCEVTruncates->erase(std::make_pair(Op, Ty));
220 void SCEVTruncateExpr::print(raw_ostream &OS) const {
221 OS << "(truncate " << *Op << " to " << *Ty << ")";
224 // SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
225 // particular input. Don't use a SCEVHandle here, or else the object will never
227 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
228 SCEVZeroExtendExpr*> > SCEVZeroExtends;
230 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
231 : SCEVCastExpr(scZeroExtend, op, ty) {
232 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
233 (Ty->isInteger() || isa<PointerType>(Ty)) &&
234 "Cannot zero extend non-integer value!");
237 SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
238 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
241 void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
242 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
245 // SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
246 // particular input. Don't use a SCEVHandle here, or else the object will never
248 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
249 SCEVSignExtendExpr*> > SCEVSignExtends;
251 SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
252 : SCEVCastExpr(scSignExtend, op, ty) {
253 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
254 (Ty->isInteger() || isa<PointerType>(Ty)) &&
255 "Cannot sign extend non-integer value!");
258 SCEVSignExtendExpr::~SCEVSignExtendExpr() {
259 SCEVSignExtends->erase(std::make_pair(Op, Ty));
262 void SCEVSignExtendExpr::print(raw_ostream &OS) const {
263 OS << "(signextend " << *Op << " to " << *Ty << ")";
266 // SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
267 // particular input. Don't use a SCEVHandle here, or else the object will never
269 static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
270 SCEVCommutativeExpr*> > SCEVCommExprs;
272 SCEVCommutativeExpr::~SCEVCommutativeExpr() {
273 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
274 std::vector<SCEV*>(Operands.begin(),
278 void SCEVCommutativeExpr::print(raw_ostream &OS) const {
279 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
280 const char *OpStr = getOperationStr();
281 OS << "(" << *Operands[0];
282 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
283 OS << OpStr << *Operands[i];
287 SCEVHandle SCEVCommutativeExpr::
288 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
289 const SCEVHandle &Conc,
290 ScalarEvolution &SE) const {
291 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
293 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
294 if (H != getOperand(i)) {
295 std::vector<SCEVHandle> NewOps;
296 NewOps.reserve(getNumOperands());
297 for (unsigned j = 0; j != i; ++j)
298 NewOps.push_back(getOperand(j));
300 for (++i; i != e; ++i)
301 NewOps.push_back(getOperand(i)->
302 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
304 if (isa<SCEVAddExpr>(this))
305 return SE.getAddExpr(NewOps);
306 else if (isa<SCEVMulExpr>(this))
307 return SE.getMulExpr(NewOps);
308 else if (isa<SCEVSMaxExpr>(this))
309 return SE.getSMaxExpr(NewOps);
310 else if (isa<SCEVUMaxExpr>(this))
311 return SE.getUMaxExpr(NewOps);
313 assert(0 && "Unknown commutative expr!");
319 bool SCEVCommutativeExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
320 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
321 if (!getOperand(i)->dominates(BB, DT))
328 // SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
329 // input. Don't use a SCEVHandle here, or else the object will never be
331 static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
332 SCEVUDivExpr*> > SCEVUDivs;
334 SCEVUDivExpr::~SCEVUDivExpr() {
335 SCEVUDivs->erase(std::make_pair(LHS, RHS));
338 bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
339 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
342 void SCEVUDivExpr::print(raw_ostream &OS) const {
343 OS << "(" << *LHS << " /u " << *RHS << ")";
346 const Type *SCEVUDivExpr::getType() const {
347 return LHS->getType();
350 // SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
351 // particular input. Don't use a SCEVHandle here, or else the object will never
353 static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
354 SCEVAddRecExpr*> > SCEVAddRecExprs;
356 SCEVAddRecExpr::~SCEVAddRecExpr() {
357 SCEVAddRecExprs->erase(std::make_pair(L,
358 std::vector<SCEV*>(Operands.begin(),
362 bool SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
363 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
364 if (!getOperand(i)->dominates(BB, DT))
371 SCEVHandle SCEVAddRecExpr::
372 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
373 const SCEVHandle &Conc,
374 ScalarEvolution &SE) const {
375 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
377 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
378 if (H != getOperand(i)) {
379 std::vector<SCEVHandle> NewOps;
380 NewOps.reserve(getNumOperands());
381 for (unsigned j = 0; j != i; ++j)
382 NewOps.push_back(getOperand(j));
384 for (++i; i != e; ++i)
385 NewOps.push_back(getOperand(i)->
386 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
388 return SE.getAddRecExpr(NewOps, L);
395 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
396 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
397 // contain L and if the start is invariant.
398 return !QueryLoop->contains(L->getHeader()) &&
399 getOperand(0)->isLoopInvariant(QueryLoop);
403 void SCEVAddRecExpr::print(raw_ostream &OS) const {
404 OS << "{" << *Operands[0];
405 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
406 OS << ",+," << *Operands[i];
407 OS << "}<" << L->getHeader()->getName() + ">";
410 // SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
411 // value. Don't use a SCEVHandle here, or else the object will never be
413 static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
415 SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
417 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
418 // All non-instruction values are loop invariant. All instructions are loop
419 // invariant if they are not contained in the specified loop.
420 if (Instruction *I = dyn_cast<Instruction>(V))
421 return !L->contains(I->getParent());
425 bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
426 if (Instruction *I = dyn_cast<Instruction>(getValue()))
427 return DT->dominates(I->getParent(), BB);
431 const Type *SCEVUnknown::getType() const {
435 void SCEVUnknown::print(raw_ostream &OS) const {
436 if (isa<PointerType>(V->getType()))
437 OS << "(ptrtoint " << *V->getType() << " ";
438 WriteAsOperand(OS, V, false);
439 if (isa<PointerType>(V->getType()))
443 //===----------------------------------------------------------------------===//
445 //===----------------------------------------------------------------------===//
448 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
449 /// than the complexity of the RHS. This comparator is used to canonicalize
451 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
452 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
453 return LHS->getSCEVType() < RHS->getSCEVType();
458 /// GroupByComplexity - Given a list of SCEV objects, order them by their
459 /// complexity, and group objects of the same complexity together by value.
460 /// When this routine is finished, we know that any duplicates in the vector are
461 /// consecutive and that complexity is monotonically increasing.
463 /// Note that we go take special precautions to ensure that we get determinstic
464 /// results from this routine. In other words, we don't want the results of
465 /// this to depend on where the addresses of various SCEV objects happened to
468 static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
469 if (Ops.size() < 2) return; // Noop
470 if (Ops.size() == 2) {
471 // This is the common case, which also happens to be trivially simple.
473 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
474 std::swap(Ops[0], Ops[1]);
478 // Do the rough sort by complexity.
479 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
481 // Now that we are sorted by complexity, group elements of the same
482 // complexity. Note that this is, at worst, N^2, but the vector is likely to
483 // be extremely short in practice. Note that we take this approach because we
484 // do not want to depend on the addresses of the objects we are grouping.
485 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
487 unsigned Complexity = S->getSCEVType();
489 // If there are any objects of the same complexity and same value as this
491 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
492 if (Ops[j] == S) { // Found a duplicate.
493 // Move it to immediately after i'th element.
494 std::swap(Ops[i+1], Ops[j]);
495 ++i; // no need to rescan it.
496 if (i == e-2) return; // Done!
504 //===----------------------------------------------------------------------===//
505 // Simple SCEV method implementations
506 //===----------------------------------------------------------------------===//
508 /// BinomialCoefficient - Compute BC(It, K). The result has width W.
510 static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
512 const Type* ResultTy) {
513 // Handle the simplest case efficiently.
515 return SE.getTruncateOrZeroExtend(It, ResultTy);
517 // We are using the following formula for BC(It, K):
519 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
521 // Suppose, W is the bitwidth of the return value. We must be prepared for
522 // overflow. Hence, we must assure that the result of our computation is
523 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
524 // safe in modular arithmetic.
526 // However, this code doesn't use exactly that formula; the formula it uses
527 // is something like the following, where T is the number of factors of 2 in
528 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
531 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
533 // This formula is trivially equivalent to the previous formula. However,
534 // this formula can be implemented much more efficiently. The trick is that
535 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
536 // arithmetic. To do exact division in modular arithmetic, all we have
537 // to do is multiply by the inverse. Therefore, this step can be done at
540 // The next issue is how to safely do the division by 2^T. The way this
541 // is done is by doing the multiplication step at a width of at least W + T
542 // bits. This way, the bottom W+T bits of the product are accurate. Then,
543 // when we perform the division by 2^T (which is equivalent to a right shift
544 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
545 // truncated out after the division by 2^T.
547 // In comparison to just directly using the first formula, this technique
548 // is much more efficient; using the first formula requires W * K bits,
549 // but this formula less than W + K bits. Also, the first formula requires
550 // a division step, whereas this formula only requires multiplies and shifts.
552 // It doesn't matter whether the subtraction step is done in the calculation
553 // width or the input iteration count's width; if the subtraction overflows,
554 // the result must be zero anyway. We prefer here to do it in the width of
555 // the induction variable because it helps a lot for certain cases; CodeGen
556 // isn't smart enough to ignore the overflow, which leads to much less
557 // efficient code if the width of the subtraction is wider than the native
560 // (It's possible to not widen at all by pulling out factors of 2 before
561 // the multiplication; for example, K=2 can be calculated as
562 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
563 // extra arithmetic, so it's not an obvious win, and it gets
564 // much more complicated for K > 3.)
566 // Protection from insane SCEVs; this bound is conservative,
567 // but it probably doesn't matter.
569 return SE.getCouldNotCompute();
571 unsigned W = SE.getTypeSizeInBits(ResultTy);
573 // Calculate K! / 2^T and T; we divide out the factors of two before
574 // multiplying for calculating K! / 2^T to avoid overflow.
575 // Other overflow doesn't matter because we only care about the bottom
576 // W bits of the result.
577 APInt OddFactorial(W, 1);
579 for (unsigned i = 3; i <= K; ++i) {
581 unsigned TwoFactors = Mult.countTrailingZeros();
583 Mult = Mult.lshr(TwoFactors);
584 OddFactorial *= Mult;
587 // We need at least W + T bits for the multiplication step
588 unsigned CalculationBits = W + T;
590 // Calcuate 2^T, at width T+W.
591 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
593 // Calculate the multiplicative inverse of K! / 2^T;
594 // this multiplication factor will perform the exact division by
596 APInt Mod = APInt::getSignedMinValue(W+1);
597 APInt MultiplyFactor = OddFactorial.zext(W+1);
598 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
599 MultiplyFactor = MultiplyFactor.trunc(W);
601 // Calculate the product, at width T+W
602 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
603 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
604 for (unsigned i = 1; i != K; ++i) {
605 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
606 Dividend = SE.getMulExpr(Dividend,
607 SE.getTruncateOrZeroExtend(S, CalculationTy));
611 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
613 // Truncate the result, and divide by K! / 2^T.
615 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
616 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
619 /// evaluateAtIteration - Return the value of this chain of recurrences at
620 /// the specified iteration number. We can evaluate this recurrence by
621 /// multiplying each element in the chain by the binomial coefficient
622 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
624 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
626 /// where BC(It, k) stands for binomial coefficient.
628 SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
629 ScalarEvolution &SE) const {
630 SCEVHandle Result = getStart();
631 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
632 // The computation is correct in the face of overflow provided that the
633 // multiplication is performed _after_ the evaluation of the binomial
635 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
636 if (isa<SCEVCouldNotCompute>(Coeff))
639 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
644 //===----------------------------------------------------------------------===//
645 // SCEV Expression folder implementations
646 //===----------------------------------------------------------------------===//
648 SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
649 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
650 "This is not a truncating conversion!");
652 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
654 ConstantExpr::getTrunc(SC->getValue(), Ty));
656 // If the input value is a chrec scev made out of constants, truncate
657 // all of the constants.
658 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
659 std::vector<SCEVHandle> Operands;
660 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
661 // FIXME: This should allow truncation of other expression types!
662 if (isa<SCEVConstant>(AddRec->getOperand(i)))
663 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
666 if (Operands.size() == AddRec->getNumOperands())
667 return getAddRecExpr(Operands, AddRec->getLoop());
670 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
671 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
675 SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
677 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
678 "This is not an extending conversion!");
680 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
681 const Type *IntTy = getEffectiveSCEVType(Ty);
682 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
683 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
684 return getUnknown(C);
687 // FIXME: If the input value is a chrec scev, and we can prove that the value
688 // did not overflow the old, smaller, value, we can zero extend all of the
689 // operands (often constants). This would allow analysis of something like
690 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
692 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
693 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
697 SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
698 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
699 "This is not an extending conversion!");
701 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
702 const Type *IntTy = getEffectiveSCEVType(Ty);
703 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
704 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
705 return getUnknown(C);
708 // FIXME: If the input value is a chrec scev, and we can prove that the value
709 // did not overflow the old, smaller, value, we can sign extend all of the
710 // operands (often constants). This would allow analysis of something like
711 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
713 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
714 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
718 // get - Get a canonical add expression, or something simpler if possible.
719 SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
720 assert(!Ops.empty() && "Cannot get empty add!");
721 if (Ops.size() == 1) return Ops[0];
723 // Sort by complexity, this groups all similar expression types together.
724 GroupByComplexity(Ops);
726 // If there are any constants, fold them together.
728 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
730 assert(Idx < Ops.size());
731 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
732 // We found two constants, fold them together!
733 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
734 RHSC->getValue()->getValue());
735 Ops[0] = getConstant(Fold);
736 Ops.erase(Ops.begin()+1); // Erase the folded element
737 if (Ops.size() == 1) return Ops[0];
738 LHSC = cast<SCEVConstant>(Ops[0]);
741 // If we are left with a constant zero being added, strip it off.
742 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
743 Ops.erase(Ops.begin());
748 if (Ops.size() == 1) return Ops[0];
750 // Okay, check to see if the same value occurs in the operand list twice. If
751 // so, merge them together into an multiply expression. Since we sorted the
752 // list, these values are required to be adjacent.
753 const Type *Ty = Ops[0]->getType();
754 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
755 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
756 // Found a match, merge the two values into a multiply, and add any
757 // remaining values to the result.
758 SCEVHandle Two = getIntegerSCEV(2, Ty);
759 SCEVHandle Mul = getMulExpr(Ops[i], Two);
762 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
764 return getAddExpr(Ops);
767 // Now we know the first non-constant operand. Skip past any cast SCEVs.
768 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
771 // If there are add operands they would be next.
772 if (Idx < Ops.size()) {
773 bool DeletedAdd = false;
774 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
775 // If we have an add, expand the add operands onto the end of the operands
777 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
778 Ops.erase(Ops.begin()+Idx);
782 // If we deleted at least one add, we added operands to the end of the list,
783 // and they are not necessarily sorted. Recurse to resort and resimplify
784 // any operands we just aquired.
786 return getAddExpr(Ops);
789 // Skip over the add expression until we get to a multiply.
790 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
793 // If we are adding something to a multiply expression, make sure the
794 // something is not already an operand of the multiply. If so, merge it into
796 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
797 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
798 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
799 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
800 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
801 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
802 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
803 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
804 if (Mul->getNumOperands() != 2) {
805 // If the multiply has more than two operands, we must get the
807 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
808 MulOps.erase(MulOps.begin()+MulOp);
809 InnerMul = getMulExpr(MulOps);
811 SCEVHandle One = getIntegerSCEV(1, Ty);
812 SCEVHandle AddOne = getAddExpr(InnerMul, One);
813 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
814 if (Ops.size() == 2) return OuterMul;
816 Ops.erase(Ops.begin()+AddOp);
817 Ops.erase(Ops.begin()+Idx-1);
819 Ops.erase(Ops.begin()+Idx);
820 Ops.erase(Ops.begin()+AddOp-1);
822 Ops.push_back(OuterMul);
823 return getAddExpr(Ops);
826 // Check this multiply against other multiplies being added together.
827 for (unsigned OtherMulIdx = Idx+1;
828 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
830 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
831 // If MulOp occurs in OtherMul, we can fold the two multiplies
833 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
834 OMulOp != e; ++OMulOp)
835 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
836 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
837 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
838 if (Mul->getNumOperands() != 2) {
839 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
840 MulOps.erase(MulOps.begin()+MulOp);
841 InnerMul1 = getMulExpr(MulOps);
843 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
844 if (OtherMul->getNumOperands() != 2) {
845 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
847 MulOps.erase(MulOps.begin()+OMulOp);
848 InnerMul2 = getMulExpr(MulOps);
850 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
851 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
852 if (Ops.size() == 2) return OuterMul;
853 Ops.erase(Ops.begin()+Idx);
854 Ops.erase(Ops.begin()+OtherMulIdx-1);
855 Ops.push_back(OuterMul);
856 return getAddExpr(Ops);
862 // If there are any add recurrences in the operands list, see if any other
863 // added values are loop invariant. If so, we can fold them into the
865 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
868 // Scan over all recurrences, trying to fold loop invariants into them.
869 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
870 // Scan all of the other operands to this add and add them to the vector if
871 // they are loop invariant w.r.t. the recurrence.
872 std::vector<SCEVHandle> LIOps;
873 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
874 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
875 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
876 LIOps.push_back(Ops[i]);
877 Ops.erase(Ops.begin()+i);
881 // If we found some loop invariants, fold them into the recurrence.
882 if (!LIOps.empty()) {
883 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
884 LIOps.push_back(AddRec->getStart());
886 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
887 AddRecOps[0] = getAddExpr(LIOps);
889 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
890 // If all of the other operands were loop invariant, we are done.
891 if (Ops.size() == 1) return NewRec;
893 // Otherwise, add the folded AddRec by the non-liv parts.
894 for (unsigned i = 0;; ++i)
895 if (Ops[i] == AddRec) {
899 return getAddExpr(Ops);
902 // Okay, if there weren't any loop invariants to be folded, check to see if
903 // there are multiple AddRec's with the same loop induction variable being
904 // added together. If so, we can fold them.
905 for (unsigned OtherIdx = Idx+1;
906 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
907 if (OtherIdx != Idx) {
908 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
909 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
910 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
911 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
912 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
913 if (i >= NewOps.size()) {
914 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
915 OtherAddRec->op_end());
918 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
920 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
922 if (Ops.size() == 2) return NewAddRec;
924 Ops.erase(Ops.begin()+Idx);
925 Ops.erase(Ops.begin()+OtherIdx-1);
926 Ops.push_back(NewAddRec);
927 return getAddExpr(Ops);
931 // Otherwise couldn't fold anything into this recurrence. Move onto the
935 // Okay, it looks like we really DO need an add expr. Check to see if we
936 // already have one, otherwise create a new one.
937 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
938 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
940 if (Result == 0) Result = new SCEVAddExpr(Ops);
945 SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
946 assert(!Ops.empty() && "Cannot get empty mul!");
948 // Sort by complexity, this groups all similar expression types together.
949 GroupByComplexity(Ops);
951 // If there are any constants, fold them together.
953 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
955 // C1*(C2+V) -> C1*C2 + C1*V
957 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
958 if (Add->getNumOperands() == 2 &&
959 isa<SCEVConstant>(Add->getOperand(0)))
960 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
961 getMulExpr(LHSC, Add->getOperand(1)));
965 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
966 // We found two constants, fold them together!
967 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
968 RHSC->getValue()->getValue());
969 Ops[0] = getConstant(Fold);
970 Ops.erase(Ops.begin()+1); // Erase the folded element
971 if (Ops.size() == 1) return Ops[0];
972 LHSC = cast<SCEVConstant>(Ops[0]);
975 // If we are left with a constant one being multiplied, strip it off.
976 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
977 Ops.erase(Ops.begin());
979 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
980 // If we have a multiply of zero, it will always be zero.
985 // Skip over the add expression until we get to a multiply.
986 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
992 // If there are mul operands inline them all into this expression.
993 if (Idx < Ops.size()) {
994 bool DeletedMul = false;
995 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
996 // If we have an mul, expand the mul operands onto the end of the operands
998 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
999 Ops.erase(Ops.begin()+Idx);
1003 // If we deleted at least one mul, we added operands to the end of the list,
1004 // and they are not necessarily sorted. Recurse to resort and resimplify
1005 // any operands we just aquired.
1007 return getMulExpr(Ops);
1010 // If there are any add recurrences in the operands list, see if any other
1011 // added values are loop invariant. If so, we can fold them into the
1013 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1016 // Scan over all recurrences, trying to fold loop invariants into them.
1017 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1018 // Scan all of the other operands to this mul and add them to the vector if
1019 // they are loop invariant w.r.t. the recurrence.
1020 std::vector<SCEVHandle> LIOps;
1021 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1022 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1023 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1024 LIOps.push_back(Ops[i]);
1025 Ops.erase(Ops.begin()+i);
1029 // If we found some loop invariants, fold them into the recurrence.
1030 if (!LIOps.empty()) {
1031 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
1032 std::vector<SCEVHandle> NewOps;
1033 NewOps.reserve(AddRec->getNumOperands());
1034 if (LIOps.size() == 1) {
1035 SCEV *Scale = LIOps[0];
1036 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1037 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1039 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1040 std::vector<SCEVHandle> MulOps(LIOps);
1041 MulOps.push_back(AddRec->getOperand(i));
1042 NewOps.push_back(getMulExpr(MulOps));
1046 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
1048 // If all of the other operands were loop invariant, we are done.
1049 if (Ops.size() == 1) return NewRec;
1051 // Otherwise, multiply the folded AddRec by the non-liv parts.
1052 for (unsigned i = 0;; ++i)
1053 if (Ops[i] == AddRec) {
1057 return getMulExpr(Ops);
1060 // Okay, if there weren't any loop invariants to be folded, check to see if
1061 // there are multiple AddRec's with the same loop induction variable being
1062 // multiplied together. If so, we can fold them.
1063 for (unsigned OtherIdx = Idx+1;
1064 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1065 if (OtherIdx != Idx) {
1066 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1067 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1068 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1069 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1070 SCEVHandle NewStart = getMulExpr(F->getStart(),
1072 SCEVHandle B = F->getStepRecurrence(*this);
1073 SCEVHandle D = G->getStepRecurrence(*this);
1074 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1077 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1079 if (Ops.size() == 2) return NewAddRec;
1081 Ops.erase(Ops.begin()+Idx);
1082 Ops.erase(Ops.begin()+OtherIdx-1);
1083 Ops.push_back(NewAddRec);
1084 return getMulExpr(Ops);
1088 // Otherwise couldn't fold anything into this recurrence. Move onto the
1092 // Okay, it looks like we really DO need an mul expr. Check to see if we
1093 // already have one, otherwise create a new one.
1094 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1095 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1098 Result = new SCEVMulExpr(Ops);
1102 SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1103 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1104 if (RHSC->getValue()->equalsInt(1))
1105 return LHS; // X udiv 1 --> x
1107 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1108 Constant *LHSCV = LHSC->getValue();
1109 Constant *RHSCV = RHSC->getValue();
1110 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
1114 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1116 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1117 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
1122 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1123 /// specified loop. Simplify the expression as much as possible.
1124 SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
1125 const SCEVHandle &Step, const Loop *L) {
1126 std::vector<SCEVHandle> Operands;
1127 Operands.push_back(Start);
1128 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1129 if (StepChrec->getLoop() == L) {
1130 Operands.insert(Operands.end(), StepChrec->op_begin(),
1131 StepChrec->op_end());
1132 return getAddRecExpr(Operands, L);
1135 Operands.push_back(Step);
1136 return getAddRecExpr(Operands, L);
1139 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1140 /// specified loop. Simplify the expression as much as possible.
1141 SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
1143 if (Operands.size() == 1) return Operands[0];
1145 if (Operands.back()->isZero()) {
1146 Operands.pop_back();
1147 return getAddRecExpr(Operands, L); // {X,+,0} --> X
1150 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1151 if (SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1152 const Loop* NestedLoop = NestedAR->getLoop();
1153 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1154 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1155 NestedAR->op_end());
1156 SCEVHandle NestedARHandle(NestedAR);
1157 Operands[0] = NestedAR->getStart();
1158 NestedOperands[0] = getAddRecExpr(Operands, L);
1159 return getAddRecExpr(NestedOperands, NestedLoop);
1163 SCEVAddRecExpr *&Result =
1164 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1166 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1170 SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1171 const SCEVHandle &RHS) {
1172 std::vector<SCEVHandle> Ops;
1175 return getSMaxExpr(Ops);
1178 SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1179 assert(!Ops.empty() && "Cannot get empty smax!");
1180 if (Ops.size() == 1) return Ops[0];
1182 // Sort by complexity, this groups all similar expression types together.
1183 GroupByComplexity(Ops);
1185 // If there are any constants, fold them together.
1187 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1189 assert(Idx < Ops.size());
1190 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1191 // We found two constants, fold them together!
1192 ConstantInt *Fold = ConstantInt::get(
1193 APIntOps::smax(LHSC->getValue()->getValue(),
1194 RHSC->getValue()->getValue()));
1195 Ops[0] = getConstant(Fold);
1196 Ops.erase(Ops.begin()+1); // Erase the folded element
1197 if (Ops.size() == 1) return Ops[0];
1198 LHSC = cast<SCEVConstant>(Ops[0]);
1201 // If we are left with a constant -inf, strip it off.
1202 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1203 Ops.erase(Ops.begin());
1208 if (Ops.size() == 1) return Ops[0];
1210 // Find the first SMax
1211 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1214 // Check to see if one of the operands is an SMax. If so, expand its operands
1215 // onto our operand list, and recurse to simplify.
1216 if (Idx < Ops.size()) {
1217 bool DeletedSMax = false;
1218 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1219 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1220 Ops.erase(Ops.begin()+Idx);
1225 return getSMaxExpr(Ops);
1228 // Okay, check to see if the same value occurs in the operand list twice. If
1229 // so, delete one. Since we sorted the list, these values are required to
1231 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1232 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1233 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1237 if (Ops.size() == 1) return Ops[0];
1239 assert(!Ops.empty() && "Reduced smax down to nothing!");
1241 // Okay, it looks like we really DO need an smax expr. Check to see if we
1242 // already have one, otherwise create a new one.
1243 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1244 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1246 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1250 SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1251 const SCEVHandle &RHS) {
1252 std::vector<SCEVHandle> Ops;
1255 return getUMaxExpr(Ops);
1258 SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1259 assert(!Ops.empty() && "Cannot get empty umax!");
1260 if (Ops.size() == 1) return Ops[0];
1262 // Sort by complexity, this groups all similar expression types together.
1263 GroupByComplexity(Ops);
1265 // If there are any constants, fold them together.
1267 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1269 assert(Idx < Ops.size());
1270 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1271 // We found two constants, fold them together!
1272 ConstantInt *Fold = ConstantInt::get(
1273 APIntOps::umax(LHSC->getValue()->getValue(),
1274 RHSC->getValue()->getValue()));
1275 Ops[0] = getConstant(Fold);
1276 Ops.erase(Ops.begin()+1); // Erase the folded element
1277 if (Ops.size() == 1) return Ops[0];
1278 LHSC = cast<SCEVConstant>(Ops[0]);
1281 // If we are left with a constant zero, strip it off.
1282 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1283 Ops.erase(Ops.begin());
1288 if (Ops.size() == 1) return Ops[0];
1290 // Find the first UMax
1291 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1294 // Check to see if one of the operands is a UMax. If so, expand its operands
1295 // onto our operand list, and recurse to simplify.
1296 if (Idx < Ops.size()) {
1297 bool DeletedUMax = false;
1298 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1299 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1300 Ops.erase(Ops.begin()+Idx);
1305 return getUMaxExpr(Ops);
1308 // Okay, check to see if the same value occurs in the operand list twice. If
1309 // so, delete one. Since we sorted the list, these values are required to
1311 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1312 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1313 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1317 if (Ops.size() == 1) return Ops[0];
1319 assert(!Ops.empty() && "Reduced umax down to nothing!");
1321 // Okay, it looks like we really DO need a umax expr. Check to see if we
1322 // already have one, otherwise create a new one.
1323 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1324 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1326 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1330 SCEVHandle ScalarEvolution::getUnknown(Value *V) {
1331 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1332 return getConstant(CI);
1333 if (isa<ConstantPointerNull>(V))
1334 return getIntegerSCEV(0, V->getType());
1335 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1336 if (Result == 0) Result = new SCEVUnknown(V);
1340 //===----------------------------------------------------------------------===//
1341 // ScalarEvolutionsImpl Definition and Implementation
1342 //===----------------------------------------------------------------------===//
1344 /// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1348 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
1349 /// SE - A reference to the public ScalarEvolution object.
1350 ScalarEvolution &SE;
1352 /// F - The function we are analyzing.
1356 /// LI - The loop information for the function we are currently analyzing.
1360 /// TD - The target data information for the target we are targetting.
1364 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1366 SCEVHandle UnknownValue;
1368 /// Scalars - This is a cache of the scalars we have analyzed so far.
1370 std::map<Value*, SCEVHandle> Scalars;
1372 /// BackedgeTakenCounts - Cache the backedge-taken count of the loops for
1373 /// this function as they are computed.
1374 std::map<const Loop*, SCEVHandle> BackedgeTakenCounts;
1376 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1377 /// the PHI instructions that we attempt to compute constant evolutions for.
1378 /// This allows us to avoid potentially expensive recomputation of these
1379 /// properties. An instruction maps to null if we are unable to compute its
1381 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
1384 ScalarEvolutionsImpl(ScalarEvolution &se, Function &f, LoopInfo &li,
1386 : SE(se), F(f), LI(li), TD(td), UnknownValue(new SCEVCouldNotCompute()) {}
1388 /// isSCEVable - Test if values of the given type are analyzable within
1389 /// the SCEV framework. This primarily includes integer types, and it
1390 /// can optionally include pointer types if the ScalarEvolution class
1391 /// has access to target-specific information.
1392 bool isSCEVable(const Type *Ty) const;
1394 /// getTypeSizeInBits - Return the size in bits of the specified type,
1395 /// for which isSCEVable must return true.
1396 uint64_t getTypeSizeInBits(const Type *Ty) const;
1398 /// getEffectiveSCEVType - Return a type with the same bitwidth as
1399 /// the given type and which represents how SCEV will treat the given
1400 /// type, for which isSCEVable must return true. For pointer types,
1401 /// this is the pointer-sized integer type.
1402 const Type *getEffectiveSCEVType(const Type *Ty) const;
1404 SCEVHandle getCouldNotCompute();
1406 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
1407 /// specified signed integer value and return a SCEV for the constant.
1408 SCEVHandle getIntegerSCEV(int Val, const Type *Ty);
1410 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1412 SCEVHandle getNegativeSCEV(const SCEVHandle &V);
1414 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
1416 SCEVHandle getNotSCEV(const SCEVHandle &V);
1418 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1420 SCEVHandle getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS);
1422 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
1423 /// of the input value to the specified type. If the type must be extended,
1424 /// it is zero extended.
1425 SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty);
1427 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
1428 /// of the input value to the specified type. If the type must be extended,
1429 /// it is sign extended.
1430 SCEVHandle getTruncateOrSignExtend(const SCEVHandle &V, const Type *Ty);
1432 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1433 /// expression and create a new one.
1434 SCEVHandle getSCEV(Value *V);
1436 /// hasSCEV - Return true if the SCEV for this value has already been
1438 bool hasSCEV(Value *V) const {
1439 return Scalars.count(V);
1442 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1443 /// the specified value.
1444 void setSCEV(Value *V, const SCEVHandle &H) {
1445 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1446 assert(isNew && "This entry already existed!");
1451 /// getSCEVAtScope - Compute the value of the specified expression within
1452 /// the indicated loop (which may be null to indicate in no loop). If the
1453 /// expression cannot be evaluated, return UnknownValue itself.
1454 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1457 /// isLoopGuardedByCond - Test whether entry to the loop is protected by
1458 /// a conditional between LHS and RHS.
1459 bool isLoopGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
1460 SCEV *LHS, SCEV *RHS);
1462 /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop
1463 /// has an analyzable loop-invariant backedge-taken count.
1464 bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
1466 /// forgetLoopBackedgeTakenCount - This method should be called by the
1467 /// client when it has changed a loop in a way that may effect
1468 /// ScalarEvolution's ability to compute a trip count, or if the loop
1470 void forgetLoopBackedgeTakenCount(const Loop *L);
1472 /// getBackedgeTakenCount - If the specified loop has a predictable
1473 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
1474 /// object. The backedge-taken count is the number of times the loop header
1475 /// will be branched to from within the loop. This is one less than the
1476 /// trip count of the loop, since it doesn't count the first iteration,
1477 /// when the header is branched to from outside the loop.
1479 /// Note that it is not valid to call this method on a loop without a
1480 /// loop-invariant backedge-taken count (see
1481 /// hasLoopInvariantBackedgeTakenCount).
1483 SCEVHandle getBackedgeTakenCount(const Loop *L);
1485 /// deleteValueFromRecords - This method should be called by the
1486 /// client before it removes a value from the program, to make sure
1487 /// that no dangling references are left around.
1488 void deleteValueFromRecords(Value *V);
1491 /// createSCEV - We know that there is no SCEV for the specified value.
1492 /// Analyze the expression.
1493 SCEVHandle createSCEV(Value *V);
1495 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1497 SCEVHandle createNodeForPHI(PHINode *PN);
1499 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1500 /// for the specified instruction and replaces any references to the
1501 /// symbolic value SymName with the specified value. This is used during
1503 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1504 const SCEVHandle &SymName,
1505 const SCEVHandle &NewVal);
1507 /// ComputeBackedgeTakenCount - Compute the number of times the specified
1508 /// loop will iterate.
1509 SCEVHandle ComputeBackedgeTakenCount(const Loop *L);
1511 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition
1512 /// of 'icmp op load X, cst', try to see if we can compute the trip count.
1514 ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI,
1517 ICmpInst::Predicate p);
1519 /// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute
1520 /// a constant number of times (the condition evolves only from constants),
1521 /// try to evaluate a few iterations of the loop until we get the exit
1522 /// condition gets a value of ExitWhen (true or false). If we cannot
1523 /// evaluate the trip count of the loop, return UnknownValue.
1524 SCEVHandle ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond,
1527 /// HowFarToZero - Return the number of times a backedge comparing the
1528 /// specified value to zero will execute. If not computable, return
1530 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1532 /// HowFarToNonZero - Return the number of times a backedge checking the
1533 /// specified value for nonzero will execute. If not computable, return
1535 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
1537 /// HowManyLessThans - Return the number of times a backedge containing the
1538 /// specified less-than comparison will execute. If not computable, return
1539 /// UnknownValue. isSigned specifies whether the less-than is signed.
1540 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
1543 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
1544 /// (which may not be an immediate predecessor) which has exactly one
1545 /// successor from which BB is reachable, or null if no such block is
1547 BasicBlock* getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
1549 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1550 /// in the header of its containing loop, we know the loop executes a
1551 /// constant number of times, and the PHI node is just a recurrence
1552 /// involving constants, fold it.
1553 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs,
1558 //===----------------------------------------------------------------------===//
1559 // Basic SCEV Analysis and PHI Idiom Recognition Code
1562 /// deleteValueFromRecords - This method should be called by the
1563 /// client before it removes an instruction from the program, to make sure
1564 /// that no dangling references are left around.
1565 void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) {
1566 SmallVector<Value *, 16> Worklist;
1568 if (Scalars.erase(V)) {
1569 if (PHINode *PN = dyn_cast<PHINode>(V))
1570 ConstantEvolutionLoopExitValue.erase(PN);
1571 Worklist.push_back(V);
1574 while (!Worklist.empty()) {
1575 Value *VV = Worklist.back();
1576 Worklist.pop_back();
1578 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
1580 Instruction *Inst = cast<Instruction>(*UI);
1581 if (Scalars.erase(Inst)) {
1582 if (PHINode *PN = dyn_cast<PHINode>(VV))
1583 ConstantEvolutionLoopExitValue.erase(PN);
1584 Worklist.push_back(Inst);
1590 /// isSCEVable - Test if values of the given type are analyzable within
1591 /// the SCEV framework. This primarily includes integer types, and it
1592 /// can optionally include pointer types if the ScalarEvolution class
1593 /// has access to target-specific information.
1594 bool ScalarEvolutionsImpl::isSCEVable(const Type *Ty) const {
1595 // Integers are always SCEVable.
1596 if (Ty->isInteger())
1599 // Pointers are SCEVable if TargetData information is available
1600 // to provide pointer size information.
1601 if (isa<PointerType>(Ty))
1604 // Otherwise it's not SCEVable.
1608 /// getTypeSizeInBits - Return the size in bits of the specified type,
1609 /// for which isSCEVable must return true.
1610 uint64_t ScalarEvolutionsImpl::getTypeSizeInBits(const Type *Ty) const {
1611 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1613 // If we have a TargetData, use it!
1615 return TD->getTypeSizeInBits(Ty);
1617 // Otherwise, we support only integer types.
1618 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1619 return Ty->getPrimitiveSizeInBits();
1622 /// getEffectiveSCEVType - Return a type with the same bitwidth as
1623 /// the given type and which represents how SCEV will treat the given
1624 /// type, for which isSCEVable must return true. For pointer types,
1625 /// this is the pointer-sized integer type.
1626 const Type *ScalarEvolutionsImpl::getEffectiveSCEVType(const Type *Ty) const {
1627 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1629 if (Ty->isInteger())
1632 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1633 return TD->getIntPtrType();
1636 SCEVHandle ScalarEvolutionsImpl::getCouldNotCompute() {
1637 return UnknownValue;
1640 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1641 /// expression and create a new one.
1642 SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1643 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
1645 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1646 if (I != Scalars.end()) return I->second;
1647 SCEVHandle S = createSCEV(V);
1648 Scalars.insert(std::make_pair(V, S));
1652 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
1653 /// specified signed integer value and return a SCEV for the constant.
1654 SCEVHandle ScalarEvolutionsImpl::getIntegerSCEV(int Val, const Type *Ty) {
1655 Ty = SE.getEffectiveSCEVType(Ty);
1658 C = Constant::getNullValue(Ty);
1659 else if (Ty->isFloatingPoint())
1660 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1661 APFloat::IEEEdouble, Val));
1663 C = ConstantInt::get(Ty, Val);
1664 return SE.getUnknown(C);
1667 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1669 SCEVHandle ScalarEvolutionsImpl::getNegativeSCEV(const SCEVHandle &V) {
1670 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
1671 return SE.getUnknown(ConstantExpr::getNeg(VC->getValue()));
1673 const Type *Ty = V->getType();
1674 Ty = SE.getEffectiveSCEVType(Ty);
1675 return SE.getMulExpr(V, SE.getConstant(ConstantInt::getAllOnesValue(Ty)));
1678 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
1679 SCEVHandle ScalarEvolutionsImpl::getNotSCEV(const SCEVHandle &V) {
1680 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
1681 return SE.getUnknown(ConstantExpr::getNot(VC->getValue()));
1683 const Type *Ty = V->getType();
1684 Ty = SE.getEffectiveSCEVType(Ty);
1685 SCEVHandle AllOnes = SE.getConstant(ConstantInt::getAllOnesValue(Ty));
1686 return getMinusSCEV(AllOnes, V);
1689 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1691 SCEVHandle ScalarEvolutionsImpl::getMinusSCEV(const SCEVHandle &LHS,
1692 const SCEVHandle &RHS) {
1694 return SE.getAddExpr(LHS, SE.getNegativeSCEV(RHS));
1697 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1698 /// input value to the specified type. If the type must be extended, it is zero
1701 ScalarEvolutionsImpl::getTruncateOrZeroExtend(const SCEVHandle &V,
1703 const Type *SrcTy = V->getType();
1704 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1705 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
1706 "Cannot truncate or zero extend with non-integer arguments!");
1707 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
1708 return V; // No conversion
1709 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
1710 return SE.getTruncateExpr(V, Ty);
1711 return SE.getZeroExtendExpr(V, Ty);
1714 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1715 /// input value to the specified type. If the type must be extended, it is sign
1718 ScalarEvolutionsImpl::getTruncateOrSignExtend(const SCEVHandle &V,
1720 const Type *SrcTy = V->getType();
1721 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1722 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
1723 "Cannot truncate or zero extend with non-integer arguments!");
1724 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
1725 return V; // No conversion
1726 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
1727 return SE.getTruncateExpr(V, Ty);
1728 return SE.getSignExtendExpr(V, Ty);
1731 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1732 /// the specified instruction and replaces any references to the symbolic value
1733 /// SymName with the specified value. This is used during PHI resolution.
1734 void ScalarEvolutionsImpl::
1735 ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1736 const SCEVHandle &NewVal) {
1737 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1738 if (SI == Scalars.end()) return;
1741 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, SE);
1742 if (NV == SI->second) return; // No change.
1744 SI->second = NV; // Update the scalars map!
1746 // Any instruction values that use this instruction might also need to be
1748 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1750 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1753 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1754 /// a loop header, making it a potential recurrence, or it doesn't.
1756 SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1757 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1758 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1759 if (L->getHeader() == PN->getParent()) {
1760 // If it lives in the loop header, it has two incoming values, one
1761 // from outside the loop, and one from inside.
1762 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1763 unsigned BackEdge = IncomingEdge^1;
1765 // While we are analyzing this PHI node, handle its value symbolically.
1766 SCEVHandle SymbolicName = SE.getUnknown(PN);
1767 assert(Scalars.find(PN) == Scalars.end() &&
1768 "PHI node already processed?");
1769 Scalars.insert(std::make_pair(PN, SymbolicName));
1771 // Using this symbolic name for the PHI, analyze the value coming around
1773 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1775 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1776 // has a special value for the first iteration of the loop.
1778 // If the value coming around the backedge is an add with the symbolic
1779 // value we just inserted, then we found a simple induction variable!
1780 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1781 // If there is a single occurrence of the symbolic value, replace it
1782 // with a recurrence.
1783 unsigned FoundIndex = Add->getNumOperands();
1784 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1785 if (Add->getOperand(i) == SymbolicName)
1786 if (FoundIndex == e) {
1791 if (FoundIndex != Add->getNumOperands()) {
1792 // Create an add with everything but the specified operand.
1793 std::vector<SCEVHandle> Ops;
1794 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1795 if (i != FoundIndex)
1796 Ops.push_back(Add->getOperand(i));
1797 SCEVHandle Accum = SE.getAddExpr(Ops);
1799 // This is not a valid addrec if the step amount is varying each
1800 // loop iteration, but is not itself an addrec in this loop.
1801 if (Accum->isLoopInvariant(L) ||
1802 (isa<SCEVAddRecExpr>(Accum) &&
1803 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1804 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1805 SCEVHandle PHISCEV = SE.getAddRecExpr(StartVal, Accum, L);
1807 // Okay, for the entire analysis of this edge we assumed the PHI
1808 // to be symbolic. We now need to go back and update all of the
1809 // entries for the scalars that use the PHI (except for the PHI
1810 // itself) to use the new analyzed value instead of the "symbolic"
1812 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1816 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1817 // Otherwise, this could be a loop like this:
1818 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1819 // In this case, j = {1,+,1} and BEValue is j.
1820 // Because the other in-value of i (0) fits the evolution of BEValue
1821 // i really is an addrec evolution.
1822 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1823 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1825 // If StartVal = j.start - j.stride, we can use StartVal as the
1826 // initial step of the addrec evolution.
1827 if (StartVal == SE.getMinusSCEV(AddRec->getOperand(0),
1828 AddRec->getOperand(1))) {
1829 SCEVHandle PHISCEV =
1830 SE.getAddRecExpr(StartVal, AddRec->getOperand(1), L);
1832 // Okay, for the entire analysis of this edge we assumed the PHI
1833 // to be symbolic. We now need to go back and update all of the
1834 // entries for the scalars that use the PHI (except for the PHI
1835 // itself) to use the new analyzed value instead of the "symbolic"
1837 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1843 return SymbolicName;
1846 // If it's not a loop phi, we can't handle it yet.
1847 return SE.getUnknown(PN);
1850 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1851 /// guaranteed to end in (at every loop iteration). It is, at the same time,
1852 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1853 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
1854 static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
1855 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
1856 return C->getValue()->getValue().countTrailingZeros();
1858 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
1859 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
1860 (uint32_t)SE.getTypeSizeInBits(T->getType()));
1862 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
1863 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1864 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1865 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
1868 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
1869 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1870 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1871 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
1874 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
1875 // The result is the min of all operands results.
1876 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
1877 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1878 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
1882 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
1883 // The result is the sum of all operands results.
1884 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1885 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
1886 for (unsigned i = 1, e = M->getNumOperands();
1887 SumOpRes != BitWidth && i != e; ++i)
1888 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
1893 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
1894 // The result is the min of all operands results.
1895 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
1896 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1897 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
1901 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1902 // The result is the min of all operands results.
1903 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1904 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1905 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
1909 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1910 // The result is the min of all operands results.
1911 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1912 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1913 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
1917 // SCEVUDivExpr, SCEVUnknown
1921 /// createSCEV - We know that there is no SCEV for the specified value.
1922 /// Analyze the expression.
1924 SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1925 if (!isSCEVable(V->getType()))
1926 return SE.getUnknown(V);
1928 unsigned Opcode = Instruction::UserOp1;
1929 if (Instruction *I = dyn_cast<Instruction>(V))
1930 Opcode = I->getOpcode();
1931 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1932 Opcode = CE->getOpcode();
1934 return SE.getUnknown(V);
1936 User *U = cast<User>(V);
1938 case Instruction::Add:
1939 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1940 getSCEV(U->getOperand(1)));
1941 case Instruction::Mul:
1942 return SE.getMulExpr(getSCEV(U->getOperand(0)),
1943 getSCEV(U->getOperand(1)));
1944 case Instruction::UDiv:
1945 return SE.getUDivExpr(getSCEV(U->getOperand(0)),
1946 getSCEV(U->getOperand(1)));
1947 case Instruction::Sub:
1948 return SE.getMinusSCEV(getSCEV(U->getOperand(0)),
1949 getSCEV(U->getOperand(1)));
1950 case Instruction::Or:
1951 // If the RHS of the Or is a constant, we may have something like:
1952 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1953 // optimizations will transparently handle this case.
1955 // In order for this transformation to be safe, the LHS must be of the
1956 // form X*(2^n) and the Or constant must be less than 2^n.
1957 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1958 SCEVHandle LHS = getSCEV(U->getOperand(0));
1959 const APInt &CIVal = CI->getValue();
1960 if (GetMinTrailingZeros(LHS, SE) >=
1961 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
1962 return SE.getAddExpr(LHS, getSCEV(U->getOperand(1)));
1965 case Instruction::Xor:
1966 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1967 // If the RHS of the xor is a signbit, then this is just an add.
1968 // Instcombine turns add of signbit into xor as a strength reduction step.
1969 if (CI->getValue().isSignBit())
1970 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1971 getSCEV(U->getOperand(1)));
1973 // If the RHS of xor is -1, then this is a not operation.
1974 else if (CI->isAllOnesValue())
1975 return SE.getNotSCEV(getSCEV(U->getOperand(0)));
1979 case Instruction::Shl:
1980 // Turn shift left of a constant amount into a multiply.
1981 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1982 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1983 Constant *X = ConstantInt::get(
1984 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1985 return SE.getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1989 case Instruction::LShr:
1990 // Turn logical shift right of a constant into a unsigned divide.
1991 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1992 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1993 Constant *X = ConstantInt::get(
1994 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1995 return SE.getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1999 case Instruction::Trunc:
2000 return SE.getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
2002 case Instruction::ZExt:
2003 return SE.getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
2005 case Instruction::SExt:
2006 return SE.getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
2008 case Instruction::BitCast:
2009 // BitCasts are no-op casts so we just eliminate the cast.
2010 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
2011 return getSCEV(U->getOperand(0));
2014 case Instruction::IntToPtr:
2015 if (!TD) break; // Without TD we can't analyze pointers.
2016 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2017 TD->getIntPtrType());
2019 case Instruction::PtrToInt:
2020 if (!TD) break; // Without TD we can't analyze pointers.
2021 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2024 case Instruction::GetElementPtr: {
2025 if (!TD) break; // Without TD we can't analyze pointers.
2026 const Type *IntPtrTy = TD->getIntPtrType();
2027 Value *Base = U->getOperand(0);
2028 SCEVHandle TotalOffset = SE.getIntegerSCEV(0, IntPtrTy);
2029 gep_type_iterator GTI = gep_type_begin(U);
2030 for (GetElementPtrInst::op_iterator I = next(U->op_begin()),
2034 // Compute the (potentially symbolic) offset in bytes for this index.
2035 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2036 // For a struct, add the member offset.
2037 const StructLayout &SL = *TD->getStructLayout(STy);
2038 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2039 uint64_t Offset = SL.getElementOffset(FieldNo);
2040 TotalOffset = SE.getAddExpr(TotalOffset,
2041 SE.getIntegerSCEV(Offset, IntPtrTy));
2043 // For an array, add the element offset, explicitly scaled.
2044 SCEVHandle LocalOffset = getSCEV(Index);
2045 if (!isa<PointerType>(LocalOffset->getType()))
2046 // Getelementptr indicies are signed.
2047 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2050 SE.getMulExpr(LocalOffset,
2051 SE.getIntegerSCEV(TD->getTypePaddedSize(*GTI),
2053 TotalOffset = SE.getAddExpr(TotalOffset, LocalOffset);
2056 return SE.getAddExpr(getSCEV(Base), TotalOffset);
2059 case Instruction::PHI:
2060 return createNodeForPHI(cast<PHINode>(U));
2062 case Instruction::Select:
2063 // This could be a smax or umax that was lowered earlier.
2064 // Try to recover it.
2065 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2066 Value *LHS = ICI->getOperand(0);
2067 Value *RHS = ICI->getOperand(1);
2068 switch (ICI->getPredicate()) {
2069 case ICmpInst::ICMP_SLT:
2070 case ICmpInst::ICMP_SLE:
2071 std::swap(LHS, RHS);
2073 case ICmpInst::ICMP_SGT:
2074 case ICmpInst::ICMP_SGE:
2075 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2076 return SE.getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
2077 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2078 // ~smax(~x, ~y) == smin(x, y).
2079 return SE.getNotSCEV(SE.getSMaxExpr(
2080 SE.getNotSCEV(getSCEV(LHS)),
2081 SE.getNotSCEV(getSCEV(RHS))));
2083 case ICmpInst::ICMP_ULT:
2084 case ICmpInst::ICMP_ULE:
2085 std::swap(LHS, RHS);
2087 case ICmpInst::ICMP_UGT:
2088 case ICmpInst::ICMP_UGE:
2089 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2090 return SE.getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
2091 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2092 // ~umax(~x, ~y) == umin(x, y)
2093 return SE.getNotSCEV(SE.getUMaxExpr(SE.getNotSCEV(getSCEV(LHS)),
2094 SE.getNotSCEV(getSCEV(RHS))));
2101 default: // We cannot analyze this expression.
2105 return SE.getUnknown(V);
2110 //===----------------------------------------------------------------------===//
2111 // Iteration Count Computation Code
2114 /// getBackedgeTakenCount - If the specified loop has a predictable
2115 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2116 /// object. The backedge-taken count is the number of times the loop header
2117 /// will be branched to from within the loop. This is one less than the
2118 /// trip count of the loop, since it doesn't count the first iteration,
2119 /// when the header is branched to from outside the loop.
2121 /// Note that it is not valid to call this method on a loop without a
2122 /// loop-invariant backedge-taken count (see
2123 /// hasLoopInvariantBackedgeTakenCount).
2125 SCEVHandle ScalarEvolutionsImpl::getBackedgeTakenCount(const Loop *L) {
2126 std::map<const Loop*, SCEVHandle>::iterator I = BackedgeTakenCounts.find(L);
2127 if (I == BackedgeTakenCounts.end()) {
2128 SCEVHandle ItCount = ComputeBackedgeTakenCount(L);
2129 I = BackedgeTakenCounts.insert(std::make_pair(L, ItCount)).first;
2130 if (ItCount != UnknownValue) {
2131 assert(ItCount->isLoopInvariant(L) &&
2132 "Computed trip count isn't loop invariant for loop!");
2133 ++NumTripCountsComputed;
2134 } else if (isa<PHINode>(L->getHeader()->begin())) {
2135 // Only count loops that have phi nodes as not being computable.
2136 ++NumTripCountsNotComputed;
2142 /// forgetLoopBackedgeTakenCount - This method should be called by the
2143 /// client when it has changed a loop in a way that may effect
2144 /// ScalarEvolution's ability to compute a trip count, or if the loop
2146 void ScalarEvolutionsImpl::forgetLoopBackedgeTakenCount(const Loop *L) {
2147 BackedgeTakenCounts.erase(L);
2150 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
2151 /// of the specified loop will execute.
2152 SCEVHandle ScalarEvolutionsImpl::ComputeBackedgeTakenCount(const Loop *L) {
2153 // If the loop has a non-one exit block count, we can't analyze it.
2154 SmallVector<BasicBlock*, 8> ExitBlocks;
2155 L->getExitBlocks(ExitBlocks);
2156 if (ExitBlocks.size() != 1) return UnknownValue;
2158 // Okay, there is one exit block. Try to find the condition that causes the
2159 // loop to be exited.
2160 BasicBlock *ExitBlock = ExitBlocks[0];
2162 BasicBlock *ExitingBlock = 0;
2163 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
2165 if (L->contains(*PI)) {
2166 if (ExitingBlock == 0)
2169 return UnknownValue; // More than one block exiting!
2171 assert(ExitingBlock && "No exits from loop, something is broken!");
2173 // Okay, we've computed the exiting block. See what condition causes us to
2176 // FIXME: we should be able to handle switch instructions (with a single exit)
2177 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2178 if (ExitBr == 0) return UnknownValue;
2179 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2181 // At this point, we know we have a conditional branch that determines whether
2182 // the loop is exited. However, we don't know if the branch is executed each
2183 // time through the loop. If not, then the execution count of the branch will
2184 // not be equal to the trip count of the loop.
2186 // Currently we check for this by checking to see if the Exit branch goes to
2187 // the loop header. If so, we know it will always execute the same number of
2188 // times as the loop. We also handle the case where the exit block *is* the
2189 // loop header. This is common for un-rotated loops. More extensive analysis
2190 // could be done to handle more cases here.
2191 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2192 ExitBr->getSuccessor(1) != L->getHeader() &&
2193 ExitBr->getParent() != L->getHeader())
2194 return UnknownValue;
2196 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2198 // If it's not an integer comparison then compute it the hard way.
2199 // Note that ICmpInst deals with pointer comparisons too so we must check
2200 // the type of the operand.
2201 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
2202 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
2203 ExitBr->getSuccessor(0) == ExitBlock);
2205 // If the condition was exit on true, convert the condition to exit on false
2206 ICmpInst::Predicate Cond;
2207 if (ExitBr->getSuccessor(1) == ExitBlock)
2208 Cond = ExitCond->getPredicate();
2210 Cond = ExitCond->getInversePredicate();
2212 // Handle common loops like: for (X = "string"; *X; ++X)
2213 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2214 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2216 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
2217 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2220 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2221 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2223 // Try to evaluate any dependencies out of the loop.
2224 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2225 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2226 Tmp = getSCEVAtScope(RHS, L);
2227 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2229 // At this point, we would like to compute how many iterations of the
2230 // loop the predicate will return true for these inputs.
2231 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2232 // If there is a loop-invariant, force it into the RHS.
2233 std::swap(LHS, RHS);
2234 Cond = ICmpInst::getSwappedPredicate(Cond);
2237 // FIXME: think about handling pointer comparisons! i.e.:
2238 // while (P != P+100) ++P;
2240 // If we have a comparison of a chrec against a constant, try to use value
2241 // ranges to answer this query.
2242 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2243 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
2244 if (AddRec->getLoop() == L) {
2245 // Form the comparison range using the constant of the correct type so
2246 // that the ConstantRange class knows to do a signed or unsigned
2248 ConstantInt *CompVal = RHSC->getValue();
2249 const Type *RealTy = ExitCond->getOperand(0)->getType();
2250 CompVal = dyn_cast<ConstantInt>(
2251 ConstantExpr::getBitCast(CompVal, RealTy));
2253 // Form the constant range.
2254 ConstantRange CompRange(
2255 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
2257 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE);
2258 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2263 case ICmpInst::ICMP_NE: { // while (X != Y)
2264 // Convert to: while (X-Y != 0)
2265 SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
2266 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2269 case ICmpInst::ICMP_EQ: {
2270 // Convert to: while (X-Y == 0) // while (X == Y)
2271 SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L);
2272 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2275 case ICmpInst::ICMP_SLT: {
2276 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
2277 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2280 case ICmpInst::ICMP_SGT: {
2281 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
2282 SE.getNotSCEV(RHS), L, true);
2283 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2286 case ICmpInst::ICMP_ULT: {
2287 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
2288 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2291 case ICmpInst::ICMP_UGT: {
2292 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
2293 SE.getNotSCEV(RHS), L, false);
2294 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2299 errs() << "ComputeBackedgeTakenCount ";
2300 if (ExitCond->getOperand(0)->getType()->isUnsigned())
2301 errs() << "[unsigned] ";
2302 errs() << *LHS << " "
2303 << Instruction::getOpcodeName(Instruction::ICmp)
2304 << " " << *RHS << "\n";
2309 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2310 ExitBr->getSuccessor(0) == ExitBlock);
2313 static ConstantInt *
2314 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2315 ScalarEvolution &SE) {
2316 SCEVHandle InVal = SE.getConstant(C);
2317 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
2318 assert(isa<SCEVConstant>(Val) &&
2319 "Evaluation of SCEV at constant didn't fold correctly?");
2320 return cast<SCEVConstant>(Val)->getValue();
2323 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
2324 /// and a GEP expression (missing the pointer index) indexing into it, return
2325 /// the addressed element of the initializer or null if the index expression is
2328 GetAddressedElementFromGlobal(GlobalVariable *GV,
2329 const std::vector<ConstantInt*> &Indices) {
2330 Constant *Init = GV->getInitializer();
2331 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2332 uint64_t Idx = Indices[i]->getZExtValue();
2333 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2334 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2335 Init = cast<Constant>(CS->getOperand(Idx));
2336 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2337 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2338 Init = cast<Constant>(CA->getOperand(Idx));
2339 } else if (isa<ConstantAggregateZero>(Init)) {
2340 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2341 assert(Idx < STy->getNumElements() && "Bad struct index!");
2342 Init = Constant::getNullValue(STy->getElementType(Idx));
2343 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2344 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2345 Init = Constant::getNullValue(ATy->getElementType());
2347 assert(0 && "Unknown constant aggregate type!");
2351 return 0; // Unknown initializer type
2357 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2358 /// 'icmp op load X, cst', try to see if we can compute the backedge
2359 /// execution count.
2360 SCEVHandle ScalarEvolutionsImpl::
2361 ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2363 ICmpInst::Predicate predicate) {
2364 if (LI->isVolatile()) return UnknownValue;
2366 // Check to see if the loaded pointer is a getelementptr of a global.
2367 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2368 if (!GEP) return UnknownValue;
2370 // Make sure that it is really a constant global we are gepping, with an
2371 // initializer, and make sure the first IDX is really 0.
2372 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2373 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2374 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2375 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2376 return UnknownValue;
2378 // Okay, we allow one non-constant index into the GEP instruction.
2380 std::vector<ConstantInt*> Indexes;
2381 unsigned VarIdxNum = 0;
2382 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2383 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2384 Indexes.push_back(CI);
2385 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2386 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2387 VarIdx = GEP->getOperand(i);
2389 Indexes.push_back(0);
2392 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2393 // Check to see if X is a loop variant variable value now.
2394 SCEVHandle Idx = getSCEV(VarIdx);
2395 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2396 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2398 // We can only recognize very limited forms of loop index expressions, in
2399 // particular, only affine AddRec's like {C1,+,C2}.
2400 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2401 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2402 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2403 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2404 return UnknownValue;
2406 unsigned MaxSteps = MaxBruteForceIterations;
2407 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2408 ConstantInt *ItCst =
2409 ConstantInt::get(IdxExpr->getType(), IterationNum);
2410 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE);
2412 // Form the GEP offset.
2413 Indexes[VarIdxNum] = Val;
2415 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2416 if (Result == 0) break; // Cannot compute!
2418 // Evaluate the condition for this iteration.
2419 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2420 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2421 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2423 errs() << "\n***\n*** Computed loop count " << *ItCst
2424 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2427 ++NumArrayLenItCounts;
2428 return SE.getConstant(ItCst); // Found terminating iteration!
2431 return UnknownValue;
2435 /// CanConstantFold - Return true if we can constant fold an instruction of the
2436 /// specified type, assuming that all operands were constants.
2437 static bool CanConstantFold(const Instruction *I) {
2438 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2439 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2442 if (const CallInst *CI = dyn_cast<CallInst>(I))
2443 if (const Function *F = CI->getCalledFunction())
2444 return canConstantFoldCallTo(F);
2448 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2449 /// in the loop that V is derived from. We allow arbitrary operations along the
2450 /// way, but the operands of an operation must either be constants or a value
2451 /// derived from a constant PHI. If this expression does not fit with these
2452 /// constraints, return null.
2453 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2454 // If this is not an instruction, or if this is an instruction outside of the
2455 // loop, it can't be derived from a loop PHI.
2456 Instruction *I = dyn_cast<Instruction>(V);
2457 if (I == 0 || !L->contains(I->getParent())) return 0;
2459 if (PHINode *PN = dyn_cast<PHINode>(I)) {
2460 if (L->getHeader() == I->getParent())
2463 // We don't currently keep track of the control flow needed to evaluate
2464 // PHIs, so we cannot handle PHIs inside of loops.
2468 // If we won't be able to constant fold this expression even if the operands
2469 // are constants, return early.
2470 if (!CanConstantFold(I)) return 0;
2472 // Otherwise, we can evaluate this instruction if all of its operands are
2473 // constant or derived from a PHI node themselves.
2475 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2476 if (!(isa<Constant>(I->getOperand(Op)) ||
2477 isa<GlobalValue>(I->getOperand(Op)))) {
2478 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2479 if (P == 0) return 0; // Not evolving from PHI
2483 return 0; // Evolving from multiple different PHIs.
2486 // This is a expression evolving from a constant PHI!
2490 /// EvaluateExpression - Given an expression that passes the
2491 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2492 /// in the loop has the value PHIVal. If we can't fold this expression for some
2493 /// reason, return null.
2494 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2495 if (isa<PHINode>(V)) return PHIVal;
2496 if (Constant *C = dyn_cast<Constant>(V)) return C;
2497 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
2498 Instruction *I = cast<Instruction>(V);
2500 std::vector<Constant*> Operands;
2501 Operands.resize(I->getNumOperands());
2503 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2504 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2505 if (Operands[i] == 0) return 0;
2508 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2509 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2510 &Operands[0], Operands.size());
2512 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2513 &Operands[0], Operands.size());
2516 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2517 /// in the header of its containing loop, we know the loop executes a
2518 /// constant number of times, and the PHI node is just a recurrence
2519 /// involving constants, fold it.
2520 Constant *ScalarEvolutionsImpl::
2521 getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
2522 std::map<PHINode*, Constant*>::iterator I =
2523 ConstantEvolutionLoopExitValue.find(PN);
2524 if (I != ConstantEvolutionLoopExitValue.end())
2527 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
2528 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2530 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2532 // Since the loop is canonicalized, the PHI node must have two entries. One
2533 // entry must be a constant (coming in from outside of the loop), and the
2534 // second must be derived from the same PHI.
2535 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2536 Constant *StartCST =
2537 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2539 return RetVal = 0; // Must be a constant.
2541 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2542 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2544 return RetVal = 0; // Not derived from same PHI.
2546 // Execute the loop symbolically to determine the exit value.
2547 if (BEs.getActiveBits() >= 32)
2548 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2550 unsigned NumIterations = BEs.getZExtValue(); // must be in range
2551 unsigned IterationNum = 0;
2552 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2553 if (IterationNum == NumIterations)
2554 return RetVal = PHIVal; // Got exit value!
2556 // Compute the value of the PHI node for the next iteration.
2557 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2558 if (NextPHI == PHIVal)
2559 return RetVal = NextPHI; // Stopped evolving!
2561 return 0; // Couldn't evaluate!
2566 /// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
2567 /// constant number of times (the condition evolves only from constants),
2568 /// try to evaluate a few iterations of the loop until we get the exit
2569 /// condition gets a value of ExitWhen (true or false). If we cannot
2570 /// evaluate the trip count of the loop, return UnknownValue.
2571 SCEVHandle ScalarEvolutionsImpl::
2572 ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
2573 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2574 if (PN == 0) return UnknownValue;
2576 // Since the loop is canonicalized, the PHI node must have two entries. One
2577 // entry must be a constant (coming in from outside of the loop), and the
2578 // second must be derived from the same PHI.
2579 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2580 Constant *StartCST =
2581 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2582 if (StartCST == 0) return UnknownValue; // Must be a constant.
2584 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2585 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2586 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2588 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2589 // the loop symbolically to determine when the condition gets a value of
2591 unsigned IterationNum = 0;
2592 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2593 for (Constant *PHIVal = StartCST;
2594 IterationNum != MaxIterations; ++IterationNum) {
2595 ConstantInt *CondVal =
2596 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2598 // Couldn't symbolically evaluate.
2599 if (!CondVal) return UnknownValue;
2601 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2602 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2603 ++NumBruteForceTripCountsComputed;
2604 return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
2607 // Compute the value of the PHI node for the next iteration.
2608 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2609 if (NextPHI == 0 || NextPHI == PHIVal)
2610 return UnknownValue; // Couldn't evaluate or not making progress...
2614 // Too many iterations were needed to evaluate.
2615 return UnknownValue;
2618 /// getSCEVAtScope - Compute the value of the specified expression within the
2619 /// indicated loop (which may be null to indicate in no loop). If the
2620 /// expression cannot be evaluated, return UnknownValue.
2621 SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2622 // FIXME: this should be turned into a virtual method on SCEV!
2624 if (isa<SCEVConstant>(V)) return V;
2626 // If this instruction is evolved from a constant-evolving PHI, compute the
2627 // exit value from the loop without using SCEVs.
2628 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2629 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2630 const Loop *LI = this->LI[I->getParent()];
2631 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2632 if (PHINode *PN = dyn_cast<PHINode>(I))
2633 if (PN->getParent() == LI->getHeader()) {
2634 // Okay, there is no closed form solution for the PHI node. Check
2635 // to see if the loop that contains it has a known backedge-taken
2636 // count. If so, we may be able to force computation of the exit
2638 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
2639 if (SCEVConstant *BTCC =
2640 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
2641 // Okay, we know how many times the containing loop executes. If
2642 // this is a constant evolving PHI node, get the final value at
2643 // the specified iteration number.
2644 Constant *RV = getConstantEvolutionLoopExitValue(PN,
2645 BTCC->getValue()->getValue(),
2647 if (RV) return SE.getUnknown(RV);
2651 // Okay, this is an expression that we cannot symbolically evaluate
2652 // into a SCEV. Check to see if it's possible to symbolically evaluate
2653 // the arguments into constants, and if so, try to constant propagate the
2654 // result. This is particularly useful for computing loop exit values.
2655 if (CanConstantFold(I)) {
2656 std::vector<Constant*> Operands;
2657 Operands.reserve(I->getNumOperands());
2658 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2659 Value *Op = I->getOperand(i);
2660 if (Constant *C = dyn_cast<Constant>(Op)) {
2661 Operands.push_back(C);
2663 // If any of the operands is non-constant and if they are
2664 // non-integer and non-pointer, don't even try to analyze them
2665 // with scev techniques.
2666 if (!isa<IntegerType>(Op->getType()) &&
2667 !isa<PointerType>(Op->getType()))
2670 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2671 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
2672 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2675 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2676 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
2677 Operands.push_back(ConstantExpr::getIntegerCast(C,
2689 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2690 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2691 &Operands[0], Operands.size());
2693 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2694 &Operands[0], Operands.size());
2695 return SE.getUnknown(C);
2699 // This is some other type of SCEVUnknown, just return it.
2703 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2704 // Avoid performing the look-up in the common case where the specified
2705 // expression has no loop-variant portions.
2706 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2707 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2708 if (OpAtScope != Comm->getOperand(i)) {
2709 if (OpAtScope == UnknownValue) return UnknownValue;
2710 // Okay, at least one of these operands is loop variant but might be
2711 // foldable. Build a new instance of the folded commutative expression.
2712 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2713 NewOps.push_back(OpAtScope);
2715 for (++i; i != e; ++i) {
2716 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2717 if (OpAtScope == UnknownValue) return UnknownValue;
2718 NewOps.push_back(OpAtScope);
2720 if (isa<SCEVAddExpr>(Comm))
2721 return SE.getAddExpr(NewOps);
2722 if (isa<SCEVMulExpr>(Comm))
2723 return SE.getMulExpr(NewOps);
2724 if (isa<SCEVSMaxExpr>(Comm))
2725 return SE.getSMaxExpr(NewOps);
2726 if (isa<SCEVUMaxExpr>(Comm))
2727 return SE.getUMaxExpr(NewOps);
2728 assert(0 && "Unknown commutative SCEV type!");
2731 // If we got here, all operands are loop invariant.
2735 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
2736 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
2737 if (LHS == UnknownValue) return LHS;
2738 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
2739 if (RHS == UnknownValue) return RHS;
2740 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2741 return Div; // must be loop invariant
2742 return SE.getUDivExpr(LHS, RHS);
2745 // If this is a loop recurrence for a loop that does not contain L, then we
2746 // are dealing with the final value computed by the loop.
2747 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2748 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2749 // To evaluate this recurrence, we need to know how many times the AddRec
2750 // loop iterates. Compute this now.
2751 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
2752 if (BackedgeTakenCount == UnknownValue) return UnknownValue;
2754 // Then, evaluate the AddRec.
2755 return AddRec->evaluateAtIteration(BackedgeTakenCount, SE);
2757 return UnknownValue;
2760 //assert(0 && "Unknown SCEV type!");
2761 return UnknownValue;
2764 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2765 /// following equation:
2767 /// A * X = B (mod N)
2769 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2770 /// A and B isn't important.
2772 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2773 static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2774 ScalarEvolution &SE) {
2775 uint32_t BW = A.getBitWidth();
2776 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2777 assert(A != 0 && "A must be non-zero.");
2781 // The gcd of A and N may have only one prime factor: 2. The number of
2782 // trailing zeros in A is its multiplicity
2783 uint32_t Mult2 = A.countTrailingZeros();
2786 // 2. Check if B is divisible by D.
2788 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2789 // is not less than multiplicity of this prime factor for D.
2790 if (B.countTrailingZeros() < Mult2)
2791 return SE.getCouldNotCompute();
2793 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2796 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2797 // bit width during computations.
2798 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2799 APInt Mod(BW + 1, 0);
2800 Mod.set(BW - Mult2); // Mod = N / D
2801 APInt I = AD.multiplicativeInverse(Mod);
2803 // 4. Compute the minimum unsigned root of the equation:
2804 // I * (B / D) mod (N / D)
2805 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2807 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2809 return SE.getConstant(Result.trunc(BW));
2812 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2813 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2814 /// might be the same) or two SCEVCouldNotCompute objects.
2816 static std::pair<SCEVHandle,SCEVHandle>
2817 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
2818 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2819 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2820 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2821 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2823 // We currently can only solve this if the coefficients are constants.
2824 if (!LC || !MC || !NC) {
2825 SCEV *CNC = SE.getCouldNotCompute();
2826 return std::make_pair(CNC, CNC);
2829 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2830 const APInt &L = LC->getValue()->getValue();
2831 const APInt &M = MC->getValue()->getValue();
2832 const APInt &N = NC->getValue()->getValue();
2833 APInt Two(BitWidth, 2);
2834 APInt Four(BitWidth, 4);
2837 using namespace APIntOps;
2839 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2840 // The B coefficient is M-N/2
2844 // The A coefficient is N/2
2845 APInt A(N.sdiv(Two));
2847 // Compute the B^2-4ac term.
2850 SqrtTerm -= Four * (A * C);
2852 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2853 // integer value or else APInt::sqrt() will assert.
2854 APInt SqrtVal(SqrtTerm.sqrt());
2856 // Compute the two solutions for the quadratic formula.
2857 // The divisions must be performed as signed divisions.
2859 APInt TwoA( A << 1 );
2860 if (TwoA.isMinValue()) {
2861 SCEV *CNC = SE.getCouldNotCompute();
2862 return std::make_pair(CNC, CNC);
2865 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2866 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2868 return std::make_pair(SE.getConstant(Solution1),
2869 SE.getConstant(Solution2));
2870 } // end APIntOps namespace
2873 /// HowFarToZero - Return the number of times a backedge comparing the specified
2874 /// value to zero will execute. If not computable, return UnknownValue
2875 SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2876 // If the value is a constant
2877 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2878 // If the value is already zero, the branch will execute zero times.
2879 if (C->getValue()->isZero()) return C;
2880 return UnknownValue; // Otherwise it will loop infinitely.
2883 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2884 if (!AddRec || AddRec->getLoop() != L)
2885 return UnknownValue;
2887 if (AddRec->isAffine()) {
2888 // If this is an affine expression, the execution count of this branch is
2889 // the minimum unsigned root of the following equation:
2891 // Start + Step*N = 0 (mod 2^BW)
2895 // Step*N = -Start (mod 2^BW)
2897 // where BW is the common bit width of Start and Step.
2899 // Get the initial value for the loop.
2900 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2901 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
2903 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
2905 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2906 // For now we handle only constant steps.
2908 // First, handle unitary steps.
2909 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
2910 return SE.getNegativeSCEV(Start); // N = -Start (as unsigned)
2911 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2912 return Start; // N = Start (as unsigned)
2914 // Then, try to solve the above equation provided that Start is constant.
2915 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
2916 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
2917 -StartC->getValue()->getValue(),SE);
2919 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2920 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2921 // the quadratic equation to solve it.
2922 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE);
2923 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2924 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2927 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
2928 << " sol#2: " << *R2 << "\n";
2930 // Pick the smallest positive root value.
2931 if (ConstantInt *CB =
2932 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2933 R1->getValue(), R2->getValue()))) {
2934 if (CB->getZExtValue() == false)
2935 std::swap(R1, R2); // R1 is the minimum root now.
2937 // We can only use this value if the chrec ends up with an exact zero
2938 // value at this index. When solving for "X*X != 5", for example, we
2939 // should not accept a root of 2.
2940 SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE);
2942 return R1; // We found a quadratic root!
2947 return UnknownValue;
2950 /// HowFarToNonZero - Return the number of times a backedge checking the
2951 /// specified value for nonzero will execute. If not computable, return
2953 SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2954 // Loops that look like: while (X == 0) are very strange indeed. We don't
2955 // handle them yet except for the trivial case. This could be expanded in the
2956 // future as needed.
2958 // If the value is a constant, check to see if it is known to be non-zero
2959 // already. If so, the backedge will execute zero times.
2960 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2961 if (!C->getValue()->isNullValue())
2962 return SE.getIntegerSCEV(0, C->getType());
2963 return UnknownValue; // Otherwise it will loop infinitely.
2966 // We could implement others, but I really doubt anyone writes loops like
2967 // this, and if they did, they would already be constant folded.
2968 return UnknownValue;
2971 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
2972 /// (which may not be an immediate predecessor) which has exactly one
2973 /// successor from which BB is reachable, or null if no such block is
2977 ScalarEvolutionsImpl::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
2978 // If the block has a unique predecessor, the predecessor must have
2979 // no other successors from which BB is reachable.
2980 if (BasicBlock *Pred = BB->getSinglePredecessor())
2983 // A loop's header is defined to be a block that dominates the loop.
2984 // If the loop has a preheader, it must be a block that has exactly
2985 // one successor that can reach BB. This is slightly more strict
2986 // than necessary, but works if critical edges are split.
2987 if (Loop *L = LI.getLoopFor(BB))
2988 return L->getLoopPreheader();
2993 /// isLoopGuardedByCond - Test whether entry to the loop is protected by
2994 /// a conditional between LHS and RHS.
2995 bool ScalarEvolutionsImpl::isLoopGuardedByCond(const Loop *L,
2996 ICmpInst::Predicate Pred,
2997 SCEV *LHS, SCEV *RHS) {
2998 BasicBlock *Preheader = L->getLoopPreheader();
2999 BasicBlock *PreheaderDest = L->getHeader();
3001 // Starting at the preheader, climb up the predecessor chain, as long as
3002 // there are predecessors that can be found that have unique successors
3003 // leading to the original header.
3005 PreheaderDest = Preheader,
3006 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
3008 BranchInst *LoopEntryPredicate =
3009 dyn_cast<BranchInst>(Preheader->getTerminator());
3010 if (!LoopEntryPredicate ||
3011 LoopEntryPredicate->isUnconditional())
3014 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3017 // Now that we found a conditional branch that dominates the loop, check to
3018 // see if it is the comparison we are looking for.
3019 Value *PreCondLHS = ICI->getOperand(0);
3020 Value *PreCondRHS = ICI->getOperand(1);
3021 ICmpInst::Predicate Cond;
3022 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
3023 Cond = ICI->getPredicate();
3025 Cond = ICI->getInversePredicate();
3028 ; // An exact match.
3029 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3030 ; // The actual condition is beyond sufficient.
3032 // Check a few special cases.
3034 case ICmpInst::ICMP_UGT:
3035 if (Pred == ICmpInst::ICMP_ULT) {
3036 std::swap(PreCondLHS, PreCondRHS);
3037 Cond = ICmpInst::ICMP_ULT;
3041 case ICmpInst::ICMP_SGT:
3042 if (Pred == ICmpInst::ICMP_SLT) {
3043 std::swap(PreCondLHS, PreCondRHS);
3044 Cond = ICmpInst::ICMP_SLT;
3048 case ICmpInst::ICMP_NE:
3049 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3050 // so check for this case by checking if the NE is comparing against
3051 // a minimum or maximum constant.
3052 if (!ICmpInst::isTrueWhenEqual(Pred))
3053 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3054 const APInt &A = CI->getValue();
3056 case ICmpInst::ICMP_SLT:
3057 if (A.isMaxSignedValue()) break;
3059 case ICmpInst::ICMP_SGT:
3060 if (A.isMinSignedValue()) break;
3062 case ICmpInst::ICMP_ULT:
3063 if (A.isMaxValue()) break;
3065 case ICmpInst::ICMP_UGT:
3066 if (A.isMinValue()) break;
3071 Cond = ICmpInst::ICMP_NE;
3072 // NE is symmetric but the original comparison may not be. Swap
3073 // the operands if necessary so that they match below.
3074 if (isa<SCEVConstant>(LHS))
3075 std::swap(PreCondLHS, PreCondRHS);
3080 // We weren't able to reconcile the condition.
3084 if (!PreCondLHS->getType()->isInteger()) continue;
3086 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3087 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3088 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
3089 (LHS == SE.getNotSCEV(PreCondRHSSCEV) &&
3090 RHS == SE.getNotSCEV(PreCondLHSSCEV)))
3097 /// HowManyLessThans - Return the number of times a backedge containing the
3098 /// specified less-than comparison will execute. If not computable, return
3100 SCEVHandle ScalarEvolutionsImpl::
3101 HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
3102 // Only handle: "ADDREC < LoopInvariant".
3103 if (!RHS->isLoopInvariant(L)) return UnknownValue;
3105 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
3106 if (!AddRec || AddRec->getLoop() != L)
3107 return UnknownValue;
3109 if (AddRec->isAffine()) {
3110 // FORNOW: We only support unit strides.
3111 SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType());
3112 if (AddRec->getOperand(1) != One)
3113 return UnknownValue;
3115 // We know the LHS is of the form {n,+,1} and the RHS is some loop-invariant
3116 // m. So, we count the number of iterations in which {n,+,1} < m is true.
3117 // Note that we cannot simply return max(m-n,0) because it's not safe to
3118 // treat m-n as signed nor unsigned due to overflow possibility.
3120 // First, we get the value of the LHS in the first iteration: n
3121 SCEVHandle Start = AddRec->getOperand(0);
3123 if (isLoopGuardedByCond(L,
3124 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3125 SE.getMinusSCEV(AddRec->getOperand(0), One), RHS)) {
3126 // Since we know that the condition is true in order to enter the loop,
3127 // we know that it will run exactly m-n times.
3128 return SE.getMinusSCEV(RHS, Start);
3130 // Then, we get the value of the LHS in the first iteration in which the
3131 // above condition doesn't hold. This equals to max(m,n).
3132 SCEVHandle End = isSigned ? SE.getSMaxExpr(RHS, Start)
3133 : SE.getUMaxExpr(RHS, Start);
3135 // Finally, we subtract these two values to get the number of times the
3136 // backedge is executed: max(m,n)-n.
3137 return SE.getMinusSCEV(End, Start);
3141 return UnknownValue;
3144 /// getNumIterationsInRange - Return the number of iterations of this loop that
3145 /// produce values in the specified constant range. Another way of looking at
3146 /// this is that it returns the first iteration number where the value is not in
3147 /// the condition, thus computing the exit count. If the iteration count can't
3148 /// be computed, an instance of SCEVCouldNotCompute is returned.
3149 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3150 ScalarEvolution &SE) const {
3151 if (Range.isFullSet()) // Infinite loop.
3152 return SE.getCouldNotCompute();
3154 // If the start is a non-zero constant, shift the range to simplify things.
3155 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
3156 if (!SC->getValue()->isZero()) {
3157 std::vector<SCEVHandle> Operands(op_begin(), op_end());
3158 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3159 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
3160 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
3161 return ShiftedAddRec->getNumIterationsInRange(
3162 Range.subtract(SC->getValue()->getValue()), SE);
3163 // This is strange and shouldn't happen.
3164 return SE.getCouldNotCompute();
3167 // The only time we can solve this is when we have all constant indices.
3168 // Otherwise, we cannot determine the overflow conditions.
3169 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3170 if (!isa<SCEVConstant>(getOperand(i)))
3171 return SE.getCouldNotCompute();
3174 // Okay at this point we know that all elements of the chrec are constants and
3175 // that the start element is zero.
3177 // First check to see if the range contains zero. If not, the first
3179 unsigned BitWidth = SE.getTypeSizeInBits(getType());
3180 if (!Range.contains(APInt(BitWidth, 0)))
3181 return SE.getConstant(ConstantInt::get(getType(),0));
3184 // If this is an affine expression then we have this situation:
3185 // Solve {0,+,A} in Range === Ax in Range
3187 // We know that zero is in the range. If A is positive then we know that
3188 // the upper value of the range must be the first possible exit value.
3189 // If A is negative then the lower of the range is the last possible loop
3190 // value. Also note that we already checked for a full range.
3191 APInt One(BitWidth,1);
3192 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3193 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3195 // The exit value should be (End+A)/A.
3196 APInt ExitVal = (End + A).udiv(A);
3197 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3199 // Evaluate at the exit value. If we really did fall out of the valid
3200 // range, then we computed our trip count, otherwise wrap around or other
3201 // things must have happened.
3202 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
3203 if (Range.contains(Val->getValue()))
3204 return SE.getCouldNotCompute(); // Something strange happened
3206 // Ensure that the previous value is in the range. This is a sanity check.
3207 assert(Range.contains(
3208 EvaluateConstantChrecAtConstant(this,
3209 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
3210 "Linear scev computation is off in a bad way!");
3211 return SE.getConstant(ExitValue);
3212 } else if (isQuadratic()) {
3213 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3214 // quadratic equation to solve it. To do this, we must frame our problem in
3215 // terms of figuring out when zero is crossed, instead of when
3216 // Range.getUpper() is crossed.
3217 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
3218 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3219 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
3221 // Next, solve the constructed addrec
3222 std::pair<SCEVHandle,SCEVHandle> Roots =
3223 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
3224 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3225 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3227 // Pick the smallest positive root value.
3228 if (ConstantInt *CB =
3229 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3230 R1->getValue(), R2->getValue()))) {
3231 if (CB->getZExtValue() == false)
3232 std::swap(R1, R2); // R1 is the minimum root now.
3234 // Make sure the root is not off by one. The returned iteration should
3235 // not be in the range, but the previous one should be. When solving
3236 // for "X*X < 5", for example, we should not return a root of 2.
3237 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
3240 if (Range.contains(R1Val->getValue())) {
3241 // The next iteration must be out of the range...
3242 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3244 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
3245 if (!Range.contains(R1Val->getValue()))
3246 return SE.getConstant(NextVal);
3247 return SE.getCouldNotCompute(); // Something strange happened
3250 // If R1 was not in the range, then it is a good return value. Make
3251 // sure that R1-1 WAS in the range though, just in case.
3252 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
3253 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
3254 if (Range.contains(R1Val->getValue()))
3256 return SE.getCouldNotCompute(); // Something strange happened
3261 return SE.getCouldNotCompute();
3266 //===----------------------------------------------------------------------===//
3267 // ScalarEvolution Class Implementation
3268 //===----------------------------------------------------------------------===//
3270 bool ScalarEvolution::runOnFunction(Function &F) {
3271 Impl = new ScalarEvolutionsImpl(*this, F,
3272 getAnalysis<LoopInfo>(),
3273 getAnalysisIfAvailable<TargetData>());
3277 void ScalarEvolution::releaseMemory() {
3278 delete (ScalarEvolutionsImpl*)Impl;
3282 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3283 AU.setPreservesAll();
3284 AU.addRequiredTransitive<LoopInfo>();
3287 bool ScalarEvolution::isSCEVable(const Type *Ty) const {
3288 return ((ScalarEvolutionsImpl*)Impl)->isSCEVable(Ty);
3291 uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
3292 return ((ScalarEvolutionsImpl*)Impl)->getTypeSizeInBits(Ty);
3295 const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
3296 return ((ScalarEvolutionsImpl*)Impl)->getEffectiveSCEVType(Ty);
3299 SCEVHandle ScalarEvolution::getCouldNotCompute() {
3300 return ((ScalarEvolutionsImpl*)Impl)->getCouldNotCompute();
3303 SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
3304 return ((ScalarEvolutionsImpl*)Impl)->getIntegerSCEV(Val, Ty);
3307 SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
3308 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
3311 /// hasSCEV - Return true if the SCEV for this value has already been
3313 bool ScalarEvolution::hasSCEV(Value *V) const {
3314 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
3318 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
3319 /// the specified value.
3320 void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
3321 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
3324 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
3326 SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
3327 return ((ScalarEvolutionsImpl*)Impl)->getNegativeSCEV(V);
3330 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
3332 SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
3333 return ((ScalarEvolutionsImpl*)Impl)->getNotSCEV(V);
3336 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
3338 SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
3339 const SCEVHandle &RHS) {
3340 return ((ScalarEvolutionsImpl*)Impl)->getMinusSCEV(LHS, RHS);
3343 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
3344 /// of the input value to the specified type. If the type must be
3345 /// extended, it is zero extended.
3346 SCEVHandle ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
3348 return ((ScalarEvolutionsImpl*)Impl)->getTruncateOrZeroExtend(V, Ty);
3351 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
3352 /// of the input value to the specified type. If the type must be
3353 /// extended, it is sign extended.
3354 SCEVHandle ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
3356 return ((ScalarEvolutionsImpl*)Impl)->getTruncateOrSignExtend(V, Ty);
3360 bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
3361 ICmpInst::Predicate Pred,
3362 SCEV *LHS, SCEV *RHS) {
3363 return ((ScalarEvolutionsImpl*)Impl)->isLoopGuardedByCond(L, Pred,
3367 SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) const {
3368 return ((ScalarEvolutionsImpl*)Impl)->getBackedgeTakenCount(L);
3371 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) const {
3372 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
3375 void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
3376 return ((ScalarEvolutionsImpl*)Impl)->forgetLoopBackedgeTakenCount(L);
3379 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
3380 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
3383 void ScalarEvolution::deleteValueFromRecords(Value *V) const {
3384 return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
3387 static void PrintLoopInfo(raw_ostream &OS, const ScalarEvolution *SE,
3389 // Print all inner loops first
3390 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3391 PrintLoopInfo(OS, SE, *I);
3393 OS << "Loop " << L->getHeader()->getName() << ": ";
3395 SmallVector<BasicBlock*, 8> ExitBlocks;
3396 L->getExitBlocks(ExitBlocks);
3397 if (ExitBlocks.size() != 1)
3398 OS << "<multiple exits> ";
3400 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3401 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
3403 OS << "Unpredictable backedge-taken count. ";
3409 void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
3410 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
3411 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
3413 OS << "Classifying expressions for: " << F.getName() << "\n";
3414 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
3415 if (I->getType()->isInteger()) {
3418 SCEVHandle SV = getSCEV(&*I);
3422 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
3424 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
3425 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3426 OS << "<<Unknown>>";
3436 OS << "Determining loop execution counts for: " << F.getName() << "\n";
3437 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
3438 PrintLoopInfo(OS, this, *I);
3441 void ScalarEvolution::print(std::ostream &o, const Module *M) const {
3442 raw_os_ostream OS(o);