1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the implementation of the scalar evolution analysis
11 // engine, which is used primarily to analyze expressions involving induction
12 // variables in loops.
14 // There are several aspects to this library. First is the representation of
15 // scalar expressions, which are represented as subclasses of the SCEV class.
16 // These classes are used to represent certain types of subexpressions that we
17 // can handle. These classes are reference counted, managed by the SCEVHandle
18 // class. We only create one SCEV of a particular shape, so pointer-comparisons
19 // for equality are legal.
21 // One important aspect of the SCEV objects is that they are never cyclic, even
22 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If
23 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
24 // recurrence) then we represent it directly as a recurrence node, otherwise we
25 // represent it as a SCEVUnknown node.
27 // In addition to being able to represent expressions of various types, we also
28 // have folders that are used to build the *canonical* representation for a
29 // particular expression. These folders are capable of using a variety of
30 // rewrite rules to simplify the expressions.
32 // Once the folders are defined, we can implement the more interesting
33 // higher-level code, such as the code that recognizes PHI nodes of various
34 // types, computes the execution count of a loop, etc.
36 // TODO: We should use these routines and value representations to implement
37 // dependence analysis!
39 //===----------------------------------------------------------------------===//
41 // There are several good references for the techniques used in this analysis.
43 // Chains of recurrences -- a method to expedite the evaluation
44 // of closed-form functions
45 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima
47 // On computational properties of chains of recurrences
50 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization
51 // Robert A. van Engelen
53 // Efficient Symbolic Analysis for Optimizing Compilers
54 // Robert A. van Engelen
56 // Using the chains of recurrences algebra for data dependence testing and
57 // induction variable substitution
58 // MS Thesis, Johnie Birch
60 //===----------------------------------------------------------------------===//
62 #define DEBUG_TYPE "scalar-evolution"
63 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
64 #include "llvm/Constants.h"
65 #include "llvm/DerivedTypes.h"
66 #include "llvm/GlobalVariable.h"
67 #include "llvm/Instructions.h"
68 #include "llvm/Analysis/ConstantFolding.h"
69 #include "llvm/Analysis/LoopInfo.h"
70 #include "llvm/Assembly/Writer.h"
71 #include "llvm/Transforms/Scalar.h"
72 #include "llvm/Support/CFG.h"
73 #include "llvm/Support/CommandLine.h"
74 #include "llvm/Support/Compiler.h"
75 #include "llvm/Support/ConstantRange.h"
76 #include "llvm/Support/InstIterator.h"
77 #include "llvm/Support/ManagedStatic.h"
78 #include "llvm/Support/MathExtras.h"
79 #include "llvm/Support/Streams.h"
80 #include "llvm/ADT/Statistic.h"
86 STATISTIC(NumBruteForceEvaluations,
87 "Number of brute force evaluations needed to "
88 "calculate high-order polynomial exit values");
89 STATISTIC(NumArrayLenItCounts,
90 "Number of trip counts computed with array length");
91 STATISTIC(NumTripCountsComputed,
92 "Number of loops with predictable loop counts");
93 STATISTIC(NumTripCountsNotComputed,
94 "Number of loops without predictable loop counts");
95 STATISTIC(NumBruteForceTripCountsComputed,
96 "Number of loops with trip counts computed by force");
99 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
100 cl::desc("Maximum number of iterations SCEV will "
101 "symbolically execute a constant derived loop"),
105 RegisterPass<ScalarEvolution>
106 R("scalar-evolution", "Scalar Evolution Analysis");
108 char ScalarEvolution::ID = 0;
110 //===----------------------------------------------------------------------===//
111 // SCEV class definitions
112 //===----------------------------------------------------------------------===//
114 //===----------------------------------------------------------------------===//
115 // Implementation of the SCEV class.
118 void SCEV::dump() const {
122 /// getValueRange - Return the tightest constant bounds that this value is
123 /// known to have. This method is only valid on integer SCEV objects.
124 ConstantRange SCEV::getValueRange() const {
125 const Type *Ty = getType();
126 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
127 // Default to a full range if no better information is available.
128 return ConstantRange(getBitWidth());
131 uint32_t SCEV::getBitWidth() const {
132 if (const IntegerType* ITy = dyn_cast<IntegerType>(getType()))
133 return ITy->getBitWidth();
138 SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
140 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
141 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
145 const Type *SCEVCouldNotCompute::getType() const {
146 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
150 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
151 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
155 SCEVHandle SCEVCouldNotCompute::
156 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
157 const SCEVHandle &Conc,
158 ScalarEvolution &SE) const {
162 void SCEVCouldNotCompute::print(std::ostream &OS) const {
163 OS << "***COULDNOTCOMPUTE***";
166 bool SCEVCouldNotCompute::classof(const SCEV *S) {
167 return S->getSCEVType() == scCouldNotCompute;
171 // SCEVConstants - Only allow the creation of one SCEVConstant for any
172 // particular value. Don't use a SCEVHandle here, or else the object will
174 static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
177 SCEVConstant::~SCEVConstant() {
178 SCEVConstants->erase(V);
181 SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
182 SCEVConstant *&R = (*SCEVConstants)[V];
183 if (R == 0) R = new SCEVConstant(V);
187 SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
188 return getConstant(ConstantInt::get(Val));
191 ConstantRange SCEVConstant::getValueRange() const {
192 return ConstantRange(V->getValue());
195 const Type *SCEVConstant::getType() const { return V->getType(); }
197 void SCEVConstant::print(std::ostream &OS) const {
198 WriteAsOperand(OS, V, false);
201 // SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
202 // particular input. Don't use a SCEVHandle here, or else the object will
204 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
205 SCEVTruncateExpr*> > SCEVTruncates;
207 SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
208 : SCEV(scTruncate), Op(op), Ty(ty) {
209 assert(Op->getType()->isInteger() && Ty->isInteger() &&
210 "Cannot truncate non-integer value!");
211 assert(Op->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()
212 && "This is not a truncating conversion!");
215 SCEVTruncateExpr::~SCEVTruncateExpr() {
216 SCEVTruncates->erase(std::make_pair(Op, Ty));
219 ConstantRange SCEVTruncateExpr::getValueRange() const {
220 return getOperand()->getValueRange().truncate(getBitWidth());
223 void SCEVTruncateExpr::print(std::ostream &OS) const {
224 OS << "(truncate " << *Op << " to " << *Ty << ")";
227 // SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
228 // particular input. Don't use a SCEVHandle here, or else the object will never
230 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
231 SCEVZeroExtendExpr*> > SCEVZeroExtends;
233 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
234 : SCEV(scZeroExtend), Op(op), Ty(ty) {
235 assert(Op->getType()->isInteger() && Ty->isInteger() &&
236 "Cannot zero extend non-integer value!");
237 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
238 && "This is not an extending conversion!");
241 SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
242 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
245 ConstantRange SCEVZeroExtendExpr::getValueRange() const {
246 return getOperand()->getValueRange().zeroExtend(getBitWidth());
249 void SCEVZeroExtendExpr::print(std::ostream &OS) const {
250 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
253 // SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
254 // particular input. Don't use a SCEVHandle here, or else the object will never
256 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
257 SCEVSignExtendExpr*> > SCEVSignExtends;
259 SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
260 : SCEV(scSignExtend), Op(op), Ty(ty) {
261 assert(Op->getType()->isInteger() && Ty->isInteger() &&
262 "Cannot sign extend non-integer value!");
263 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
264 && "This is not an extending conversion!");
267 SCEVSignExtendExpr::~SCEVSignExtendExpr() {
268 SCEVSignExtends->erase(std::make_pair(Op, Ty));
271 ConstantRange SCEVSignExtendExpr::getValueRange() const {
272 return getOperand()->getValueRange().signExtend(getBitWidth());
275 void SCEVSignExtendExpr::print(std::ostream &OS) const {
276 OS << "(signextend " << *Op << " to " << *Ty << ")";
279 // SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
280 // particular input. Don't use a SCEVHandle here, or else the object will never
282 static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
283 SCEVCommutativeExpr*> > SCEVCommExprs;
285 SCEVCommutativeExpr::~SCEVCommutativeExpr() {
286 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
287 std::vector<SCEV*>(Operands.begin(),
291 void SCEVCommutativeExpr::print(std::ostream &OS) const {
292 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
293 const char *OpStr = getOperationStr();
294 OS << "(" << *Operands[0];
295 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
296 OS << OpStr << *Operands[i];
300 SCEVHandle SCEVCommutativeExpr::
301 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
302 const SCEVHandle &Conc,
303 ScalarEvolution &SE) const {
304 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
306 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
307 if (H != getOperand(i)) {
308 std::vector<SCEVHandle> NewOps;
309 NewOps.reserve(getNumOperands());
310 for (unsigned j = 0; j != i; ++j)
311 NewOps.push_back(getOperand(j));
313 for (++i; i != e; ++i)
314 NewOps.push_back(getOperand(i)->
315 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
317 if (isa<SCEVAddExpr>(this))
318 return SE.getAddExpr(NewOps);
319 else if (isa<SCEVMulExpr>(this))
320 return SE.getMulExpr(NewOps);
321 else if (isa<SCEVSMaxExpr>(this))
322 return SE.getSMaxExpr(NewOps);
324 assert(0 && "Unknown commutative expr!");
331 // SCEVSDivs - Only allow the creation of one SCEVSDivExpr for any particular
332 // input. Don't use a SCEVHandle here, or else the object will never be
334 static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
335 SCEVSDivExpr*> > SCEVSDivs;
337 SCEVSDivExpr::~SCEVSDivExpr() {
338 SCEVSDivs->erase(std::make_pair(LHS, RHS));
341 void SCEVSDivExpr::print(std::ostream &OS) const {
342 OS << "(" << *LHS << " /s " << *RHS << ")";
345 const Type *SCEVSDivExpr::getType() const {
346 return LHS->getType();
349 // SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
350 // particular input. Don't use a SCEVHandle here, or else the object will never
352 static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
353 SCEVAddRecExpr*> > SCEVAddRecExprs;
355 SCEVAddRecExpr::~SCEVAddRecExpr() {
356 SCEVAddRecExprs->erase(std::make_pair(L,
357 std::vector<SCEV*>(Operands.begin(),
361 SCEVHandle SCEVAddRecExpr::
362 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
363 const SCEVHandle &Conc,
364 ScalarEvolution &SE) const {
365 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
367 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
368 if (H != getOperand(i)) {
369 std::vector<SCEVHandle> NewOps;
370 NewOps.reserve(getNumOperands());
371 for (unsigned j = 0; j != i; ++j)
372 NewOps.push_back(getOperand(j));
374 for (++i; i != e; ++i)
375 NewOps.push_back(getOperand(i)->
376 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
378 return SE.getAddRecExpr(NewOps, L);
385 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
386 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
387 // contain L and if the start is invariant.
388 return !QueryLoop->contains(L->getHeader()) &&
389 getOperand(0)->isLoopInvariant(QueryLoop);
393 void SCEVAddRecExpr::print(std::ostream &OS) const {
394 OS << "{" << *Operands[0];
395 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
396 OS << ",+," << *Operands[i];
397 OS << "}<" << L->getHeader()->getName() + ">";
400 // SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
401 // value. Don't use a SCEVHandle here, or else the object will never be
403 static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
405 SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
407 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
408 // All non-instruction values are loop invariant. All instructions are loop
409 // invariant if they are not contained in the specified loop.
410 if (Instruction *I = dyn_cast<Instruction>(V))
411 return !L->contains(I->getParent());
415 const Type *SCEVUnknown::getType() const {
419 void SCEVUnknown::print(std::ostream &OS) const {
420 WriteAsOperand(OS, V, false);
423 //===----------------------------------------------------------------------===//
425 //===----------------------------------------------------------------------===//
428 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
429 /// than the complexity of the RHS. This comparator is used to canonicalize
431 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
432 bool operator()(SCEV *LHS, SCEV *RHS) {
433 return LHS->getSCEVType() < RHS->getSCEVType();
438 /// GroupByComplexity - Given a list of SCEV objects, order them by their
439 /// complexity, and group objects of the same complexity together by value.
440 /// When this routine is finished, we know that any duplicates in the vector are
441 /// consecutive and that complexity is monotonically increasing.
443 /// Note that we go take special precautions to ensure that we get determinstic
444 /// results from this routine. In other words, we don't want the results of
445 /// this to depend on where the addresses of various SCEV objects happened to
448 static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
449 if (Ops.size() < 2) return; // Noop
450 if (Ops.size() == 2) {
451 // This is the common case, which also happens to be trivially simple.
453 if (Ops[0]->getSCEVType() > Ops[1]->getSCEVType())
454 std::swap(Ops[0], Ops[1]);
458 // Do the rough sort by complexity.
459 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
461 // Now that we are sorted by complexity, group elements of the same
462 // complexity. Note that this is, at worst, N^2, but the vector is likely to
463 // be extremely short in practice. Note that we take this approach because we
464 // do not want to depend on the addresses of the objects we are grouping.
465 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
467 unsigned Complexity = S->getSCEVType();
469 // If there are any objects of the same complexity and same value as this
471 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
472 if (Ops[j] == S) { // Found a duplicate.
473 // Move it to immediately after i'th element.
474 std::swap(Ops[i+1], Ops[j]);
475 ++i; // no need to rescan it.
476 if (i == e-2) return; // Done!
484 //===----------------------------------------------------------------------===//
485 // Simple SCEV method implementations
486 //===----------------------------------------------------------------------===//
488 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
489 /// specified signed integer value and return a SCEV for the constant.
490 SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
493 C = Constant::getNullValue(Ty);
494 else if (Ty->isFloatingPoint())
495 C = ConstantFP::get(Ty, APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
496 APFloat::IEEEdouble, Val));
498 C = ConstantInt::get(Ty, Val);
499 return getUnknown(C);
502 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
503 /// input value to the specified type. If the type must be extended, it is zero
505 static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty,
506 ScalarEvolution &SE) {
507 const Type *SrcTy = V->getType();
508 assert(SrcTy->isInteger() && Ty->isInteger() &&
509 "Cannot truncate or zero extend with non-integer arguments!");
510 if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
511 return V; // No conversion
512 if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits())
513 return SE.getTruncateExpr(V, Ty);
514 return SE.getZeroExtendExpr(V, Ty);
517 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
519 SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
520 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
521 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
523 return getMulExpr(V, getIntegerSCEV(-1, V->getType()));
526 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
528 SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
529 const SCEVHandle &RHS) {
531 return getAddExpr(LHS, getNegativeSCEV(RHS));
535 /// PartialFact - Compute V!/(V-NumSteps)!
536 static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps,
537 ScalarEvolution &SE) {
538 // Handle this case efficiently, it is common to have constant iteration
539 // counts while computing loop exit values.
540 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
541 const APInt& Val = SC->getValue()->getValue();
542 APInt Result(Val.getBitWidth(), 1);
543 for (; NumSteps; --NumSteps)
544 Result *= Val-(NumSteps-1);
545 return SE.getConstant(Result);
548 const Type *Ty = V->getType();
550 return SE.getIntegerSCEV(1, Ty);
552 SCEVHandle Result = V;
553 for (unsigned i = 1; i != NumSteps; ++i)
554 Result = SE.getMulExpr(Result, SE.getMinusSCEV(V,
555 SE.getIntegerSCEV(i, Ty)));
560 /// evaluateAtIteration - Return the value of this chain of recurrences at
561 /// the specified iteration number. We can evaluate this recurrence by
562 /// multiplying each element in the chain by the binomial coefficient
563 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
565 /// A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3)
567 /// FIXME/VERIFY: I don't trust that this is correct in the face of overflow.
568 /// Is the binomial equation safe using modular arithmetic??
570 SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
571 ScalarEvolution &SE) const {
572 SCEVHandle Result = getStart();
574 const Type *Ty = It->getType();
575 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
576 SCEVHandle BC = PartialFact(It, i, SE);
578 SCEVHandle Val = SE.getSDivExpr(SE.getMulExpr(BC, getOperand(i)),
579 SE.getIntegerSCEV(Divisor,Ty));
580 Result = SE.getAddExpr(Result, Val);
586 //===----------------------------------------------------------------------===//
587 // SCEV Expression folder implementations
588 //===----------------------------------------------------------------------===//
590 SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
591 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
593 ConstantExpr::getTrunc(SC->getValue(), Ty));
595 // If the input value is a chrec scev made out of constants, truncate
596 // all of the constants.
597 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
598 std::vector<SCEVHandle> Operands;
599 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
600 // FIXME: This should allow truncation of other expression types!
601 if (isa<SCEVConstant>(AddRec->getOperand(i)))
602 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
605 if (Operands.size() == AddRec->getNumOperands())
606 return getAddRecExpr(Operands, AddRec->getLoop());
609 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
610 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
614 SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty) {
615 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
617 ConstantExpr::getZExt(SC->getValue(), Ty));
619 // FIXME: If the input value is a chrec scev, and we can prove that the value
620 // did not overflow the old, smaller, value, we can zero extend all of the
621 // operands (often constants). This would allow analysis of something like
622 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
624 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
625 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
629 SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
630 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
632 ConstantExpr::getSExt(SC->getValue(), Ty));
634 // FIXME: If the input value is a chrec scev, and we can prove that the value
635 // did not overflow the old, smaller, value, we can sign extend all of the
636 // operands (often constants). This would allow analysis of something like
637 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
639 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
640 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
644 // get - Get a canonical add expression, or something simpler if possible.
645 SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
646 assert(!Ops.empty() && "Cannot get empty add!");
647 if (Ops.size() == 1) return Ops[0];
649 // Sort by complexity, this groups all similar expression types together.
650 GroupByComplexity(Ops);
652 // If there are any constants, fold them together.
654 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
656 assert(Idx < Ops.size());
657 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
658 // We found two constants, fold them together!
659 Constant *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
660 RHSC->getValue()->getValue());
661 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
662 Ops[0] = getConstant(CI);
663 Ops.erase(Ops.begin()+1); // Erase the folded element
664 if (Ops.size() == 1) return Ops[0];
665 LHSC = cast<SCEVConstant>(Ops[0]);
667 // If we couldn't fold the expression, move to the next constant. Note
668 // that this is impossible to happen in practice because we always
669 // constant fold constant ints to constant ints.
674 // If we are left with a constant zero being added, strip it off.
675 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
676 Ops.erase(Ops.begin());
681 if (Ops.size() == 1) return Ops[0];
683 // Okay, check to see if the same value occurs in the operand list twice. If
684 // so, merge them together into an multiply expression. Since we sorted the
685 // list, these values are required to be adjacent.
686 const Type *Ty = Ops[0]->getType();
687 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
688 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
689 // Found a match, merge the two values into a multiply, and add any
690 // remaining values to the result.
691 SCEVHandle Two = getIntegerSCEV(2, Ty);
692 SCEVHandle Mul = getMulExpr(Ops[i], Two);
695 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
697 return getAddExpr(Ops);
700 // Now we know the first non-constant operand. Skip past any cast SCEVs.
701 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
704 // If there are add operands they would be next.
705 if (Idx < Ops.size()) {
706 bool DeletedAdd = false;
707 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
708 // If we have an add, expand the add operands onto the end of the operands
710 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
711 Ops.erase(Ops.begin()+Idx);
715 // If we deleted at least one add, we added operands to the end of the list,
716 // and they are not necessarily sorted. Recurse to resort and resimplify
717 // any operands we just aquired.
719 return getAddExpr(Ops);
722 // Skip over the add expression until we get to a multiply.
723 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
726 // If we are adding something to a multiply expression, make sure the
727 // something is not already an operand of the multiply. If so, merge it into
729 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
730 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
731 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
732 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
733 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
734 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
735 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
736 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
737 if (Mul->getNumOperands() != 2) {
738 // If the multiply has more than two operands, we must get the
740 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
741 MulOps.erase(MulOps.begin()+MulOp);
742 InnerMul = getMulExpr(MulOps);
744 SCEVHandle One = getIntegerSCEV(1, Ty);
745 SCEVHandle AddOne = getAddExpr(InnerMul, One);
746 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
747 if (Ops.size() == 2) return OuterMul;
749 Ops.erase(Ops.begin()+AddOp);
750 Ops.erase(Ops.begin()+Idx-1);
752 Ops.erase(Ops.begin()+Idx);
753 Ops.erase(Ops.begin()+AddOp-1);
755 Ops.push_back(OuterMul);
756 return getAddExpr(Ops);
759 // Check this multiply against other multiplies being added together.
760 for (unsigned OtherMulIdx = Idx+1;
761 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
763 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
764 // If MulOp occurs in OtherMul, we can fold the two multiplies
766 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
767 OMulOp != e; ++OMulOp)
768 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
769 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
770 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
771 if (Mul->getNumOperands() != 2) {
772 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
773 MulOps.erase(MulOps.begin()+MulOp);
774 InnerMul1 = getMulExpr(MulOps);
776 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
777 if (OtherMul->getNumOperands() != 2) {
778 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
780 MulOps.erase(MulOps.begin()+OMulOp);
781 InnerMul2 = getMulExpr(MulOps);
783 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
784 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
785 if (Ops.size() == 2) return OuterMul;
786 Ops.erase(Ops.begin()+Idx);
787 Ops.erase(Ops.begin()+OtherMulIdx-1);
788 Ops.push_back(OuterMul);
789 return getAddExpr(Ops);
795 // If there are any add recurrences in the operands list, see if any other
796 // added values are loop invariant. If so, we can fold them into the
798 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
801 // Scan over all recurrences, trying to fold loop invariants into them.
802 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
803 // Scan all of the other operands to this add and add them to the vector if
804 // they are loop invariant w.r.t. the recurrence.
805 std::vector<SCEVHandle> LIOps;
806 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
807 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
808 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
809 LIOps.push_back(Ops[i]);
810 Ops.erase(Ops.begin()+i);
814 // If we found some loop invariants, fold them into the recurrence.
815 if (!LIOps.empty()) {
816 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
817 LIOps.push_back(AddRec->getStart());
819 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
820 AddRecOps[0] = getAddExpr(LIOps);
822 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
823 // If all of the other operands were loop invariant, we are done.
824 if (Ops.size() == 1) return NewRec;
826 // Otherwise, add the folded AddRec by the non-liv parts.
827 for (unsigned i = 0;; ++i)
828 if (Ops[i] == AddRec) {
832 return getAddExpr(Ops);
835 // Okay, if there weren't any loop invariants to be folded, check to see if
836 // there are multiple AddRec's with the same loop induction variable being
837 // added together. If so, we can fold them.
838 for (unsigned OtherIdx = Idx+1;
839 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
840 if (OtherIdx != Idx) {
841 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
842 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
843 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
844 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
845 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
846 if (i >= NewOps.size()) {
847 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
848 OtherAddRec->op_end());
851 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
853 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
855 if (Ops.size() == 2) return NewAddRec;
857 Ops.erase(Ops.begin()+Idx);
858 Ops.erase(Ops.begin()+OtherIdx-1);
859 Ops.push_back(NewAddRec);
860 return getAddExpr(Ops);
864 // Otherwise couldn't fold anything into this recurrence. Move onto the
868 // Okay, it looks like we really DO need an add expr. Check to see if we
869 // already have one, otherwise create a new one.
870 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
871 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
873 if (Result == 0) Result = new SCEVAddExpr(Ops);
878 SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
879 assert(!Ops.empty() && "Cannot get empty mul!");
881 // Sort by complexity, this groups all similar expression types together.
882 GroupByComplexity(Ops);
884 // If there are any constants, fold them together.
886 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
888 // C1*(C2+V) -> C1*C2 + C1*V
890 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
891 if (Add->getNumOperands() == 2 &&
892 isa<SCEVConstant>(Add->getOperand(0)))
893 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
894 getMulExpr(LHSC, Add->getOperand(1)));
898 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
899 // We found two constants, fold them together!
900 Constant *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
901 RHSC->getValue()->getValue());
902 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
903 Ops[0] = getConstant(CI);
904 Ops.erase(Ops.begin()+1); // Erase the folded element
905 if (Ops.size() == 1) return Ops[0];
906 LHSC = cast<SCEVConstant>(Ops[0]);
908 // If we couldn't fold the expression, move to the next constant. Note
909 // that this is impossible to happen in practice because we always
910 // constant fold constant ints to constant ints.
915 // If we are left with a constant one being multiplied, strip it off.
916 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
917 Ops.erase(Ops.begin());
919 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
920 // If we have a multiply of zero, it will always be zero.
925 // Skip over the add expression until we get to a multiply.
926 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
932 // If there are mul operands inline them all into this expression.
933 if (Idx < Ops.size()) {
934 bool DeletedMul = false;
935 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
936 // If we have an mul, expand the mul operands onto the end of the operands
938 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
939 Ops.erase(Ops.begin()+Idx);
943 // If we deleted at least one mul, we added operands to the end of the list,
944 // and they are not necessarily sorted. Recurse to resort and resimplify
945 // any operands we just aquired.
947 return getMulExpr(Ops);
950 // If there are any add recurrences in the operands list, see if any other
951 // added values are loop invariant. If so, we can fold them into the
953 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
956 // Scan over all recurrences, trying to fold loop invariants into them.
957 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
958 // Scan all of the other operands to this mul and add them to the vector if
959 // they are loop invariant w.r.t. the recurrence.
960 std::vector<SCEVHandle> LIOps;
961 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
962 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
963 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
964 LIOps.push_back(Ops[i]);
965 Ops.erase(Ops.begin()+i);
969 // If we found some loop invariants, fold them into the recurrence.
970 if (!LIOps.empty()) {
971 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
972 std::vector<SCEVHandle> NewOps;
973 NewOps.reserve(AddRec->getNumOperands());
974 if (LIOps.size() == 1) {
975 SCEV *Scale = LIOps[0];
976 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
977 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
979 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
980 std::vector<SCEVHandle> MulOps(LIOps);
981 MulOps.push_back(AddRec->getOperand(i));
982 NewOps.push_back(getMulExpr(MulOps));
986 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
988 // If all of the other operands were loop invariant, we are done.
989 if (Ops.size() == 1) return NewRec;
991 // Otherwise, multiply the folded AddRec by the non-liv parts.
992 for (unsigned i = 0;; ++i)
993 if (Ops[i] == AddRec) {
997 return getMulExpr(Ops);
1000 // Okay, if there weren't any loop invariants to be folded, check to see if
1001 // there are multiple AddRec's with the same loop induction variable being
1002 // multiplied together. If so, we can fold them.
1003 for (unsigned OtherIdx = Idx+1;
1004 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1005 if (OtherIdx != Idx) {
1006 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1007 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1008 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1009 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1010 SCEVHandle NewStart = getMulExpr(F->getStart(),
1012 SCEVHandle B = F->getStepRecurrence(*this);
1013 SCEVHandle D = G->getStepRecurrence(*this);
1014 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1017 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1019 if (Ops.size() == 2) return NewAddRec;
1021 Ops.erase(Ops.begin()+Idx);
1022 Ops.erase(Ops.begin()+OtherIdx-1);
1023 Ops.push_back(NewAddRec);
1024 return getMulExpr(Ops);
1028 // Otherwise couldn't fold anything into this recurrence. Move onto the
1032 // Okay, it looks like we really DO need an mul expr. Check to see if we
1033 // already have one, otherwise create a new one.
1034 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1035 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1038 Result = new SCEVMulExpr(Ops);
1042 SCEVHandle ScalarEvolution::getSDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1043 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1044 if (RHSC->getValue()->equalsInt(1))
1045 return LHS; // X sdiv 1 --> x
1046 if (RHSC->getValue()->isAllOnesValue())
1047 return getNegativeSCEV(LHS); // X sdiv -1 --> -x
1049 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1050 Constant *LHSCV = LHSC->getValue();
1051 Constant *RHSCV = RHSC->getValue();
1052 return getUnknown(ConstantExpr::getSDiv(LHSCV, RHSCV));
1056 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1058 SCEVSDivExpr *&Result = (*SCEVSDivs)[std::make_pair(LHS, RHS)];
1059 if (Result == 0) Result = new SCEVSDivExpr(LHS, RHS);
1064 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1065 /// specified loop. Simplify the expression as much as possible.
1066 SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
1067 const SCEVHandle &Step, const Loop *L) {
1068 std::vector<SCEVHandle> Operands;
1069 Operands.push_back(Start);
1070 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1071 if (StepChrec->getLoop() == L) {
1072 Operands.insert(Operands.end(), StepChrec->op_begin(),
1073 StepChrec->op_end());
1074 return getAddRecExpr(Operands, L);
1077 Operands.push_back(Step);
1078 return getAddRecExpr(Operands, L);
1081 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1082 /// specified loop. Simplify the expression as much as possible.
1083 SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
1085 if (Operands.size() == 1) return Operands[0];
1087 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
1088 if (StepC->getValue()->isZero()) {
1089 Operands.pop_back();
1090 return getAddRecExpr(Operands, L); // { X,+,0 } --> X
1093 SCEVAddRecExpr *&Result =
1094 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1096 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1100 SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1101 const SCEVHandle &RHS) {
1102 std::vector<SCEVHandle> Ops;
1105 return getSMaxExpr(Ops);
1108 SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1109 assert(!Ops.empty() && "Cannot get empty smax!");
1110 if (Ops.size() == 1) return Ops[0];
1112 // Sort by complexity, this groups all similar expression types together.
1113 GroupByComplexity(Ops);
1115 // If there are any constants, fold them together.
1117 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1119 assert(Idx < Ops.size());
1120 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1121 // We found two constants, fold them together!
1122 Constant *Fold = ConstantInt::get(
1123 APIntOps::smax(LHSC->getValue()->getValue(),
1124 RHSC->getValue()->getValue()));
1125 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
1126 Ops[0] = getConstant(CI);
1127 Ops.erase(Ops.begin()+1); // Erase the folded element
1128 if (Ops.size() == 1) return Ops[0];
1129 LHSC = cast<SCEVConstant>(Ops[0]);
1131 // If we couldn't fold the expression, move to the next constant. Note
1132 // that this is impossible to happen in practice because we always
1133 // constant fold constant ints to constant ints.
1138 // If we are left with a constant -inf, strip it off.
1139 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1140 Ops.erase(Ops.begin());
1145 if (Ops.size() == 1) return Ops[0];
1147 // Find the first SMax
1148 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1151 // Check to see if one of the operands is an SMax. If so, expand its operands
1152 // onto our operand list, and recurse to simplify.
1153 if (Idx < Ops.size()) {
1154 bool DeletedSMax = false;
1155 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1156 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1157 Ops.erase(Ops.begin()+Idx);
1162 return getSMaxExpr(Ops);
1165 // Okay, check to see if the same value occurs in the operand list twice. If
1166 // so, delete one. Since we sorted the list, these values are required to
1168 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1169 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1170 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1174 if (Ops.size() == 1) return Ops[0];
1176 assert(!Ops.empty() && "Reduced smax down to nothing!");
1178 // Okay, it looks like we really DO need an add expr. Check to see if we
1179 // already have one, otherwise create a new one.
1180 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1181 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1183 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1187 SCEVHandle ScalarEvolution::getUnknown(Value *V) {
1188 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1189 return getConstant(CI);
1190 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1191 if (Result == 0) Result = new SCEVUnknown(V);
1196 //===----------------------------------------------------------------------===//
1197 // ScalarEvolutionsImpl Definition and Implementation
1198 //===----------------------------------------------------------------------===//
1200 /// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1204 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
1205 /// SE - A reference to the public ScalarEvolution object.
1206 ScalarEvolution &SE;
1208 /// F - The function we are analyzing.
1212 /// LI - The loop information for the function we are currently analyzing.
1216 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1218 SCEVHandle UnknownValue;
1220 /// Scalars - This is a cache of the scalars we have analyzed so far.
1222 std::map<Value*, SCEVHandle> Scalars;
1224 /// IterationCounts - Cache the iteration count of the loops for this
1225 /// function as they are computed.
1226 std::map<const Loop*, SCEVHandle> IterationCounts;
1228 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1229 /// the PHI instructions that we attempt to compute constant evolutions for.
1230 /// This allows us to avoid potentially expensive recomputation of these
1231 /// properties. An instruction maps to null if we are unable to compute its
1233 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
1236 ScalarEvolutionsImpl(ScalarEvolution &se, Function &f, LoopInfo &li)
1237 : SE(se), F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1239 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1240 /// expression and create a new one.
1241 SCEVHandle getSCEV(Value *V);
1243 /// hasSCEV - Return true if the SCEV for this value has already been
1245 bool hasSCEV(Value *V) const {
1246 return Scalars.count(V);
1249 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1250 /// the specified value.
1251 void setSCEV(Value *V, const SCEVHandle &H) {
1252 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1253 assert(isNew && "This entry already existed!");
1257 /// getSCEVAtScope - Compute the value of the specified expression within
1258 /// the indicated loop (which may be null to indicate in no loop). If the
1259 /// expression cannot be evaluated, return UnknownValue itself.
1260 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1263 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1264 /// an analyzable loop-invariant iteration count.
1265 bool hasLoopInvariantIterationCount(const Loop *L);
1267 /// getIterationCount - If the specified loop has a predictable iteration
1268 /// count, return it. Note that it is not valid to call this method on a
1269 /// loop without a loop-invariant iteration count.
1270 SCEVHandle getIterationCount(const Loop *L);
1272 /// deleteValueFromRecords - This method should be called by the
1273 /// client before it removes a value from the program, to make sure
1274 /// that no dangling references are left around.
1275 void deleteValueFromRecords(Value *V);
1278 /// createSCEV - We know that there is no SCEV for the specified value.
1279 /// Analyze the expression.
1280 SCEVHandle createSCEV(Value *V);
1282 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1284 SCEVHandle createNodeForPHI(PHINode *PN);
1286 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1287 /// for the specified instruction and replaces any references to the
1288 /// symbolic value SymName with the specified value. This is used during
1290 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1291 const SCEVHandle &SymName,
1292 const SCEVHandle &NewVal);
1294 /// ComputeIterationCount - Compute the number of times the specified loop
1296 SCEVHandle ComputeIterationCount(const Loop *L);
1298 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1299 /// 'icmp op load X, cst', try to see if we can compute the trip count.
1300 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1303 ICmpInst::Predicate p);
1305 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1306 /// constant number of times (the condition evolves only from constants),
1307 /// try to evaluate a few iterations of the loop until we get the exit
1308 /// condition gets a value of ExitWhen (true or false). If we cannot
1309 /// evaluate the trip count of the loop, return UnknownValue.
1310 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1313 /// HowFarToZero - Return the number of times a backedge comparing the
1314 /// specified value to zero will execute. If not computable, return
1316 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1318 /// HowFarToNonZero - Return the number of times a backedge checking the
1319 /// specified value for nonzero will execute. If not computable, return
1321 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
1323 /// HowManyLessThans - Return the number of times a backedge containing the
1324 /// specified less-than comparison will execute. If not computable, return
1325 /// UnknownValue. isSigned specifies whether the less-than is signed.
1326 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
1329 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1330 /// in the header of its containing loop, we know the loop executes a
1331 /// constant number of times, and the PHI node is just a recurrence
1332 /// involving constants, fold it.
1333 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its,
1338 //===----------------------------------------------------------------------===//
1339 // Basic SCEV Analysis and PHI Idiom Recognition Code
1342 /// deleteValueFromRecords - This method should be called by the
1343 /// client before it removes an instruction from the program, to make sure
1344 /// that no dangling references are left around.
1345 void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) {
1346 SmallVector<Value *, 16> Worklist;
1348 if (Scalars.erase(V)) {
1349 if (PHINode *PN = dyn_cast<PHINode>(V))
1350 ConstantEvolutionLoopExitValue.erase(PN);
1351 Worklist.push_back(V);
1354 while (!Worklist.empty()) {
1355 Value *VV = Worklist.back();
1356 Worklist.pop_back();
1358 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
1360 Instruction *Inst = cast<Instruction>(*UI);
1361 if (Scalars.erase(Inst)) {
1362 if (PHINode *PN = dyn_cast<PHINode>(VV))
1363 ConstantEvolutionLoopExitValue.erase(PN);
1364 Worklist.push_back(Inst);
1371 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1372 /// expression and create a new one.
1373 SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1374 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1376 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1377 if (I != Scalars.end()) return I->second;
1378 SCEVHandle S = createSCEV(V);
1379 Scalars.insert(std::make_pair(V, S));
1383 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1384 /// the specified instruction and replaces any references to the symbolic value
1385 /// SymName with the specified value. This is used during PHI resolution.
1386 void ScalarEvolutionsImpl::
1387 ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1388 const SCEVHandle &NewVal) {
1389 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1390 if (SI == Scalars.end()) return;
1393 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, SE);
1394 if (NV == SI->second) return; // No change.
1396 SI->second = NV; // Update the scalars map!
1398 // Any instruction values that use this instruction might also need to be
1400 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1402 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1405 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1406 /// a loop header, making it a potential recurrence, or it doesn't.
1408 SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1409 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1410 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1411 if (L->getHeader() == PN->getParent()) {
1412 // If it lives in the loop header, it has two incoming values, one
1413 // from outside the loop, and one from inside.
1414 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1415 unsigned BackEdge = IncomingEdge^1;
1417 // While we are analyzing this PHI node, handle its value symbolically.
1418 SCEVHandle SymbolicName = SE.getUnknown(PN);
1419 assert(Scalars.find(PN) == Scalars.end() &&
1420 "PHI node already processed?");
1421 Scalars.insert(std::make_pair(PN, SymbolicName));
1423 // Using this symbolic name for the PHI, analyze the value coming around
1425 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1427 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1428 // has a special value for the first iteration of the loop.
1430 // If the value coming around the backedge is an add with the symbolic
1431 // value we just inserted, then we found a simple induction variable!
1432 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1433 // If there is a single occurrence of the symbolic value, replace it
1434 // with a recurrence.
1435 unsigned FoundIndex = Add->getNumOperands();
1436 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1437 if (Add->getOperand(i) == SymbolicName)
1438 if (FoundIndex == e) {
1443 if (FoundIndex != Add->getNumOperands()) {
1444 // Create an add with everything but the specified operand.
1445 std::vector<SCEVHandle> Ops;
1446 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1447 if (i != FoundIndex)
1448 Ops.push_back(Add->getOperand(i));
1449 SCEVHandle Accum = SE.getAddExpr(Ops);
1451 // This is not a valid addrec if the step amount is varying each
1452 // loop iteration, but is not itself an addrec in this loop.
1453 if (Accum->isLoopInvariant(L) ||
1454 (isa<SCEVAddRecExpr>(Accum) &&
1455 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1456 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1457 SCEVHandle PHISCEV = SE.getAddRecExpr(StartVal, Accum, L);
1459 // Okay, for the entire analysis of this edge we assumed the PHI
1460 // to be symbolic. We now need to go back and update all of the
1461 // entries for the scalars that use the PHI (except for the PHI
1462 // itself) to use the new analyzed value instead of the "symbolic"
1464 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1468 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1469 // Otherwise, this could be a loop like this:
1470 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1471 // In this case, j = {1,+,1} and BEValue is j.
1472 // Because the other in-value of i (0) fits the evolution of BEValue
1473 // i really is an addrec evolution.
1474 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1475 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1477 // If StartVal = j.start - j.stride, we can use StartVal as the
1478 // initial step of the addrec evolution.
1479 if (StartVal == SE.getMinusSCEV(AddRec->getOperand(0),
1480 AddRec->getOperand(1))) {
1481 SCEVHandle PHISCEV =
1482 SE.getAddRecExpr(StartVal, AddRec->getOperand(1), L);
1484 // Okay, for the entire analysis of this edge we assumed the PHI
1485 // to be symbolic. We now need to go back and update all of the
1486 // entries for the scalars that use the PHI (except for the PHI
1487 // itself) to use the new analyzed value instead of the "symbolic"
1489 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1495 return SymbolicName;
1498 // If it's not a loop phi, we can't handle it yet.
1499 return SE.getUnknown(PN);
1502 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1503 /// guaranteed to end in (at every loop iteration). It is, at the same time,
1504 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1505 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
1506 static uint32_t GetMinTrailingZeros(SCEVHandle S) {
1507 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
1508 return C->getValue()->getValue().countTrailingZeros();
1510 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
1511 return std::min(GetMinTrailingZeros(T->getOperand()), T->getBitWidth());
1513 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
1514 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1515 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1518 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
1519 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1520 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1523 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
1524 // The result is the min of all operands results.
1525 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1526 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1527 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1531 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
1532 // The result is the sum of all operands results.
1533 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
1534 uint32_t BitWidth = M->getBitWidth();
1535 for (unsigned i = 1, e = M->getNumOperands();
1536 SumOpRes != BitWidth && i != e; ++i)
1537 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
1542 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
1543 // The result is the min of all operands results.
1544 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1545 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1546 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1550 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1551 // The result is the min of all operands results.
1552 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1553 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1554 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1558 // SCEVSDivExpr, SCEVUnknown
1562 /// createSCEV - We know that there is no SCEV for the specified value.
1563 /// Analyze the expression.
1565 SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1566 if (!isa<IntegerType>(V->getType()))
1567 return SE.getUnknown(V);
1569 if (Instruction *I = dyn_cast<Instruction>(V)) {
1570 switch (I->getOpcode()) {
1571 case Instruction::Add:
1572 return SE.getAddExpr(getSCEV(I->getOperand(0)),
1573 getSCEV(I->getOperand(1)));
1574 case Instruction::Mul:
1575 return SE.getMulExpr(getSCEV(I->getOperand(0)),
1576 getSCEV(I->getOperand(1)));
1577 case Instruction::SDiv:
1578 return SE.getSDivExpr(getSCEV(I->getOperand(0)),
1579 getSCEV(I->getOperand(1)));
1580 case Instruction::Sub:
1581 return SE.getMinusSCEV(getSCEV(I->getOperand(0)),
1582 getSCEV(I->getOperand(1)));
1583 case Instruction::Or:
1584 // If the RHS of the Or is a constant, we may have something like:
1585 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1586 // optimizations will transparently handle this case.
1588 // In order for this transformation to be safe, the LHS must be of the
1589 // form X*(2^n) and the Or constant must be less than 2^n.
1590 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1591 SCEVHandle LHS = getSCEV(I->getOperand(0));
1592 const APInt &CIVal = CI->getValue();
1593 if (GetMinTrailingZeros(LHS) >=
1594 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
1595 return SE.getAddExpr(LHS, getSCEV(I->getOperand(1)));
1598 case Instruction::Xor:
1599 // If the RHS of the xor is a signbit, then this is just an add.
1600 // Instcombine turns add of signbit into xor as a strength reduction step.
1601 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1602 if (CI->getValue().isSignBit())
1603 return SE.getAddExpr(getSCEV(I->getOperand(0)),
1604 getSCEV(I->getOperand(1)));
1608 case Instruction::Shl:
1609 // Turn shift left of a constant amount into a multiply.
1610 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1611 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1612 Constant *X = ConstantInt::get(
1613 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1614 return SE.getMulExpr(getSCEV(I->getOperand(0)), getSCEV(X));
1618 case Instruction::Trunc:
1619 return SE.getTruncateExpr(getSCEV(I->getOperand(0)), I->getType());
1621 case Instruction::ZExt:
1622 return SE.getZeroExtendExpr(getSCEV(I->getOperand(0)), I->getType());
1624 case Instruction::SExt:
1625 return SE.getSignExtendExpr(getSCEV(I->getOperand(0)), I->getType());
1627 case Instruction::BitCast:
1628 // BitCasts are no-op casts so we just eliminate the cast.
1629 if (I->getType()->isInteger() &&
1630 I->getOperand(0)->getType()->isInteger())
1631 return getSCEV(I->getOperand(0));
1634 case Instruction::PHI:
1635 return createNodeForPHI(cast<PHINode>(I));
1637 case Instruction::Select:
1638 // This could be an SCEVSMax that was lowered earlier. Try to recover it.
1639 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I->getOperand(0))) {
1640 Value *LHS = ICI->getOperand(0);
1641 Value *RHS = ICI->getOperand(1);
1642 switch (ICI->getPredicate()) {
1643 case ICmpInst::ICMP_SLT:
1644 case ICmpInst::ICMP_SLE:
1645 std::swap(LHS, RHS);
1647 case ICmpInst::ICMP_SGT:
1648 case ICmpInst::ICMP_SGE:
1649 if (LHS == I->getOperand(1) && RHS == I->getOperand(2))
1650 return SE.getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
1656 default: // We cannot analyze this expression.
1661 return SE.getUnknown(V);
1666 //===----------------------------------------------------------------------===//
1667 // Iteration Count Computation Code
1670 /// getIterationCount - If the specified loop has a predictable iteration
1671 /// count, return it. Note that it is not valid to call this method on a
1672 /// loop without a loop-invariant iteration count.
1673 SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1674 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1675 if (I == IterationCounts.end()) {
1676 SCEVHandle ItCount = ComputeIterationCount(L);
1677 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1678 if (ItCount != UnknownValue) {
1679 assert(ItCount->isLoopInvariant(L) &&
1680 "Computed trip count isn't loop invariant for loop!");
1681 ++NumTripCountsComputed;
1682 } else if (isa<PHINode>(L->getHeader()->begin())) {
1683 // Only count loops that have phi nodes as not being computable.
1684 ++NumTripCountsNotComputed;
1690 /// ComputeIterationCount - Compute the number of times the specified loop
1692 SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1693 // If the loop has a non-one exit block count, we can't analyze it.
1694 SmallVector<BasicBlock*, 8> ExitBlocks;
1695 L->getExitBlocks(ExitBlocks);
1696 if (ExitBlocks.size() != 1) return UnknownValue;
1698 // Okay, there is one exit block. Try to find the condition that causes the
1699 // loop to be exited.
1700 BasicBlock *ExitBlock = ExitBlocks[0];
1702 BasicBlock *ExitingBlock = 0;
1703 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1705 if (L->contains(*PI)) {
1706 if (ExitingBlock == 0)
1709 return UnknownValue; // More than one block exiting!
1711 assert(ExitingBlock && "No exits from loop, something is broken!");
1713 // Okay, we've computed the exiting block. See what condition causes us to
1716 // FIXME: we should be able to handle switch instructions (with a single exit)
1717 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1718 if (ExitBr == 0) return UnknownValue;
1719 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1721 // At this point, we know we have a conditional branch that determines whether
1722 // the loop is exited. However, we don't know if the branch is executed each
1723 // time through the loop. If not, then the execution count of the branch will
1724 // not be equal to the trip count of the loop.
1726 // Currently we check for this by checking to see if the Exit branch goes to
1727 // the loop header. If so, we know it will always execute the same number of
1728 // times as the loop. We also handle the case where the exit block *is* the
1729 // loop header. This is common for un-rotated loops. More extensive analysis
1730 // could be done to handle more cases here.
1731 if (ExitBr->getSuccessor(0) != L->getHeader() &&
1732 ExitBr->getSuccessor(1) != L->getHeader() &&
1733 ExitBr->getParent() != L->getHeader())
1734 return UnknownValue;
1736 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
1738 // If its not an integer comparison then compute it the hard way.
1739 // Note that ICmpInst deals with pointer comparisons too so we must check
1740 // the type of the operand.
1741 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
1742 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1743 ExitBr->getSuccessor(0) == ExitBlock);
1745 // If the condition was exit on true, convert the condition to exit on false
1746 ICmpInst::Predicate Cond;
1747 if (ExitBr->getSuccessor(1) == ExitBlock)
1748 Cond = ExitCond->getPredicate();
1750 Cond = ExitCond->getInversePredicate();
1752 // Handle common loops like: for (X = "string"; *X; ++X)
1753 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1754 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1756 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1757 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1760 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1761 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1763 // Try to evaluate any dependencies out of the loop.
1764 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1765 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1766 Tmp = getSCEVAtScope(RHS, L);
1767 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1769 // At this point, we would like to compute how many iterations of the
1770 // loop the predicate will return true for these inputs.
1771 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1772 // If there is a constant, force it into the RHS.
1773 std::swap(LHS, RHS);
1774 Cond = ICmpInst::getSwappedPredicate(Cond);
1777 // FIXME: think about handling pointer comparisons! i.e.:
1778 // while (P != P+100) ++P;
1780 // If we have a comparison of a chrec against a constant, try to use value
1781 // ranges to answer this query.
1782 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1783 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1784 if (AddRec->getLoop() == L) {
1785 // Form the comparison range using the constant of the correct type so
1786 // that the ConstantRange class knows to do a signed or unsigned
1788 ConstantInt *CompVal = RHSC->getValue();
1789 const Type *RealTy = ExitCond->getOperand(0)->getType();
1790 CompVal = dyn_cast<ConstantInt>(
1791 ConstantExpr::getBitCast(CompVal, RealTy));
1793 // Form the constant range.
1794 ConstantRange CompRange(
1795 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
1797 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE);
1798 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1803 case ICmpInst::ICMP_NE: { // while (X != Y)
1804 // Convert to: while (X-Y != 0)
1805 SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
1806 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1809 case ICmpInst::ICMP_EQ: {
1810 // Convert to: while (X-Y == 0) // while (X == Y)
1811 SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L);
1812 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1815 case ICmpInst::ICMP_SLT: {
1816 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
1817 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1820 case ICmpInst::ICMP_SGT: {
1821 SCEVHandle TC = HowManyLessThans(SE.getNegativeSCEV(LHS),
1822 SE.getNegativeSCEV(RHS), L, true);
1823 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1826 case ICmpInst::ICMP_ULT: {
1827 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
1828 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1831 case ICmpInst::ICMP_UGT: {
1832 SCEVHandle TC = HowManyLessThans(SE.getNegativeSCEV(LHS),
1833 SE.getNegativeSCEV(RHS), L, false);
1834 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1839 cerr << "ComputeIterationCount ";
1840 if (ExitCond->getOperand(0)->getType()->isUnsigned())
1841 cerr << "[unsigned] ";
1843 << Instruction::getOpcodeName(Instruction::ICmp)
1844 << " " << *RHS << "\n";
1848 return ComputeIterationCountExhaustively(L, ExitCond,
1849 ExitBr->getSuccessor(0) == ExitBlock);
1852 static ConstantInt *
1853 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
1854 ScalarEvolution &SE) {
1855 SCEVHandle InVal = SE.getConstant(C);
1856 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
1857 assert(isa<SCEVConstant>(Val) &&
1858 "Evaluation of SCEV at constant didn't fold correctly?");
1859 return cast<SCEVConstant>(Val)->getValue();
1862 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
1863 /// and a GEP expression (missing the pointer index) indexing into it, return
1864 /// the addressed element of the initializer or null if the index expression is
1867 GetAddressedElementFromGlobal(GlobalVariable *GV,
1868 const std::vector<ConstantInt*> &Indices) {
1869 Constant *Init = GV->getInitializer();
1870 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1871 uint64_t Idx = Indices[i]->getZExtValue();
1872 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1873 assert(Idx < CS->getNumOperands() && "Bad struct index!");
1874 Init = cast<Constant>(CS->getOperand(Idx));
1875 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1876 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
1877 Init = cast<Constant>(CA->getOperand(Idx));
1878 } else if (isa<ConstantAggregateZero>(Init)) {
1879 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1880 assert(Idx < STy->getNumElements() && "Bad struct index!");
1881 Init = Constant::getNullValue(STy->getElementType(Idx));
1882 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
1883 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
1884 Init = Constant::getNullValue(ATy->getElementType());
1886 assert(0 && "Unknown constant aggregate type!");
1890 return 0; // Unknown initializer type
1896 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1897 /// 'icmp op load X, cst', try to se if we can compute the trip count.
1898 SCEVHandle ScalarEvolutionsImpl::
1899 ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
1901 ICmpInst::Predicate predicate) {
1902 if (LI->isVolatile()) return UnknownValue;
1904 // Check to see if the loaded pointer is a getelementptr of a global.
1905 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
1906 if (!GEP) return UnknownValue;
1908 // Make sure that it is really a constant global we are gepping, with an
1909 // initializer, and make sure the first IDX is really 0.
1910 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1911 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1912 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
1913 !cast<Constant>(GEP->getOperand(1))->isNullValue())
1914 return UnknownValue;
1916 // Okay, we allow one non-constant index into the GEP instruction.
1918 std::vector<ConstantInt*> Indexes;
1919 unsigned VarIdxNum = 0;
1920 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
1921 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
1922 Indexes.push_back(CI);
1923 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
1924 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
1925 VarIdx = GEP->getOperand(i);
1927 Indexes.push_back(0);
1930 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
1931 // Check to see if X is a loop variant variable value now.
1932 SCEVHandle Idx = getSCEV(VarIdx);
1933 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
1934 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
1936 // We can only recognize very limited forms of loop index expressions, in
1937 // particular, only affine AddRec's like {C1,+,C2}.
1938 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
1939 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
1940 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
1941 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
1942 return UnknownValue;
1944 unsigned MaxSteps = MaxBruteForceIterations;
1945 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
1946 ConstantInt *ItCst =
1947 ConstantInt::get(IdxExpr->getType(), IterationNum);
1948 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE);
1950 // Form the GEP offset.
1951 Indexes[VarIdxNum] = Val;
1953 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
1954 if (Result == 0) break; // Cannot compute!
1956 // Evaluate the condition for this iteration.
1957 Result = ConstantExpr::getICmp(predicate, Result, RHS);
1958 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
1959 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
1961 cerr << "\n***\n*** Computed loop count " << *ItCst
1962 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
1965 ++NumArrayLenItCounts;
1966 return SE.getConstant(ItCst); // Found terminating iteration!
1969 return UnknownValue;
1973 /// CanConstantFold - Return true if we can constant fold an instruction of the
1974 /// specified type, assuming that all operands were constants.
1975 static bool CanConstantFold(const Instruction *I) {
1976 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
1977 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
1980 if (const CallInst *CI = dyn_cast<CallInst>(I))
1981 if (const Function *F = CI->getCalledFunction())
1982 return canConstantFoldCallTo(F);
1986 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
1987 /// in the loop that V is derived from. We allow arbitrary operations along the
1988 /// way, but the operands of an operation must either be constants or a value
1989 /// derived from a constant PHI. If this expression does not fit with these
1990 /// constraints, return null.
1991 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
1992 // If this is not an instruction, or if this is an instruction outside of the
1993 // loop, it can't be derived from a loop PHI.
1994 Instruction *I = dyn_cast<Instruction>(V);
1995 if (I == 0 || !L->contains(I->getParent())) return 0;
1997 if (PHINode *PN = dyn_cast<PHINode>(I))
1998 if (L->getHeader() == I->getParent())
2001 // We don't currently keep track of the control flow needed to evaluate
2002 // PHIs, so we cannot handle PHIs inside of loops.
2005 // If we won't be able to constant fold this expression even if the operands
2006 // are constants, return early.
2007 if (!CanConstantFold(I)) return 0;
2009 // Otherwise, we can evaluate this instruction if all of its operands are
2010 // constant or derived from a PHI node themselves.
2012 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2013 if (!(isa<Constant>(I->getOperand(Op)) ||
2014 isa<GlobalValue>(I->getOperand(Op)))) {
2015 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2016 if (P == 0) return 0; // Not evolving from PHI
2020 return 0; // Evolving from multiple different PHIs.
2023 // This is a expression evolving from a constant PHI!
2027 /// EvaluateExpression - Given an expression that passes the
2028 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2029 /// in the loop has the value PHIVal. If we can't fold this expression for some
2030 /// reason, return null.
2031 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2032 if (isa<PHINode>(V)) return PHIVal;
2033 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
2035 if (Constant *C = dyn_cast<Constant>(V)) return C;
2036 Instruction *I = cast<Instruction>(V);
2038 std::vector<Constant*> Operands;
2039 Operands.resize(I->getNumOperands());
2041 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2042 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2043 if (Operands[i] == 0) return 0;
2046 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2047 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2048 &Operands[0], Operands.size());
2050 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2051 &Operands[0], Operands.size());
2054 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2055 /// in the header of its containing loop, we know the loop executes a
2056 /// constant number of times, and the PHI node is just a recurrence
2057 /// involving constants, fold it.
2058 Constant *ScalarEvolutionsImpl::
2059 getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, const Loop *L){
2060 std::map<PHINode*, Constant*>::iterator I =
2061 ConstantEvolutionLoopExitValue.find(PN);
2062 if (I != ConstantEvolutionLoopExitValue.end())
2065 if (Its.ugt(APInt(Its.getBitWidth(),MaxBruteForceIterations)))
2066 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2068 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2070 // Since the loop is canonicalized, the PHI node must have two entries. One
2071 // entry must be a constant (coming in from outside of the loop), and the
2072 // second must be derived from the same PHI.
2073 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2074 Constant *StartCST =
2075 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2077 return RetVal = 0; // Must be a constant.
2079 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2080 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2082 return RetVal = 0; // Not derived from same PHI.
2084 // Execute the loop symbolically to determine the exit value.
2085 if (Its.getActiveBits() >= 32)
2086 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2088 unsigned NumIterations = Its.getZExtValue(); // must be in range
2089 unsigned IterationNum = 0;
2090 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2091 if (IterationNum == NumIterations)
2092 return RetVal = PHIVal; // Got exit value!
2094 // Compute the value of the PHI node for the next iteration.
2095 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2096 if (NextPHI == PHIVal)
2097 return RetVal = NextPHI; // Stopped evolving!
2099 return 0; // Couldn't evaluate!
2104 /// ComputeIterationCountExhaustively - If the trip is known to execute a
2105 /// constant number of times (the condition evolves only from constants),
2106 /// try to evaluate a few iterations of the loop until we get the exit
2107 /// condition gets a value of ExitWhen (true or false). If we cannot
2108 /// evaluate the trip count of the loop, return UnknownValue.
2109 SCEVHandle ScalarEvolutionsImpl::
2110 ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
2111 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2112 if (PN == 0) return UnknownValue;
2114 // Since the loop is canonicalized, the PHI node must have two entries. One
2115 // entry must be a constant (coming in from outside of the loop), and the
2116 // second must be derived from the same PHI.
2117 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2118 Constant *StartCST =
2119 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2120 if (StartCST == 0) return UnknownValue; // Must be a constant.
2122 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2123 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2124 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2126 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2127 // the loop symbolically to determine when the condition gets a value of
2129 unsigned IterationNum = 0;
2130 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2131 for (Constant *PHIVal = StartCST;
2132 IterationNum != MaxIterations; ++IterationNum) {
2133 ConstantInt *CondVal =
2134 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2136 // Couldn't symbolically evaluate.
2137 if (!CondVal) return UnknownValue;
2139 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2140 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2141 ++NumBruteForceTripCountsComputed;
2142 return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
2145 // Compute the value of the PHI node for the next iteration.
2146 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2147 if (NextPHI == 0 || NextPHI == PHIVal)
2148 return UnknownValue; // Couldn't evaluate or not making progress...
2152 // Too many iterations were needed to evaluate.
2153 return UnknownValue;
2156 /// getSCEVAtScope - Compute the value of the specified expression within the
2157 /// indicated loop (which may be null to indicate in no loop). If the
2158 /// expression cannot be evaluated, return UnknownValue.
2159 SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2160 // FIXME: this should be turned into a virtual method on SCEV!
2162 if (isa<SCEVConstant>(V)) return V;
2164 // If this instruction is evolves from a constant-evolving PHI, compute the
2165 // exit value from the loop without using SCEVs.
2166 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2167 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2168 const Loop *LI = this->LI[I->getParent()];
2169 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2170 if (PHINode *PN = dyn_cast<PHINode>(I))
2171 if (PN->getParent() == LI->getHeader()) {
2172 // Okay, there is no closed form solution for the PHI node. Check
2173 // to see if the loop that contains it has a known iteration count.
2174 // If so, we may be able to force computation of the exit value.
2175 SCEVHandle IterationCount = getIterationCount(LI);
2176 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
2177 // Okay, we know how many times the containing loop executes. If
2178 // this is a constant evolving PHI node, get the final value at
2179 // the specified iteration number.
2180 Constant *RV = getConstantEvolutionLoopExitValue(PN,
2181 ICC->getValue()->getValue(),
2183 if (RV) return SE.getUnknown(RV);
2187 // Okay, this is an expression that we cannot symbolically evaluate
2188 // into a SCEV. Check to see if it's possible to symbolically evaluate
2189 // the arguments into constants, and if so, try to constant propagate the
2190 // result. This is particularly useful for computing loop exit values.
2191 if (CanConstantFold(I)) {
2192 std::vector<Constant*> Operands;
2193 Operands.reserve(I->getNumOperands());
2194 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2195 Value *Op = I->getOperand(i);
2196 if (Constant *C = dyn_cast<Constant>(Op)) {
2197 Operands.push_back(C);
2199 // If any of the operands is non-constant and if they are
2200 // non-integer, don't even try to analyze them with scev techniques.
2201 if (!isa<IntegerType>(Op->getType()))
2204 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2205 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
2206 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2209 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2210 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
2211 Operands.push_back(ConstantExpr::getIntegerCast(C,
2223 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2224 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2225 &Operands[0], Operands.size());
2227 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2228 &Operands[0], Operands.size());
2229 return SE.getUnknown(C);
2233 // This is some other type of SCEVUnknown, just return it.
2237 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2238 // Avoid performing the look-up in the common case where the specified
2239 // expression has no loop-variant portions.
2240 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2241 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2242 if (OpAtScope != Comm->getOperand(i)) {
2243 if (OpAtScope == UnknownValue) return UnknownValue;
2244 // Okay, at least one of these operands is loop variant but might be
2245 // foldable. Build a new instance of the folded commutative expression.
2246 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2247 NewOps.push_back(OpAtScope);
2249 for (++i; i != e; ++i) {
2250 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2251 if (OpAtScope == UnknownValue) return UnknownValue;
2252 NewOps.push_back(OpAtScope);
2254 if (isa<SCEVAddExpr>(Comm))
2255 return SE.getAddExpr(NewOps);
2256 if (isa<SCEVMulExpr>(Comm))
2257 return SE.getMulExpr(NewOps);
2258 if (isa<SCEVSMaxExpr>(Comm))
2259 return SE.getSMaxExpr(NewOps);
2260 assert(0 && "Unknown commutative SCEV type!");
2263 // If we got here, all operands are loop invariant.
2267 if (SCEVSDivExpr *Div = dyn_cast<SCEVSDivExpr>(V)) {
2268 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
2269 if (LHS == UnknownValue) return LHS;
2270 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
2271 if (RHS == UnknownValue) return RHS;
2272 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2273 return Div; // must be loop invariant
2274 return SE.getSDivExpr(LHS, RHS);
2277 // If this is a loop recurrence for a loop that does not contain L, then we
2278 // are dealing with the final value computed by the loop.
2279 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2280 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2281 // To evaluate this recurrence, we need to know how many times the AddRec
2282 // loop iterates. Compute this now.
2283 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2284 if (IterationCount == UnknownValue) return UnknownValue;
2285 IterationCount = getTruncateOrZeroExtend(IterationCount,
2286 AddRec->getType(), SE);
2288 // If the value is affine, simplify the expression evaluation to just
2289 // Start + Step*IterationCount.
2290 if (AddRec->isAffine())
2291 return SE.getAddExpr(AddRec->getStart(),
2292 SE.getMulExpr(IterationCount,
2293 AddRec->getOperand(1)));
2295 // Otherwise, evaluate it the hard way.
2296 return AddRec->evaluateAtIteration(IterationCount, SE);
2298 return UnknownValue;
2301 //assert(0 && "Unknown SCEV type!");
2302 return UnknownValue;
2306 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2307 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2308 /// might be the same) or two SCEVCouldNotCompute objects.
2310 static std::pair<SCEVHandle,SCEVHandle>
2311 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
2312 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2313 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2314 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2315 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2317 // We currently can only solve this if the coefficients are constants.
2318 if (!LC || !MC || !NC) {
2319 SCEV *CNC = new SCEVCouldNotCompute();
2320 return std::make_pair(CNC, CNC);
2323 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2324 const APInt &L = LC->getValue()->getValue();
2325 const APInt &M = MC->getValue()->getValue();
2326 const APInt &N = NC->getValue()->getValue();
2327 APInt Two(BitWidth, 2);
2328 APInt Four(BitWidth, 4);
2331 using namespace APIntOps;
2333 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2334 // The B coefficient is M-N/2
2338 // The A coefficient is N/2
2339 APInt A(N.sdiv(Two));
2341 // Compute the B^2-4ac term.
2344 SqrtTerm -= Four * (A * C);
2346 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2347 // integer value or else APInt::sqrt() will assert.
2348 APInt SqrtVal(SqrtTerm.sqrt());
2350 // Compute the two solutions for the quadratic formula.
2351 // The divisions must be performed as signed divisions.
2353 APInt TwoA( A << 1 );
2354 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2355 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2357 return std::make_pair(SE.getConstant(Solution1),
2358 SE.getConstant(Solution2));
2359 } // end APIntOps namespace
2362 /// HowFarToZero - Return the number of times a backedge comparing the specified
2363 /// value to zero will execute. If not computable, return UnknownValue
2364 SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2365 // If the value is a constant
2366 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2367 // If the value is already zero, the branch will execute zero times.
2368 if (C->getValue()->isZero()) return C;
2369 return UnknownValue; // Otherwise it will loop infinitely.
2372 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2373 if (!AddRec || AddRec->getLoop() != L)
2374 return UnknownValue;
2376 if (AddRec->isAffine()) {
2377 // If this is an affine expression the execution count of this branch is
2380 // (0 - Start/Step) iff Start % Step == 0
2382 // Get the initial value for the loop.
2383 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2384 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
2385 SCEVHandle Step = AddRec->getOperand(1);
2387 Step = getSCEVAtScope(Step, L->getParentLoop());
2389 // Figure out if Start % Step == 0.
2390 // FIXME: We should add DivExpr and RemExpr operations to our AST.
2391 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2392 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
2393 return SE.getNegativeSCEV(Start); // 0 - Start/1 == -Start
2394 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
2395 return Start; // 0 - Start/-1 == Start
2397 // Check to see if Start is divisible by SC with no remainder.
2398 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2399 ConstantInt *StartCC = StartC->getValue();
2400 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
2401 Constant *Rem = ConstantExpr::getSRem(StartNegC, StepC->getValue());
2402 if (Rem->isNullValue()) {
2403 Constant *Result =ConstantExpr::getSDiv(StartNegC,StepC->getValue());
2404 return SE.getUnknown(Result);
2408 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2409 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2410 // the quadratic equation to solve it.
2411 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE);
2412 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2413 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2416 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2417 << " sol#2: " << *R2 << "\n";
2419 // Pick the smallest positive root value.
2420 if (ConstantInt *CB =
2421 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2422 R1->getValue(), R2->getValue()))) {
2423 if (CB->getZExtValue() == false)
2424 std::swap(R1, R2); // R1 is the minimum root now.
2426 // We can only use this value if the chrec ends up with an exact zero
2427 // value at this index. When solving for "X*X != 5", for example, we
2428 // should not accept a root of 2.
2429 SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE);
2430 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
2431 if (EvalVal->getValue()->isZero())
2432 return R1; // We found a quadratic root!
2437 return UnknownValue;
2440 /// HowFarToNonZero - Return the number of times a backedge checking the
2441 /// specified value for nonzero will execute. If not computable, return
2443 SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2444 // Loops that look like: while (X == 0) are very strange indeed. We don't
2445 // handle them yet except for the trivial case. This could be expanded in the
2446 // future as needed.
2448 // If the value is a constant, check to see if it is known to be non-zero
2449 // already. If so, the backedge will execute zero times.
2450 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2451 Constant *Zero = Constant::getNullValue(C->getValue()->getType());
2453 ConstantExpr::getICmp(ICmpInst::ICMP_NE, C->getValue(), Zero);
2454 if (NonZero == ConstantInt::getTrue())
2455 return getSCEV(Zero);
2456 return UnknownValue; // Otherwise it will loop infinitely.
2459 // We could implement others, but I really doubt anyone writes loops like
2460 // this, and if they did, they would already be constant folded.
2461 return UnknownValue;
2464 /// HowManyLessThans - Return the number of times a backedge containing the
2465 /// specified less-than comparison will execute. If not computable, return
2467 SCEVHandle ScalarEvolutionsImpl::
2468 HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
2469 // Only handle: "ADDREC < LoopInvariant".
2470 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2472 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2473 if (!AddRec || AddRec->getLoop() != L)
2474 return UnknownValue;
2476 if (AddRec->isAffine()) {
2477 // The number of iterations for "{n,+,1} < m", is m-n. However, we don't
2478 // know that m is >= n on input to the loop. If it is, the condition
2479 // returns true zero times. To handle both cases, we return SMAX(0, m-n).
2481 // FORNOW: We only support unit strides.
2482 SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType());
2483 if (AddRec->getOperand(1) != One)
2484 return UnknownValue;
2486 SCEVHandle Iters = SE.getMinusSCEV(RHS, AddRec->getOperand(0));
2489 return SE.getSMaxExpr(SE.getIntegerSCEV(0, RHS->getType()), Iters);
2494 return UnknownValue;
2497 /// getNumIterationsInRange - Return the number of iterations of this loop that
2498 /// produce values in the specified constant range. Another way of looking at
2499 /// this is that it returns the first iteration number where the value is not in
2500 /// the condition, thus computing the exit count. If the iteration count can't
2501 /// be computed, an instance of SCEVCouldNotCompute is returned.
2502 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
2503 ScalarEvolution &SE) const {
2504 if (Range.isFullSet()) // Infinite loop.
2505 return new SCEVCouldNotCompute();
2507 // If the start is a non-zero constant, shift the range to simplify things.
2508 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2509 if (!SC->getValue()->isZero()) {
2510 std::vector<SCEVHandle> Operands(op_begin(), op_end());
2511 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
2512 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
2513 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2514 return ShiftedAddRec->getNumIterationsInRange(
2515 Range.subtract(SC->getValue()->getValue()), SE);
2516 // This is strange and shouldn't happen.
2517 return new SCEVCouldNotCompute();
2520 // The only time we can solve this is when we have all constant indices.
2521 // Otherwise, we cannot determine the overflow conditions.
2522 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2523 if (!isa<SCEVConstant>(getOperand(i)))
2524 return new SCEVCouldNotCompute();
2527 // Okay at this point we know that all elements of the chrec are constants and
2528 // that the start element is zero.
2530 // First check to see if the range contains zero. If not, the first
2532 if (!Range.contains(APInt(getBitWidth(),0)))
2533 return SE.getConstant(ConstantInt::get(getType(),0));
2536 // If this is an affine expression then we have this situation:
2537 // Solve {0,+,A} in Range === Ax in Range
2539 // We know that zero is in the range. If A is positive then we know that
2540 // the upper value of the range must be the first possible exit value.
2541 // If A is negative then the lower of the range is the last possible loop
2542 // value. Also note that we already checked for a full range.
2543 APInt One(getBitWidth(),1);
2544 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
2545 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
2547 // The exit value should be (End+A)/A.
2548 APInt ExitVal = (End + A).udiv(A);
2549 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
2551 // Evaluate at the exit value. If we really did fall out of the valid
2552 // range, then we computed our trip count, otherwise wrap around or other
2553 // things must have happened.
2554 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
2555 if (Range.contains(Val->getValue()))
2556 return new SCEVCouldNotCompute(); // Something strange happened
2558 // Ensure that the previous value is in the range. This is a sanity check.
2559 assert(Range.contains(
2560 EvaluateConstantChrecAtConstant(this,
2561 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
2562 "Linear scev computation is off in a bad way!");
2563 return SE.getConstant(ExitValue);
2564 } else if (isQuadratic()) {
2565 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2566 // quadratic equation to solve it. To do this, we must frame our problem in
2567 // terms of figuring out when zero is crossed, instead of when
2568 // Range.getUpper() is crossed.
2569 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
2570 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
2571 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
2573 // Next, solve the constructed addrec
2574 std::pair<SCEVHandle,SCEVHandle> Roots =
2575 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
2576 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2577 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2579 // Pick the smallest positive root value.
2580 if (ConstantInt *CB =
2581 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2582 R1->getValue(), R2->getValue()))) {
2583 if (CB->getZExtValue() == false)
2584 std::swap(R1, R2); // R1 is the minimum root now.
2586 // Make sure the root is not off by one. The returned iteration should
2587 // not be in the range, but the previous one should be. When solving
2588 // for "X*X < 5", for example, we should not return a root of 2.
2589 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2592 if (Range.contains(R1Val->getValue())) {
2593 // The next iteration must be out of the range...
2594 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
2596 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
2597 if (!Range.contains(R1Val->getValue()))
2598 return SE.getConstant(NextVal);
2599 return new SCEVCouldNotCompute(); // Something strange happened
2602 // If R1 was not in the range, then it is a good return value. Make
2603 // sure that R1-1 WAS in the range though, just in case.
2604 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
2605 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
2606 if (Range.contains(R1Val->getValue()))
2608 return new SCEVCouldNotCompute(); // Something strange happened
2613 // Fallback, if this is a general polynomial, figure out the progression
2614 // through brute force: evaluate until we find an iteration that fails the
2615 // test. This is likely to be slow, but getting an accurate trip count is
2616 // incredibly important, we will be able to simplify the exit test a lot, and
2617 // we are almost guaranteed to get a trip count in this case.
2618 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2619 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2621 ++NumBruteForceEvaluations;
2622 SCEVHandle Val = evaluateAtIteration(SE.getConstant(TestVal), SE);
2623 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2624 return new SCEVCouldNotCompute();
2626 // Check to see if we found the value!
2627 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()->getValue()))
2628 return SE.getConstant(TestVal);
2630 // Increment to test the next index.
2631 TestVal = ConstantInt::get(TestVal->getValue()+1);
2632 } while (TestVal != EndVal);
2634 return new SCEVCouldNotCompute();
2639 //===----------------------------------------------------------------------===//
2640 // ScalarEvolution Class Implementation
2641 //===----------------------------------------------------------------------===//
2643 bool ScalarEvolution::runOnFunction(Function &F) {
2644 Impl = new ScalarEvolutionsImpl(*this, F, getAnalysis<LoopInfo>());
2648 void ScalarEvolution::releaseMemory() {
2649 delete (ScalarEvolutionsImpl*)Impl;
2653 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2654 AU.setPreservesAll();
2655 AU.addRequiredTransitive<LoopInfo>();
2658 SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2659 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2662 /// hasSCEV - Return true if the SCEV for this value has already been
2664 bool ScalarEvolution::hasSCEV(Value *V) const {
2665 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
2669 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
2670 /// the specified value.
2671 void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
2672 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
2676 SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2677 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2680 bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2681 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2684 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2685 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2688 void ScalarEvolution::deleteValueFromRecords(Value *V) const {
2689 return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
2692 static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
2694 // Print all inner loops first
2695 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2696 PrintLoopInfo(OS, SE, *I);
2698 OS << "Loop " << L->getHeader()->getName() << ": ";
2700 SmallVector<BasicBlock*, 8> ExitBlocks;
2701 L->getExitBlocks(ExitBlocks);
2702 if (ExitBlocks.size() != 1)
2703 OS << "<multiple exits> ";
2705 if (SE->hasLoopInvariantIterationCount(L)) {
2706 OS << *SE->getIterationCount(L) << " iterations! ";
2708 OS << "Unpredictable iteration count. ";
2714 void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
2715 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2716 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2718 OS << "Classifying expressions for: " << F.getName() << "\n";
2719 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
2720 if (I->getType()->isInteger()) {
2723 SCEVHandle SV = getSCEV(&*I);
2727 if ((*I).getType()->isInteger()) {
2728 ConstantRange Bounds = SV->getValueRange();
2729 if (!Bounds.isFullSet())
2730 OS << "Bounds: " << Bounds << " ";
2733 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
2735 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
2736 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2737 OS << "<<Unknown>>";
2747 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2748 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2749 PrintLoopInfo(OS, this, *I);