Teach getZeroExtendExpr and getSignExtendExpr to use trip-count
[llvm/msp430.git] / lib / Analysis / ScalarEvolution.cpp
blob63ad2970f48be3989f4b8b99a98750cd384ed698
1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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
48 // Eugene V. Zima
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"
85 #include <ostream>
86 #include <algorithm>
87 #include <cmath>
88 using namespace llvm;
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"),
103 cl::init(100));
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.
116 SCEV::~SCEV() {}
117 void SCEV::dump() const {
118 print(errs());
119 errs() << '\n';
122 void SCEV::print(std::ostream &o) const {
123 raw_os_ostream OS(o);
124 print(OS);
127 bool SCEV::isZero() const {
128 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
129 return SC->getValue()->isZero();
130 return false;
134 SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
135 SCEVCouldNotCompute::~SCEVCouldNotCompute() {}
137 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
138 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
139 return false;
142 const Type *SCEVCouldNotCompute::getType() const {
143 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
144 return 0;
147 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
148 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
149 return false;
152 SCEVHandle SCEVCouldNotCompute::
153 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
154 const SCEVHandle &Conc,
155 ScalarEvolution &SE) const {
156 return this;
159 void SCEVCouldNotCompute::print(raw_ostream &OS) const {
160 OS << "***COULDNOTCOMPUTE***";
163 bool SCEVCouldNotCompute::classof(const SCEV *S) {
164 return S->getSCEVType() == scCouldNotCompute;
168 // SCEVConstants - Only allow the creation of one SCEVConstant for any
169 // particular value. Don't use a SCEVHandle here, or else the object will
170 // never be deleted!
171 static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
174 SCEVConstant::~SCEVConstant() {
175 SCEVConstants->erase(V);
178 SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
179 SCEVConstant *&R = (*SCEVConstants)[V];
180 if (R == 0) R = new SCEVConstant(V);
181 return R;
184 SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
185 return getConstant(ConstantInt::get(Val));
188 const Type *SCEVConstant::getType() const { return V->getType(); }
190 void SCEVConstant::print(raw_ostream &OS) const {
191 WriteAsOperand(OS, V, false);
194 SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
195 const SCEVHandle &op, const Type *ty)
196 : SCEV(SCEVTy), Op(op), Ty(ty) {}
198 SCEVCastExpr::~SCEVCastExpr() {}
200 bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
201 return Op->dominates(BB, DT);
204 // SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
205 // particular input. Don't use a SCEVHandle here, or else the object will
206 // never be deleted!
207 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
208 SCEVTruncateExpr*> > SCEVTruncates;
210 SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
211 : SCEVCastExpr(scTruncate, op, ty) {
212 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
213 (Ty->isInteger() || isa<PointerType>(Ty)) &&
214 "Cannot truncate non-integer value!");
217 SCEVTruncateExpr::~SCEVTruncateExpr() {
218 SCEVTruncates->erase(std::make_pair(Op, Ty));
221 void SCEVTruncateExpr::print(raw_ostream &OS) const {
222 OS << "(truncate " << *Op << " to " << *Ty << ")";
225 // SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
226 // particular input. Don't use a SCEVHandle here, or else the object will never
227 // be deleted!
228 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
229 SCEVZeroExtendExpr*> > SCEVZeroExtends;
231 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
232 : SCEVCastExpr(scZeroExtend, op, ty) {
233 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
234 (Ty->isInteger() || isa<PointerType>(Ty)) &&
235 "Cannot zero extend non-integer value!");
238 SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
239 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
242 void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
243 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
246 // SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
247 // particular input. Don't use a SCEVHandle here, or else the object will never
248 // be deleted!
249 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
250 SCEVSignExtendExpr*> > SCEVSignExtends;
252 SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
253 : SCEVCastExpr(scSignExtend, op, ty) {
254 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
255 (Ty->isInteger() || isa<PointerType>(Ty)) &&
256 "Cannot sign extend non-integer value!");
259 SCEVSignExtendExpr::~SCEVSignExtendExpr() {
260 SCEVSignExtends->erase(std::make_pair(Op, Ty));
263 void SCEVSignExtendExpr::print(raw_ostream &OS) const {
264 OS << "(signextend " << *Op << " to " << *Ty << ")";
267 // SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
268 // particular input. Don't use a SCEVHandle here, or else the object will never
269 // be deleted!
270 static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
271 SCEVCommutativeExpr*> > SCEVCommExprs;
273 SCEVCommutativeExpr::~SCEVCommutativeExpr() {
274 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
275 std::vector<SCEV*>(Operands.begin(),
276 Operands.end())));
279 void SCEVCommutativeExpr::print(raw_ostream &OS) const {
280 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
281 const char *OpStr = getOperationStr();
282 OS << "(" << *Operands[0];
283 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
284 OS << OpStr << *Operands[i];
285 OS << ")";
288 SCEVHandle SCEVCommutativeExpr::
289 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
290 const SCEVHandle &Conc,
291 ScalarEvolution &SE) const {
292 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
293 SCEVHandle H =
294 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
295 if (H != getOperand(i)) {
296 std::vector<SCEVHandle> NewOps;
297 NewOps.reserve(getNumOperands());
298 for (unsigned j = 0; j != i; ++j)
299 NewOps.push_back(getOperand(j));
300 NewOps.push_back(H);
301 for (++i; i != e; ++i)
302 NewOps.push_back(getOperand(i)->
303 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
305 if (isa<SCEVAddExpr>(this))
306 return SE.getAddExpr(NewOps);
307 else if (isa<SCEVMulExpr>(this))
308 return SE.getMulExpr(NewOps);
309 else if (isa<SCEVSMaxExpr>(this))
310 return SE.getSMaxExpr(NewOps);
311 else if (isa<SCEVUMaxExpr>(this))
312 return SE.getUMaxExpr(NewOps);
313 else
314 assert(0 && "Unknown commutative expr!");
317 return this;
320 bool SCEVCommutativeExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
321 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
322 if (!getOperand(i)->dominates(BB, DT))
323 return false;
325 return true;
329 // SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
330 // input. Don't use a SCEVHandle here, or else the object will never be
331 // deleted!
332 static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
333 SCEVUDivExpr*> > SCEVUDivs;
335 SCEVUDivExpr::~SCEVUDivExpr() {
336 SCEVUDivs->erase(std::make_pair(LHS, RHS));
339 bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
340 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
343 void SCEVUDivExpr::print(raw_ostream &OS) const {
344 OS << "(" << *LHS << " /u " << *RHS << ")";
347 const Type *SCEVUDivExpr::getType() const {
348 return LHS->getType();
351 // SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
352 // particular input. Don't use a SCEVHandle here, or else the object will never
353 // be deleted!
354 static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
355 SCEVAddRecExpr*> > SCEVAddRecExprs;
357 SCEVAddRecExpr::~SCEVAddRecExpr() {
358 SCEVAddRecExprs->erase(std::make_pair(L,
359 std::vector<SCEV*>(Operands.begin(),
360 Operands.end())));
363 bool SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
364 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
365 if (!getOperand(i)->dominates(BB, DT))
366 return false;
368 return true;
372 SCEVHandle SCEVAddRecExpr::
373 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
374 const SCEVHandle &Conc,
375 ScalarEvolution &SE) const {
376 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
377 SCEVHandle H =
378 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
379 if (H != getOperand(i)) {
380 std::vector<SCEVHandle> NewOps;
381 NewOps.reserve(getNumOperands());
382 for (unsigned j = 0; j != i; ++j)
383 NewOps.push_back(getOperand(j));
384 NewOps.push_back(H);
385 for (++i; i != e; ++i)
386 NewOps.push_back(getOperand(i)->
387 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
389 return SE.getAddRecExpr(NewOps, L);
392 return this;
396 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
397 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
398 // contain L and if the start is invariant.
399 return !QueryLoop->contains(L->getHeader()) &&
400 getOperand(0)->isLoopInvariant(QueryLoop);
404 void SCEVAddRecExpr::print(raw_ostream &OS) const {
405 OS << "{" << *Operands[0];
406 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
407 OS << ",+," << *Operands[i];
408 OS << "}<" << L->getHeader()->getName() + ">";
411 // SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
412 // value. Don't use a SCEVHandle here, or else the object will never be
413 // deleted!
414 static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
416 SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
418 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
419 // All non-instruction values are loop invariant. All instructions are loop
420 // invariant if they are not contained in the specified loop.
421 if (Instruction *I = dyn_cast<Instruction>(V))
422 return !L->contains(I->getParent());
423 return true;
426 bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
427 if (Instruction *I = dyn_cast<Instruction>(getValue()))
428 return DT->dominates(I->getParent(), BB);
429 return true;
432 const Type *SCEVUnknown::getType() const {
433 return V->getType();
436 void SCEVUnknown::print(raw_ostream &OS) const {
437 if (isa<PointerType>(V->getType()))
438 OS << "(ptrtoint " << *V->getType() << " ";
439 WriteAsOperand(OS, V, false);
440 if (isa<PointerType>(V->getType()))
441 OS << " to iPTR)";
444 //===----------------------------------------------------------------------===//
445 // SCEV Utilities
446 //===----------------------------------------------------------------------===//
448 namespace {
449 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
450 /// than the complexity of the RHS. This comparator is used to canonicalize
451 /// expressions.
452 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
453 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
454 return LHS->getSCEVType() < RHS->getSCEVType();
459 /// GroupByComplexity - Given a list of SCEV objects, order them by their
460 /// complexity, and group objects of the same complexity together by value.
461 /// When this routine is finished, we know that any duplicates in the vector are
462 /// consecutive and that complexity is monotonically increasing.
464 /// Note that we go take special precautions to ensure that we get determinstic
465 /// results from this routine. In other words, we don't want the results of
466 /// this to depend on where the addresses of various SCEV objects happened to
467 /// land in memory.
469 static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
470 if (Ops.size() < 2) return; // Noop
471 if (Ops.size() == 2) {
472 // This is the common case, which also happens to be trivially simple.
473 // Special case it.
474 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
475 std::swap(Ops[0], Ops[1]);
476 return;
479 // Do the rough sort by complexity.
480 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
482 // Now that we are sorted by complexity, group elements of the same
483 // complexity. Note that this is, at worst, N^2, but the vector is likely to
484 // be extremely short in practice. Note that we take this approach because we
485 // do not want to depend on the addresses of the objects we are grouping.
486 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
487 SCEV *S = Ops[i];
488 unsigned Complexity = S->getSCEVType();
490 // If there are any objects of the same complexity and same value as this
491 // one, group them.
492 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
493 if (Ops[j] == S) { // Found a duplicate.
494 // Move it to immediately after i'th element.
495 std::swap(Ops[i+1], Ops[j]);
496 ++i; // no need to rescan it.
497 if (i == e-2) return; // Done!
505 //===----------------------------------------------------------------------===//
506 // Simple SCEV method implementations
507 //===----------------------------------------------------------------------===//
509 /// BinomialCoefficient - Compute BC(It, K). The result has width W.
510 // Assume, K > 0.
511 static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
512 ScalarEvolution &SE,
513 const Type* ResultTy) {
514 // Handle the simplest case efficiently.
515 if (K == 1)
516 return SE.getTruncateOrZeroExtend(It, ResultTy);
518 // We are using the following formula for BC(It, K):
520 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
522 // Suppose, W is the bitwidth of the return value. We must be prepared for
523 // overflow. Hence, we must assure that the result of our computation is
524 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
525 // safe in modular arithmetic.
527 // However, this code doesn't use exactly that formula; the formula it uses
528 // is something like the following, where T is the number of factors of 2 in
529 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
530 // exponentiation:
532 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
534 // This formula is trivially equivalent to the previous formula. However,
535 // this formula can be implemented much more efficiently. The trick is that
536 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
537 // arithmetic. To do exact division in modular arithmetic, all we have
538 // to do is multiply by the inverse. Therefore, this step can be done at
539 // width W.
541 // The next issue is how to safely do the division by 2^T. The way this
542 // is done is by doing the multiplication step at a width of at least W + T
543 // bits. This way, the bottom W+T bits of the product are accurate. Then,
544 // when we perform the division by 2^T (which is equivalent to a right shift
545 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
546 // truncated out after the division by 2^T.
548 // In comparison to just directly using the first formula, this technique
549 // is much more efficient; using the first formula requires W * K bits,
550 // but this formula less than W + K bits. Also, the first formula requires
551 // a division step, whereas this formula only requires multiplies and shifts.
553 // It doesn't matter whether the subtraction step is done in the calculation
554 // width or the input iteration count's width; if the subtraction overflows,
555 // the result must be zero anyway. We prefer here to do it in the width of
556 // the induction variable because it helps a lot for certain cases; CodeGen
557 // isn't smart enough to ignore the overflow, which leads to much less
558 // efficient code if the width of the subtraction is wider than the native
559 // register width.
561 // (It's possible to not widen at all by pulling out factors of 2 before
562 // the multiplication; for example, K=2 can be calculated as
563 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
564 // extra arithmetic, so it's not an obvious win, and it gets
565 // much more complicated for K > 3.)
567 // Protection from insane SCEVs; this bound is conservative,
568 // but it probably doesn't matter.
569 if (K > 1000)
570 return SE.getCouldNotCompute();
572 unsigned W = SE.getTypeSizeInBits(ResultTy);
574 // Calculate K! / 2^T and T; we divide out the factors of two before
575 // multiplying for calculating K! / 2^T to avoid overflow.
576 // Other overflow doesn't matter because we only care about the bottom
577 // W bits of the result.
578 APInt OddFactorial(W, 1);
579 unsigned T = 1;
580 for (unsigned i = 3; i <= K; ++i) {
581 APInt Mult(W, i);
582 unsigned TwoFactors = Mult.countTrailingZeros();
583 T += TwoFactors;
584 Mult = Mult.lshr(TwoFactors);
585 OddFactorial *= Mult;
588 // We need at least W + T bits for the multiplication step
589 unsigned CalculationBits = W + T;
591 // Calcuate 2^T, at width T+W.
592 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
594 // Calculate the multiplicative inverse of K! / 2^T;
595 // this multiplication factor will perform the exact division by
596 // K! / 2^T.
597 APInt Mod = APInt::getSignedMinValue(W+1);
598 APInt MultiplyFactor = OddFactorial.zext(W+1);
599 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
600 MultiplyFactor = MultiplyFactor.trunc(W);
602 // Calculate the product, at width T+W
603 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
604 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
605 for (unsigned i = 1; i != K; ++i) {
606 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
607 Dividend = SE.getMulExpr(Dividend,
608 SE.getTruncateOrZeroExtend(S, CalculationTy));
611 // Divide by 2^T
612 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
614 // Truncate the result, and divide by K! / 2^T.
616 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
617 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
620 /// evaluateAtIteration - Return the value of this chain of recurrences at
621 /// the specified iteration number. We can evaluate this recurrence by
622 /// multiplying each element in the chain by the binomial coefficient
623 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
625 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
627 /// where BC(It, k) stands for binomial coefficient.
629 SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
630 ScalarEvolution &SE) const {
631 SCEVHandle Result = getStart();
632 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
633 // The computation is correct in the face of overflow provided that the
634 // multiplication is performed _after_ the evaluation of the binomial
635 // coefficient.
636 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
637 if (isa<SCEVCouldNotCompute>(Coeff))
638 return Coeff;
640 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
642 return Result;
645 //===----------------------------------------------------------------------===//
646 // SCEV Expression folder implementations
647 //===----------------------------------------------------------------------===//
649 SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
650 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
651 "This is not a truncating conversion!");
653 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
654 return getUnknown(
655 ConstantExpr::getTrunc(SC->getValue(), Ty));
657 // trunc(trunc(x)) --> trunc(x)
658 if (SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
659 return getTruncateExpr(ST->getOperand(), Ty);
661 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
662 if (SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
663 return getTruncateOrSignExtend(SS->getOperand(), Ty);
665 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
666 if (SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
667 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
669 // If the input value is a chrec scev made out of constants, truncate
670 // all of the constants.
671 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
672 std::vector<SCEVHandle> Operands;
673 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
674 // FIXME: This should allow truncation of other expression types!
675 if (isa<SCEVConstant>(AddRec->getOperand(i)))
676 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
677 else
678 break;
679 if (Operands.size() == AddRec->getNumOperands())
680 return getAddRecExpr(Operands, AddRec->getLoop());
683 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
684 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
685 return Result;
688 SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
689 const Type *Ty) {
690 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
691 "This is not an extending conversion!");
693 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
694 const Type *IntTy = getEffectiveSCEVType(Ty);
695 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
696 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
697 return getUnknown(C);
700 // zext(zext(x)) --> zext(x)
701 if (SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
702 return getZeroExtendExpr(SZ->getOperand(), Ty);
704 // If the input value is a chrec scev, and we can prove that the value
705 // did not overflow the old, smaller, value, we can zero extend all of the
706 // operands (often constants). This allows analysis of something like
707 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
708 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
709 if (AR->isAffine()) {
710 // Check whether the backedge-taken count is SCEVCouldNotCompute.
711 // Note that this serves two purposes: It filters out loops that are
712 // simply not analyzable, and it covers the case where this code is
713 // being called from within backedge-taken count analysis, such that
714 // attempting to ask for the backedge-taken count would likely result
715 // in infinite recursion. In the later case, the analysis code will
716 // cope with a conservative value, and it will take care to purge
717 // that value once it has finished.
718 SCEVHandle BECount = getBackedgeTakenCount(AR->getLoop());
719 if (!isa<SCEVCouldNotCompute>(BECount)) {
720 // Compute the extent of AR and divide it by the step value. This is
721 // used to determine if it's safe to extend the stride value.
722 SCEVHandle Start = AR->getStart();
723 SCEVHandle Step = AR->getStepRecurrence(*this);
725 // Check whether the backedge-taken count can be losslessly casted to
726 // the addrec's type. The count is always unsigned.
727 SCEVHandle CastedBECount =
728 getTruncateOrZeroExtend(BECount, Start->getType());
729 if (BECount ==
730 getTruncateOrZeroExtend(CastedBECount, BECount->getType())) {
731 const Type *WideTy =
732 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
733 SCEVHandle ZMul =
734 getMulExpr(CastedBECount,
735 getTruncateOrZeroExtend(Step, Start->getType()));
736 // Check whether Start+Step*BECount has no unsigned overflow.
737 if (getZeroExtendExpr(ZMul, WideTy) ==
738 getMulExpr(getZeroExtendExpr(CastedBECount, WideTy),
739 getZeroExtendExpr(Step, WideTy))) {
740 SCEVHandle Add = getAddExpr(Start, ZMul);
741 if (getZeroExtendExpr(Add, WideTy) ==
742 getAddExpr(getZeroExtendExpr(Start, WideTy),
743 getZeroExtendExpr(ZMul, WideTy)))
744 // Return the expression with the addrec on the outside.
745 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
746 getZeroExtendExpr(Step, Ty),
747 AR->getLoop());
750 // Similar to above, only this time treat the step value as signed.
751 // This covers loops that count down.
752 SCEVHandle SMul =
753 getMulExpr(CastedBECount,
754 getTruncateOrSignExtend(Step, Start->getType()));
755 // Check whether Start+Step*BECount has no unsigned overflow.
756 if (getSignExtendExpr(SMul, WideTy) ==
757 getMulExpr(getZeroExtendExpr(CastedBECount, WideTy),
758 getSignExtendExpr(Step, WideTy))) {
759 SCEVHandle Add = getAddExpr(Start, SMul);
760 if (getZeroExtendExpr(Add, WideTy) ==
761 getAddExpr(getZeroExtendExpr(Start, WideTy),
762 getSignExtendExpr(SMul, WideTy)))
763 // Return the expression with the addrec on the outside.
764 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
765 getSignExtendExpr(Step, Ty),
766 AR->getLoop());
772 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
773 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
774 return Result;
777 SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op,
778 const Type *Ty) {
779 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
780 "This is not an extending conversion!");
782 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
783 const Type *IntTy = getEffectiveSCEVType(Ty);
784 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
785 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
786 return getUnknown(C);
789 // sext(sext(x)) --> sext(x)
790 if (SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
791 return getSignExtendExpr(SS->getOperand(), Ty);
793 // If the input value is a chrec scev, and we can prove that the value
794 // did not overflow the old, smaller, value, we can sign extend all of the
795 // operands (often constants). This allows analysis of something like
796 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
797 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
798 if (AR->isAffine()) {
799 // Check whether the backedge-taken count is SCEVCouldNotCompute.
800 // Note that this serves two purposes: It filters out loops that are
801 // simply not analyzable, and it covers the case where this code is
802 // being called from within backedge-taken count analysis, such that
803 // attempting to ask for the backedge-taken count would likely result
804 // in infinite recursion. In the later case, the analysis code will
805 // cope with a conservative value, and it will take care to purge
806 // that value once it has finished.
807 SCEVHandle BECount = getBackedgeTakenCount(AR->getLoop());
808 if (!isa<SCEVCouldNotCompute>(BECount)) {
809 // Compute the extent of AR and divide it by the step value. This is
810 // used to determine if it's safe to extend the stride value.
811 SCEVHandle Start = AR->getStart();
812 SCEVHandle Step = AR->getStepRecurrence(*this);
814 // Check whether the backedge-taken count can be losslessly casted to
815 // the addrec's type. The count is always unsigned.
816 SCEVHandle CastedBECount =
817 getTruncateOrZeroExtend(BECount, Start->getType());
818 if (BECount ==
819 getTruncateOrZeroExtend(CastedBECount, BECount->getType())) {
820 const Type *WideTy =
821 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
822 SCEVHandle SMul =
823 getMulExpr(CastedBECount,
824 getTruncateOrSignExtend(Step, Start->getType()));
825 // Check whether Start+Step*BECount has no signed overflow.
826 if (getSignExtendExpr(SMul, WideTy) ==
827 getMulExpr(getSignExtendExpr(CastedBECount, WideTy),
828 getSignExtendExpr(Step, WideTy))) {
829 SCEVHandle Add = getAddExpr(Start, SMul);
830 if (getSignExtendExpr(Add, WideTy) ==
831 getAddExpr(getSignExtendExpr(Start, WideTy),
832 getSignExtendExpr(SMul, WideTy)))
833 // Return the expression with the addrec on the outside.
834 return getAddRecExpr(getSignExtendExpr(Start, Ty),
835 getSignExtendExpr(Step, Ty),
836 AR->getLoop());
842 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
843 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
844 return Result;
847 // get - Get a canonical add expression, or something simpler if possible.
848 SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
849 assert(!Ops.empty() && "Cannot get empty add!");
850 if (Ops.size() == 1) return Ops[0];
852 // Sort by complexity, this groups all similar expression types together.
853 GroupByComplexity(Ops);
855 // If there are any constants, fold them together.
856 unsigned Idx = 0;
857 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
858 ++Idx;
859 assert(Idx < Ops.size());
860 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
861 // We found two constants, fold them together!
862 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
863 RHSC->getValue()->getValue());
864 Ops[0] = getConstant(Fold);
865 Ops.erase(Ops.begin()+1); // Erase the folded element
866 if (Ops.size() == 1) return Ops[0];
867 LHSC = cast<SCEVConstant>(Ops[0]);
870 // If we are left with a constant zero being added, strip it off.
871 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
872 Ops.erase(Ops.begin());
873 --Idx;
877 if (Ops.size() == 1) return Ops[0];
879 // Okay, check to see if the same value occurs in the operand list twice. If
880 // so, merge them together into an multiply expression. Since we sorted the
881 // list, these values are required to be adjacent.
882 const Type *Ty = Ops[0]->getType();
883 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
884 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
885 // Found a match, merge the two values into a multiply, and add any
886 // remaining values to the result.
887 SCEVHandle Two = getIntegerSCEV(2, Ty);
888 SCEVHandle Mul = getMulExpr(Ops[i], Two);
889 if (Ops.size() == 2)
890 return Mul;
891 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
892 Ops.push_back(Mul);
893 return getAddExpr(Ops);
896 // Now we know the first non-constant operand. Skip past any cast SCEVs.
897 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
898 ++Idx;
900 // If there are add operands they would be next.
901 if (Idx < Ops.size()) {
902 bool DeletedAdd = false;
903 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
904 // If we have an add, expand the add operands onto the end of the operands
905 // list.
906 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
907 Ops.erase(Ops.begin()+Idx);
908 DeletedAdd = true;
911 // If we deleted at least one add, we added operands to the end of the list,
912 // and they are not necessarily sorted. Recurse to resort and resimplify
913 // any operands we just aquired.
914 if (DeletedAdd)
915 return getAddExpr(Ops);
918 // Skip over the add expression until we get to a multiply.
919 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
920 ++Idx;
922 // If we are adding something to a multiply expression, make sure the
923 // something is not already an operand of the multiply. If so, merge it into
924 // the multiply.
925 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
926 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
927 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
928 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
929 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
930 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
931 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
932 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
933 if (Mul->getNumOperands() != 2) {
934 // If the multiply has more than two operands, we must get the
935 // Y*Z term.
936 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
937 MulOps.erase(MulOps.begin()+MulOp);
938 InnerMul = getMulExpr(MulOps);
940 SCEVHandle One = getIntegerSCEV(1, Ty);
941 SCEVHandle AddOne = getAddExpr(InnerMul, One);
942 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
943 if (Ops.size() == 2) return OuterMul;
944 if (AddOp < Idx) {
945 Ops.erase(Ops.begin()+AddOp);
946 Ops.erase(Ops.begin()+Idx-1);
947 } else {
948 Ops.erase(Ops.begin()+Idx);
949 Ops.erase(Ops.begin()+AddOp-1);
951 Ops.push_back(OuterMul);
952 return getAddExpr(Ops);
955 // Check this multiply against other multiplies being added together.
956 for (unsigned OtherMulIdx = Idx+1;
957 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
958 ++OtherMulIdx) {
959 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
960 // If MulOp occurs in OtherMul, we can fold the two multiplies
961 // together.
962 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
963 OMulOp != e; ++OMulOp)
964 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
965 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
966 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
967 if (Mul->getNumOperands() != 2) {
968 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
969 MulOps.erase(MulOps.begin()+MulOp);
970 InnerMul1 = getMulExpr(MulOps);
972 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
973 if (OtherMul->getNumOperands() != 2) {
974 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
975 OtherMul->op_end());
976 MulOps.erase(MulOps.begin()+OMulOp);
977 InnerMul2 = getMulExpr(MulOps);
979 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
980 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
981 if (Ops.size() == 2) return OuterMul;
982 Ops.erase(Ops.begin()+Idx);
983 Ops.erase(Ops.begin()+OtherMulIdx-1);
984 Ops.push_back(OuterMul);
985 return getAddExpr(Ops);
991 // If there are any add recurrences in the operands list, see if any other
992 // added values are loop invariant. If so, we can fold them into the
993 // recurrence.
994 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
995 ++Idx;
997 // Scan over all recurrences, trying to fold loop invariants into them.
998 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
999 // Scan all of the other operands to this add and add them to the vector if
1000 // they are loop invariant w.r.t. the recurrence.
1001 std::vector<SCEVHandle> LIOps;
1002 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1003 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1004 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1005 LIOps.push_back(Ops[i]);
1006 Ops.erase(Ops.begin()+i);
1007 --i; --e;
1010 // If we found some loop invariants, fold them into the recurrence.
1011 if (!LIOps.empty()) {
1012 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
1013 LIOps.push_back(AddRec->getStart());
1015 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
1016 AddRecOps[0] = getAddExpr(LIOps);
1018 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
1019 // If all of the other operands were loop invariant, we are done.
1020 if (Ops.size() == 1) return NewRec;
1022 // Otherwise, add the folded AddRec by the non-liv parts.
1023 for (unsigned i = 0;; ++i)
1024 if (Ops[i] == AddRec) {
1025 Ops[i] = NewRec;
1026 break;
1028 return getAddExpr(Ops);
1031 // Okay, if there weren't any loop invariants to be folded, check to see if
1032 // there are multiple AddRec's with the same loop induction variable being
1033 // added together. If so, we can fold them.
1034 for (unsigned OtherIdx = Idx+1;
1035 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1036 if (OtherIdx != Idx) {
1037 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1038 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1039 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1040 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
1041 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1042 if (i >= NewOps.size()) {
1043 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1044 OtherAddRec->op_end());
1045 break;
1047 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
1049 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
1051 if (Ops.size() == 2) return NewAddRec;
1053 Ops.erase(Ops.begin()+Idx);
1054 Ops.erase(Ops.begin()+OtherIdx-1);
1055 Ops.push_back(NewAddRec);
1056 return getAddExpr(Ops);
1060 // Otherwise couldn't fold anything into this recurrence. Move onto the
1061 // next one.
1064 // Okay, it looks like we really DO need an add expr. Check to see if we
1065 // already have one, otherwise create a new one.
1066 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1067 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
1068 SCEVOps)];
1069 if (Result == 0) Result = new SCEVAddExpr(Ops);
1070 return Result;
1074 SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
1075 assert(!Ops.empty() && "Cannot get empty mul!");
1077 // Sort by complexity, this groups all similar expression types together.
1078 GroupByComplexity(Ops);
1080 // If there are any constants, fold them together.
1081 unsigned Idx = 0;
1082 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1084 // C1*(C2+V) -> C1*C2 + C1*V
1085 if (Ops.size() == 2)
1086 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1087 if (Add->getNumOperands() == 2 &&
1088 isa<SCEVConstant>(Add->getOperand(0)))
1089 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1090 getMulExpr(LHSC, Add->getOperand(1)));
1093 ++Idx;
1094 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1095 // We found two constants, fold them together!
1096 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1097 RHSC->getValue()->getValue());
1098 Ops[0] = getConstant(Fold);
1099 Ops.erase(Ops.begin()+1); // Erase the folded element
1100 if (Ops.size() == 1) return Ops[0];
1101 LHSC = cast<SCEVConstant>(Ops[0]);
1104 // If we are left with a constant one being multiplied, strip it off.
1105 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1106 Ops.erase(Ops.begin());
1107 --Idx;
1108 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1109 // If we have a multiply of zero, it will always be zero.
1110 return Ops[0];
1114 // Skip over the add expression until we get to a multiply.
1115 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1116 ++Idx;
1118 if (Ops.size() == 1)
1119 return Ops[0];
1121 // If there are mul operands inline them all into this expression.
1122 if (Idx < Ops.size()) {
1123 bool DeletedMul = false;
1124 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1125 // If we have an mul, expand the mul operands onto the end of the operands
1126 // list.
1127 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1128 Ops.erase(Ops.begin()+Idx);
1129 DeletedMul = true;
1132 // If we deleted at least one mul, we added operands to the end of the list,
1133 // and they are not necessarily sorted. Recurse to resort and resimplify
1134 // any operands we just aquired.
1135 if (DeletedMul)
1136 return getMulExpr(Ops);
1139 // If there are any add recurrences in the operands list, see if any other
1140 // added values are loop invariant. If so, we can fold them into the
1141 // recurrence.
1142 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1143 ++Idx;
1145 // Scan over all recurrences, trying to fold loop invariants into them.
1146 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1147 // Scan all of the other operands to this mul and add them to the vector if
1148 // they are loop invariant w.r.t. the recurrence.
1149 std::vector<SCEVHandle> LIOps;
1150 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1151 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1152 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1153 LIOps.push_back(Ops[i]);
1154 Ops.erase(Ops.begin()+i);
1155 --i; --e;
1158 // If we found some loop invariants, fold them into the recurrence.
1159 if (!LIOps.empty()) {
1160 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
1161 std::vector<SCEVHandle> NewOps;
1162 NewOps.reserve(AddRec->getNumOperands());
1163 if (LIOps.size() == 1) {
1164 SCEV *Scale = LIOps[0];
1165 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1166 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1167 } else {
1168 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1169 std::vector<SCEVHandle> MulOps(LIOps);
1170 MulOps.push_back(AddRec->getOperand(i));
1171 NewOps.push_back(getMulExpr(MulOps));
1175 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
1177 // If all of the other operands were loop invariant, we are done.
1178 if (Ops.size() == 1) return NewRec;
1180 // Otherwise, multiply the folded AddRec by the non-liv parts.
1181 for (unsigned i = 0;; ++i)
1182 if (Ops[i] == AddRec) {
1183 Ops[i] = NewRec;
1184 break;
1186 return getMulExpr(Ops);
1189 // Okay, if there weren't any loop invariants to be folded, check to see if
1190 // there are multiple AddRec's with the same loop induction variable being
1191 // multiplied together. If so, we can fold them.
1192 for (unsigned OtherIdx = Idx+1;
1193 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1194 if (OtherIdx != Idx) {
1195 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1196 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1197 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1198 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1199 SCEVHandle NewStart = getMulExpr(F->getStart(),
1200 G->getStart());
1201 SCEVHandle B = F->getStepRecurrence(*this);
1202 SCEVHandle D = G->getStepRecurrence(*this);
1203 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1204 getMulExpr(G, B),
1205 getMulExpr(B, D));
1206 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1207 F->getLoop());
1208 if (Ops.size() == 2) return NewAddRec;
1210 Ops.erase(Ops.begin()+Idx);
1211 Ops.erase(Ops.begin()+OtherIdx-1);
1212 Ops.push_back(NewAddRec);
1213 return getMulExpr(Ops);
1217 // Otherwise couldn't fold anything into this recurrence. Move onto the
1218 // next one.
1221 // Okay, it looks like we really DO need an mul expr. Check to see if we
1222 // already have one, otherwise create a new one.
1223 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1224 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1225 SCEVOps)];
1226 if (Result == 0)
1227 Result = new SCEVMulExpr(Ops);
1228 return Result;
1231 SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1232 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1233 if (RHSC->getValue()->equalsInt(1))
1234 return LHS; // X udiv 1 --> x
1236 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1237 Constant *LHSCV = LHSC->getValue();
1238 Constant *RHSCV = RHSC->getValue();
1239 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
1243 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1245 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1246 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
1247 return Result;
1251 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1252 /// specified loop. Simplify the expression as much as possible.
1253 SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
1254 const SCEVHandle &Step, const Loop *L) {
1255 std::vector<SCEVHandle> Operands;
1256 Operands.push_back(Start);
1257 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1258 if (StepChrec->getLoop() == L) {
1259 Operands.insert(Operands.end(), StepChrec->op_begin(),
1260 StepChrec->op_end());
1261 return getAddRecExpr(Operands, L);
1264 Operands.push_back(Step);
1265 return getAddRecExpr(Operands, L);
1268 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1269 /// specified loop. Simplify the expression as much as possible.
1270 SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
1271 const Loop *L) {
1272 if (Operands.size() == 1) return Operands[0];
1274 if (Operands.back()->isZero()) {
1275 Operands.pop_back();
1276 return getAddRecExpr(Operands, L); // {X,+,0} --> X
1279 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1280 if (SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1281 const Loop* NestedLoop = NestedAR->getLoop();
1282 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1283 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1284 NestedAR->op_end());
1285 SCEVHandle NestedARHandle(NestedAR);
1286 Operands[0] = NestedAR->getStart();
1287 NestedOperands[0] = getAddRecExpr(Operands, L);
1288 return getAddRecExpr(NestedOperands, NestedLoop);
1292 SCEVAddRecExpr *&Result =
1293 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1294 Operands.end()))];
1295 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1296 return Result;
1299 SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1300 const SCEVHandle &RHS) {
1301 std::vector<SCEVHandle> Ops;
1302 Ops.push_back(LHS);
1303 Ops.push_back(RHS);
1304 return getSMaxExpr(Ops);
1307 SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1308 assert(!Ops.empty() && "Cannot get empty smax!");
1309 if (Ops.size() == 1) return Ops[0];
1311 // Sort by complexity, this groups all similar expression types together.
1312 GroupByComplexity(Ops);
1314 // If there are any constants, fold them together.
1315 unsigned Idx = 0;
1316 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1317 ++Idx;
1318 assert(Idx < Ops.size());
1319 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1320 // We found two constants, fold them together!
1321 ConstantInt *Fold = ConstantInt::get(
1322 APIntOps::smax(LHSC->getValue()->getValue(),
1323 RHSC->getValue()->getValue()));
1324 Ops[0] = getConstant(Fold);
1325 Ops.erase(Ops.begin()+1); // Erase the folded element
1326 if (Ops.size() == 1) return Ops[0];
1327 LHSC = cast<SCEVConstant>(Ops[0]);
1330 // If we are left with a constant -inf, strip it off.
1331 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1332 Ops.erase(Ops.begin());
1333 --Idx;
1337 if (Ops.size() == 1) return Ops[0];
1339 // Find the first SMax
1340 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1341 ++Idx;
1343 // Check to see if one of the operands is an SMax. If so, expand its operands
1344 // onto our operand list, and recurse to simplify.
1345 if (Idx < Ops.size()) {
1346 bool DeletedSMax = false;
1347 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1348 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1349 Ops.erase(Ops.begin()+Idx);
1350 DeletedSMax = true;
1353 if (DeletedSMax)
1354 return getSMaxExpr(Ops);
1357 // Okay, check to see if the same value occurs in the operand list twice. If
1358 // so, delete one. Since we sorted the list, these values are required to
1359 // be adjacent.
1360 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1361 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1362 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1363 --i; --e;
1366 if (Ops.size() == 1) return Ops[0];
1368 assert(!Ops.empty() && "Reduced smax down to nothing!");
1370 // Okay, it looks like we really DO need an smax expr. Check to see if we
1371 // already have one, otherwise create a new one.
1372 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1373 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1374 SCEVOps)];
1375 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1376 return Result;
1379 SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1380 const SCEVHandle &RHS) {
1381 std::vector<SCEVHandle> Ops;
1382 Ops.push_back(LHS);
1383 Ops.push_back(RHS);
1384 return getUMaxExpr(Ops);
1387 SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1388 assert(!Ops.empty() && "Cannot get empty umax!");
1389 if (Ops.size() == 1) return Ops[0];
1391 // Sort by complexity, this groups all similar expression types together.
1392 GroupByComplexity(Ops);
1394 // If there are any constants, fold them together.
1395 unsigned Idx = 0;
1396 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1397 ++Idx;
1398 assert(Idx < Ops.size());
1399 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1400 // We found two constants, fold them together!
1401 ConstantInt *Fold = ConstantInt::get(
1402 APIntOps::umax(LHSC->getValue()->getValue(),
1403 RHSC->getValue()->getValue()));
1404 Ops[0] = getConstant(Fold);
1405 Ops.erase(Ops.begin()+1); // Erase the folded element
1406 if (Ops.size() == 1) return Ops[0];
1407 LHSC = cast<SCEVConstant>(Ops[0]);
1410 // If we are left with a constant zero, strip it off.
1411 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1412 Ops.erase(Ops.begin());
1413 --Idx;
1417 if (Ops.size() == 1) return Ops[0];
1419 // Find the first UMax
1420 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1421 ++Idx;
1423 // Check to see if one of the operands is a UMax. If so, expand its operands
1424 // onto our operand list, and recurse to simplify.
1425 if (Idx < Ops.size()) {
1426 bool DeletedUMax = false;
1427 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1428 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1429 Ops.erase(Ops.begin()+Idx);
1430 DeletedUMax = true;
1433 if (DeletedUMax)
1434 return getUMaxExpr(Ops);
1437 // Okay, check to see if the same value occurs in the operand list twice. If
1438 // so, delete one. Since we sorted the list, these values are required to
1439 // be adjacent.
1440 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1441 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1442 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1443 --i; --e;
1446 if (Ops.size() == 1) return Ops[0];
1448 assert(!Ops.empty() && "Reduced umax down to nothing!");
1450 // Okay, it looks like we really DO need a umax expr. Check to see if we
1451 // already have one, otherwise create a new one.
1452 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1453 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1454 SCEVOps)];
1455 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1456 return Result;
1459 SCEVHandle ScalarEvolution::getUnknown(Value *V) {
1460 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1461 return getConstant(CI);
1462 if (isa<ConstantPointerNull>(V))
1463 return getIntegerSCEV(0, V->getType());
1464 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1465 if (Result == 0) Result = new SCEVUnknown(V);
1466 return Result;
1469 //===----------------------------------------------------------------------===//
1470 // Basic SCEV Analysis and PHI Idiom Recognition Code
1473 /// deleteValueFromRecords - This method should be called by the
1474 /// client before it removes an instruction from the program, to make sure
1475 /// that no dangling references are left around.
1476 void ScalarEvolution::deleteValueFromRecords(Value *V) {
1477 SmallVector<Value *, 16> Worklist;
1479 if (Scalars.erase(V)) {
1480 if (PHINode *PN = dyn_cast<PHINode>(V))
1481 ConstantEvolutionLoopExitValue.erase(PN);
1482 Worklist.push_back(V);
1485 while (!Worklist.empty()) {
1486 Value *VV = Worklist.back();
1487 Worklist.pop_back();
1489 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
1490 UI != UE; ++UI) {
1491 Instruction *Inst = cast<Instruction>(*UI);
1492 if (Scalars.erase(Inst)) {
1493 if (PHINode *PN = dyn_cast<PHINode>(VV))
1494 ConstantEvolutionLoopExitValue.erase(PN);
1495 Worklist.push_back(Inst);
1501 /// isSCEVable - Test if values of the given type are analyzable within
1502 /// the SCEV framework. This primarily includes integer types, and it
1503 /// can optionally include pointer types if the ScalarEvolution class
1504 /// has access to target-specific information.
1505 bool ScalarEvolution::isSCEVable(const Type *Ty) const {
1506 // Integers are always SCEVable.
1507 if (Ty->isInteger())
1508 return true;
1510 // Pointers are SCEVable if TargetData information is available
1511 // to provide pointer size information.
1512 if (isa<PointerType>(Ty))
1513 return TD != NULL;
1515 // Otherwise it's not SCEVable.
1516 return false;
1519 /// getTypeSizeInBits - Return the size in bits of the specified type,
1520 /// for which isSCEVable must return true.
1521 uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
1522 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1524 // If we have a TargetData, use it!
1525 if (TD)
1526 return TD->getTypeSizeInBits(Ty);
1528 // Otherwise, we support only integer types.
1529 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1530 return Ty->getPrimitiveSizeInBits();
1533 /// getEffectiveSCEVType - Return a type with the same bitwidth as
1534 /// the given type and which represents how SCEV will treat the given
1535 /// type, for which isSCEVable must return true. For pointer types,
1536 /// this is the pointer-sized integer type.
1537 const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
1538 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1540 if (Ty->isInteger())
1541 return Ty;
1543 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1544 return TD->getIntPtrType();
1547 SCEVHandle ScalarEvolution::getCouldNotCompute() {
1548 return UnknownValue;
1551 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1552 /// expression and create a new one.
1553 SCEVHandle ScalarEvolution::getSCEV(Value *V) {
1554 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
1556 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1557 if (I != Scalars.end()) return I->second;
1558 SCEVHandle S = createSCEV(V);
1559 Scalars.insert(std::make_pair(V, S));
1560 return S;
1563 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
1564 /// specified signed integer value and return a SCEV for the constant.
1565 SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1566 Ty = getEffectiveSCEVType(Ty);
1567 Constant *C;
1568 if (Val == 0)
1569 C = Constant::getNullValue(Ty);
1570 else if (Ty->isFloatingPoint())
1571 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1572 APFloat::IEEEdouble, Val));
1573 else
1574 C = ConstantInt::get(Ty, Val);
1575 return getUnknown(C);
1578 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1580 SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
1581 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
1582 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
1584 const Type *Ty = V->getType();
1585 Ty = getEffectiveSCEVType(Ty);
1586 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
1589 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
1590 SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
1591 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
1592 return getUnknown(ConstantExpr::getNot(VC->getValue()));
1594 const Type *Ty = V->getType();
1595 Ty = getEffectiveSCEVType(Ty);
1596 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
1597 return getMinusSCEV(AllOnes, V);
1600 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1602 SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
1603 const SCEVHandle &RHS) {
1604 // X - Y --> X + -Y
1605 return getAddExpr(LHS, getNegativeSCEV(RHS));
1608 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1609 /// input value to the specified type. If the type must be extended, it is zero
1610 /// extended.
1611 SCEVHandle
1612 ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
1613 const Type *Ty) {
1614 const Type *SrcTy = V->getType();
1615 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1616 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
1617 "Cannot truncate or zero extend with non-integer arguments!");
1618 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
1619 return V; // No conversion
1620 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
1621 return getTruncateExpr(V, Ty);
1622 return getZeroExtendExpr(V, Ty);
1625 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1626 /// input value to the specified type. If the type must be extended, it is sign
1627 /// extended.
1628 SCEVHandle
1629 ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
1630 const Type *Ty) {
1631 const Type *SrcTy = V->getType();
1632 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1633 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
1634 "Cannot truncate or zero extend with non-integer arguments!");
1635 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
1636 return V; // No conversion
1637 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
1638 return getTruncateExpr(V, Ty);
1639 return getSignExtendExpr(V, Ty);
1642 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1643 /// the specified instruction and replaces any references to the symbolic value
1644 /// SymName with the specified value. This is used during PHI resolution.
1645 void ScalarEvolution::
1646 ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1647 const SCEVHandle &NewVal) {
1648 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1649 if (SI == Scalars.end()) return;
1651 SCEVHandle NV =
1652 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
1653 if (NV == SI->second) return; // No change.
1655 SI->second = NV; // Update the scalars map!
1657 // Any instruction values that use this instruction might also need to be
1658 // updated!
1659 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1660 UI != E; ++UI)
1661 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1664 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1665 /// a loop header, making it a potential recurrence, or it doesn't.
1667 SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
1668 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1669 if (const Loop *L = LI->getLoopFor(PN->getParent()))
1670 if (L->getHeader() == PN->getParent()) {
1671 // If it lives in the loop header, it has two incoming values, one
1672 // from outside the loop, and one from inside.
1673 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1674 unsigned BackEdge = IncomingEdge^1;
1676 // While we are analyzing this PHI node, handle its value symbolically.
1677 SCEVHandle SymbolicName = getUnknown(PN);
1678 assert(Scalars.find(PN) == Scalars.end() &&
1679 "PHI node already processed?");
1680 Scalars.insert(std::make_pair(PN, SymbolicName));
1682 // Using this symbolic name for the PHI, analyze the value coming around
1683 // the back-edge.
1684 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1686 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1687 // has a special value for the first iteration of the loop.
1689 // If the value coming around the backedge is an add with the symbolic
1690 // value we just inserted, then we found a simple induction variable!
1691 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1692 // If there is a single occurrence of the symbolic value, replace it
1693 // with a recurrence.
1694 unsigned FoundIndex = Add->getNumOperands();
1695 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1696 if (Add->getOperand(i) == SymbolicName)
1697 if (FoundIndex == e) {
1698 FoundIndex = i;
1699 break;
1702 if (FoundIndex != Add->getNumOperands()) {
1703 // Create an add with everything but the specified operand.
1704 std::vector<SCEVHandle> Ops;
1705 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1706 if (i != FoundIndex)
1707 Ops.push_back(Add->getOperand(i));
1708 SCEVHandle Accum = getAddExpr(Ops);
1710 // This is not a valid addrec if the step amount is varying each
1711 // loop iteration, but is not itself an addrec in this loop.
1712 if (Accum->isLoopInvariant(L) ||
1713 (isa<SCEVAddRecExpr>(Accum) &&
1714 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1715 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1716 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L);
1718 // Okay, for the entire analysis of this edge we assumed the PHI
1719 // to be symbolic. We now need to go back and update all of the
1720 // entries for the scalars that use the PHI (except for the PHI
1721 // itself) to use the new analyzed value instead of the "symbolic"
1722 // value.
1723 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1724 return PHISCEV;
1727 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1728 // Otherwise, this could be a loop like this:
1729 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1730 // In this case, j = {1,+,1} and BEValue is j.
1731 // Because the other in-value of i (0) fits the evolution of BEValue
1732 // i really is an addrec evolution.
1733 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1734 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1736 // If StartVal = j.start - j.stride, we can use StartVal as the
1737 // initial step of the addrec evolution.
1738 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
1739 AddRec->getOperand(1))) {
1740 SCEVHandle PHISCEV =
1741 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
1743 // Okay, for the entire analysis of this edge we assumed the PHI
1744 // to be symbolic. We now need to go back and update all of the
1745 // entries for the scalars that use the PHI (except for the PHI
1746 // itself) to use the new analyzed value instead of the "symbolic"
1747 // value.
1748 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1749 return PHISCEV;
1754 return SymbolicName;
1757 // If it's not a loop phi, we can't handle it yet.
1758 return getUnknown(PN);
1761 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1762 /// guaranteed to end in (at every loop iteration). It is, at the same time,
1763 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1764 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
1765 static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
1766 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
1767 return C->getValue()->getValue().countTrailingZeros();
1769 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
1770 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
1771 (uint32_t)SE.getTypeSizeInBits(T->getType()));
1773 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
1774 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1775 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1776 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
1779 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
1780 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1781 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1782 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
1785 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
1786 // The result is the min of all operands results.
1787 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
1788 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1789 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
1790 return MinOpRes;
1793 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
1794 // The result is the sum of all operands results.
1795 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1796 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
1797 for (unsigned i = 1, e = M->getNumOperands();
1798 SumOpRes != BitWidth && i != e; ++i)
1799 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
1800 BitWidth);
1801 return SumOpRes;
1804 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
1805 // The result is the min of all operands results.
1806 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
1807 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1808 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
1809 return MinOpRes;
1812 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1813 // The result is the min of all operands results.
1814 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1815 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1816 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
1817 return MinOpRes;
1820 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1821 // The result is the min of all operands results.
1822 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1823 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1824 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
1825 return MinOpRes;
1828 // SCEVUDivExpr, SCEVUnknown
1829 return 0;
1832 /// createSCEV - We know that there is no SCEV for the specified value.
1833 /// Analyze the expression.
1835 SCEVHandle ScalarEvolution::createSCEV(Value *V) {
1836 if (!isSCEVable(V->getType()))
1837 return getUnknown(V);
1839 unsigned Opcode = Instruction::UserOp1;
1840 if (Instruction *I = dyn_cast<Instruction>(V))
1841 Opcode = I->getOpcode();
1842 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1843 Opcode = CE->getOpcode();
1844 else
1845 return getUnknown(V);
1847 User *U = cast<User>(V);
1848 switch (Opcode) {
1849 case Instruction::Add:
1850 return getAddExpr(getSCEV(U->getOperand(0)),
1851 getSCEV(U->getOperand(1)));
1852 case Instruction::Mul:
1853 return getMulExpr(getSCEV(U->getOperand(0)),
1854 getSCEV(U->getOperand(1)));
1855 case Instruction::UDiv:
1856 return getUDivExpr(getSCEV(U->getOperand(0)),
1857 getSCEV(U->getOperand(1)));
1858 case Instruction::Sub:
1859 return getMinusSCEV(getSCEV(U->getOperand(0)),
1860 getSCEV(U->getOperand(1)));
1861 case Instruction::And:
1862 // For an expression like x&255 that merely masks off the high bits,
1863 // use zext(trunc(x)) as the SCEV expression.
1864 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1865 if (CI->isNullValue())
1866 return getSCEV(U->getOperand(1));
1867 if (CI->isAllOnesValue())
1868 return getSCEV(U->getOperand(0));
1869 const APInt &A = CI->getValue();
1870 unsigned Ones = A.countTrailingOnes();
1871 if (APIntOps::isMask(Ones, A))
1872 return
1873 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
1874 IntegerType::get(Ones)),
1875 U->getType());
1877 break;
1878 case Instruction::Or:
1879 // If the RHS of the Or is a constant, we may have something like:
1880 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1881 // optimizations will transparently handle this case.
1883 // In order for this transformation to be safe, the LHS must be of the
1884 // form X*(2^n) and the Or constant must be less than 2^n.
1885 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1886 SCEVHandle LHS = getSCEV(U->getOperand(0));
1887 const APInt &CIVal = CI->getValue();
1888 if (GetMinTrailingZeros(LHS, *this) >=
1889 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
1890 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
1892 break;
1893 case Instruction::Xor:
1894 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1895 // If the RHS of the xor is a signbit, then this is just an add.
1896 // Instcombine turns add of signbit into xor as a strength reduction step.
1897 if (CI->getValue().isSignBit())
1898 return getAddExpr(getSCEV(U->getOperand(0)),
1899 getSCEV(U->getOperand(1)));
1901 // If the RHS of xor is -1, then this is a not operation.
1902 else if (CI->isAllOnesValue())
1903 return getNotSCEV(getSCEV(U->getOperand(0)));
1905 break;
1907 case Instruction::Shl:
1908 // Turn shift left of a constant amount into a multiply.
1909 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1910 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1911 Constant *X = ConstantInt::get(
1912 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1913 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1915 break;
1917 case Instruction::LShr:
1918 // Turn logical shift right of a constant into a unsigned divide.
1919 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1920 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1921 Constant *X = ConstantInt::get(
1922 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1923 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1925 break;
1927 case Instruction::AShr:
1928 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
1929 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
1930 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
1931 if (L->getOpcode() == Instruction::Shl &&
1932 L->getOperand(1) == U->getOperand(1)) {
1933 unsigned BitWidth = getTypeSizeInBits(U->getType());
1934 uint64_t Amt = BitWidth - CI->getZExtValue();
1935 if (Amt == BitWidth)
1936 return getSCEV(L->getOperand(0)); // shift by zero --> noop
1937 if (Amt > BitWidth)
1938 return getIntegerSCEV(0, U->getType()); // value is undefined
1939 return
1940 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
1941 IntegerType::get(Amt)),
1942 U->getType());
1944 break;
1946 case Instruction::Trunc:
1947 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
1949 case Instruction::ZExt:
1950 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1952 case Instruction::SExt:
1953 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1955 case Instruction::BitCast:
1956 // BitCasts are no-op casts so we just eliminate the cast.
1957 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
1958 return getSCEV(U->getOperand(0));
1959 break;
1961 case Instruction::IntToPtr:
1962 if (!TD) break; // Without TD we can't analyze pointers.
1963 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
1964 TD->getIntPtrType());
1966 case Instruction::PtrToInt:
1967 if (!TD) break; // Without TD we can't analyze pointers.
1968 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
1969 U->getType());
1971 case Instruction::GetElementPtr: {
1972 if (!TD) break; // Without TD we can't analyze pointers.
1973 const Type *IntPtrTy = TD->getIntPtrType();
1974 Value *Base = U->getOperand(0);
1975 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
1976 gep_type_iterator GTI = gep_type_begin(U);
1977 for (GetElementPtrInst::op_iterator I = next(U->op_begin()),
1978 E = U->op_end();
1979 I != E; ++I) {
1980 Value *Index = *I;
1981 // Compute the (potentially symbolic) offset in bytes for this index.
1982 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
1983 // For a struct, add the member offset.
1984 const StructLayout &SL = *TD->getStructLayout(STy);
1985 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
1986 uint64_t Offset = SL.getElementOffset(FieldNo);
1987 TotalOffset = getAddExpr(TotalOffset,
1988 getIntegerSCEV(Offset, IntPtrTy));
1989 } else {
1990 // For an array, add the element offset, explicitly scaled.
1991 SCEVHandle LocalOffset = getSCEV(Index);
1992 if (!isa<PointerType>(LocalOffset->getType()))
1993 // Getelementptr indicies are signed.
1994 LocalOffset = getTruncateOrSignExtend(LocalOffset,
1995 IntPtrTy);
1996 LocalOffset =
1997 getMulExpr(LocalOffset,
1998 getIntegerSCEV(TD->getTypePaddedSize(*GTI),
1999 IntPtrTy));
2000 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2003 return getAddExpr(getSCEV(Base), TotalOffset);
2006 case Instruction::PHI:
2007 return createNodeForPHI(cast<PHINode>(U));
2009 case Instruction::Select:
2010 // This could be a smax or umax that was lowered earlier.
2011 // Try to recover it.
2012 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2013 Value *LHS = ICI->getOperand(0);
2014 Value *RHS = ICI->getOperand(1);
2015 switch (ICI->getPredicate()) {
2016 case ICmpInst::ICMP_SLT:
2017 case ICmpInst::ICMP_SLE:
2018 std::swap(LHS, RHS);
2019 // fall through
2020 case ICmpInst::ICMP_SGT:
2021 case ICmpInst::ICMP_SGE:
2022 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2023 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
2024 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2025 // ~smax(~x, ~y) == smin(x, y).
2026 return getNotSCEV(getSMaxExpr(
2027 getNotSCEV(getSCEV(LHS)),
2028 getNotSCEV(getSCEV(RHS))));
2029 break;
2030 case ICmpInst::ICMP_ULT:
2031 case ICmpInst::ICMP_ULE:
2032 std::swap(LHS, RHS);
2033 // fall through
2034 case ICmpInst::ICMP_UGT:
2035 case ICmpInst::ICMP_UGE:
2036 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2037 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
2038 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2039 // ~umax(~x, ~y) == umin(x, y)
2040 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)),
2041 getNotSCEV(getSCEV(RHS))));
2042 break;
2043 default:
2044 break;
2048 default: // We cannot analyze this expression.
2049 break;
2052 return getUnknown(V);
2057 //===----------------------------------------------------------------------===//
2058 // Iteration Count Computation Code
2061 /// getBackedgeTakenCount - If the specified loop has a predictable
2062 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2063 /// object. The backedge-taken count is the number of times the loop header
2064 /// will be branched to from within the loop. This is one less than the
2065 /// trip count of the loop, since it doesn't count the first iteration,
2066 /// when the header is branched to from outside the loop.
2068 /// Note that it is not valid to call this method on a loop without a
2069 /// loop-invariant backedge-taken count (see
2070 /// hasLoopInvariantBackedgeTakenCount).
2072 SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
2073 // Initially insert a CouldNotCompute for this loop. If the insertion
2074 // succeeds, procede to actually compute a backedge-taken count and
2075 // update the value. The temporary CouldNotCompute value tells SCEV
2076 // code elsewhere that it shouldn't attempt to request a new
2077 // backedge-taken count, which could result in infinite recursion.
2078 std::pair<std::map<const Loop*, SCEVHandle>::iterator, bool> Pair =
2079 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2080 if (Pair.second) {
2081 SCEVHandle ItCount = ComputeBackedgeTakenCount(L);
2082 if (ItCount != UnknownValue) {
2083 assert(ItCount->isLoopInvariant(L) &&
2084 "Computed trip count isn't loop invariant for loop!");
2085 ++NumTripCountsComputed;
2087 // Now that we know the trip count for this loop, forget any
2088 // existing SCEV values for PHI nodes in this loop since they
2089 // are only conservative estimates made without the benefit
2090 // of trip count information.
2091 for (BasicBlock::iterator I = L->getHeader()->begin();
2092 PHINode *PN = dyn_cast<PHINode>(I); ++I)
2093 deleteValueFromRecords(PN);
2095 // Update the value in the map.
2096 Pair.first->second = ItCount;
2097 } else if (isa<PHINode>(L->getHeader()->begin())) {
2098 // Only count loops that have phi nodes as not being computable.
2099 ++NumTripCountsNotComputed;
2102 return Pair.first->second;
2105 /// forgetLoopBackedgeTakenCount - This method should be called by the
2106 /// client when it has changed a loop in a way that may effect
2107 /// ScalarEvolution's ability to compute a trip count, or if the loop
2108 /// is deleted.
2109 void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
2110 BackedgeTakenCounts.erase(L);
2113 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
2114 /// of the specified loop will execute.
2115 SCEVHandle ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
2116 // If the loop has a non-one exit block count, we can't analyze it.
2117 SmallVector<BasicBlock*, 8> ExitBlocks;
2118 L->getExitBlocks(ExitBlocks);
2119 if (ExitBlocks.size() != 1) return UnknownValue;
2121 // Okay, there is one exit block. Try to find the condition that causes the
2122 // loop to be exited.
2123 BasicBlock *ExitBlock = ExitBlocks[0];
2125 BasicBlock *ExitingBlock = 0;
2126 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
2127 PI != E; ++PI)
2128 if (L->contains(*PI)) {
2129 if (ExitingBlock == 0)
2130 ExitingBlock = *PI;
2131 else
2132 return UnknownValue; // More than one block exiting!
2134 assert(ExitingBlock && "No exits from loop, something is broken!");
2136 // Okay, we've computed the exiting block. See what condition causes us to
2137 // exit.
2139 // FIXME: we should be able to handle switch instructions (with a single exit)
2140 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2141 if (ExitBr == 0) return UnknownValue;
2142 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2144 // At this point, we know we have a conditional branch that determines whether
2145 // the loop is exited. However, we don't know if the branch is executed each
2146 // time through the loop. If not, then the execution count of the branch will
2147 // not be equal to the trip count of the loop.
2149 // Currently we check for this by checking to see if the Exit branch goes to
2150 // the loop header. If so, we know it will always execute the same number of
2151 // times as the loop. We also handle the case where the exit block *is* the
2152 // loop header. This is common for un-rotated loops. More extensive analysis
2153 // could be done to handle more cases here.
2154 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2155 ExitBr->getSuccessor(1) != L->getHeader() &&
2156 ExitBr->getParent() != L->getHeader())
2157 return UnknownValue;
2159 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2161 // If it's not an integer comparison then compute it the hard way.
2162 // Note that ICmpInst deals with pointer comparisons too so we must check
2163 // the type of the operand.
2164 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
2165 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
2166 ExitBr->getSuccessor(0) == ExitBlock);
2168 // If the condition was exit on true, convert the condition to exit on false
2169 ICmpInst::Predicate Cond;
2170 if (ExitBr->getSuccessor(1) == ExitBlock)
2171 Cond = ExitCond->getPredicate();
2172 else
2173 Cond = ExitCond->getInversePredicate();
2175 // Handle common loops like: for (X = "string"; *X; ++X)
2176 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2177 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2178 SCEVHandle ItCnt =
2179 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
2180 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2183 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2184 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2186 // Try to evaluate any dependencies out of the loop.
2187 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2188 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2189 Tmp = getSCEVAtScope(RHS, L);
2190 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2192 // At this point, we would like to compute how many iterations of the
2193 // loop the predicate will return true for these inputs.
2194 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2195 // If there is a loop-invariant, force it into the RHS.
2196 std::swap(LHS, RHS);
2197 Cond = ICmpInst::getSwappedPredicate(Cond);
2200 // If we have a comparison of a chrec against a constant, try to use value
2201 // ranges to answer this query.
2202 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2203 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
2204 if (AddRec->getLoop() == L) {
2205 // Form the comparison range using the constant of the correct type so
2206 // that the ConstantRange class knows to do a signed or unsigned
2207 // comparison.
2208 ConstantInt *CompVal = RHSC->getValue();
2209 const Type *RealTy = ExitCond->getOperand(0)->getType();
2210 CompVal = dyn_cast<ConstantInt>(
2211 ConstantExpr::getBitCast(CompVal, RealTy));
2212 if (CompVal) {
2213 // Form the constant range.
2214 ConstantRange CompRange(
2215 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
2217 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
2218 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2222 switch (Cond) {
2223 case ICmpInst::ICMP_NE: { // while (X != Y)
2224 // Convert to: while (X-Y != 0)
2225 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
2226 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2227 break;
2229 case ICmpInst::ICMP_EQ: {
2230 // Convert to: while (X-Y == 0) // while (X == Y)
2231 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
2232 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2233 break;
2235 case ICmpInst::ICMP_SLT: {
2236 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
2237 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2238 break;
2240 case ICmpInst::ICMP_SGT: {
2241 SCEVHandle TC = HowManyLessThans(getNotSCEV(LHS),
2242 getNotSCEV(RHS), L, true);
2243 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2244 break;
2246 case ICmpInst::ICMP_ULT: {
2247 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
2248 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2249 break;
2251 case ICmpInst::ICMP_UGT: {
2252 SCEVHandle TC = HowManyLessThans(getNotSCEV(LHS),
2253 getNotSCEV(RHS), L, false);
2254 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2255 break;
2257 default:
2258 #if 0
2259 errs() << "ComputeBackedgeTakenCount ";
2260 if (ExitCond->getOperand(0)->getType()->isUnsigned())
2261 errs() << "[unsigned] ";
2262 errs() << *LHS << " "
2263 << Instruction::getOpcodeName(Instruction::ICmp)
2264 << " " << *RHS << "\n";
2265 #endif
2266 break;
2268 return
2269 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2270 ExitBr->getSuccessor(0) == ExitBlock);
2273 static ConstantInt *
2274 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2275 ScalarEvolution &SE) {
2276 SCEVHandle InVal = SE.getConstant(C);
2277 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
2278 assert(isa<SCEVConstant>(Val) &&
2279 "Evaluation of SCEV at constant didn't fold correctly?");
2280 return cast<SCEVConstant>(Val)->getValue();
2283 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
2284 /// and a GEP expression (missing the pointer index) indexing into it, return
2285 /// the addressed element of the initializer or null if the index expression is
2286 /// invalid.
2287 static Constant *
2288 GetAddressedElementFromGlobal(GlobalVariable *GV,
2289 const std::vector<ConstantInt*> &Indices) {
2290 Constant *Init = GV->getInitializer();
2291 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2292 uint64_t Idx = Indices[i]->getZExtValue();
2293 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2294 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2295 Init = cast<Constant>(CS->getOperand(Idx));
2296 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2297 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2298 Init = cast<Constant>(CA->getOperand(Idx));
2299 } else if (isa<ConstantAggregateZero>(Init)) {
2300 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2301 assert(Idx < STy->getNumElements() && "Bad struct index!");
2302 Init = Constant::getNullValue(STy->getElementType(Idx));
2303 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2304 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2305 Init = Constant::getNullValue(ATy->getElementType());
2306 } else {
2307 assert(0 && "Unknown constant aggregate type!");
2309 return 0;
2310 } else {
2311 return 0; // Unknown initializer type
2314 return Init;
2317 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2318 /// 'icmp op load X, cst', try to see if we can compute the backedge
2319 /// execution count.
2320 SCEVHandle ScalarEvolution::
2321 ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2322 const Loop *L,
2323 ICmpInst::Predicate predicate) {
2324 if (LI->isVolatile()) return UnknownValue;
2326 // Check to see if the loaded pointer is a getelementptr of a global.
2327 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2328 if (!GEP) return UnknownValue;
2330 // Make sure that it is really a constant global we are gepping, with an
2331 // initializer, and make sure the first IDX is really 0.
2332 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2333 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2334 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2335 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2336 return UnknownValue;
2338 // Okay, we allow one non-constant index into the GEP instruction.
2339 Value *VarIdx = 0;
2340 std::vector<ConstantInt*> Indexes;
2341 unsigned VarIdxNum = 0;
2342 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2343 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2344 Indexes.push_back(CI);
2345 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2346 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2347 VarIdx = GEP->getOperand(i);
2348 VarIdxNum = i-2;
2349 Indexes.push_back(0);
2352 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2353 // Check to see if X is a loop variant variable value now.
2354 SCEVHandle Idx = getSCEV(VarIdx);
2355 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2356 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2358 // We can only recognize very limited forms of loop index expressions, in
2359 // particular, only affine AddRec's like {C1,+,C2}.
2360 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2361 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2362 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2363 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2364 return UnknownValue;
2366 unsigned MaxSteps = MaxBruteForceIterations;
2367 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2368 ConstantInt *ItCst =
2369 ConstantInt::get(IdxExpr->getType(), IterationNum);
2370 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
2372 // Form the GEP offset.
2373 Indexes[VarIdxNum] = Val;
2375 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2376 if (Result == 0) break; // Cannot compute!
2378 // Evaluate the condition for this iteration.
2379 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2380 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2381 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2382 #if 0
2383 errs() << "\n***\n*** Computed loop count " << *ItCst
2384 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2385 << "***\n";
2386 #endif
2387 ++NumArrayLenItCounts;
2388 return getConstant(ItCst); // Found terminating iteration!
2391 return UnknownValue;
2395 /// CanConstantFold - Return true if we can constant fold an instruction of the
2396 /// specified type, assuming that all operands were constants.
2397 static bool CanConstantFold(const Instruction *I) {
2398 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2399 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2400 return true;
2402 if (const CallInst *CI = dyn_cast<CallInst>(I))
2403 if (const Function *F = CI->getCalledFunction())
2404 return canConstantFoldCallTo(F);
2405 return false;
2408 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2409 /// in the loop that V is derived from. We allow arbitrary operations along the
2410 /// way, but the operands of an operation must either be constants or a value
2411 /// derived from a constant PHI. If this expression does not fit with these
2412 /// constraints, return null.
2413 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2414 // If this is not an instruction, or if this is an instruction outside of the
2415 // loop, it can't be derived from a loop PHI.
2416 Instruction *I = dyn_cast<Instruction>(V);
2417 if (I == 0 || !L->contains(I->getParent())) return 0;
2419 if (PHINode *PN = dyn_cast<PHINode>(I)) {
2420 if (L->getHeader() == I->getParent())
2421 return PN;
2422 else
2423 // We don't currently keep track of the control flow needed to evaluate
2424 // PHIs, so we cannot handle PHIs inside of loops.
2425 return 0;
2428 // If we won't be able to constant fold this expression even if the operands
2429 // are constants, return early.
2430 if (!CanConstantFold(I)) return 0;
2432 // Otherwise, we can evaluate this instruction if all of its operands are
2433 // constant or derived from a PHI node themselves.
2434 PHINode *PHI = 0;
2435 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2436 if (!(isa<Constant>(I->getOperand(Op)) ||
2437 isa<GlobalValue>(I->getOperand(Op)))) {
2438 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2439 if (P == 0) return 0; // Not evolving from PHI
2440 if (PHI == 0)
2441 PHI = P;
2442 else if (PHI != P)
2443 return 0; // Evolving from multiple different PHIs.
2446 // This is a expression evolving from a constant PHI!
2447 return PHI;
2450 /// EvaluateExpression - Given an expression that passes the
2451 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2452 /// in the loop has the value PHIVal. If we can't fold this expression for some
2453 /// reason, return null.
2454 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2455 if (isa<PHINode>(V)) return PHIVal;
2456 if (Constant *C = dyn_cast<Constant>(V)) return C;
2457 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
2458 Instruction *I = cast<Instruction>(V);
2460 std::vector<Constant*> Operands;
2461 Operands.resize(I->getNumOperands());
2463 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2464 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2465 if (Operands[i] == 0) return 0;
2468 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2469 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2470 &Operands[0], Operands.size());
2471 else
2472 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2473 &Operands[0], Operands.size());
2476 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2477 /// in the header of its containing loop, we know the loop executes a
2478 /// constant number of times, and the PHI node is just a recurrence
2479 /// involving constants, fold it.
2480 Constant *ScalarEvolution::
2481 getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
2482 std::map<PHINode*, Constant*>::iterator I =
2483 ConstantEvolutionLoopExitValue.find(PN);
2484 if (I != ConstantEvolutionLoopExitValue.end())
2485 return I->second;
2487 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
2488 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2490 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2492 // Since the loop is canonicalized, the PHI node must have two entries. One
2493 // entry must be a constant (coming in from outside of the loop), and the
2494 // second must be derived from the same PHI.
2495 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2496 Constant *StartCST =
2497 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2498 if (StartCST == 0)
2499 return RetVal = 0; // Must be a constant.
2501 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2502 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2503 if (PN2 != PN)
2504 return RetVal = 0; // Not derived from same PHI.
2506 // Execute the loop symbolically to determine the exit value.
2507 if (BEs.getActiveBits() >= 32)
2508 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2510 unsigned NumIterations = BEs.getZExtValue(); // must be in range
2511 unsigned IterationNum = 0;
2512 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2513 if (IterationNum == NumIterations)
2514 return RetVal = PHIVal; // Got exit value!
2516 // Compute the value of the PHI node for the next iteration.
2517 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2518 if (NextPHI == PHIVal)
2519 return RetVal = NextPHI; // Stopped evolving!
2520 if (NextPHI == 0)
2521 return 0; // Couldn't evaluate!
2522 PHIVal = NextPHI;
2526 /// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
2527 /// constant number of times (the condition evolves only from constants),
2528 /// try to evaluate a few iterations of the loop until we get the exit
2529 /// condition gets a value of ExitWhen (true or false). If we cannot
2530 /// evaluate the trip count of the loop, return UnknownValue.
2531 SCEVHandle ScalarEvolution::
2532 ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
2533 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2534 if (PN == 0) return UnknownValue;
2536 // Since the loop is canonicalized, the PHI node must have two entries. One
2537 // entry must be a constant (coming in from outside of the loop), and the
2538 // second must be derived from the same PHI.
2539 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2540 Constant *StartCST =
2541 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2542 if (StartCST == 0) return UnknownValue; // Must be a constant.
2544 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2545 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2546 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2548 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2549 // the loop symbolically to determine when the condition gets a value of
2550 // "ExitWhen".
2551 unsigned IterationNum = 0;
2552 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2553 for (Constant *PHIVal = StartCST;
2554 IterationNum != MaxIterations; ++IterationNum) {
2555 ConstantInt *CondVal =
2556 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2558 // Couldn't symbolically evaluate.
2559 if (!CondVal) return UnknownValue;
2561 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2562 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2563 ++NumBruteForceTripCountsComputed;
2564 return getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
2567 // Compute the value of the PHI node for the next iteration.
2568 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2569 if (NextPHI == 0 || NextPHI == PHIVal)
2570 return UnknownValue; // Couldn't evaluate or not making progress...
2571 PHIVal = NextPHI;
2574 // Too many iterations were needed to evaluate.
2575 return UnknownValue;
2578 /// getSCEVAtScope - Compute the value of the specified expression within the
2579 /// indicated loop (which may be null to indicate in no loop). If the
2580 /// expression cannot be evaluated, return UnknownValue.
2581 SCEVHandle ScalarEvolution::getSCEVAtScope(SCEV *V, const Loop *L) {
2582 // FIXME: this should be turned into a virtual method on SCEV!
2584 if (isa<SCEVConstant>(V)) return V;
2586 // If this instruction is evolved from a constant-evolving PHI, compute the
2587 // exit value from the loop without using SCEVs.
2588 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2589 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2590 const Loop *LI = (*this->LI)[I->getParent()];
2591 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2592 if (PHINode *PN = dyn_cast<PHINode>(I))
2593 if (PN->getParent() == LI->getHeader()) {
2594 // Okay, there is no closed form solution for the PHI node. Check
2595 // to see if the loop that contains it has a known backedge-taken
2596 // count. If so, we may be able to force computation of the exit
2597 // value.
2598 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
2599 if (SCEVConstant *BTCC =
2600 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
2601 // Okay, we know how many times the containing loop executes. If
2602 // this is a constant evolving PHI node, get the final value at
2603 // the specified iteration number.
2604 Constant *RV = getConstantEvolutionLoopExitValue(PN,
2605 BTCC->getValue()->getValue(),
2606 LI);
2607 if (RV) return getUnknown(RV);
2611 // Okay, this is an expression that we cannot symbolically evaluate
2612 // into a SCEV. Check to see if it's possible to symbolically evaluate
2613 // the arguments into constants, and if so, try to constant propagate the
2614 // result. This is particularly useful for computing loop exit values.
2615 if (CanConstantFold(I)) {
2616 std::vector<Constant*> Operands;
2617 Operands.reserve(I->getNumOperands());
2618 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2619 Value *Op = I->getOperand(i);
2620 if (Constant *C = dyn_cast<Constant>(Op)) {
2621 Operands.push_back(C);
2622 } else {
2623 // If any of the operands is non-constant and if they are
2624 // non-integer and non-pointer, don't even try to analyze them
2625 // with scev techniques.
2626 if (!isa<IntegerType>(Op->getType()) &&
2627 !isa<PointerType>(Op->getType()))
2628 return V;
2630 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2631 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
2632 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2633 Op->getType(),
2634 false));
2635 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2636 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
2637 Operands.push_back(ConstantExpr::getIntegerCast(C,
2638 Op->getType(),
2639 false));
2640 else
2641 return V;
2642 } else {
2643 return V;
2648 Constant *C;
2649 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2650 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2651 &Operands[0], Operands.size());
2652 else
2653 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2654 &Operands[0], Operands.size());
2655 return getUnknown(C);
2659 // This is some other type of SCEVUnknown, just return it.
2660 return V;
2663 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2664 // Avoid performing the look-up in the common case where the specified
2665 // expression has no loop-variant portions.
2666 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2667 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2668 if (OpAtScope != Comm->getOperand(i)) {
2669 if (OpAtScope == UnknownValue) return UnknownValue;
2670 // Okay, at least one of these operands is loop variant but might be
2671 // foldable. Build a new instance of the folded commutative expression.
2672 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2673 NewOps.push_back(OpAtScope);
2675 for (++i; i != e; ++i) {
2676 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2677 if (OpAtScope == UnknownValue) return UnknownValue;
2678 NewOps.push_back(OpAtScope);
2680 if (isa<SCEVAddExpr>(Comm))
2681 return getAddExpr(NewOps);
2682 if (isa<SCEVMulExpr>(Comm))
2683 return getMulExpr(NewOps);
2684 if (isa<SCEVSMaxExpr>(Comm))
2685 return getSMaxExpr(NewOps);
2686 if (isa<SCEVUMaxExpr>(Comm))
2687 return getUMaxExpr(NewOps);
2688 assert(0 && "Unknown commutative SCEV type!");
2691 // If we got here, all operands are loop invariant.
2692 return Comm;
2695 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
2696 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
2697 if (LHS == UnknownValue) return LHS;
2698 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
2699 if (RHS == UnknownValue) return RHS;
2700 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2701 return Div; // must be loop invariant
2702 return getUDivExpr(LHS, RHS);
2705 // If this is a loop recurrence for a loop that does not contain L, then we
2706 // are dealing with the final value computed by the loop.
2707 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2708 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2709 // To evaluate this recurrence, we need to know how many times the AddRec
2710 // loop iterates. Compute this now.
2711 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
2712 if (BackedgeTakenCount == UnknownValue) return UnknownValue;
2714 // Then, evaluate the AddRec.
2715 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
2717 return UnknownValue;
2720 //assert(0 && "Unknown SCEV type!");
2721 return UnknownValue;
2724 /// getSCEVAtScope - Return a SCEV expression handle for the specified value
2725 /// at the specified scope in the program. The L value specifies a loop
2726 /// nest to evaluate the expression at, where null is the top-level or a
2727 /// specified loop is immediately inside of the loop.
2729 /// This method can be used to compute the exit value for a variable defined
2730 /// in a loop by querying what the value will hold in the parent loop.
2732 /// If this value is not computable at this scope, a SCEVCouldNotCompute
2733 /// object is returned.
2734 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
2735 return getSCEVAtScope(getSCEV(V), L);
2738 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2739 /// following equation:
2741 /// A * X = B (mod N)
2743 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2744 /// A and B isn't important.
2746 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2747 static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2748 ScalarEvolution &SE) {
2749 uint32_t BW = A.getBitWidth();
2750 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2751 assert(A != 0 && "A must be non-zero.");
2753 // 1. D = gcd(A, N)
2755 // The gcd of A and N may have only one prime factor: 2. The number of
2756 // trailing zeros in A is its multiplicity
2757 uint32_t Mult2 = A.countTrailingZeros();
2758 // D = 2^Mult2
2760 // 2. Check if B is divisible by D.
2762 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2763 // is not less than multiplicity of this prime factor for D.
2764 if (B.countTrailingZeros() < Mult2)
2765 return SE.getCouldNotCompute();
2767 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2768 // modulo (N / D).
2770 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2771 // bit width during computations.
2772 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2773 APInt Mod(BW + 1, 0);
2774 Mod.set(BW - Mult2); // Mod = N / D
2775 APInt I = AD.multiplicativeInverse(Mod);
2777 // 4. Compute the minimum unsigned root of the equation:
2778 // I * (B / D) mod (N / D)
2779 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2781 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2782 // bits.
2783 return SE.getConstant(Result.trunc(BW));
2786 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2787 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2788 /// might be the same) or two SCEVCouldNotCompute objects.
2790 static std::pair<SCEVHandle,SCEVHandle>
2791 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
2792 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2793 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2794 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2795 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2797 // We currently can only solve this if the coefficients are constants.
2798 if (!LC || !MC || !NC) {
2799 SCEV *CNC = SE.getCouldNotCompute();
2800 return std::make_pair(CNC, CNC);
2803 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2804 const APInt &L = LC->getValue()->getValue();
2805 const APInt &M = MC->getValue()->getValue();
2806 const APInt &N = NC->getValue()->getValue();
2807 APInt Two(BitWidth, 2);
2808 APInt Four(BitWidth, 4);
2811 using namespace APIntOps;
2812 const APInt& C = L;
2813 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2814 // The B coefficient is M-N/2
2815 APInt B(M);
2816 B -= sdiv(N,Two);
2818 // The A coefficient is N/2
2819 APInt A(N.sdiv(Two));
2821 // Compute the B^2-4ac term.
2822 APInt SqrtTerm(B);
2823 SqrtTerm *= B;
2824 SqrtTerm -= Four * (A * C);
2826 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2827 // integer value or else APInt::sqrt() will assert.
2828 APInt SqrtVal(SqrtTerm.sqrt());
2830 // Compute the two solutions for the quadratic formula.
2831 // The divisions must be performed as signed divisions.
2832 APInt NegB(-B);
2833 APInt TwoA( A << 1 );
2834 if (TwoA.isMinValue()) {
2835 SCEV *CNC = SE.getCouldNotCompute();
2836 return std::make_pair(CNC, CNC);
2839 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2840 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2842 return std::make_pair(SE.getConstant(Solution1),
2843 SE.getConstant(Solution2));
2844 } // end APIntOps namespace
2847 /// HowFarToZero - Return the number of times a backedge comparing the specified
2848 /// value to zero will execute. If not computable, return UnknownValue
2849 SCEVHandle ScalarEvolution::HowFarToZero(SCEV *V, const Loop *L) {
2850 // If the value is a constant
2851 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2852 // If the value is already zero, the branch will execute zero times.
2853 if (C->getValue()->isZero()) return C;
2854 return UnknownValue; // Otherwise it will loop infinitely.
2857 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2858 if (!AddRec || AddRec->getLoop() != L)
2859 return UnknownValue;
2861 if (AddRec->isAffine()) {
2862 // If this is an affine expression, the execution count of this branch is
2863 // the minimum unsigned root of the following equation:
2865 // Start + Step*N = 0 (mod 2^BW)
2867 // equivalent to:
2869 // Step*N = -Start (mod 2^BW)
2871 // where BW is the common bit width of Start and Step.
2873 // Get the initial value for the loop.
2874 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2875 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
2877 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
2879 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2880 // For now we handle only constant steps.
2882 // First, handle unitary steps.
2883 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
2884 return getNegativeSCEV(Start); // N = -Start (as unsigned)
2885 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2886 return Start; // N = Start (as unsigned)
2888 // Then, try to solve the above equation provided that Start is constant.
2889 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
2890 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
2891 -StartC->getValue()->getValue(),
2892 *this);
2894 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2895 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2896 // the quadratic equation to solve it.
2897 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
2898 *this);
2899 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2900 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2901 if (R1) {
2902 #if 0
2903 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
2904 << " sol#2: " << *R2 << "\n";
2905 #endif
2906 // Pick the smallest positive root value.
2907 if (ConstantInt *CB =
2908 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2909 R1->getValue(), R2->getValue()))) {
2910 if (CB->getZExtValue() == false)
2911 std::swap(R1, R2); // R1 is the minimum root now.
2913 // We can only use this value if the chrec ends up with an exact zero
2914 // value at this index. When solving for "X*X != 5", for example, we
2915 // should not accept a root of 2.
2916 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
2917 if (Val->isZero())
2918 return R1; // We found a quadratic root!
2923 return UnknownValue;
2926 /// HowFarToNonZero - Return the number of times a backedge checking the
2927 /// specified value for nonzero will execute. If not computable, return
2928 /// UnknownValue
2929 SCEVHandle ScalarEvolution::HowFarToNonZero(SCEV *V, const Loop *L) {
2930 // Loops that look like: while (X == 0) are very strange indeed. We don't
2931 // handle them yet except for the trivial case. This could be expanded in the
2932 // future as needed.
2934 // If the value is a constant, check to see if it is known to be non-zero
2935 // already. If so, the backedge will execute zero times.
2936 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2937 if (!C->getValue()->isNullValue())
2938 return getIntegerSCEV(0, C->getType());
2939 return UnknownValue; // Otherwise it will loop infinitely.
2942 // We could implement others, but I really doubt anyone writes loops like
2943 // this, and if they did, they would already be constant folded.
2944 return UnknownValue;
2947 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
2948 /// (which may not be an immediate predecessor) which has exactly one
2949 /// successor from which BB is reachable, or null if no such block is
2950 /// found.
2952 BasicBlock *
2953 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
2954 // If the block has a unique predecessor, the predecessor must have
2955 // no other successors from which BB is reachable.
2956 if (BasicBlock *Pred = BB->getSinglePredecessor())
2957 return Pred;
2959 // A loop's header is defined to be a block that dominates the loop.
2960 // If the loop has a preheader, it must be a block that has exactly
2961 // one successor that can reach BB. This is slightly more strict
2962 // than necessary, but works if critical edges are split.
2963 if (Loop *L = LI->getLoopFor(BB))
2964 return L->getLoopPreheader();
2966 return 0;
2969 /// isLoopGuardedByCond - Test whether entry to the loop is protected by
2970 /// a conditional between LHS and RHS.
2971 bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
2972 ICmpInst::Predicate Pred,
2973 SCEV *LHS, SCEV *RHS) {
2974 BasicBlock *Preheader = L->getLoopPreheader();
2975 BasicBlock *PreheaderDest = L->getHeader();
2977 // Starting at the preheader, climb up the predecessor chain, as long as
2978 // there are predecessors that can be found that have unique successors
2979 // leading to the original header.
2980 for (; Preheader;
2981 PreheaderDest = Preheader,
2982 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
2984 BranchInst *LoopEntryPredicate =
2985 dyn_cast<BranchInst>(Preheader->getTerminator());
2986 if (!LoopEntryPredicate ||
2987 LoopEntryPredicate->isUnconditional())
2988 continue;
2990 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
2991 if (!ICI) continue;
2993 // Now that we found a conditional branch that dominates the loop, check to
2994 // see if it is the comparison we are looking for.
2995 Value *PreCondLHS = ICI->getOperand(0);
2996 Value *PreCondRHS = ICI->getOperand(1);
2997 ICmpInst::Predicate Cond;
2998 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2999 Cond = ICI->getPredicate();
3000 else
3001 Cond = ICI->getInversePredicate();
3003 if (Cond == Pred)
3004 ; // An exact match.
3005 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3006 ; // The actual condition is beyond sufficient.
3007 else
3008 // Check a few special cases.
3009 switch (Cond) {
3010 case ICmpInst::ICMP_UGT:
3011 if (Pred == ICmpInst::ICMP_ULT) {
3012 std::swap(PreCondLHS, PreCondRHS);
3013 Cond = ICmpInst::ICMP_ULT;
3014 break;
3016 continue;
3017 case ICmpInst::ICMP_SGT:
3018 if (Pred == ICmpInst::ICMP_SLT) {
3019 std::swap(PreCondLHS, PreCondRHS);
3020 Cond = ICmpInst::ICMP_SLT;
3021 break;
3023 continue;
3024 case ICmpInst::ICMP_NE:
3025 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3026 // so check for this case by checking if the NE is comparing against
3027 // a minimum or maximum constant.
3028 if (!ICmpInst::isTrueWhenEqual(Pred))
3029 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3030 const APInt &A = CI->getValue();
3031 switch (Pred) {
3032 case ICmpInst::ICMP_SLT:
3033 if (A.isMaxSignedValue()) break;
3034 continue;
3035 case ICmpInst::ICMP_SGT:
3036 if (A.isMinSignedValue()) break;
3037 continue;
3038 case ICmpInst::ICMP_ULT:
3039 if (A.isMaxValue()) break;
3040 continue;
3041 case ICmpInst::ICMP_UGT:
3042 if (A.isMinValue()) break;
3043 continue;
3044 default:
3045 continue;
3047 Cond = ICmpInst::ICMP_NE;
3048 // NE is symmetric but the original comparison may not be. Swap
3049 // the operands if necessary so that they match below.
3050 if (isa<SCEVConstant>(LHS))
3051 std::swap(PreCondLHS, PreCondRHS);
3052 break;
3054 continue;
3055 default:
3056 // We weren't able to reconcile the condition.
3057 continue;
3060 if (!PreCondLHS->getType()->isInteger()) continue;
3062 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3063 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3064 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
3065 (LHS == getNotSCEV(PreCondRHSSCEV) &&
3066 RHS == getNotSCEV(PreCondLHSSCEV)))
3067 return true;
3070 return false;
3073 /// HowManyLessThans - Return the number of times a backedge containing the
3074 /// specified less-than comparison will execute. If not computable, return
3075 /// UnknownValue.
3076 SCEVHandle ScalarEvolution::
3077 HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
3078 // Only handle: "ADDREC < LoopInvariant".
3079 if (!RHS->isLoopInvariant(L)) return UnknownValue;
3081 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
3082 if (!AddRec || AddRec->getLoop() != L)
3083 return UnknownValue;
3085 if (AddRec->isAffine()) {
3086 // FORNOW: We only support unit strides.
3087 SCEVHandle One = getIntegerSCEV(1, RHS->getType());
3088 if (AddRec->getOperand(1) != One)
3089 return UnknownValue;
3091 // We know the LHS is of the form {n,+,1} and the RHS is some loop-invariant
3092 // m. So, we count the number of iterations in which {n,+,1} < m is true.
3093 // Note that we cannot simply return max(m-n,0) because it's not safe to
3094 // treat m-n as signed nor unsigned due to overflow possibility.
3096 // First, we get the value of the LHS in the first iteration: n
3097 SCEVHandle Start = AddRec->getOperand(0);
3099 if (isLoopGuardedByCond(L,
3100 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3101 getMinusSCEV(AddRec->getOperand(0), One), RHS)) {
3102 // Since we know that the condition is true in order to enter the loop,
3103 // we know that it will run exactly m-n times.
3104 return getMinusSCEV(RHS, Start);
3105 } else {
3106 // Then, we get the value of the LHS in the first iteration in which the
3107 // above condition doesn't hold. This equals to max(m,n).
3108 SCEVHandle End = isSigned ? getSMaxExpr(RHS, Start)
3109 : getUMaxExpr(RHS, Start);
3111 // Finally, we subtract these two values to get the number of times the
3112 // backedge is executed: max(m,n)-n.
3113 return getMinusSCEV(End, Start);
3117 return UnknownValue;
3120 /// getNumIterationsInRange - Return the number of iterations of this loop that
3121 /// produce values in the specified constant range. Another way of looking at
3122 /// this is that it returns the first iteration number where the value is not in
3123 /// the condition, thus computing the exit count. If the iteration count can't
3124 /// be computed, an instance of SCEVCouldNotCompute is returned.
3125 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3126 ScalarEvolution &SE) const {
3127 if (Range.isFullSet()) // Infinite loop.
3128 return SE.getCouldNotCompute();
3130 // If the start is a non-zero constant, shift the range to simplify things.
3131 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
3132 if (!SC->getValue()->isZero()) {
3133 std::vector<SCEVHandle> Operands(op_begin(), op_end());
3134 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3135 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
3136 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
3137 return ShiftedAddRec->getNumIterationsInRange(
3138 Range.subtract(SC->getValue()->getValue()), SE);
3139 // This is strange and shouldn't happen.
3140 return SE.getCouldNotCompute();
3143 // The only time we can solve this is when we have all constant indices.
3144 // Otherwise, we cannot determine the overflow conditions.
3145 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3146 if (!isa<SCEVConstant>(getOperand(i)))
3147 return SE.getCouldNotCompute();
3150 // Okay at this point we know that all elements of the chrec are constants and
3151 // that the start element is zero.
3153 // First check to see if the range contains zero. If not, the first
3154 // iteration exits.
3155 unsigned BitWidth = SE.getTypeSizeInBits(getType());
3156 if (!Range.contains(APInt(BitWidth, 0)))
3157 return SE.getConstant(ConstantInt::get(getType(),0));
3159 if (isAffine()) {
3160 // If this is an affine expression then we have this situation:
3161 // Solve {0,+,A} in Range === Ax in Range
3163 // We know that zero is in the range. If A is positive then we know that
3164 // the upper value of the range must be the first possible exit value.
3165 // If A is negative then the lower of the range is the last possible loop
3166 // value. Also note that we already checked for a full range.
3167 APInt One(BitWidth,1);
3168 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3169 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3171 // The exit value should be (End+A)/A.
3172 APInt ExitVal = (End + A).udiv(A);
3173 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3175 // Evaluate at the exit value. If we really did fall out of the valid
3176 // range, then we computed our trip count, otherwise wrap around or other
3177 // things must have happened.
3178 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
3179 if (Range.contains(Val->getValue()))
3180 return SE.getCouldNotCompute(); // Something strange happened
3182 // Ensure that the previous value is in the range. This is a sanity check.
3183 assert(Range.contains(
3184 EvaluateConstantChrecAtConstant(this,
3185 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
3186 "Linear scev computation is off in a bad way!");
3187 return SE.getConstant(ExitValue);
3188 } else if (isQuadratic()) {
3189 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3190 // quadratic equation to solve it. To do this, we must frame our problem in
3191 // terms of figuring out when zero is crossed, instead of when
3192 // Range.getUpper() is crossed.
3193 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
3194 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3195 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
3197 // Next, solve the constructed addrec
3198 std::pair<SCEVHandle,SCEVHandle> Roots =
3199 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
3200 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3201 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3202 if (R1) {
3203 // Pick the smallest positive root value.
3204 if (ConstantInt *CB =
3205 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3206 R1->getValue(), R2->getValue()))) {
3207 if (CB->getZExtValue() == false)
3208 std::swap(R1, R2); // R1 is the minimum root now.
3210 // Make sure the root is not off by one. The returned iteration should
3211 // not be in the range, but the previous one should be. When solving
3212 // for "X*X < 5", for example, we should not return a root of 2.
3213 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
3214 R1->getValue(),
3215 SE);
3216 if (Range.contains(R1Val->getValue())) {
3217 // The next iteration must be out of the range...
3218 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3220 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
3221 if (!Range.contains(R1Val->getValue()))
3222 return SE.getConstant(NextVal);
3223 return SE.getCouldNotCompute(); // Something strange happened
3226 // If R1 was not in the range, then it is a good return value. Make
3227 // sure that R1-1 WAS in the range though, just in case.
3228 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
3229 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
3230 if (Range.contains(R1Val->getValue()))
3231 return R1;
3232 return SE.getCouldNotCompute(); // Something strange happened
3237 return SE.getCouldNotCompute();
3242 //===----------------------------------------------------------------------===//
3243 // ScalarEvolution Class Implementation
3244 //===----------------------------------------------------------------------===//
3246 ScalarEvolution::ScalarEvolution()
3247 : FunctionPass(&ID), UnknownValue(new SCEVCouldNotCompute()) {
3250 bool ScalarEvolution::runOnFunction(Function &F) {
3251 this->F = &F;
3252 LI = &getAnalysis<LoopInfo>();
3253 TD = getAnalysisIfAvailable<TargetData>();
3254 return false;
3257 void ScalarEvolution::releaseMemory() {
3258 Scalars.clear();
3259 BackedgeTakenCounts.clear();
3260 ConstantEvolutionLoopExitValue.clear();
3263 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3264 AU.setPreservesAll();
3265 AU.addRequiredTransitive<LoopInfo>();
3268 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
3269 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
3272 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
3273 const Loop *L) {
3274 // Print all inner loops first
3275 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3276 PrintLoopInfo(OS, SE, *I);
3278 OS << "Loop " << L->getHeader()->getName() << ": ";
3280 SmallVector<BasicBlock*, 8> ExitBlocks;
3281 L->getExitBlocks(ExitBlocks);
3282 if (ExitBlocks.size() != 1)
3283 OS << "<multiple exits> ";
3285 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3286 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
3287 } else {
3288 OS << "Unpredictable backedge-taken count. ";
3291 OS << "\n";
3294 void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
3295 // ScalarEvolution's implementaiton of the print method is to print
3296 // out SCEV values of all instructions that are interesting. Doing
3297 // this potentially causes it to create new SCEV objects though,
3298 // which technically conflicts with the const qualifier. This isn't
3299 // observable from outside the class though (the hasSCEV function
3300 // notwithstanding), so casting away the const isn't dangerous.
3301 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
3303 OS << "Classifying expressions for: " << F->getName() << "\n";
3304 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
3305 if (I->getType()->isInteger()) {
3306 OS << *I;
3307 OS << " --> ";
3308 SCEVHandle SV = SE.getSCEV(&*I);
3309 SV->print(OS);
3310 OS << "\t\t";
3312 if (const Loop *L = LI->getLoopFor((*I).getParent())) {
3313 OS << "Exits: ";
3314 SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop());
3315 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3316 OS << "<<Unknown>>";
3317 } else {
3318 OS << *ExitValue;
3323 OS << "\n";
3326 OS << "Determining loop execution counts for: " << F->getName() << "\n";
3327 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
3328 PrintLoopInfo(OS, &SE, *I);
3331 void ScalarEvolution::print(std::ostream &o, const Module *M) const {
3332 raw_os_ostream OS(o);
3333 print(OS, M);