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 const SCEV*
18 // class. We only create one SCEV of a particular shape, so pointer-comparisons
19 // for equality are legal.
21 // One important aspect of the SCEV objects is that they are never cyclic, even
22 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If
23 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
24 // recurrence) then we represent it directly as a recurrence node, otherwise we
25 // represent it as a SCEVUnknown node.
27 // In addition to being able to represent expressions of various types, we also
28 // have folders that are used to build the *canonical* representation for a
29 // particular expression. These folders are capable of using a variety of
30 // rewrite rules to simplify the expressions.
32 // Once the folders are defined, we can implement the more interesting
33 // higher-level code, such as the code that recognizes PHI nodes of various
34 // types, computes the execution count of a loop, etc.
36 // TODO: We should use these routines and value representations to implement
37 // dependence analysis!
39 //===----------------------------------------------------------------------===//
41 // There are several good references for the techniques used in this analysis.
43 // Chains of recurrences -- a method to expedite the evaluation
44 // of closed-form functions
45 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima
47 // On computational properties of chains of recurrences
50 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization
51 // Robert A. van Engelen
53 // Efficient Symbolic Analysis for Optimizing Compilers
54 // Robert A. van Engelen
56 // Using the chains of recurrences algebra for data dependence testing and
57 // induction variable substitution
58 // MS Thesis, Johnie Birch
60 //===----------------------------------------------------------------------===//
62 #define DEBUG_TYPE "scalar-evolution"
63 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
64 #include "llvm/Constants.h"
65 #include "llvm/DerivedTypes.h"
66 #include "llvm/GlobalVariable.h"
67 #include "llvm/Instructions.h"
68 #include "llvm/Analysis/ConstantFolding.h"
69 #include "llvm/Analysis/Dominators.h"
70 #include "llvm/Analysis/LoopInfo.h"
71 #include "llvm/Analysis/ValueTracking.h"
72 #include "llvm/Assembly/Writer.h"
73 #include "llvm/Target/TargetData.h"
74 #include "llvm/Support/CommandLine.h"
75 #include "llvm/Support/Compiler.h"
76 #include "llvm/Support/ConstantRange.h"
77 #include "llvm/Support/GetElementPtrTypeIterator.h"
78 #include "llvm/Support/InstIterator.h"
79 #include "llvm/Support/MathExtras.h"
80 #include "llvm/Support/raw_ostream.h"
81 #include "llvm/ADT/Statistic.h"
82 #include "llvm/ADT/STLExtras.h"
86 STATISTIC(NumArrayLenItCounts,
87 "Number of trip counts computed with array length");
88 STATISTIC(NumTripCountsComputed,
89 "Number of loops with predictable loop counts");
90 STATISTIC(NumTripCountsNotComputed,
91 "Number of loops without predictable loop counts");
92 STATISTIC(NumBruteForceTripCountsComputed,
93 "Number of loops with trip counts computed by force");
95 static cl::opt<unsigned>
96 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
97 cl::desc("Maximum number of iterations SCEV will "
98 "symbolically execute a constant "
102 static RegisterPass<ScalarEvolution>
103 R("scalar-evolution", "Scalar Evolution Analysis", false, true);
104 char ScalarEvolution::ID = 0;
106 //===----------------------------------------------------------------------===//
107 // SCEV class definitions
108 //===----------------------------------------------------------------------===//
110 //===----------------------------------------------------------------------===//
111 // Implementation of the SCEV class.
114 void SCEV::dump() const {
119 void SCEV::print(std::ostream &o) const {
120 raw_os_ostream OS(o);
124 bool SCEV::isZero() const {
125 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
126 return SC->getValue()->isZero();
130 bool SCEV::isOne() const {
131 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
132 return SC->getValue()->isOne();
136 bool SCEV::isAllOnesValue() const {
137 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
138 return SC->getValue()->isAllOnesValue();
142 SCEVCouldNotCompute::SCEVCouldNotCompute() :
143 SCEV(scCouldNotCompute) {}
145 void SCEVCouldNotCompute::Profile(FoldingSetNodeID &ID) const {
146 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
149 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
150 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
154 const Type *SCEVCouldNotCompute::getType() const {
155 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
159 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
160 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
165 SCEVCouldNotCompute::replaceSymbolicValuesWithConcrete(
168 ScalarEvolution &SE) const {
172 void SCEVCouldNotCompute::print(raw_ostream &OS) const {
173 OS << "***COULDNOTCOMPUTE***";
176 bool SCEVCouldNotCompute::classof(const SCEV *S) {
177 return S->getSCEVType() == scCouldNotCompute;
180 const SCEV* ScalarEvolution::getConstant(ConstantInt *V) {
182 ID.AddInteger(scConstant);
185 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
186 SCEV *S = SCEVAllocator.Allocate<SCEVConstant>();
187 new (S) SCEVConstant(V);
188 UniqueSCEVs.InsertNode(S, IP);
192 const SCEV* ScalarEvolution::getConstant(const APInt& Val) {
193 return getConstant(ConstantInt::get(Val));
197 ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
198 return getConstant(ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
201 void SCEVConstant::Profile(FoldingSetNodeID &ID) const {
202 ID.AddInteger(scConstant);
206 const Type *SCEVConstant::getType() const { return V->getType(); }
208 void SCEVConstant::print(raw_ostream &OS) const {
209 WriteAsOperand(OS, V, false);
212 SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
213 const SCEV* op, const Type *ty)
214 : SCEV(SCEVTy), Op(op), Ty(ty) {}
216 void SCEVCastExpr::Profile(FoldingSetNodeID &ID) const {
217 ID.AddInteger(getSCEVType());
222 bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
223 return Op->dominates(BB, DT);
226 SCEVTruncateExpr::SCEVTruncateExpr(const SCEV* op, const Type *ty)
227 : SCEVCastExpr(scTruncate, op, ty) {
228 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
229 (Ty->isInteger() || isa<PointerType>(Ty)) &&
230 "Cannot truncate non-integer value!");
233 void SCEVTruncateExpr::print(raw_ostream &OS) const {
234 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
237 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEV* op, const Type *ty)
238 : SCEVCastExpr(scZeroExtend, op, ty) {
239 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
240 (Ty->isInteger() || isa<PointerType>(Ty)) &&
241 "Cannot zero extend non-integer value!");
244 void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
245 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
248 SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEV* op, const Type *ty)
249 : SCEVCastExpr(scSignExtend, op, ty) {
250 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
251 (Ty->isInteger() || isa<PointerType>(Ty)) &&
252 "Cannot sign extend non-integer value!");
255 void SCEVSignExtendExpr::print(raw_ostream &OS) const {
256 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
259 void SCEVCommutativeExpr::print(raw_ostream &OS) const {
260 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
261 const char *OpStr = getOperationStr();
262 OS << "(" << *Operands[0];
263 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
264 OS << OpStr << *Operands[i];
269 SCEVCommutativeExpr::replaceSymbolicValuesWithConcrete(
272 ScalarEvolution &SE) const {
273 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
275 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
276 if (H != getOperand(i)) {
277 SmallVector<const SCEV*, 8> NewOps;
278 NewOps.reserve(getNumOperands());
279 for (unsigned j = 0; j != i; ++j)
280 NewOps.push_back(getOperand(j));
282 for (++i; i != e; ++i)
283 NewOps.push_back(getOperand(i)->
284 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
286 if (isa<SCEVAddExpr>(this))
287 return SE.getAddExpr(NewOps);
288 else if (isa<SCEVMulExpr>(this))
289 return SE.getMulExpr(NewOps);
290 else if (isa<SCEVSMaxExpr>(this))
291 return SE.getSMaxExpr(NewOps);
292 else if (isa<SCEVUMaxExpr>(this))
293 return SE.getUMaxExpr(NewOps);
295 assert(0 && "Unknown commutative expr!");
301 void SCEVNAryExpr::Profile(FoldingSetNodeID &ID) const {
302 ID.AddInteger(getSCEVType());
303 ID.AddInteger(Operands.size());
304 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
305 ID.AddPointer(Operands[i]);
308 bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
309 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
310 if (!getOperand(i)->dominates(BB, DT))
316 void SCEVUDivExpr::Profile(FoldingSetNodeID &ID) const {
317 ID.AddInteger(scUDivExpr);
322 bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
323 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
326 void SCEVUDivExpr::print(raw_ostream &OS) const {
327 OS << "(" << *LHS << " /u " << *RHS << ")";
330 const Type *SCEVUDivExpr::getType() const {
331 // In most cases the types of LHS and RHS will be the same, but in some
332 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
333 // depend on the type for correctness, but handling types carefully can
334 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
335 // a pointer type than the RHS, so use the RHS' type here.
336 return RHS->getType();
339 void SCEVAddRecExpr::Profile(FoldingSetNodeID &ID) const {
340 ID.AddInteger(scAddRecExpr);
341 ID.AddInteger(Operands.size());
342 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
343 ID.AddPointer(Operands[i]);
348 SCEVAddRecExpr::replaceSymbolicValuesWithConcrete(const SCEV *Sym,
350 ScalarEvolution &SE) const {
351 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
353 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
354 if (H != getOperand(i)) {
355 SmallVector<const SCEV*, 8> NewOps;
356 NewOps.reserve(getNumOperands());
357 for (unsigned j = 0; j != i; ++j)
358 NewOps.push_back(getOperand(j));
360 for (++i; i != e; ++i)
361 NewOps.push_back(getOperand(i)->
362 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
364 return SE.getAddRecExpr(NewOps, L);
371 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
372 // Add recurrences are never invariant in the function-body (null loop).
376 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
377 if (QueryLoop->contains(L->getHeader()))
380 // This recurrence is variant w.r.t. QueryLoop if any of its operands
382 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
383 if (!getOperand(i)->isLoopInvariant(QueryLoop))
386 // Otherwise it's loop-invariant.
391 void SCEVAddRecExpr::print(raw_ostream &OS) const {
392 OS << "{" << *Operands[0];
393 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
394 OS << ",+," << *Operands[i];
395 OS << "}<" << L->getHeader()->getName() + ">";
398 void SCEVUnknown::Profile(FoldingSetNodeID &ID) const {
399 ID.AddInteger(scUnknown);
403 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
404 // All non-instruction values are loop invariant. All instructions are loop
405 // invariant if they are not contained in the specified loop.
406 // Instructions are never considered invariant in the function body
407 // (null loop) because they are defined within the "loop".
408 if (Instruction *I = dyn_cast<Instruction>(V))
409 return L && !L->contains(I->getParent());
413 bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
414 if (Instruction *I = dyn_cast<Instruction>(getValue()))
415 return DT->dominates(I->getParent(), BB);
419 const Type *SCEVUnknown::getType() const {
423 void SCEVUnknown::print(raw_ostream &OS) const {
424 WriteAsOperand(OS, V, false);
427 //===----------------------------------------------------------------------===//
429 //===----------------------------------------------------------------------===//
432 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
433 /// than the complexity of the RHS. This comparator is used to canonicalize
435 class VISIBILITY_HIDDEN SCEVComplexityCompare {
438 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
440 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
441 // Primarily, sort the SCEVs by their getSCEVType().
442 if (LHS->getSCEVType() != RHS->getSCEVType())
443 return LHS->getSCEVType() < RHS->getSCEVType();
445 // Aside from the getSCEVType() ordering, the particular ordering
446 // isn't very important except that it's beneficial to be consistent,
447 // so that (a + b) and (b + a) don't end up as different expressions.
449 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
450 // not as complete as it could be.
451 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
452 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
454 // Order pointer values after integer values. This helps SCEVExpander
456 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
458 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
461 // Compare getValueID values.
462 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
463 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
465 // Sort arguments by their position.
466 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
467 const Argument *RA = cast<Argument>(RU->getValue());
468 return LA->getArgNo() < RA->getArgNo();
471 // For instructions, compare their loop depth, and their opcode.
472 // This is pretty loose.
473 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
474 Instruction *RV = cast<Instruction>(RU->getValue());
476 // Compare loop depths.
477 if (LI->getLoopDepth(LV->getParent()) !=
478 LI->getLoopDepth(RV->getParent()))
479 return LI->getLoopDepth(LV->getParent()) <
480 LI->getLoopDepth(RV->getParent());
483 if (LV->getOpcode() != RV->getOpcode())
484 return LV->getOpcode() < RV->getOpcode();
486 // Compare the number of operands.
487 if (LV->getNumOperands() != RV->getNumOperands())
488 return LV->getNumOperands() < RV->getNumOperands();
494 // Compare constant values.
495 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
496 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
497 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
500 // Compare addrec loop depths.
501 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
502 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
503 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
504 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
507 // Lexicographically compare n-ary expressions.
508 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
509 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
510 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
511 if (i >= RC->getNumOperands())
513 if (operator()(LC->getOperand(i), RC->getOperand(i)))
515 if (operator()(RC->getOperand(i), LC->getOperand(i)))
518 return LC->getNumOperands() < RC->getNumOperands();
521 // Lexicographically compare udiv expressions.
522 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
523 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
524 if (operator()(LC->getLHS(), RC->getLHS()))
526 if (operator()(RC->getLHS(), LC->getLHS()))
528 if (operator()(LC->getRHS(), RC->getRHS()))
530 if (operator()(RC->getRHS(), LC->getRHS()))
535 // Compare cast expressions by operand.
536 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
537 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
538 return operator()(LC->getOperand(), RC->getOperand());
541 assert(0 && "Unknown SCEV kind!");
547 /// GroupByComplexity - Given a list of SCEV objects, order them by their
548 /// complexity, and group objects of the same complexity together by value.
549 /// When this routine is finished, we know that any duplicates in the vector are
550 /// consecutive and that complexity is monotonically increasing.
552 /// Note that we go take special precautions to ensure that we get determinstic
553 /// results from this routine. In other words, we don't want the results of
554 /// this to depend on where the addresses of various SCEV objects happened to
557 static void GroupByComplexity(SmallVectorImpl<const SCEV*> &Ops,
559 if (Ops.size() < 2) return; // Noop
560 if (Ops.size() == 2) {
561 // This is the common case, which also happens to be trivially simple.
563 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
564 std::swap(Ops[0], Ops[1]);
568 // Do the rough sort by complexity.
569 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
571 // Now that we are sorted by complexity, group elements of the same
572 // complexity. Note that this is, at worst, N^2, but the vector is likely to
573 // be extremely short in practice. Note that we take this approach because we
574 // do not want to depend on the addresses of the objects we are grouping.
575 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
576 const SCEV *S = Ops[i];
577 unsigned Complexity = S->getSCEVType();
579 // If there are any objects of the same complexity and same value as this
581 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
582 if (Ops[j] == S) { // Found a duplicate.
583 // Move it to immediately after i'th element.
584 std::swap(Ops[i+1], Ops[j]);
585 ++i; // no need to rescan it.
586 if (i == e-2) return; // Done!
594 //===----------------------------------------------------------------------===//
595 // Simple SCEV method implementations
596 //===----------------------------------------------------------------------===//
598 /// BinomialCoefficient - Compute BC(It, K). The result has width W.
600 static const SCEV* BinomialCoefficient(const SCEV* It, unsigned K,
602 const Type* ResultTy) {
603 // Handle the simplest case efficiently.
605 return SE.getTruncateOrZeroExtend(It, ResultTy);
607 // We are using the following formula for BC(It, K):
609 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
611 // Suppose, W is the bitwidth of the return value. We must be prepared for
612 // overflow. Hence, we must assure that the result of our computation is
613 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
614 // safe in modular arithmetic.
616 // However, this code doesn't use exactly that formula; the formula it uses
617 // is something like the following, where T is the number of factors of 2 in
618 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
621 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
623 // This formula is trivially equivalent to the previous formula. However,
624 // this formula can be implemented much more efficiently. The trick is that
625 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
626 // arithmetic. To do exact division in modular arithmetic, all we have
627 // to do is multiply by the inverse. Therefore, this step can be done at
630 // The next issue is how to safely do the division by 2^T. The way this
631 // is done is by doing the multiplication step at a width of at least W + T
632 // bits. This way, the bottom W+T bits of the product are accurate. Then,
633 // when we perform the division by 2^T (which is equivalent to a right shift
634 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
635 // truncated out after the division by 2^T.
637 // In comparison to just directly using the first formula, this technique
638 // is much more efficient; using the first formula requires W * K bits,
639 // but this formula less than W + K bits. Also, the first formula requires
640 // a division step, whereas this formula only requires multiplies and shifts.
642 // It doesn't matter whether the subtraction step is done in the calculation
643 // width or the input iteration count's width; if the subtraction overflows,
644 // the result must be zero anyway. We prefer here to do it in the width of
645 // the induction variable because it helps a lot for certain cases; CodeGen
646 // isn't smart enough to ignore the overflow, which leads to much less
647 // efficient code if the width of the subtraction is wider than the native
650 // (It's possible to not widen at all by pulling out factors of 2 before
651 // the multiplication; for example, K=2 can be calculated as
652 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
653 // extra arithmetic, so it's not an obvious win, and it gets
654 // much more complicated for K > 3.)
656 // Protection from insane SCEVs; this bound is conservative,
657 // but it probably doesn't matter.
659 return SE.getCouldNotCompute();
661 unsigned W = SE.getTypeSizeInBits(ResultTy);
663 // Calculate K! / 2^T and T; we divide out the factors of two before
664 // multiplying for calculating K! / 2^T to avoid overflow.
665 // Other overflow doesn't matter because we only care about the bottom
666 // W bits of the result.
667 APInt OddFactorial(W, 1);
669 for (unsigned i = 3; i <= K; ++i) {
671 unsigned TwoFactors = Mult.countTrailingZeros();
673 Mult = Mult.lshr(TwoFactors);
674 OddFactorial *= Mult;
677 // We need at least W + T bits for the multiplication step
678 unsigned CalculationBits = W + T;
680 // Calcuate 2^T, at width T+W.
681 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
683 // Calculate the multiplicative inverse of K! / 2^T;
684 // this multiplication factor will perform the exact division by
686 APInt Mod = APInt::getSignedMinValue(W+1);
687 APInt MultiplyFactor = OddFactorial.zext(W+1);
688 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
689 MultiplyFactor = MultiplyFactor.trunc(W);
691 // Calculate the product, at width T+W
692 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
693 const SCEV* Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
694 for (unsigned i = 1; i != K; ++i) {
695 const SCEV* S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
696 Dividend = SE.getMulExpr(Dividend,
697 SE.getTruncateOrZeroExtend(S, CalculationTy));
701 const SCEV* DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
703 // Truncate the result, and divide by K! / 2^T.
705 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
706 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
709 /// evaluateAtIteration - Return the value of this chain of recurrences at
710 /// the specified iteration number. We can evaluate this recurrence by
711 /// multiplying each element in the chain by the binomial coefficient
712 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
714 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
716 /// where BC(It, k) stands for binomial coefficient.
718 const SCEV* SCEVAddRecExpr::evaluateAtIteration(const SCEV* It,
719 ScalarEvolution &SE) const {
720 const SCEV* Result = getStart();
721 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
722 // The computation is correct in the face of overflow provided that the
723 // multiplication is performed _after_ the evaluation of the binomial
725 const SCEV* Coeff = BinomialCoefficient(It, i, SE, getType());
726 if (isa<SCEVCouldNotCompute>(Coeff))
729 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
734 //===----------------------------------------------------------------------===//
735 // SCEV Expression folder implementations
736 //===----------------------------------------------------------------------===//
738 const SCEV* ScalarEvolution::getTruncateExpr(const SCEV* Op,
740 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
741 "This is not a truncating conversion!");
742 assert(isSCEVable(Ty) &&
743 "This is not a conversion to a SCEVable type!");
744 Ty = getEffectiveSCEVType(Ty);
746 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
748 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
750 // trunc(trunc(x)) --> trunc(x)
751 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
752 return getTruncateExpr(ST->getOperand(), Ty);
754 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
755 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
756 return getTruncateOrSignExtend(SS->getOperand(), Ty);
758 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
759 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
760 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
762 // If the input value is a chrec scev, truncate the chrec's operands.
763 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
764 SmallVector<const SCEV*, 4> Operands;
765 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
766 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
767 return getAddRecExpr(Operands, AddRec->getLoop());
771 ID.AddInteger(scTruncate);
775 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
776 SCEV *S = SCEVAllocator.Allocate<SCEVTruncateExpr>();
777 new (S) SCEVTruncateExpr(Op, Ty);
778 UniqueSCEVs.InsertNode(S, IP);
782 const SCEV* ScalarEvolution::getZeroExtendExpr(const SCEV* Op,
784 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
785 "This is not an extending conversion!");
786 assert(isSCEVable(Ty) &&
787 "This is not a conversion to a SCEVable type!");
788 Ty = getEffectiveSCEVType(Ty);
790 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
791 const Type *IntTy = getEffectiveSCEVType(Ty);
792 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
793 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
794 return getConstant(cast<ConstantInt>(C));
797 // zext(zext(x)) --> zext(x)
798 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
799 return getZeroExtendExpr(SZ->getOperand(), Ty);
801 // If the input value is a chrec scev, and we can prove that the value
802 // did not overflow the old, smaller, value, we can zero extend all of the
803 // operands (often constants). This allows analysis of something like
804 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
805 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
806 if (AR->isAffine()) {
807 // Check whether the backedge-taken count is SCEVCouldNotCompute.
808 // Note that this serves two purposes: It filters out loops that are
809 // simply not analyzable, and it covers the case where this code is
810 // being called from within backedge-taken count analysis, such that
811 // attempting to ask for the backedge-taken count would likely result
812 // in infinite recursion. In the later case, the analysis code will
813 // cope with a conservative value, and it will take care to purge
814 // that value once it has finished.
815 const SCEV* MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
816 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
817 // Manually compute the final value for AR, checking for
819 const SCEV* Start = AR->getStart();
820 const SCEV* Step = AR->getStepRecurrence(*this);
822 // Check whether the backedge-taken count can be losslessly casted to
823 // the addrec's type. The count is always unsigned.
824 const SCEV* CastedMaxBECount =
825 getTruncateOrZeroExtend(MaxBECount, Start->getType());
826 const SCEV* RecastedMaxBECount =
827 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
828 if (MaxBECount == RecastedMaxBECount) {
830 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
831 // Check whether Start+Step*MaxBECount has no unsigned overflow.
833 getMulExpr(CastedMaxBECount,
834 getTruncateOrZeroExtend(Step, Start->getType()));
835 const SCEV* Add = getAddExpr(Start, ZMul);
836 const SCEV* OperandExtendedAdd =
837 getAddExpr(getZeroExtendExpr(Start, WideTy),
838 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
839 getZeroExtendExpr(Step, WideTy)));
840 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
841 // Return the expression with the addrec on the outside.
842 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
843 getZeroExtendExpr(Step, Ty),
846 // Similar to above, only this time treat the step value as signed.
847 // This covers loops that count down.
849 getMulExpr(CastedMaxBECount,
850 getTruncateOrSignExtend(Step, Start->getType()));
851 Add = getAddExpr(Start, SMul);
853 getAddExpr(getZeroExtendExpr(Start, WideTy),
854 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
855 getSignExtendExpr(Step, WideTy)));
856 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
857 // Return the expression with the addrec on the outside.
858 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
859 getSignExtendExpr(Step, Ty),
866 ID.AddInteger(scZeroExtend);
870 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
871 SCEV *S = SCEVAllocator.Allocate<SCEVZeroExtendExpr>();
872 new (S) SCEVZeroExtendExpr(Op, Ty);
873 UniqueSCEVs.InsertNode(S, IP);
877 const SCEV* ScalarEvolution::getSignExtendExpr(const SCEV* Op,
879 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
880 "This is not an extending conversion!");
881 assert(isSCEVable(Ty) &&
882 "This is not a conversion to a SCEVable type!");
883 Ty = getEffectiveSCEVType(Ty);
885 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
886 const Type *IntTy = getEffectiveSCEVType(Ty);
887 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
888 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
889 return getConstant(cast<ConstantInt>(C));
892 // sext(sext(x)) --> sext(x)
893 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
894 return getSignExtendExpr(SS->getOperand(), Ty);
896 // If the input value is a chrec scev, and we can prove that the value
897 // did not overflow the old, smaller, value, we can sign extend all of the
898 // operands (often constants). This allows analysis of something like
899 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
900 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
901 if (AR->isAffine()) {
902 // Check whether the backedge-taken count is SCEVCouldNotCompute.
903 // Note that this serves two purposes: It filters out loops that are
904 // simply not analyzable, and it covers the case where this code is
905 // being called from within backedge-taken count analysis, such that
906 // attempting to ask for the backedge-taken count would likely result
907 // in infinite recursion. In the later case, the analysis code will
908 // cope with a conservative value, and it will take care to purge
909 // that value once it has finished.
910 const SCEV* MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
911 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
912 // Manually compute the final value for AR, checking for
914 const SCEV* Start = AR->getStart();
915 const SCEV* Step = AR->getStepRecurrence(*this);
917 // Check whether the backedge-taken count can be losslessly casted to
918 // the addrec's type. The count is always unsigned.
919 const SCEV* CastedMaxBECount =
920 getTruncateOrZeroExtend(MaxBECount, Start->getType());
921 const SCEV* RecastedMaxBECount =
922 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
923 if (MaxBECount == RecastedMaxBECount) {
925 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
926 // Check whether Start+Step*MaxBECount has no signed overflow.
928 getMulExpr(CastedMaxBECount,
929 getTruncateOrSignExtend(Step, Start->getType()));
930 const SCEV* Add = getAddExpr(Start, SMul);
931 const SCEV* OperandExtendedAdd =
932 getAddExpr(getSignExtendExpr(Start, WideTy),
933 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
934 getSignExtendExpr(Step, WideTy)));
935 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
936 // Return the expression with the addrec on the outside.
937 return getAddRecExpr(getSignExtendExpr(Start, Ty),
938 getSignExtendExpr(Step, Ty),
945 ID.AddInteger(scSignExtend);
949 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
950 SCEV *S = SCEVAllocator.Allocate<SCEVSignExtendExpr>();
951 new (S) SCEVSignExtendExpr(Op, Ty);
952 UniqueSCEVs.InsertNode(S, IP);
956 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
957 /// unspecified bits out to the given type.
959 const SCEV* ScalarEvolution::getAnyExtendExpr(const SCEV* Op,
961 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
962 "This is not an extending conversion!");
963 assert(isSCEVable(Ty) &&
964 "This is not a conversion to a SCEVable type!");
965 Ty = getEffectiveSCEVType(Ty);
967 // Sign-extend negative constants.
968 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
969 if (SC->getValue()->getValue().isNegative())
970 return getSignExtendExpr(Op, Ty);
972 // Peel off a truncate cast.
973 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
974 const SCEV* NewOp = T->getOperand();
975 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
976 return getAnyExtendExpr(NewOp, Ty);
977 return getTruncateOrNoop(NewOp, Ty);
980 // Next try a zext cast. If the cast is folded, use it.
981 const SCEV* ZExt = getZeroExtendExpr(Op, Ty);
982 if (!isa<SCEVZeroExtendExpr>(ZExt))
985 // Next try a sext cast. If the cast is folded, use it.
986 const SCEV* SExt = getSignExtendExpr(Op, Ty);
987 if (!isa<SCEVSignExtendExpr>(SExt))
990 // If the expression is obviously signed, use the sext cast value.
991 if (isa<SCEVSMaxExpr>(Op))
994 // Absent any other information, use the zext cast value.
998 /// CollectAddOperandsWithScales - Process the given Ops list, which is
999 /// a list of operands to be added under the given scale, update the given
1000 /// map. This is a helper function for getAddRecExpr. As an example of
1001 /// what it does, given a sequence of operands that would form an add
1002 /// expression like this:
1004 /// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1006 /// where A and B are constants, update the map with these values:
1008 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1010 /// and add 13 + A*B*29 to AccumulatedConstant.
1011 /// This will allow getAddRecExpr to produce this:
1013 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1015 /// This form often exposes folding opportunities that are hidden in
1016 /// the original operand list.
1018 /// Return true iff it appears that any interesting folding opportunities
1019 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
1020 /// the common case where no interesting opportunities are present, and
1021 /// is also used as a check to avoid infinite recursion.
1024 CollectAddOperandsWithScales(DenseMap<const SCEV*, APInt> &M,
1025 SmallVector<const SCEV*, 8> &NewOps,
1026 APInt &AccumulatedConstant,
1027 const SmallVectorImpl<const SCEV*> &Ops,
1029 ScalarEvolution &SE) {
1030 bool Interesting = false;
1032 // Iterate over the add operands.
1033 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1034 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1035 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1037 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1038 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1039 // A multiplication of a constant with another add; recurse.
1041 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1042 cast<SCEVAddExpr>(Mul->getOperand(1))
1046 // A multiplication of a constant with some other value. Update
1048 SmallVector<const SCEV*, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1049 const SCEV* Key = SE.getMulExpr(MulOps);
1050 std::pair<DenseMap<const SCEV*, APInt>::iterator, bool> Pair =
1051 M.insert(std::make_pair(Key, NewScale));
1053 NewOps.push_back(Pair.first->first);
1055 Pair.first->second += NewScale;
1056 // The map already had an entry for this value, which may indicate
1057 // a folding opportunity.
1061 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1062 // Pull a buried constant out to the outside.
1063 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1065 AccumulatedConstant += Scale * C->getValue()->getValue();
1067 // An ordinary operand. Update the map.
1068 std::pair<DenseMap<const SCEV*, APInt>::iterator, bool> Pair =
1069 M.insert(std::make_pair(Ops[i], Scale));
1071 NewOps.push_back(Pair.first->first);
1073 Pair.first->second += Scale;
1074 // The map already had an entry for this value, which may indicate
1075 // a folding opportunity.
1085 struct APIntCompare {
1086 bool operator()(const APInt &LHS, const APInt &RHS) const {
1087 return LHS.ult(RHS);
1092 /// getAddExpr - Get a canonical add expression, or something simpler if
1094 const SCEV* ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV*> &Ops) {
1095 assert(!Ops.empty() && "Cannot get empty add!");
1096 if (Ops.size() == 1) return Ops[0];
1098 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1099 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1100 getEffectiveSCEVType(Ops[0]->getType()) &&
1101 "SCEVAddExpr operand types don't match!");
1104 // Sort by complexity, this groups all similar expression types together.
1105 GroupByComplexity(Ops, LI);
1107 // If there are any constants, fold them together.
1109 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1111 assert(Idx < Ops.size());
1112 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1113 // We found two constants, fold them together!
1114 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1115 RHSC->getValue()->getValue());
1116 if (Ops.size() == 2) return Ops[0];
1117 Ops.erase(Ops.begin()+1); // Erase the folded element
1118 LHSC = cast<SCEVConstant>(Ops[0]);
1121 // If we are left with a constant zero being added, strip it off.
1122 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1123 Ops.erase(Ops.begin());
1128 if (Ops.size() == 1) return Ops[0];
1130 // Okay, check to see if the same value occurs in the operand list twice. If
1131 // so, merge them together into an multiply expression. Since we sorted the
1132 // list, these values are required to be adjacent.
1133 const Type *Ty = Ops[0]->getType();
1134 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1135 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1136 // Found a match, merge the two values into a multiply, and add any
1137 // remaining values to the result.
1138 const SCEV* Two = getIntegerSCEV(2, Ty);
1139 const SCEV* Mul = getMulExpr(Ops[i], Two);
1140 if (Ops.size() == 2)
1142 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1144 return getAddExpr(Ops);
1147 // Check for truncates. If all the operands are truncated from the same
1148 // type, see if factoring out the truncate would permit the result to be
1149 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1150 // if the contents of the resulting outer trunc fold to something simple.
1151 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1152 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1153 const Type *DstType = Trunc->getType();
1154 const Type *SrcType = Trunc->getOperand()->getType();
1155 SmallVector<const SCEV*, 8> LargeOps;
1157 // Check all the operands to see if they can be represented in the
1158 // source type of the truncate.
1159 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1160 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1161 if (T->getOperand()->getType() != SrcType) {
1165 LargeOps.push_back(T->getOperand());
1166 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1167 // This could be either sign or zero extension, but sign extension
1168 // is much more likely to be foldable here.
1169 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1170 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
1171 SmallVector<const SCEV*, 8> LargeMulOps;
1172 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1173 if (const SCEVTruncateExpr *T =
1174 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1175 if (T->getOperand()->getType() != SrcType) {
1179 LargeMulOps.push_back(T->getOperand());
1180 } else if (const SCEVConstant *C =
1181 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1182 // This could be either sign or zero extension, but sign extension
1183 // is much more likely to be foldable here.
1184 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1191 LargeOps.push_back(getMulExpr(LargeMulOps));
1198 // Evaluate the expression in the larger type.
1199 const SCEV* Fold = getAddExpr(LargeOps);
1200 // If it folds to something simple, use it. Otherwise, don't.
1201 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1202 return getTruncateExpr(Fold, DstType);
1206 // Skip past any other cast SCEVs.
1207 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1210 // If there are add operands they would be next.
1211 if (Idx < Ops.size()) {
1212 bool DeletedAdd = false;
1213 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
1214 // If we have an add, expand the add operands onto the end of the operands
1216 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1217 Ops.erase(Ops.begin()+Idx);
1221 // If we deleted at least one add, we added operands to the end of the list,
1222 // and they are not necessarily sorted. Recurse to resort and resimplify
1223 // any operands we just aquired.
1225 return getAddExpr(Ops);
1228 // Skip over the add expression until we get to a multiply.
1229 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1232 // Check to see if there are any folding opportunities present with
1233 // operands multiplied by constant values.
1234 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1235 uint64_t BitWidth = getTypeSizeInBits(Ty);
1236 DenseMap<const SCEV*, APInt> M;
1237 SmallVector<const SCEV*, 8> NewOps;
1238 APInt AccumulatedConstant(BitWidth, 0);
1239 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1240 Ops, APInt(BitWidth, 1), *this)) {
1241 // Some interesting folding opportunity is present, so its worthwhile to
1242 // re-generate the operands list. Group the operands by constant scale,
1243 // to avoid multiplying by the same constant scale multiple times.
1244 std::map<APInt, SmallVector<const SCEV*, 4>, APIntCompare> MulOpLists;
1245 for (SmallVector<const SCEV*, 8>::iterator I = NewOps.begin(),
1246 E = NewOps.end(); I != E; ++I)
1247 MulOpLists[M.find(*I)->second].push_back(*I);
1248 // Re-generate the operands list.
1250 if (AccumulatedConstant != 0)
1251 Ops.push_back(getConstant(AccumulatedConstant));
1252 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1253 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
1255 Ops.push_back(getMulExpr(getConstant(I->first),
1256 getAddExpr(I->second)));
1258 return getIntegerSCEV(0, Ty);
1259 if (Ops.size() == 1)
1261 return getAddExpr(Ops);
1265 // If we are adding something to a multiply expression, make sure the
1266 // something is not already an operand of the multiply. If so, merge it into
1268 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
1269 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
1270 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
1271 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
1272 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
1273 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
1274 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1275 const SCEV* InnerMul = Mul->getOperand(MulOp == 0);
1276 if (Mul->getNumOperands() != 2) {
1277 // If the multiply has more than two operands, we must get the
1279 SmallVector<const SCEV*, 4> MulOps(Mul->op_begin(), Mul->op_end());
1280 MulOps.erase(MulOps.begin()+MulOp);
1281 InnerMul = getMulExpr(MulOps);
1283 const SCEV* One = getIntegerSCEV(1, Ty);
1284 const SCEV* AddOne = getAddExpr(InnerMul, One);
1285 const SCEV* OuterMul = getMulExpr(AddOne, Ops[AddOp]);
1286 if (Ops.size() == 2) return OuterMul;
1288 Ops.erase(Ops.begin()+AddOp);
1289 Ops.erase(Ops.begin()+Idx-1);
1291 Ops.erase(Ops.begin()+Idx);
1292 Ops.erase(Ops.begin()+AddOp-1);
1294 Ops.push_back(OuterMul);
1295 return getAddExpr(Ops);
1298 // Check this multiply against other multiplies being added together.
1299 for (unsigned OtherMulIdx = Idx+1;
1300 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1302 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
1303 // If MulOp occurs in OtherMul, we can fold the two multiplies
1305 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1306 OMulOp != e; ++OMulOp)
1307 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1308 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1309 const SCEV* InnerMul1 = Mul->getOperand(MulOp == 0);
1310 if (Mul->getNumOperands() != 2) {
1311 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1313 MulOps.erase(MulOps.begin()+MulOp);
1314 InnerMul1 = getMulExpr(MulOps);
1316 const SCEV* InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1317 if (OtherMul->getNumOperands() != 2) {
1318 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1319 OtherMul->op_end());
1320 MulOps.erase(MulOps.begin()+OMulOp);
1321 InnerMul2 = getMulExpr(MulOps);
1323 const SCEV* InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1324 const SCEV* OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
1325 if (Ops.size() == 2) return OuterMul;
1326 Ops.erase(Ops.begin()+Idx);
1327 Ops.erase(Ops.begin()+OtherMulIdx-1);
1328 Ops.push_back(OuterMul);
1329 return getAddExpr(Ops);
1335 // If there are any add recurrences in the operands list, see if any other
1336 // added values are loop invariant. If so, we can fold them into the
1338 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1341 // Scan over all recurrences, trying to fold loop invariants into them.
1342 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1343 // Scan all of the other operands to this add and add them to the vector if
1344 // they are loop invariant w.r.t. the recurrence.
1345 SmallVector<const SCEV*, 8> LIOps;
1346 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1347 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1348 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1349 LIOps.push_back(Ops[i]);
1350 Ops.erase(Ops.begin()+i);
1354 // If we found some loop invariants, fold them into the recurrence.
1355 if (!LIOps.empty()) {
1356 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
1357 LIOps.push_back(AddRec->getStart());
1359 SmallVector<const SCEV*, 4> AddRecOps(AddRec->op_begin(),
1361 AddRecOps[0] = getAddExpr(LIOps);
1363 const SCEV* NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
1364 // If all of the other operands were loop invariant, we are done.
1365 if (Ops.size() == 1) return NewRec;
1367 // Otherwise, add the folded AddRec by the non-liv parts.
1368 for (unsigned i = 0;; ++i)
1369 if (Ops[i] == AddRec) {
1373 return getAddExpr(Ops);
1376 // Okay, if there weren't any loop invariants to be folded, check to see if
1377 // there are multiple AddRec's with the same loop induction variable being
1378 // added together. If so, we can fold them.
1379 for (unsigned OtherIdx = Idx+1;
1380 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1381 if (OtherIdx != Idx) {
1382 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1383 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1384 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1385 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1387 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1388 if (i >= NewOps.size()) {
1389 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1390 OtherAddRec->op_end());
1393 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
1395 const SCEV* NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
1397 if (Ops.size() == 2) return NewAddRec;
1399 Ops.erase(Ops.begin()+Idx);
1400 Ops.erase(Ops.begin()+OtherIdx-1);
1401 Ops.push_back(NewAddRec);
1402 return getAddExpr(Ops);
1406 // Otherwise couldn't fold anything into this recurrence. Move onto the
1410 // Okay, it looks like we really DO need an add expr. Check to see if we
1411 // already have one, otherwise create a new one.
1412 FoldingSetNodeID ID;
1413 ID.AddInteger(scAddExpr);
1414 ID.AddInteger(Ops.size());
1415 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1416 ID.AddPointer(Ops[i]);
1418 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1419 SCEV *S = SCEVAllocator.Allocate<SCEVAddExpr>();
1420 new (S) SCEVAddExpr(Ops);
1421 UniqueSCEVs.InsertNode(S, IP);
1426 /// getMulExpr - Get a canonical multiply expression, or something simpler if
1428 const SCEV* ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV*> &Ops) {
1429 assert(!Ops.empty() && "Cannot get empty mul!");
1431 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1432 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1433 getEffectiveSCEVType(Ops[0]->getType()) &&
1434 "SCEVMulExpr operand types don't match!");
1437 // Sort by complexity, this groups all similar expression types together.
1438 GroupByComplexity(Ops, LI);
1440 // If there are any constants, fold them together.
1442 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1444 // C1*(C2+V) -> C1*C2 + C1*V
1445 if (Ops.size() == 2)
1446 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1447 if (Add->getNumOperands() == 2 &&
1448 isa<SCEVConstant>(Add->getOperand(0)))
1449 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1450 getMulExpr(LHSC, Add->getOperand(1)));
1454 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1455 // We found two constants, fold them together!
1456 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1457 RHSC->getValue()->getValue());
1458 Ops[0] = getConstant(Fold);
1459 Ops.erase(Ops.begin()+1); // Erase the folded element
1460 if (Ops.size() == 1) return Ops[0];
1461 LHSC = cast<SCEVConstant>(Ops[0]);
1464 // If we are left with a constant one being multiplied, strip it off.
1465 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1466 Ops.erase(Ops.begin());
1468 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1469 // If we have a multiply of zero, it will always be zero.
1474 // Skip over the add expression until we get to a multiply.
1475 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1478 if (Ops.size() == 1)
1481 // If there are mul operands inline them all into this expression.
1482 if (Idx < Ops.size()) {
1483 bool DeletedMul = false;
1484 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1485 // If we have an mul, expand the mul operands onto the end of the operands
1487 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1488 Ops.erase(Ops.begin()+Idx);
1492 // If we deleted at least one mul, we added operands to the end of the list,
1493 // and they are not necessarily sorted. Recurse to resort and resimplify
1494 // any operands we just aquired.
1496 return getMulExpr(Ops);
1499 // If there are any add recurrences in the operands list, see if any other
1500 // added values are loop invariant. If so, we can fold them into the
1502 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1505 // Scan over all recurrences, trying to fold loop invariants into them.
1506 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1507 // Scan all of the other operands to this mul and add them to the vector if
1508 // they are loop invariant w.r.t. the recurrence.
1509 SmallVector<const SCEV*, 8> LIOps;
1510 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1511 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1512 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1513 LIOps.push_back(Ops[i]);
1514 Ops.erase(Ops.begin()+i);
1518 // If we found some loop invariants, fold them into the recurrence.
1519 if (!LIOps.empty()) {
1520 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
1521 SmallVector<const SCEV*, 4> NewOps;
1522 NewOps.reserve(AddRec->getNumOperands());
1523 if (LIOps.size() == 1) {
1524 const SCEV *Scale = LIOps[0];
1525 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1526 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1528 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1529 SmallVector<const SCEV*, 4> MulOps(LIOps.begin(), LIOps.end());
1530 MulOps.push_back(AddRec->getOperand(i));
1531 NewOps.push_back(getMulExpr(MulOps));
1535 const SCEV* NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
1537 // If all of the other operands were loop invariant, we are done.
1538 if (Ops.size() == 1) return NewRec;
1540 // Otherwise, multiply the folded AddRec by the non-liv parts.
1541 for (unsigned i = 0;; ++i)
1542 if (Ops[i] == AddRec) {
1546 return getMulExpr(Ops);
1549 // Okay, if there weren't any loop invariants to be folded, check to see if
1550 // there are multiple AddRec's with the same loop induction variable being
1551 // multiplied together. If so, we can fold them.
1552 for (unsigned OtherIdx = Idx+1;
1553 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1554 if (OtherIdx != Idx) {
1555 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1556 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1557 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1558 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1559 const SCEV* NewStart = getMulExpr(F->getStart(),
1561 const SCEV* B = F->getStepRecurrence(*this);
1562 const SCEV* D = G->getStepRecurrence(*this);
1563 const SCEV* NewStep = getAddExpr(getMulExpr(F, D),
1566 const SCEV* NewAddRec = getAddRecExpr(NewStart, NewStep,
1568 if (Ops.size() == 2) return NewAddRec;
1570 Ops.erase(Ops.begin()+Idx);
1571 Ops.erase(Ops.begin()+OtherIdx-1);
1572 Ops.push_back(NewAddRec);
1573 return getMulExpr(Ops);
1577 // Otherwise couldn't fold anything into this recurrence. Move onto the
1581 // Okay, it looks like we really DO need an mul expr. Check to see if we
1582 // already have one, otherwise create a new one.
1583 FoldingSetNodeID ID;
1584 ID.AddInteger(scMulExpr);
1585 ID.AddInteger(Ops.size());
1586 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1587 ID.AddPointer(Ops[i]);
1589 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1590 SCEV *S = SCEVAllocator.Allocate<SCEVMulExpr>();
1591 new (S) SCEVMulExpr(Ops);
1592 UniqueSCEVs.InsertNode(S, IP);
1596 /// getUDivExpr - Get a canonical multiply expression, or something simpler if
1598 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1600 assert(getEffectiveSCEVType(LHS->getType()) ==
1601 getEffectiveSCEVType(RHS->getType()) &&
1602 "SCEVUDivExpr operand types don't match!");
1604 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1605 if (RHSC->getValue()->equalsInt(1))
1606 return LHS; // X udiv 1 --> x
1608 return getIntegerSCEV(0, LHS->getType()); // value is undefined
1610 // Determine if the division can be folded into the operands of
1612 // TODO: Generalize this to non-constants by using known-bits information.
1613 const Type *Ty = LHS->getType();
1614 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1615 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1616 // For non-power-of-two values, effectively round the value up to the
1617 // nearest power of two.
1618 if (!RHSC->getValue()->getValue().isPowerOf2())
1620 const IntegerType *ExtTy =
1621 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1622 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1623 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1624 if (const SCEVConstant *Step =
1625 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1626 if (!Step->getValue()->getValue()
1627 .urem(RHSC->getValue()->getValue()) &&
1628 getZeroExtendExpr(AR, ExtTy) ==
1629 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1630 getZeroExtendExpr(Step, ExtTy),
1632 SmallVector<const SCEV*, 4> Operands;
1633 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1634 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1635 return getAddRecExpr(Operands, AR->getLoop());
1637 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1638 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1639 SmallVector<const SCEV*, 4> Operands;
1640 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1641 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1642 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
1643 // Find an operand that's safely divisible.
1644 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1645 const SCEV* Op = M->getOperand(i);
1646 const SCEV* Div = getUDivExpr(Op, RHSC);
1647 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1648 const SmallVectorImpl<const SCEV*> &MOperands = M->getOperands();
1649 Operands = SmallVector<const SCEV*, 4>(MOperands.begin(),
1652 return getMulExpr(Operands);
1656 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
1657 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1658 SmallVector<const SCEV*, 4> Operands;
1659 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1660 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1661 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1663 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1664 const SCEV* Op = getUDivExpr(A->getOperand(i), RHS);
1665 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1667 Operands.push_back(Op);
1669 if (Operands.size() == A->getNumOperands())
1670 return getAddExpr(Operands);
1674 // Fold if both operands are constant.
1675 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1676 Constant *LHSCV = LHSC->getValue();
1677 Constant *RHSCV = RHSC->getValue();
1678 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1683 FoldingSetNodeID ID;
1684 ID.AddInteger(scUDivExpr);
1688 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1689 SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>();
1690 new (S) SCEVUDivExpr(LHS, RHS);
1691 UniqueSCEVs.InsertNode(S, IP);
1696 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1697 /// Simplify the expression as much as possible.
1698 const SCEV* ScalarEvolution::getAddRecExpr(const SCEV* Start,
1699 const SCEV* Step, const Loop *L) {
1700 SmallVector<const SCEV*, 4> Operands;
1701 Operands.push_back(Start);
1702 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1703 if (StepChrec->getLoop() == L) {
1704 Operands.insert(Operands.end(), StepChrec->op_begin(),
1705 StepChrec->op_end());
1706 return getAddRecExpr(Operands, L);
1709 Operands.push_back(Step);
1710 return getAddRecExpr(Operands, L);
1713 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1714 /// Simplify the expression as much as possible.
1716 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV*> &Operands,
1718 if (Operands.size() == 1) return Operands[0];
1720 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1721 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1722 getEffectiveSCEVType(Operands[0]->getType()) &&
1723 "SCEVAddRecExpr operand types don't match!");
1726 if (Operands.back()->isZero()) {
1727 Operands.pop_back();
1728 return getAddRecExpr(Operands, L); // {X,+,0} --> X
1731 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1732 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1733 const Loop* NestedLoop = NestedAR->getLoop();
1734 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1735 SmallVector<const SCEV*, 4> NestedOperands(NestedAR->op_begin(),
1736 NestedAR->op_end());
1737 Operands[0] = NestedAR->getStart();
1738 // AddRecs require their operands be loop-invariant with respect to their
1739 // loops. Don't perform this transformation if it would break this
1741 bool AllInvariant = true;
1742 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1743 if (!Operands[i]->isLoopInvariant(L)) {
1744 AllInvariant = false;
1748 NestedOperands[0] = getAddRecExpr(Operands, L);
1749 AllInvariant = true;
1750 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
1751 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
1752 AllInvariant = false;
1756 // Ok, both add recurrences are valid after the transformation.
1757 return getAddRecExpr(NestedOperands, NestedLoop);
1759 // Reset Operands to its original state.
1760 Operands[0] = NestedAR;
1764 FoldingSetNodeID ID;
1765 ID.AddInteger(scAddRecExpr);
1766 ID.AddInteger(Operands.size());
1767 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1768 ID.AddPointer(Operands[i]);
1771 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1772 SCEV *S = SCEVAllocator.Allocate<SCEVAddRecExpr>();
1773 new (S) SCEVAddRecExpr(Operands, L);
1774 UniqueSCEVs.InsertNode(S, IP);
1778 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
1780 SmallVector<const SCEV*, 2> Ops;
1783 return getSMaxExpr(Ops);
1787 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV*> &Ops) {
1788 assert(!Ops.empty() && "Cannot get empty smax!");
1789 if (Ops.size() == 1) return Ops[0];
1791 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1792 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1793 getEffectiveSCEVType(Ops[0]->getType()) &&
1794 "SCEVSMaxExpr operand types don't match!");
1797 // Sort by complexity, this groups all similar expression types together.
1798 GroupByComplexity(Ops, LI);
1800 // If there are any constants, fold them together.
1802 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1804 assert(Idx < Ops.size());
1805 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1806 // We found two constants, fold them together!
1807 ConstantInt *Fold = ConstantInt::get(
1808 APIntOps::smax(LHSC->getValue()->getValue(),
1809 RHSC->getValue()->getValue()));
1810 Ops[0] = getConstant(Fold);
1811 Ops.erase(Ops.begin()+1); // Erase the folded element
1812 if (Ops.size() == 1) return Ops[0];
1813 LHSC = cast<SCEVConstant>(Ops[0]);
1816 // If we are left with a constant minimum-int, strip it off.
1817 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1818 Ops.erase(Ops.begin());
1820 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
1821 // If we have an smax with a constant maximum-int, it will always be
1827 if (Ops.size() == 1) return Ops[0];
1829 // Find the first SMax
1830 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1833 // Check to see if one of the operands is an SMax. If so, expand its operands
1834 // onto our operand list, and recurse to simplify.
1835 if (Idx < Ops.size()) {
1836 bool DeletedSMax = false;
1837 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1838 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1839 Ops.erase(Ops.begin()+Idx);
1844 return getSMaxExpr(Ops);
1847 // Okay, check to see if the same value occurs in the operand list twice. If
1848 // so, delete one. Since we sorted the list, these values are required to
1850 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1851 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1852 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1856 if (Ops.size() == 1) return Ops[0];
1858 assert(!Ops.empty() && "Reduced smax down to nothing!");
1860 // Okay, it looks like we really DO need an smax expr. Check to see if we
1861 // already have one, otherwise create a new one.
1862 FoldingSetNodeID ID;
1863 ID.AddInteger(scSMaxExpr);
1864 ID.AddInteger(Ops.size());
1865 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1866 ID.AddPointer(Ops[i]);
1868 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1869 SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>();
1870 new (S) SCEVSMaxExpr(Ops);
1871 UniqueSCEVs.InsertNode(S, IP);
1875 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
1877 SmallVector<const SCEV*, 2> Ops;
1880 return getUMaxExpr(Ops);
1884 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV*> &Ops) {
1885 assert(!Ops.empty() && "Cannot get empty umax!");
1886 if (Ops.size() == 1) return Ops[0];
1888 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1889 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1890 getEffectiveSCEVType(Ops[0]->getType()) &&
1891 "SCEVUMaxExpr operand types don't match!");
1894 // Sort by complexity, this groups all similar expression types together.
1895 GroupByComplexity(Ops, LI);
1897 // If there are any constants, fold them together.
1899 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1901 assert(Idx < Ops.size());
1902 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1903 // We found two constants, fold them together!
1904 ConstantInt *Fold = ConstantInt::get(
1905 APIntOps::umax(LHSC->getValue()->getValue(),
1906 RHSC->getValue()->getValue()));
1907 Ops[0] = getConstant(Fold);
1908 Ops.erase(Ops.begin()+1); // Erase the folded element
1909 if (Ops.size() == 1) return Ops[0];
1910 LHSC = cast<SCEVConstant>(Ops[0]);
1913 // If we are left with a constant minimum-int, strip it off.
1914 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1915 Ops.erase(Ops.begin());
1917 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
1918 // If we have an umax with a constant maximum-int, it will always be
1924 if (Ops.size() == 1) return Ops[0];
1926 // Find the first UMax
1927 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1930 // Check to see if one of the operands is a UMax. If so, expand its operands
1931 // onto our operand list, and recurse to simplify.
1932 if (Idx < Ops.size()) {
1933 bool DeletedUMax = false;
1934 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1935 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1936 Ops.erase(Ops.begin()+Idx);
1941 return getUMaxExpr(Ops);
1944 // Okay, check to see if the same value occurs in the operand list twice. If
1945 // so, delete one. Since we sorted the list, these values are required to
1947 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1948 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1949 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1953 if (Ops.size() == 1) return Ops[0];
1955 assert(!Ops.empty() && "Reduced umax down to nothing!");
1957 // Okay, it looks like we really DO need a umax expr. Check to see if we
1958 // already have one, otherwise create a new one.
1959 FoldingSetNodeID ID;
1960 ID.AddInteger(scUMaxExpr);
1961 ID.AddInteger(Ops.size());
1962 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1963 ID.AddPointer(Ops[i]);
1965 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1966 SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>();
1967 new (S) SCEVUMaxExpr(Ops);
1968 UniqueSCEVs.InsertNode(S, IP);
1972 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
1974 // ~smax(~x, ~y) == smin(x, y).
1975 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
1978 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
1980 // ~umax(~x, ~y) == umin(x, y)
1981 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
1984 const SCEV* ScalarEvolution::getUnknown(Value *V) {
1985 // Don't attempt to do anything other than create a SCEVUnknown object
1986 // here. createSCEV only calls getUnknown after checking for all other
1987 // interesting possibilities, and any other code that calls getUnknown
1988 // is doing so in order to hide a value from SCEV canonicalization.
1990 FoldingSetNodeID ID;
1991 ID.AddInteger(scUnknown);
1994 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1995 SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>();
1996 new (S) SCEVUnknown(V);
1997 UniqueSCEVs.InsertNode(S, IP);
2001 //===----------------------------------------------------------------------===//
2002 // Basic SCEV Analysis and PHI Idiom Recognition Code
2005 /// isSCEVable - Test if values of the given type are analyzable within
2006 /// the SCEV framework. This primarily includes integer types, and it
2007 /// can optionally include pointer types if the ScalarEvolution class
2008 /// has access to target-specific information.
2009 bool ScalarEvolution::isSCEVable(const Type *Ty) const {
2010 // Integers are always SCEVable.
2011 if (Ty->isInteger())
2014 // Pointers are SCEVable if TargetData information is available
2015 // to provide pointer size information.
2016 if (isa<PointerType>(Ty))
2019 // Otherwise it's not SCEVable.
2023 /// getTypeSizeInBits - Return the size in bits of the specified type,
2024 /// for which isSCEVable must return true.
2025 uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
2026 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2028 // If we have a TargetData, use it!
2030 return TD->getTypeSizeInBits(Ty);
2032 // Otherwise, we support only integer types.
2033 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
2034 return Ty->getPrimitiveSizeInBits();
2037 /// getEffectiveSCEVType - Return a type with the same bitwidth as
2038 /// the given type and which represents how SCEV will treat the given
2039 /// type, for which isSCEVable must return true. For pointer types,
2040 /// this is the pointer-sized integer type.
2041 const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
2042 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2044 if (Ty->isInteger())
2047 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
2048 return TD->getIntPtrType();
2051 const SCEV* ScalarEvolution::getCouldNotCompute() {
2052 return &CouldNotCompute;
2055 /// hasSCEV - Return true if the SCEV for this value has already been
2057 bool ScalarEvolution::hasSCEV(Value *V) const {
2058 return Scalars.count(V);
2061 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2062 /// expression and create a new one.
2063 const SCEV* ScalarEvolution::getSCEV(Value *V) {
2064 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
2066 std::map<SCEVCallbackVH, const SCEV*>::iterator I = Scalars.find(V);
2067 if (I != Scalars.end()) return I->second;
2068 const SCEV* S = createSCEV(V);
2069 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
2073 /// getIntegerSCEV - Given a SCEVable type, create a constant for the
2074 /// specified signed integer value and return a SCEV for the constant.
2075 const SCEV* ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
2076 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
2077 return getConstant(ConstantInt::get(ITy, Val));
2080 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2082 const SCEV* ScalarEvolution::getNegativeSCEV(const SCEV* V) {
2083 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2084 return getConstant(cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
2086 const Type *Ty = V->getType();
2087 Ty = getEffectiveSCEVType(Ty);
2088 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
2091 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
2092 const SCEV* ScalarEvolution::getNotSCEV(const SCEV* V) {
2093 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2094 return getConstant(cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
2096 const Type *Ty = V->getType();
2097 Ty = getEffectiveSCEVType(Ty);
2098 const SCEV* AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
2099 return getMinusSCEV(AllOnes, V);
2102 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2104 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2107 return getAddExpr(LHS, getNegativeSCEV(RHS));
2110 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2111 /// input value to the specified type. If the type must be extended, it is zero
2114 ScalarEvolution::getTruncateOrZeroExtend(const SCEV* V,
2116 const Type *SrcTy = V->getType();
2117 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2118 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2119 "Cannot truncate or zero extend with non-integer arguments!");
2120 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2121 return V; // No conversion
2122 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2123 return getTruncateExpr(V, Ty);
2124 return getZeroExtendExpr(V, Ty);
2127 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2128 /// input value to the specified type. If the type must be extended, it is sign
2131 ScalarEvolution::getTruncateOrSignExtend(const SCEV* V,
2133 const Type *SrcTy = V->getType();
2134 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2135 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2136 "Cannot truncate or zero extend with non-integer arguments!");
2137 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2138 return V; // No conversion
2139 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2140 return getTruncateExpr(V, Ty);
2141 return getSignExtendExpr(V, Ty);
2144 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2145 /// input value to the specified type. If the type must be extended, it is zero
2146 /// extended. The conversion must not be narrowing.
2148 ScalarEvolution::getNoopOrZeroExtend(const SCEV* V, const Type *Ty) {
2149 const Type *SrcTy = V->getType();
2150 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2151 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2152 "Cannot noop or zero extend with non-integer arguments!");
2153 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2154 "getNoopOrZeroExtend cannot truncate!");
2155 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2156 return V; // No conversion
2157 return getZeroExtendExpr(V, Ty);
2160 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2161 /// input value to the specified type. If the type must be extended, it is sign
2162 /// extended. The conversion must not be narrowing.
2164 ScalarEvolution::getNoopOrSignExtend(const SCEV* V, const Type *Ty) {
2165 const Type *SrcTy = V->getType();
2166 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2167 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2168 "Cannot noop or sign extend with non-integer arguments!");
2169 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2170 "getNoopOrSignExtend cannot truncate!");
2171 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2172 return V; // No conversion
2173 return getSignExtendExpr(V, Ty);
2176 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2177 /// the input value to the specified type. If the type must be extended,
2178 /// it is extended with unspecified bits. The conversion must not be
2181 ScalarEvolution::getNoopOrAnyExtend(const SCEV* V, const Type *Ty) {
2182 const Type *SrcTy = V->getType();
2183 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2184 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2185 "Cannot noop or any extend with non-integer arguments!");
2186 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2187 "getNoopOrAnyExtend cannot truncate!");
2188 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2189 return V; // No conversion
2190 return getAnyExtendExpr(V, Ty);
2193 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2194 /// input value to the specified type. The conversion must not be widening.
2196 ScalarEvolution::getTruncateOrNoop(const SCEV* V, const Type *Ty) {
2197 const Type *SrcTy = V->getType();
2198 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2199 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2200 "Cannot truncate or noop with non-integer arguments!");
2201 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2202 "getTruncateOrNoop cannot extend!");
2203 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2204 return V; // No conversion
2205 return getTruncateExpr(V, Ty);
2208 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2209 /// the types using zero-extension, and then perform a umax operation
2211 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2213 const SCEV* PromotedLHS = LHS;
2214 const SCEV* PromotedRHS = RHS;
2216 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2217 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2219 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2221 return getUMaxExpr(PromotedLHS, PromotedRHS);
2224 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
2225 /// the types using zero-extension, and then perform a umin operation
2227 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2229 const SCEV* PromotedLHS = LHS;
2230 const SCEV* PromotedRHS = RHS;
2232 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2233 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2235 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2237 return getUMinExpr(PromotedLHS, PromotedRHS);
2240 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
2241 /// the specified instruction and replaces any references to the symbolic value
2242 /// SymName with the specified value. This is used during PHI resolution.
2244 ScalarEvolution::ReplaceSymbolicValueWithConcrete(Instruction *I,
2245 const SCEV *SymName,
2246 const SCEV *NewVal) {
2247 std::map<SCEVCallbackVH, const SCEV*>::iterator SI =
2248 Scalars.find(SCEVCallbackVH(I, this));
2249 if (SI == Scalars.end()) return;
2252 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
2253 if (NV == SI->second) return; // No change.
2255 SI->second = NV; // Update the scalars map!
2257 // Any instruction values that use this instruction might also need to be
2259 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2261 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
2264 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2265 /// a loop header, making it a potential recurrence, or it doesn't.
2267 const SCEV* ScalarEvolution::createNodeForPHI(PHINode *PN) {
2268 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
2269 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2270 if (L->getHeader() == PN->getParent()) {
2271 // If it lives in the loop header, it has two incoming values, one
2272 // from outside the loop, and one from inside.
2273 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2274 unsigned BackEdge = IncomingEdge^1;
2276 // While we are analyzing this PHI node, handle its value symbolically.
2277 const SCEV* SymbolicName = getUnknown(PN);
2278 assert(Scalars.find(PN) == Scalars.end() &&
2279 "PHI node already processed?");
2280 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
2282 // Using this symbolic name for the PHI, analyze the value coming around
2284 const SCEV* BEValue = getSCEV(PN->getIncomingValue(BackEdge));
2286 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2287 // has a special value for the first iteration of the loop.
2289 // If the value coming around the backedge is an add with the symbolic
2290 // value we just inserted, then we found a simple induction variable!
2291 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
2292 // If there is a single occurrence of the symbolic value, replace it
2293 // with a recurrence.
2294 unsigned FoundIndex = Add->getNumOperands();
2295 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2296 if (Add->getOperand(i) == SymbolicName)
2297 if (FoundIndex == e) {
2302 if (FoundIndex != Add->getNumOperands()) {
2303 // Create an add with everything but the specified operand.
2304 SmallVector<const SCEV*, 8> Ops;
2305 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2306 if (i != FoundIndex)
2307 Ops.push_back(Add->getOperand(i));
2308 const SCEV* Accum = getAddExpr(Ops);
2310 // This is not a valid addrec if the step amount is varying each
2311 // loop iteration, but is not itself an addrec in this loop.
2312 if (Accum->isLoopInvariant(L) ||
2313 (isa<SCEVAddRecExpr>(Accum) &&
2314 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
2315 const SCEV *StartVal =
2316 getSCEV(PN->getIncomingValue(IncomingEdge));
2317 const SCEV *PHISCEV =
2318 getAddRecExpr(StartVal, Accum, L);
2320 // Okay, for the entire analysis of this edge we assumed the PHI
2321 // to be symbolic. We now need to go back and update all of the
2322 // entries for the scalars that use the PHI (except for the PHI
2323 // itself) to use the new analyzed value instead of the "symbolic"
2325 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2329 } else if (const SCEVAddRecExpr *AddRec =
2330 dyn_cast<SCEVAddRecExpr>(BEValue)) {
2331 // Otherwise, this could be a loop like this:
2332 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2333 // In this case, j = {1,+,1} and BEValue is j.
2334 // Because the other in-value of i (0) fits the evolution of BEValue
2335 // i really is an addrec evolution.
2336 if (AddRec->getLoop() == L && AddRec->isAffine()) {
2337 const SCEV* StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
2339 // If StartVal = j.start - j.stride, we can use StartVal as the
2340 // initial step of the addrec evolution.
2341 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
2342 AddRec->getOperand(1))) {
2343 const SCEV* PHISCEV =
2344 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
2346 // Okay, for the entire analysis of this edge we assumed the PHI
2347 // to be symbolic. We now need to go back and update all of the
2348 // entries for the scalars that use the PHI (except for the PHI
2349 // itself) to use the new analyzed value instead of the "symbolic"
2351 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2357 return SymbolicName;
2360 // If it's not a loop phi, we can't handle it yet.
2361 return getUnknown(PN);
2364 /// createNodeForGEP - Expand GEP instructions into add and multiply
2365 /// operations. This allows them to be analyzed by regular SCEV code.
2367 const SCEV* ScalarEvolution::createNodeForGEP(User *GEP) {
2369 const Type *IntPtrTy = TD->getIntPtrType();
2370 Value *Base = GEP->getOperand(0);
2371 // Don't attempt to analyze GEPs over unsized objects.
2372 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2373 return getUnknown(GEP);
2374 const SCEV* TotalOffset = getIntegerSCEV(0, IntPtrTy);
2375 gep_type_iterator GTI = gep_type_begin(GEP);
2376 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2380 // Compute the (potentially symbolic) offset in bytes for this index.
2381 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2382 // For a struct, add the member offset.
2383 const StructLayout &SL = *TD->getStructLayout(STy);
2384 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2385 uint64_t Offset = SL.getElementOffset(FieldNo);
2386 TotalOffset = getAddExpr(TotalOffset,
2387 getIntegerSCEV(Offset, IntPtrTy));
2389 // For an array, add the element offset, explicitly scaled.
2390 const SCEV* LocalOffset = getSCEV(Index);
2391 if (!isa<PointerType>(LocalOffset->getType()))
2392 // Getelementptr indicies are signed.
2393 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2396 getMulExpr(LocalOffset,
2397 getIntegerSCEV(TD->getTypeAllocSize(*GTI),
2399 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2402 return getAddExpr(getSCEV(Base), TotalOffset);
2405 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2406 /// guaranteed to end in (at every loop iteration). It is, at the same time,
2407 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2408 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
2410 ScalarEvolution::GetMinTrailingZeros(const SCEV* S) {
2411 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2412 return C->getValue()->getValue().countTrailingZeros();
2414 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
2415 return std::min(GetMinTrailingZeros(T->getOperand()),
2416 (uint32_t)getTypeSizeInBits(T->getType()));
2418 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
2419 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2420 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2421 getTypeSizeInBits(E->getType()) : OpRes;
2424 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
2425 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2426 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2427 getTypeSizeInBits(E->getType()) : OpRes;
2430 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
2431 // The result is the min of all operands results.
2432 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2433 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2434 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2438 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
2439 // The result is the sum of all operands results.
2440 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2441 uint32_t BitWidth = getTypeSizeInBits(M->getType());
2442 for (unsigned i = 1, e = M->getNumOperands();
2443 SumOpRes != BitWidth && i != e; ++i)
2444 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
2449 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
2450 // The result is the min of all operands results.
2451 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2452 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2453 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2457 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
2458 // The result is the min of all operands results.
2459 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2460 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2461 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2465 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
2466 // The result is the min of all operands results.
2467 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2468 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2469 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2473 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2474 // For a SCEVUnknown, ask ValueTracking.
2475 unsigned BitWidth = getTypeSizeInBits(U->getType());
2476 APInt Mask = APInt::getAllOnesValue(BitWidth);
2477 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2478 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2479 return Zeros.countTrailingOnes();
2487 ScalarEvolution::GetMinLeadingZeros(const SCEV* S) {
2488 // TODO: Handle other SCEV expression types here.
2490 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2491 return C->getValue()->getValue().countLeadingZeros();
2493 if (const SCEVZeroExtendExpr *C = dyn_cast<SCEVZeroExtendExpr>(S)) {
2494 // A zero-extension cast adds zero bits.
2495 return GetMinLeadingZeros(C->getOperand()) +
2496 (getTypeSizeInBits(C->getType()) -
2497 getTypeSizeInBits(C->getOperand()->getType()));
2500 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2501 // For a SCEVUnknown, ask ValueTracking.
2502 unsigned BitWidth = getTypeSizeInBits(U->getType());
2503 APInt Mask = APInt::getAllOnesValue(BitWidth);
2504 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2505 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
2506 return Zeros.countLeadingOnes();
2513 ScalarEvolution::GetMinSignBits(const SCEV* S) {
2514 // TODO: Handle other SCEV expression types here.
2516 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
2517 const APInt &A = C->getValue()->getValue();
2518 return A.isNegative() ? A.countLeadingOnes() :
2519 A.countLeadingZeros();
2522 if (const SCEVSignExtendExpr *C = dyn_cast<SCEVSignExtendExpr>(S)) {
2523 // A sign-extension cast adds sign bits.
2524 return GetMinSignBits(C->getOperand()) +
2525 (getTypeSizeInBits(C->getType()) -
2526 getTypeSizeInBits(C->getOperand()->getType()));
2529 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
2530 unsigned BitWidth = getTypeSizeInBits(A->getType());
2532 // Special case decrementing a value (ADD X, -1):
2533 if (const SCEVConstant *CRHS = dyn_cast<SCEVConstant>(A->getOperand(0)))
2534 if (CRHS->isAllOnesValue()) {
2535 SmallVector<const SCEV *, 4> OtherOps(A->op_begin() + 1, A->op_end());
2536 const SCEV *OtherOpsAdd = getAddExpr(OtherOps);
2537 unsigned LZ = GetMinLeadingZeros(OtherOpsAdd);
2539 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2541 if (LZ == BitWidth - 1)
2544 // If we are subtracting one from a positive number, there is no carry
2545 // out of the result.
2547 return GetMinSignBits(OtherOpsAdd);
2550 // Add can have at most one carry bit. Thus we know that the output
2551 // is, at worst, one more bit than the inputs.
2552 unsigned Min = BitWidth;
2553 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2554 unsigned N = GetMinSignBits(A->getOperand(i));
2555 Min = std::min(Min, N) - 1;
2556 if (Min == 0) return 1;
2561 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2562 // For a SCEVUnknown, ask ValueTracking.
2563 return ComputeNumSignBits(U->getValue(), TD);
2569 /// createSCEV - We know that there is no SCEV for the specified value.
2570 /// Analyze the expression.
2572 const SCEV* ScalarEvolution::createSCEV(Value *V) {
2573 if (!isSCEVable(V->getType()))
2574 return getUnknown(V);
2576 unsigned Opcode = Instruction::UserOp1;
2577 if (Instruction *I = dyn_cast<Instruction>(V))
2578 Opcode = I->getOpcode();
2579 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2580 Opcode = CE->getOpcode();
2581 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2582 return getConstant(CI);
2583 else if (isa<ConstantPointerNull>(V))
2584 return getIntegerSCEV(0, V->getType());
2585 else if (isa<UndefValue>(V))
2586 return getIntegerSCEV(0, V->getType());
2588 return getUnknown(V);
2590 User *U = cast<User>(V);
2592 case Instruction::Add:
2593 return getAddExpr(getSCEV(U->getOperand(0)),
2594 getSCEV(U->getOperand(1)));
2595 case Instruction::Mul:
2596 return getMulExpr(getSCEV(U->getOperand(0)),
2597 getSCEV(U->getOperand(1)));
2598 case Instruction::UDiv:
2599 return getUDivExpr(getSCEV(U->getOperand(0)),
2600 getSCEV(U->getOperand(1)));
2601 case Instruction::Sub:
2602 return getMinusSCEV(getSCEV(U->getOperand(0)),
2603 getSCEV(U->getOperand(1)));
2604 case Instruction::And:
2605 // For an expression like x&255 that merely masks off the high bits,
2606 // use zext(trunc(x)) as the SCEV expression.
2607 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2608 if (CI->isNullValue())
2609 return getSCEV(U->getOperand(1));
2610 if (CI->isAllOnesValue())
2611 return getSCEV(U->getOperand(0));
2612 const APInt &A = CI->getValue();
2614 // Instcombine's ShrinkDemandedConstant may strip bits out of
2615 // constants, obscuring what would otherwise be a low-bits mask.
2616 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2617 // knew about to reconstruct a low-bits mask value.
2618 unsigned LZ = A.countLeadingZeros();
2619 unsigned BitWidth = A.getBitWidth();
2620 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2621 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2622 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2624 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2626 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
2628 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
2629 IntegerType::get(BitWidth - LZ)),
2634 case Instruction::Or:
2635 // If the RHS of the Or is a constant, we may have something like:
2636 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2637 // optimizations will transparently handle this case.
2639 // In order for this transformation to be safe, the LHS must be of the
2640 // form X*(2^n) and the Or constant must be less than 2^n.
2641 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2642 const SCEV* LHS = getSCEV(U->getOperand(0));
2643 const APInt &CIVal = CI->getValue();
2644 if (GetMinTrailingZeros(LHS) >=
2645 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
2646 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
2649 case Instruction::Xor:
2650 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2651 // If the RHS of the xor is a signbit, then this is just an add.
2652 // Instcombine turns add of signbit into xor as a strength reduction step.
2653 if (CI->getValue().isSignBit())
2654 return getAddExpr(getSCEV(U->getOperand(0)),
2655 getSCEV(U->getOperand(1)));
2657 // If the RHS of xor is -1, then this is a not operation.
2658 if (CI->isAllOnesValue())
2659 return getNotSCEV(getSCEV(U->getOperand(0)));
2661 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2662 // This is a variant of the check for xor with -1, and it handles
2663 // the case where instcombine has trimmed non-demanded bits out
2664 // of an xor with -1.
2665 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2666 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2667 if (BO->getOpcode() == Instruction::And &&
2668 LCI->getValue() == CI->getValue())
2669 if (const SCEVZeroExtendExpr *Z =
2670 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
2671 const Type *UTy = U->getType();
2672 const SCEV* Z0 = Z->getOperand();
2673 const Type *Z0Ty = Z0->getType();
2674 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
2676 // If C is a low-bits mask, the zero extend is zerving to
2677 // mask off the high bits. Complement the operand and
2678 // re-apply the zext.
2679 if (APIntOps::isMask(Z0TySize, CI->getValue()))
2680 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
2682 // If C is a single bit, it may be in the sign-bit position
2683 // before the zero-extend. In this case, represent the xor
2684 // using an add, which is equivalent, and re-apply the zext.
2685 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
2686 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
2688 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
2694 case Instruction::Shl:
2695 // Turn shift left of a constant amount into a multiply.
2696 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2697 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2698 Constant *X = ConstantInt::get(
2699 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
2700 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
2704 case Instruction::LShr:
2705 // Turn logical shift right of a constant into a unsigned divide.
2706 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2707 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2708 Constant *X = ConstantInt::get(
2709 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
2710 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
2714 case Instruction::AShr:
2715 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2716 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2717 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2718 if (L->getOpcode() == Instruction::Shl &&
2719 L->getOperand(1) == U->getOperand(1)) {
2720 unsigned BitWidth = getTypeSizeInBits(U->getType());
2721 uint64_t Amt = BitWidth - CI->getZExtValue();
2722 if (Amt == BitWidth)
2723 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2725 return getIntegerSCEV(0, U->getType()); // value is undefined
2727 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
2728 IntegerType::get(Amt)),
2733 case Instruction::Trunc:
2734 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
2736 case Instruction::ZExt:
2737 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
2739 case Instruction::SExt:
2740 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
2742 case Instruction::BitCast:
2743 // BitCasts are no-op casts so we just eliminate the cast.
2744 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
2745 return getSCEV(U->getOperand(0));
2748 case Instruction::IntToPtr:
2749 if (!TD) break; // Without TD we can't analyze pointers.
2750 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2751 TD->getIntPtrType());
2753 case Instruction::PtrToInt:
2754 if (!TD) break; // Without TD we can't analyze pointers.
2755 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2758 case Instruction::GetElementPtr:
2759 if (!TD) break; // Without TD we can't analyze pointers.
2760 return createNodeForGEP(U);
2762 case Instruction::PHI:
2763 return createNodeForPHI(cast<PHINode>(U));
2765 case Instruction::Select:
2766 // This could be a smax or umax that was lowered earlier.
2767 // Try to recover it.
2768 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2769 Value *LHS = ICI->getOperand(0);
2770 Value *RHS = ICI->getOperand(1);
2771 switch (ICI->getPredicate()) {
2772 case ICmpInst::ICMP_SLT:
2773 case ICmpInst::ICMP_SLE:
2774 std::swap(LHS, RHS);
2776 case ICmpInst::ICMP_SGT:
2777 case ICmpInst::ICMP_SGE:
2778 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2779 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
2780 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2781 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
2783 case ICmpInst::ICMP_ULT:
2784 case ICmpInst::ICMP_ULE:
2785 std::swap(LHS, RHS);
2787 case ICmpInst::ICMP_UGT:
2788 case ICmpInst::ICMP_UGE:
2789 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2790 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
2791 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2792 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
2794 case ICmpInst::ICMP_NE:
2795 // n != 0 ? n : 1 -> umax(n, 1)
2796 if (LHS == U->getOperand(1) &&
2797 isa<ConstantInt>(U->getOperand(2)) &&
2798 cast<ConstantInt>(U->getOperand(2))->isOne() &&
2799 isa<ConstantInt>(RHS) &&
2800 cast<ConstantInt>(RHS)->isZero())
2801 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
2803 case ICmpInst::ICMP_EQ:
2804 // n == 0 ? 1 : n -> umax(n, 1)
2805 if (LHS == U->getOperand(2) &&
2806 isa<ConstantInt>(U->getOperand(1)) &&
2807 cast<ConstantInt>(U->getOperand(1))->isOne() &&
2808 isa<ConstantInt>(RHS) &&
2809 cast<ConstantInt>(RHS)->isZero())
2810 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
2817 default: // We cannot analyze this expression.
2821 return getUnknown(V);
2826 //===----------------------------------------------------------------------===//
2827 // Iteration Count Computation Code
2830 /// getBackedgeTakenCount - If the specified loop has a predictable
2831 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2832 /// object. The backedge-taken count is the number of times the loop header
2833 /// will be branched to from within the loop. This is one less than the
2834 /// trip count of the loop, since it doesn't count the first iteration,
2835 /// when the header is branched to from outside the loop.
2837 /// Note that it is not valid to call this method on a loop without a
2838 /// loop-invariant backedge-taken count (see
2839 /// hasLoopInvariantBackedgeTakenCount).
2841 const SCEV* ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
2842 return getBackedgeTakenInfo(L).Exact;
2845 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2846 /// return the least SCEV value that is known never to be less than the
2847 /// actual backedge taken count.
2848 const SCEV* ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
2849 return getBackedgeTakenInfo(L).Max;
2852 const ScalarEvolution::BackedgeTakenInfo &
2853 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
2854 // Initially insert a CouldNotCompute for this loop. If the insertion
2855 // succeeds, procede to actually compute a backedge-taken count and
2856 // update the value. The temporary CouldNotCompute value tells SCEV
2857 // code elsewhere that it shouldn't attempt to request a new
2858 // backedge-taken count, which could result in infinite recursion.
2859 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
2860 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2862 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
2863 if (ItCount.Exact != getCouldNotCompute()) {
2864 assert(ItCount.Exact->isLoopInvariant(L) &&
2865 ItCount.Max->isLoopInvariant(L) &&
2866 "Computed trip count isn't loop invariant for loop!");
2867 ++NumTripCountsComputed;
2869 // Update the value in the map.
2870 Pair.first->second = ItCount;
2872 if (ItCount.Max != getCouldNotCompute())
2873 // Update the value in the map.
2874 Pair.first->second = ItCount;
2875 if (isa<PHINode>(L->getHeader()->begin()))
2876 // Only count loops that have phi nodes as not being computable.
2877 ++NumTripCountsNotComputed;
2880 // Now that we know more about the trip count for this loop, forget any
2881 // existing SCEV values for PHI nodes in this loop since they are only
2882 // conservative estimates made without the benefit
2883 // of trip count information.
2884 if (ItCount.hasAnyInfo())
2887 return Pair.first->second;
2890 /// forgetLoopBackedgeTakenCount - This method should be called by the
2891 /// client when it has changed a loop in a way that may effect
2892 /// ScalarEvolution's ability to compute a trip count, or if the loop
2894 void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
2895 BackedgeTakenCounts.erase(L);
2899 /// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2900 /// PHI nodes in the given loop. This is used when the trip count of
2901 /// the loop may have changed.
2902 void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
2903 BasicBlock *Header = L->getHeader();
2905 // Push all Loop-header PHIs onto the Worklist stack, except those
2906 // that are presently represented via a SCEVUnknown. SCEVUnknown for
2907 // a PHI either means that it has an unrecognized structure, or it's
2908 // a PHI that's in the progress of being computed by createNodeForPHI.
2909 // In the former case, additional loop trip count information isn't
2910 // going to change anything. In the later case, createNodeForPHI will
2911 // perform the necessary updates on its own when it gets to that point.
2912 SmallVector<Instruction *, 16> Worklist;
2913 for (BasicBlock::iterator I = Header->begin();
2914 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
2915 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
2916 Scalars.find((Value*)I);
2917 if (It != Scalars.end() && !isa<SCEVUnknown>(It->second))
2918 Worklist.push_back(PN);
2921 while (!Worklist.empty()) {
2922 Instruction *I = Worklist.pop_back_val();
2923 if (Scalars.erase(I))
2924 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2926 Worklist.push_back(cast<Instruction>(UI));
2930 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
2931 /// of the specified loop will execute.
2932 ScalarEvolution::BackedgeTakenInfo
2933 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
2934 SmallVector<BasicBlock*, 8> ExitingBlocks;
2935 L->getExitingBlocks(ExitingBlocks);
2937 // Examine all exits and pick the most conservative values.
2938 const SCEV* BECount = getCouldNotCompute();
2939 const SCEV* MaxBECount = getCouldNotCompute();
2940 bool CouldNotComputeBECount = false;
2941 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
2942 BackedgeTakenInfo NewBTI =
2943 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
2945 if (NewBTI.Exact == getCouldNotCompute()) {
2946 // We couldn't compute an exact value for this exit, so
2947 // we won't be able to compute an exact value for the loop.
2948 CouldNotComputeBECount = true;
2949 BECount = getCouldNotCompute();
2950 } else if (!CouldNotComputeBECount) {
2951 if (BECount == getCouldNotCompute())
2952 BECount = NewBTI.Exact;
2954 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
2956 if (MaxBECount == getCouldNotCompute())
2957 MaxBECount = NewBTI.Max;
2958 else if (NewBTI.Max != getCouldNotCompute())
2959 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
2962 return BackedgeTakenInfo(BECount, MaxBECount);
2965 /// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
2966 /// of the specified loop will execute if it exits via the specified block.
2967 ScalarEvolution::BackedgeTakenInfo
2968 ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
2969 BasicBlock *ExitingBlock) {
2971 // Okay, we've chosen an exiting block. See what condition causes us to
2972 // exit at this block.
2974 // FIXME: we should be able to handle switch instructions (with a single exit)
2975 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2976 if (ExitBr == 0) return getCouldNotCompute();
2977 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2979 // At this point, we know we have a conditional branch that determines whether
2980 // the loop is exited. However, we don't know if the branch is executed each
2981 // time through the loop. If not, then the execution count of the branch will
2982 // not be equal to the trip count of the loop.
2984 // Currently we check for this by checking to see if the Exit branch goes to
2985 // the loop header. If so, we know it will always execute the same number of
2986 // times as the loop. We also handle the case where the exit block *is* the
2987 // loop header. This is common for un-rotated loops.
2989 // If both of those tests fail, walk up the unique predecessor chain to the
2990 // header, stopping if there is an edge that doesn't exit the loop. If the
2991 // header is reached, the execution count of the branch will be equal to the
2992 // trip count of the loop.
2994 // More extensive analysis could be done to handle more cases here.
2996 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2997 ExitBr->getSuccessor(1) != L->getHeader() &&
2998 ExitBr->getParent() != L->getHeader()) {
2999 // The simple checks failed, try climbing the unique predecessor chain
3000 // up to the header.
3002 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3003 BasicBlock *Pred = BB->getUniquePredecessor();
3005 return getCouldNotCompute();
3006 TerminatorInst *PredTerm = Pred->getTerminator();
3007 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3008 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3011 // If the predecessor has a successor that isn't BB and isn't
3012 // outside the loop, assume the worst.
3013 if (L->contains(PredSucc))
3014 return getCouldNotCompute();
3016 if (Pred == L->getHeader()) {
3023 return getCouldNotCompute();
3026 // Procede to the next level to examine the exit condition expression.
3027 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3028 ExitBr->getSuccessor(0),
3029 ExitBr->getSuccessor(1));
3032 /// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3033 /// backedge of the specified loop will execute if its exit condition
3034 /// were a conditional branch of ExitCond, TBB, and FBB.
3035 ScalarEvolution::BackedgeTakenInfo
3036 ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3040 // Check if the controlling expression for this loop is an And or Or.
3041 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3042 if (BO->getOpcode() == Instruction::And) {
3043 // Recurse on the operands of the and.
3044 BackedgeTakenInfo BTI0 =
3045 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3046 BackedgeTakenInfo BTI1 =
3047 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3048 const SCEV* BECount = getCouldNotCompute();
3049 const SCEV* MaxBECount = getCouldNotCompute();
3050 if (L->contains(TBB)) {
3051 // Both conditions must be true for the loop to continue executing.
3052 // Choose the less conservative count.
3053 if (BTI0.Exact == getCouldNotCompute() ||
3054 BTI1.Exact == getCouldNotCompute())
3055 BECount = getCouldNotCompute();
3057 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3058 if (BTI0.Max == getCouldNotCompute())
3059 MaxBECount = BTI1.Max;
3060 else if (BTI1.Max == getCouldNotCompute())
3061 MaxBECount = BTI0.Max;
3063 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3065 // Both conditions must be true for the loop to exit.
3066 assert(L->contains(FBB) && "Loop block has no successor in loop!");
3067 if (BTI0.Exact != getCouldNotCompute() &&
3068 BTI1.Exact != getCouldNotCompute())
3069 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3070 if (BTI0.Max != getCouldNotCompute() &&
3071 BTI1.Max != getCouldNotCompute())
3072 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3075 return BackedgeTakenInfo(BECount, MaxBECount);
3077 if (BO->getOpcode() == Instruction::Or) {
3078 // Recurse on the operands of the or.
3079 BackedgeTakenInfo BTI0 =
3080 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3081 BackedgeTakenInfo BTI1 =
3082 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3083 const SCEV* BECount = getCouldNotCompute();
3084 const SCEV* MaxBECount = getCouldNotCompute();
3085 if (L->contains(FBB)) {
3086 // Both conditions must be false for the loop to continue executing.
3087 // Choose the less conservative count.
3088 if (BTI0.Exact == getCouldNotCompute() ||
3089 BTI1.Exact == getCouldNotCompute())
3090 BECount = getCouldNotCompute();
3092 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3093 if (BTI0.Max == getCouldNotCompute())
3094 MaxBECount = BTI1.Max;
3095 else if (BTI1.Max == getCouldNotCompute())
3096 MaxBECount = BTI0.Max;
3098 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3100 // Both conditions must be false for the loop to exit.
3101 assert(L->contains(TBB) && "Loop block has no successor in loop!");
3102 if (BTI0.Exact != getCouldNotCompute() &&
3103 BTI1.Exact != getCouldNotCompute())
3104 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3105 if (BTI0.Max != getCouldNotCompute() &&
3106 BTI1.Max != getCouldNotCompute())
3107 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3110 return BackedgeTakenInfo(BECount, MaxBECount);
3114 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3115 // Procede to the next level to examine the icmp.
3116 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3117 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
3119 // If it's not an integer or pointer comparison then compute it the hard way.
3120 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3123 /// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3124 /// backedge of the specified loop will execute if its exit condition
3125 /// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3126 ScalarEvolution::BackedgeTakenInfo
3127 ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3132 // If the condition was exit on true, convert the condition to exit on false
3133 ICmpInst::Predicate Cond;
3134 if (!L->contains(FBB))
3135 Cond = ExitCond->getPredicate();
3137 Cond = ExitCond->getInversePredicate();
3139 // Handle common loops like: for (X = "string"; *X; ++X)
3140 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3141 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
3143 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
3144 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
3145 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
3146 return BackedgeTakenInfo(ItCnt,
3147 isa<SCEVConstant>(ItCnt) ? ItCnt :
3148 getConstant(APInt::getMaxValue(BitWidth)-1));
3152 const SCEV* LHS = getSCEV(ExitCond->getOperand(0));
3153 const SCEV* RHS = getSCEV(ExitCond->getOperand(1));
3155 // Try to evaluate any dependencies out of the loop.
3156 LHS = getSCEVAtScope(LHS, L);
3157 RHS = getSCEVAtScope(RHS, L);
3159 // At this point, we would like to compute how many iterations of the
3160 // loop the predicate will return true for these inputs.
3161 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3162 // If there is a loop-invariant, force it into the RHS.
3163 std::swap(LHS, RHS);
3164 Cond = ICmpInst::getSwappedPredicate(Cond);
3167 // If we have a comparison of a chrec against a constant, try to use value
3168 // ranges to answer this query.
3169 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3170 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
3171 if (AddRec->getLoop() == L) {
3172 // Form the constant range.
3173 ConstantRange CompRange(
3174 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
3176 const SCEV* Ret = AddRec->getNumIterationsInRange(CompRange, *this);
3177 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
3181 case ICmpInst::ICMP_NE: { // while (X != Y)
3182 // Convert to: while (X-Y != 0)
3183 const SCEV* TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
3184 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3187 case ICmpInst::ICMP_EQ: {
3188 // Convert to: while (X-Y == 0) // while (X == Y)
3189 const SCEV* TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
3190 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3193 case ICmpInst::ICMP_SLT: {
3194 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3195 if (BTI.hasAnyInfo()) return BTI;
3198 case ICmpInst::ICMP_SGT: {
3199 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3200 getNotSCEV(RHS), L, true);
3201 if (BTI.hasAnyInfo()) return BTI;
3204 case ICmpInst::ICMP_ULT: {
3205 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3206 if (BTI.hasAnyInfo()) return BTI;
3209 case ICmpInst::ICMP_UGT: {
3210 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3211 getNotSCEV(RHS), L, false);
3212 if (BTI.hasAnyInfo()) return BTI;
3217 errs() << "ComputeBackedgeTakenCount ";
3218 if (ExitCond->getOperand(0)->getType()->isUnsigned())
3219 errs() << "[unsigned] ";
3220 errs() << *LHS << " "
3221 << Instruction::getOpcodeName(Instruction::ICmp)
3222 << " " << *RHS << "\n";
3227 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3230 static ConstantInt *
3231 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3232 ScalarEvolution &SE) {
3233 const SCEV* InVal = SE.getConstant(C);
3234 const SCEV* Val = AddRec->evaluateAtIteration(InVal, SE);
3235 assert(isa<SCEVConstant>(Val) &&
3236 "Evaluation of SCEV at constant didn't fold correctly?");
3237 return cast<SCEVConstant>(Val)->getValue();
3240 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
3241 /// and a GEP expression (missing the pointer index) indexing into it, return
3242 /// the addressed element of the initializer or null if the index expression is
3245 GetAddressedElementFromGlobal(GlobalVariable *GV,
3246 const std::vector<ConstantInt*> &Indices) {
3247 Constant *Init = GV->getInitializer();
3248 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
3249 uint64_t Idx = Indices[i]->getZExtValue();
3250 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3251 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3252 Init = cast<Constant>(CS->getOperand(Idx));
3253 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3254 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3255 Init = cast<Constant>(CA->getOperand(Idx));
3256 } else if (isa<ConstantAggregateZero>(Init)) {
3257 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3258 assert(Idx < STy->getNumElements() && "Bad struct index!");
3259 Init = Constant::getNullValue(STy->getElementType(Idx));
3260 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3261 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
3262 Init = Constant::getNullValue(ATy->getElementType());
3264 assert(0 && "Unknown constant aggregate type!");
3268 return 0; // Unknown initializer type
3274 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3275 /// 'icmp op load X, cst', try to see if we can compute the backedge
3276 /// execution count.
3278 ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3282 ICmpInst::Predicate predicate) {
3283 if (LI->isVolatile()) return getCouldNotCompute();
3285 // Check to see if the loaded pointer is a getelementptr of a global.
3286 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
3287 if (!GEP) return getCouldNotCompute();
3289 // Make sure that it is really a constant global we are gepping, with an
3290 // initializer, and make sure the first IDX is really 0.
3291 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
3292 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
3293 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3294 !cast<Constant>(GEP->getOperand(1))->isNullValue())
3295 return getCouldNotCompute();
3297 // Okay, we allow one non-constant index into the GEP instruction.
3299 std::vector<ConstantInt*> Indexes;
3300 unsigned VarIdxNum = 0;
3301 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3302 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3303 Indexes.push_back(CI);
3304 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
3305 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
3306 VarIdx = GEP->getOperand(i);
3308 Indexes.push_back(0);
3311 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3312 // Check to see if X is a loop variant variable value now.
3313 const SCEV* Idx = getSCEV(VarIdx);
3314 Idx = getSCEVAtScope(Idx, L);
3316 // We can only recognize very limited forms of loop index expressions, in
3317 // particular, only affine AddRec's like {C1,+,C2}.
3318 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
3319 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3320 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3321 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
3322 return getCouldNotCompute();
3324 unsigned MaxSteps = MaxBruteForceIterations;
3325 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
3326 ConstantInt *ItCst =
3327 ConstantInt::get(cast<IntegerType>(IdxExpr->getType()), IterationNum);
3328 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
3330 // Form the GEP offset.
3331 Indexes[VarIdxNum] = Val;
3333 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
3334 if (Result == 0) break; // Cannot compute!
3336 // Evaluate the condition for this iteration.
3337 Result = ConstantExpr::getICmp(predicate, Result, RHS);
3338 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
3339 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
3341 errs() << "\n***\n*** Computed loop count " << *ItCst
3342 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3345 ++NumArrayLenItCounts;
3346 return getConstant(ItCst); // Found terminating iteration!
3349 return getCouldNotCompute();
3353 /// CanConstantFold - Return true if we can constant fold an instruction of the
3354 /// specified type, assuming that all operands were constants.
3355 static bool CanConstantFold(const Instruction *I) {
3356 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
3357 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3360 if (const CallInst *CI = dyn_cast<CallInst>(I))
3361 if (const Function *F = CI->getCalledFunction())
3362 return canConstantFoldCallTo(F);
3366 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3367 /// in the loop that V is derived from. We allow arbitrary operations along the
3368 /// way, but the operands of an operation must either be constants or a value
3369 /// derived from a constant PHI. If this expression does not fit with these
3370 /// constraints, return null.
3371 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3372 // If this is not an instruction, or if this is an instruction outside of the
3373 // loop, it can't be derived from a loop PHI.
3374 Instruction *I = dyn_cast<Instruction>(V);
3375 if (I == 0 || !L->contains(I->getParent())) return 0;
3377 if (PHINode *PN = dyn_cast<PHINode>(I)) {
3378 if (L->getHeader() == I->getParent())
3381 // We don't currently keep track of the control flow needed to evaluate
3382 // PHIs, so we cannot handle PHIs inside of loops.
3386 // If we won't be able to constant fold this expression even if the operands
3387 // are constants, return early.
3388 if (!CanConstantFold(I)) return 0;
3390 // Otherwise, we can evaluate this instruction if all of its operands are
3391 // constant or derived from a PHI node themselves.
3393 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3394 if (!(isa<Constant>(I->getOperand(Op)) ||
3395 isa<GlobalValue>(I->getOperand(Op)))) {
3396 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3397 if (P == 0) return 0; // Not evolving from PHI
3401 return 0; // Evolving from multiple different PHIs.
3404 // This is a expression evolving from a constant PHI!
3408 /// EvaluateExpression - Given an expression that passes the
3409 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3410 /// in the loop has the value PHIVal. If we can't fold this expression for some
3411 /// reason, return null.
3412 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3413 if (isa<PHINode>(V)) return PHIVal;
3414 if (Constant *C = dyn_cast<Constant>(V)) return C;
3415 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
3416 Instruction *I = cast<Instruction>(V);
3418 std::vector<Constant*> Operands;
3419 Operands.resize(I->getNumOperands());
3421 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3422 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3423 if (Operands[i] == 0) return 0;
3426 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3427 return ConstantFoldCompareInstOperands(CI->getPredicate(),
3428 &Operands[0], Operands.size());
3430 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3431 &Operands[0], Operands.size());
3434 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3435 /// in the header of its containing loop, we know the loop executes a
3436 /// constant number of times, and the PHI node is just a recurrence
3437 /// involving constants, fold it.
3439 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
3442 std::map<PHINode*, Constant*>::iterator I =
3443 ConstantEvolutionLoopExitValue.find(PN);
3444 if (I != ConstantEvolutionLoopExitValue.end())
3447 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
3448 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3450 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3452 // Since the loop is canonicalized, the PHI node must have two entries. One
3453 // entry must be a constant (coming in from outside of the loop), and the
3454 // second must be derived from the same PHI.
3455 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3456 Constant *StartCST =
3457 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3459 return RetVal = 0; // Must be a constant.
3461 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3462 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3464 return RetVal = 0; // Not derived from same PHI.
3466 // Execute the loop symbolically to determine the exit value.
3467 if (BEs.getActiveBits() >= 32)
3468 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
3470 unsigned NumIterations = BEs.getZExtValue(); // must be in range
3471 unsigned IterationNum = 0;
3472 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3473 if (IterationNum == NumIterations)
3474 return RetVal = PHIVal; // Got exit value!
3476 // Compute the value of the PHI node for the next iteration.
3477 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3478 if (NextPHI == PHIVal)
3479 return RetVal = NextPHI; // Stopped evolving!
3481 return 0; // Couldn't evaluate!
3486 /// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
3487 /// constant number of times (the condition evolves only from constants),
3488 /// try to evaluate a few iterations of the loop until we get the exit
3489 /// condition gets a value of ExitWhen (true or false). If we cannot
3490 /// evaluate the trip count of the loop, return getCouldNotCompute().
3492 ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
3495 PHINode *PN = getConstantEvolvingPHI(Cond, L);
3496 if (PN == 0) return getCouldNotCompute();
3498 // Since the loop is canonicalized, the PHI node must have two entries. One
3499 // entry must be a constant (coming in from outside of the loop), and the
3500 // second must be derived from the same PHI.
3501 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3502 Constant *StartCST =
3503 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3504 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
3506 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3507 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3508 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
3510 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3511 // the loop symbolically to determine when the condition gets a value of
3513 unsigned IterationNum = 0;
3514 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3515 for (Constant *PHIVal = StartCST;
3516 IterationNum != MaxIterations; ++IterationNum) {
3517 ConstantInt *CondVal =
3518 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
3520 // Couldn't symbolically evaluate.
3521 if (!CondVal) return getCouldNotCompute();
3523 if (CondVal->getValue() == uint64_t(ExitWhen)) {
3524 ++NumBruteForceTripCountsComputed;
3525 return getConstant(Type::Int32Ty, IterationNum);
3528 // Compute the value of the PHI node for the next iteration.
3529 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3530 if (NextPHI == 0 || NextPHI == PHIVal)
3531 return getCouldNotCompute();// Couldn't evaluate or not making progress...
3535 // Too many iterations were needed to evaluate.
3536 return getCouldNotCompute();
3539 /// getSCEVAtScope - Return a SCEV expression handle for the specified value
3540 /// at the specified scope in the program. The L value specifies a loop
3541 /// nest to evaluate the expression at, where null is the top-level or a
3542 /// specified loop is immediately inside of the loop.
3544 /// This method can be used to compute the exit value for a variable defined
3545 /// in a loop by querying what the value will hold in the parent loop.
3547 /// In the case that a relevant loop exit value cannot be computed, the
3548 /// original value V is returned.
3549 const SCEV* ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
3550 // FIXME: this should be turned into a virtual method on SCEV!
3552 if (isa<SCEVConstant>(V)) return V;
3554 // If this instruction is evolved from a constant-evolving PHI, compute the
3555 // exit value from the loop without using SCEVs.
3556 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
3557 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
3558 const Loop *LI = (*this->LI)[I->getParent()];
3559 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3560 if (PHINode *PN = dyn_cast<PHINode>(I))
3561 if (PN->getParent() == LI->getHeader()) {
3562 // Okay, there is no closed form solution for the PHI node. Check
3563 // to see if the loop that contains it has a known backedge-taken
3564 // count. If so, we may be able to force computation of the exit
3566 const SCEV* BackedgeTakenCount = getBackedgeTakenCount(LI);
3567 if (const SCEVConstant *BTCC =
3568 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
3569 // Okay, we know how many times the containing loop executes. If
3570 // this is a constant evolving PHI node, get the final value at
3571 // the specified iteration number.
3572 Constant *RV = getConstantEvolutionLoopExitValue(PN,
3573 BTCC->getValue()->getValue(),
3575 if (RV) return getSCEV(RV);
3579 // Okay, this is an expression that we cannot symbolically evaluate
3580 // into a SCEV. Check to see if it's possible to symbolically evaluate
3581 // the arguments into constants, and if so, try to constant propagate the
3582 // result. This is particularly useful for computing loop exit values.
3583 if (CanConstantFold(I)) {
3584 // Check to see if we've folded this instruction at this loop before.
3585 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3586 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3587 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3589 return Pair.first->second ? &*getSCEV(Pair.first->second) : V;
3591 std::vector<Constant*> Operands;
3592 Operands.reserve(I->getNumOperands());
3593 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3594 Value *Op = I->getOperand(i);
3595 if (Constant *C = dyn_cast<Constant>(Op)) {
3596 Operands.push_back(C);
3598 // If any of the operands is non-constant and if they are
3599 // non-integer and non-pointer, don't even try to analyze them
3600 // with scev techniques.
3601 if (!isSCEVable(Op->getType()))
3604 const SCEV* OpV = getSCEVAtScope(getSCEV(Op), L);
3605 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
3606 Constant *C = SC->getValue();
3607 if (C->getType() != Op->getType())
3608 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3612 Operands.push_back(C);
3613 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
3614 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3615 if (C->getType() != Op->getType())
3617 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3621 Operands.push_back(C);
3631 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3632 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
3633 &Operands[0], Operands.size());
3635 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3636 &Operands[0], Operands.size());
3637 Pair.first->second = C;
3642 // This is some other type of SCEVUnknown, just return it.
3646 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
3647 // Avoid performing the look-up in the common case where the specified
3648 // expression has no loop-variant portions.
3649 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
3650 const SCEV* OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
3651 if (OpAtScope != Comm->getOperand(i)) {
3652 // Okay, at least one of these operands is loop variant but might be
3653 // foldable. Build a new instance of the folded commutative expression.
3654 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
3655 Comm->op_begin()+i);
3656 NewOps.push_back(OpAtScope);
3658 for (++i; i != e; ++i) {
3659 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
3660 NewOps.push_back(OpAtScope);
3662 if (isa<SCEVAddExpr>(Comm))
3663 return getAddExpr(NewOps);
3664 if (isa<SCEVMulExpr>(Comm))
3665 return getMulExpr(NewOps);
3666 if (isa<SCEVSMaxExpr>(Comm))
3667 return getSMaxExpr(NewOps);
3668 if (isa<SCEVUMaxExpr>(Comm))
3669 return getUMaxExpr(NewOps);
3670 assert(0 && "Unknown commutative SCEV type!");
3673 // If we got here, all operands are loop invariant.
3677 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
3678 const SCEV* LHS = getSCEVAtScope(Div->getLHS(), L);
3679 const SCEV* RHS = getSCEVAtScope(Div->getRHS(), L);
3680 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3681 return Div; // must be loop invariant
3682 return getUDivExpr(LHS, RHS);
3685 // If this is a loop recurrence for a loop that does not contain L, then we
3686 // are dealing with the final value computed by the loop.
3687 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
3688 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3689 // To evaluate this recurrence, we need to know how many times the AddRec
3690 // loop iterates. Compute this now.
3691 const SCEV* BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
3692 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
3694 // Then, evaluate the AddRec.
3695 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
3700 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
3701 const SCEV* Op = getSCEVAtScope(Cast->getOperand(), L);
3702 if (Op == Cast->getOperand())
3703 return Cast; // must be loop invariant
3704 return getZeroExtendExpr(Op, Cast->getType());
3707 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
3708 const SCEV* Op = getSCEVAtScope(Cast->getOperand(), L);
3709 if (Op == Cast->getOperand())
3710 return Cast; // must be loop invariant
3711 return getSignExtendExpr(Op, Cast->getType());
3714 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
3715 const SCEV* Op = getSCEVAtScope(Cast->getOperand(), L);
3716 if (Op == Cast->getOperand())
3717 return Cast; // must be loop invariant
3718 return getTruncateExpr(Op, Cast->getType());
3721 assert(0 && "Unknown SCEV type!");
3725 /// getSCEVAtScope - This is a convenience function which does
3726 /// getSCEVAtScope(getSCEV(V), L).
3727 const SCEV* ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
3728 return getSCEVAtScope(getSCEV(V), L);
3731 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3732 /// following equation:
3734 /// A * X = B (mod N)
3736 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3737 /// A and B isn't important.
3739 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
3740 static const SCEV* SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
3741 ScalarEvolution &SE) {
3742 uint32_t BW = A.getBitWidth();
3743 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3744 assert(A != 0 && "A must be non-zero.");
3748 // The gcd of A and N may have only one prime factor: 2. The number of
3749 // trailing zeros in A is its multiplicity
3750 uint32_t Mult2 = A.countTrailingZeros();
3753 // 2. Check if B is divisible by D.
3755 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3756 // is not less than multiplicity of this prime factor for D.
3757 if (B.countTrailingZeros() < Mult2)
3758 return SE.getCouldNotCompute();
3760 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3763 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3764 // bit width during computations.
3765 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3766 APInt Mod(BW + 1, 0);
3767 Mod.set(BW - Mult2); // Mod = N / D
3768 APInt I = AD.multiplicativeInverse(Mod);
3770 // 4. Compute the minimum unsigned root of the equation:
3771 // I * (B / D) mod (N / D)
3772 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
3774 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
3776 return SE.getConstant(Result.trunc(BW));
3779 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
3780 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
3781 /// might be the same) or two SCEVCouldNotCompute objects.
3783 static std::pair<const SCEV*,const SCEV*>
3784 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
3785 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
3786 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
3787 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
3788 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
3790 // We currently can only solve this if the coefficients are constants.
3791 if (!LC || !MC || !NC) {
3792 const SCEV *CNC = SE.getCouldNotCompute();
3793 return std::make_pair(CNC, CNC);
3796 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
3797 const APInt &L = LC->getValue()->getValue();
3798 const APInt &M = MC->getValue()->getValue();
3799 const APInt &N = NC->getValue()->getValue();
3800 APInt Two(BitWidth, 2);
3801 APInt Four(BitWidth, 4);
3804 using namespace APIntOps;
3806 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
3807 // The B coefficient is M-N/2
3811 // The A coefficient is N/2
3812 APInt A(N.sdiv(Two));
3814 // Compute the B^2-4ac term.
3817 SqrtTerm -= Four * (A * C);
3819 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
3820 // integer value or else APInt::sqrt() will assert.
3821 APInt SqrtVal(SqrtTerm.sqrt());
3823 // Compute the two solutions for the quadratic formula.
3824 // The divisions must be performed as signed divisions.
3826 APInt TwoA( A << 1 );
3827 if (TwoA.isMinValue()) {
3828 const SCEV *CNC = SE.getCouldNotCompute();
3829 return std::make_pair(CNC, CNC);
3832 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
3833 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
3835 return std::make_pair(SE.getConstant(Solution1),
3836 SE.getConstant(Solution2));
3837 } // end APIntOps namespace
3840 /// HowFarToZero - Return the number of times a backedge comparing the specified
3841 /// value to zero will execute. If not computable, return CouldNotCompute.
3842 const SCEV* ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
3843 // If the value is a constant
3844 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
3845 // If the value is already zero, the branch will execute zero times.
3846 if (C->getValue()->isZero()) return C;
3847 return getCouldNotCompute(); // Otherwise it will loop infinitely.
3850 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
3851 if (!AddRec || AddRec->getLoop() != L)
3852 return getCouldNotCompute();
3854 if (AddRec->isAffine()) {
3855 // If this is an affine expression, the execution count of this branch is
3856 // the minimum unsigned root of the following equation:
3858 // Start + Step*N = 0 (mod 2^BW)
3862 // Step*N = -Start (mod 2^BW)
3864 // where BW is the common bit width of Start and Step.
3866 // Get the initial value for the loop.
3867 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
3868 L->getParentLoop());
3869 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
3870 L->getParentLoop());
3872 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
3873 // For now we handle only constant steps.
3875 // First, handle unitary steps.
3876 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
3877 return getNegativeSCEV(Start); // N = -Start (as unsigned)
3878 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
3879 return Start; // N = Start (as unsigned)
3881 // Then, try to solve the above equation provided that Start is constant.
3882 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
3883 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
3884 -StartC->getValue()->getValue(),
3887 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
3888 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
3889 // the quadratic equation to solve it.
3890 std::pair<const SCEV*,const SCEV*> Roots = SolveQuadraticEquation(AddRec,
3892 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3893 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3896 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3897 << " sol#2: " << *R2 << "\n";
3899 // Pick the smallest positive root value.
3900 if (ConstantInt *CB =
3901 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3902 R1->getValue(), R2->getValue()))) {
3903 if (CB->getZExtValue() == false)
3904 std::swap(R1, R2); // R1 is the minimum root now.
3906 // We can only use this value if the chrec ends up with an exact zero
3907 // value at this index. When solving for "X*X != 5", for example, we
3908 // should not accept a root of 2.
3909 const SCEV* Val = AddRec->evaluateAtIteration(R1, *this);
3911 return R1; // We found a quadratic root!
3916 return getCouldNotCompute();
3919 /// HowFarToNonZero - Return the number of times a backedge checking the
3920 /// specified value for nonzero will execute. If not computable, return
3922 const SCEV* ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
3923 // Loops that look like: while (X == 0) are very strange indeed. We don't
3924 // handle them yet except for the trivial case. This could be expanded in the
3925 // future as needed.
3927 // If the value is a constant, check to see if it is known to be non-zero
3928 // already. If so, the backedge will execute zero times.
3929 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
3930 if (!C->getValue()->isNullValue())
3931 return getIntegerSCEV(0, C->getType());
3932 return getCouldNotCompute(); // Otherwise it will loop infinitely.
3935 // We could implement others, but I really doubt anyone writes loops like
3936 // this, and if they did, they would already be constant folded.
3937 return getCouldNotCompute();
3940 /// getLoopPredecessor - If the given loop's header has exactly one unique
3941 /// predecessor outside the loop, return it. Otherwise return null.
3943 BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
3944 BasicBlock *Header = L->getHeader();
3945 BasicBlock *Pred = 0;
3946 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
3948 if (!L->contains(*PI)) {
3949 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
3955 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
3956 /// (which may not be an immediate predecessor) which has exactly one
3957 /// successor from which BB is reachable, or null if no such block is
3961 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
3962 // If the block has a unique predecessor, then there is no path from the
3963 // predecessor to the block that does not go through the direct edge
3964 // from the predecessor to the block.
3965 if (BasicBlock *Pred = BB->getSinglePredecessor())
3968 // A loop's header is defined to be a block that dominates the loop.
3969 // If the header has a unique predecessor outside the loop, it must be
3970 // a block that has exactly one successor that can reach the loop.
3971 if (Loop *L = LI->getLoopFor(BB))
3972 return getLoopPredecessor(L);
3977 /// HasSameValue - SCEV structural equivalence is usually sufficient for
3978 /// testing whether two expressions are equal, however for the purposes of
3979 /// looking for a condition guarding a loop, it can be useful to be a little
3980 /// more general, since a front-end may have replicated the controlling
3983 static bool HasSameValue(const SCEV* A, const SCEV* B) {
3984 // Quick check to see if they are the same SCEV.
3985 if (A == B) return true;
3987 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
3988 // two different instructions with the same value. Check for this case.
3989 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
3990 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
3991 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
3992 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
3993 if (AI->isIdenticalTo(BI))
3996 // Otherwise assume they may have a different value.
4000 /// isLoopGuardedByCond - Test whether entry to the loop is protected by
4001 /// a conditional between LHS and RHS. This is used to help avoid max
4002 /// expressions in loop trip counts.
4003 bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
4004 ICmpInst::Predicate Pred,
4005 const SCEV *LHS, const SCEV *RHS) {
4006 // Interpret a null as meaning no loop, where there is obviously no guard
4007 // (interprocedural conditions notwithstanding).
4008 if (!L) return false;
4010 BasicBlock *Predecessor = getLoopPredecessor(L);
4011 BasicBlock *PredecessorDest = L->getHeader();
4013 // Starting at the loop predecessor, climb up the predecessor chain, as long
4014 // as there are predecessors that can be found that have unique successors
4015 // leading to the original header.
4017 PredecessorDest = Predecessor,
4018 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
4020 BranchInst *LoopEntryPredicate =
4021 dyn_cast<BranchInst>(Predecessor->getTerminator());
4022 if (!LoopEntryPredicate ||
4023 LoopEntryPredicate->isUnconditional())
4026 if (isNecessaryCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
4027 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
4034 /// isNecessaryCond - Test whether the given CondValue value is a condition
4035 /// which is at least as strict as the one described by Pred, LHS, and RHS.
4036 bool ScalarEvolution::isNecessaryCond(Value *CondValue,
4037 ICmpInst::Predicate Pred,
4038 const SCEV *LHS, const SCEV *RHS,
4040 // Recursivly handle And and Or conditions.
4041 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
4042 if (BO->getOpcode() == Instruction::And) {
4044 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4045 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4046 } else if (BO->getOpcode() == Instruction::Or) {
4048 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4049 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4053 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
4054 if (!ICI) return false;
4056 // Now that we found a conditional branch that dominates the loop, check to
4057 // see if it is the comparison we are looking for.
4058 Value *PreCondLHS = ICI->getOperand(0);
4059 Value *PreCondRHS = ICI->getOperand(1);
4060 ICmpInst::Predicate Cond;
4062 Cond = ICI->getInversePredicate();
4064 Cond = ICI->getPredicate();
4067 ; // An exact match.
4068 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
4069 ; // The actual condition is beyond sufficient.
4071 // Check a few special cases.
4073 case ICmpInst::ICMP_UGT:
4074 if (Pred == ICmpInst::ICMP_ULT) {
4075 std::swap(PreCondLHS, PreCondRHS);
4076 Cond = ICmpInst::ICMP_ULT;
4080 case ICmpInst::ICMP_SGT:
4081 if (Pred == ICmpInst::ICMP_SLT) {
4082 std::swap(PreCondLHS, PreCondRHS);
4083 Cond = ICmpInst::ICMP_SLT;
4087 case ICmpInst::ICMP_NE:
4088 // Expressions like (x >u 0) are often canonicalized to (x != 0),
4089 // so check for this case by checking if the NE is comparing against
4090 // a minimum or maximum constant.
4091 if (!ICmpInst::isTrueWhenEqual(Pred))
4092 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
4093 const APInt &A = CI->getValue();
4095 case ICmpInst::ICMP_SLT:
4096 if (A.isMaxSignedValue()) break;
4098 case ICmpInst::ICMP_SGT:
4099 if (A.isMinSignedValue()) break;
4101 case ICmpInst::ICMP_ULT:
4102 if (A.isMaxValue()) break;
4104 case ICmpInst::ICMP_UGT:
4105 if (A.isMinValue()) break;
4110 Cond = ICmpInst::ICMP_NE;
4111 // NE is symmetric but the original comparison may not be. Swap
4112 // the operands if necessary so that they match below.
4113 if (isa<SCEVConstant>(LHS))
4114 std::swap(PreCondLHS, PreCondRHS);
4119 // We weren't able to reconcile the condition.
4123 if (!PreCondLHS->getType()->isInteger()) return false;
4125 const SCEV *PreCondLHSSCEV = getSCEV(PreCondLHS);
4126 const SCEV *PreCondRHSSCEV = getSCEV(PreCondRHS);
4127 return (HasSameValue(LHS, PreCondLHSSCEV) &&
4128 HasSameValue(RHS, PreCondRHSSCEV)) ||
4129 (HasSameValue(LHS, getNotSCEV(PreCondRHSSCEV)) &&
4130 HasSameValue(RHS, getNotSCEV(PreCondLHSSCEV)));
4133 /// getBECount - Subtract the end and start values and divide by the step,
4134 /// rounding up, to get the number of times the backedge is executed. Return
4135 /// CouldNotCompute if an intermediate computation overflows.
4136 const SCEV* ScalarEvolution::getBECount(const SCEV* Start,
4139 const Type *Ty = Start->getType();
4140 const SCEV* NegOne = getIntegerSCEV(-1, Ty);
4141 const SCEV* Diff = getMinusSCEV(End, Start);
4142 const SCEV* RoundUp = getAddExpr(Step, NegOne);
4144 // Add an adjustment to the difference between End and Start so that
4145 // the division will effectively round up.
4146 const SCEV* Add = getAddExpr(Diff, RoundUp);
4148 // Check Add for unsigned overflow.
4149 // TODO: More sophisticated things could be done here.
4150 const Type *WideTy = IntegerType::get(getTypeSizeInBits(Ty) + 1);
4151 const SCEV* OperandExtendedAdd =
4152 getAddExpr(getZeroExtendExpr(Diff, WideTy),
4153 getZeroExtendExpr(RoundUp, WideTy));
4154 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
4155 return getCouldNotCompute();
4157 return getUDivExpr(Add, Step);
4160 /// HowManyLessThans - Return the number of times a backedge containing the
4161 /// specified less-than comparison will execute. If not computable, return
4162 /// CouldNotCompute.
4163 ScalarEvolution::BackedgeTakenInfo
4164 ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
4165 const Loop *L, bool isSigned) {
4166 // Only handle: "ADDREC < LoopInvariant".
4167 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
4169 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
4170 if (!AddRec || AddRec->getLoop() != L)
4171 return getCouldNotCompute();
4173 if (AddRec->isAffine()) {
4174 // FORNOW: We only support unit strides.
4175 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
4176 const SCEV* Step = AddRec->getStepRecurrence(*this);
4178 // TODO: handle non-constant strides.
4179 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
4180 if (!CStep || CStep->isZero())
4181 return getCouldNotCompute();
4182 if (CStep->isOne()) {
4183 // With unit stride, the iteration never steps past the limit value.
4184 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
4185 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
4186 // Test whether a positive iteration iteration can step past the limit
4187 // value and past the maximum value for its type in a single step.
4189 APInt Max = APInt::getSignedMaxValue(BitWidth);
4190 if ((Max - CStep->getValue()->getValue())
4191 .slt(CLimit->getValue()->getValue()))
4192 return getCouldNotCompute();
4194 APInt Max = APInt::getMaxValue(BitWidth);
4195 if ((Max - CStep->getValue()->getValue())
4196 .ult(CLimit->getValue()->getValue()))
4197 return getCouldNotCompute();
4200 // TODO: handle non-constant limit values below.
4201 return getCouldNotCompute();
4203 // TODO: handle negative strides below.
4204 return getCouldNotCompute();
4206 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
4207 // m. So, we count the number of iterations in which {n,+,s} < m is true.
4208 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
4209 // treat m-n as signed nor unsigned due to overflow possibility.
4211 // First, we get the value of the LHS in the first iteration: n
4212 const SCEV* Start = AddRec->getOperand(0);
4214 // Determine the minimum constant start value.
4215 const SCEV *MinStart = isa<SCEVConstant>(Start) ? Start :
4216 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
4217 APInt::getMinValue(BitWidth));
4219 // If we know that the condition is true in order to enter the loop,
4220 // then we know that it will run exactly (m-n)/s times. Otherwise, we
4221 // only know that it will execute (max(m,n)-n)/s times. In both cases,
4222 // the division must round up.
4223 const SCEV* End = RHS;
4224 if (!isLoopGuardedByCond(L,
4225 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
4226 getMinusSCEV(Start, Step), RHS))
4227 End = isSigned ? getSMaxExpr(RHS, Start)
4228 : getUMaxExpr(RHS, Start);
4230 // Determine the maximum constant end value.
4231 const SCEV* MaxEnd =
4232 isa<SCEVConstant>(End) ? End :
4233 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth)
4234 .ashr(GetMinSignBits(End) - 1) :
4235 APInt::getMaxValue(BitWidth)
4236 .lshr(GetMinLeadingZeros(End)));
4238 // Finally, we subtract these two values and divide, rounding up, to get
4239 // the number of times the backedge is executed.
4240 const SCEV* BECount = getBECount(Start, End, Step);
4242 // The maximum backedge count is similar, except using the minimum start
4243 // value and the maximum end value.
4244 const SCEV* MaxBECount = getBECount(MinStart, MaxEnd, Step);;
4246 return BackedgeTakenInfo(BECount, MaxBECount);
4249 return getCouldNotCompute();
4252 /// getNumIterationsInRange - Return the number of iterations of this loop that
4253 /// produce values in the specified constant range. Another way of looking at
4254 /// this is that it returns the first iteration number where the value is not in
4255 /// the condition, thus computing the exit count. If the iteration count can't
4256 /// be computed, an instance of SCEVCouldNotCompute is returned.
4257 const SCEV* SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
4258 ScalarEvolution &SE) const {
4259 if (Range.isFullSet()) // Infinite loop.
4260 return SE.getCouldNotCompute();
4262 // If the start is a non-zero constant, shift the range to simplify things.
4263 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
4264 if (!SC->getValue()->isZero()) {
4265 SmallVector<const SCEV*, 4> Operands(op_begin(), op_end());
4266 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
4267 const SCEV* Shifted = SE.getAddRecExpr(Operands, getLoop());
4268 if (const SCEVAddRecExpr *ShiftedAddRec =
4269 dyn_cast<SCEVAddRecExpr>(Shifted))
4270 return ShiftedAddRec->getNumIterationsInRange(
4271 Range.subtract(SC->getValue()->getValue()), SE);
4272 // This is strange and shouldn't happen.
4273 return SE.getCouldNotCompute();
4276 // The only time we can solve this is when we have all constant indices.
4277 // Otherwise, we cannot determine the overflow conditions.
4278 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4279 if (!isa<SCEVConstant>(getOperand(i)))
4280 return SE.getCouldNotCompute();
4283 // Okay at this point we know that all elements of the chrec are constants and
4284 // that the start element is zero.
4286 // First check to see if the range contains zero. If not, the first
4288 unsigned BitWidth = SE.getTypeSizeInBits(getType());
4289 if (!Range.contains(APInt(BitWidth, 0)))
4290 return SE.getIntegerSCEV(0, getType());
4293 // If this is an affine expression then we have this situation:
4294 // Solve {0,+,A} in Range === Ax in Range
4296 // We know that zero is in the range. If A is positive then we know that
4297 // the upper value of the range must be the first possible exit value.
4298 // If A is negative then the lower of the range is the last possible loop
4299 // value. Also note that we already checked for a full range.
4300 APInt One(BitWidth,1);
4301 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
4302 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
4304 // The exit value should be (End+A)/A.
4305 APInt ExitVal = (End + A).udiv(A);
4306 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
4308 // Evaluate at the exit value. If we really did fall out of the valid
4309 // range, then we computed our trip count, otherwise wrap around or other
4310 // things must have happened.
4311 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
4312 if (Range.contains(Val->getValue()))
4313 return SE.getCouldNotCompute(); // Something strange happened
4315 // Ensure that the previous value is in the range. This is a sanity check.
4316 assert(Range.contains(
4317 EvaluateConstantChrecAtConstant(this,
4318 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
4319 "Linear scev computation is off in a bad way!");
4320 return SE.getConstant(ExitValue);
4321 } else if (isQuadratic()) {
4322 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
4323 // quadratic equation to solve it. To do this, we must frame our problem in
4324 // terms of figuring out when zero is crossed, instead of when
4325 // Range.getUpper() is crossed.
4326 SmallVector<const SCEV*, 4> NewOps(op_begin(), op_end());
4327 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
4328 const SCEV* NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
4330 // Next, solve the constructed addrec
4331 std::pair<const SCEV*,const SCEV*> Roots =
4332 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
4333 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4334 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
4336 // Pick the smallest positive root value.
4337 if (ConstantInt *CB =
4338 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
4339 R1->getValue(), R2->getValue()))) {
4340 if (CB->getZExtValue() == false)
4341 std::swap(R1, R2); // R1 is the minimum root now.
4343 // Make sure the root is not off by one. The returned iteration should
4344 // not be in the range, but the previous one should be. When solving
4345 // for "X*X < 5", for example, we should not return a root of 2.
4346 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
4349 if (Range.contains(R1Val->getValue())) {
4350 // The next iteration must be out of the range...
4351 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
4353 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
4354 if (!Range.contains(R1Val->getValue()))
4355 return SE.getConstant(NextVal);
4356 return SE.getCouldNotCompute(); // Something strange happened
4359 // If R1 was not in the range, then it is a good return value. Make
4360 // sure that R1-1 WAS in the range though, just in case.
4361 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
4362 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
4363 if (Range.contains(R1Val->getValue()))
4365 return SE.getCouldNotCompute(); // Something strange happened
4370 return SE.getCouldNotCompute();
4375 //===----------------------------------------------------------------------===//
4376 // SCEVCallbackVH Class Implementation
4377 //===----------------------------------------------------------------------===//
4379 void ScalarEvolution::SCEVCallbackVH::deleted() {
4380 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4381 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
4382 SE->ConstantEvolutionLoopExitValue.erase(PN);
4383 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
4384 SE->ValuesAtScopes.erase(I);
4385 SE->Scalars.erase(getValPtr());
4386 // this now dangles!
4389 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
4390 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4392 // Forget all the expressions associated with users of the old value,
4393 // so that future queries will recompute the expressions using the new
4395 SmallVector<User *, 16> Worklist;
4396 Value *Old = getValPtr();
4397 bool DeleteOld = false;
4398 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
4400 Worklist.push_back(*UI);
4401 while (!Worklist.empty()) {
4402 User *U = Worklist.pop_back_val();
4403 // Deleting the Old value will cause this to dangle. Postpone
4404 // that until everything else is done.
4409 if (PHINode *PN = dyn_cast<PHINode>(U))
4410 SE->ConstantEvolutionLoopExitValue.erase(PN);
4411 if (Instruction *I = dyn_cast<Instruction>(U))
4412 SE->ValuesAtScopes.erase(I);
4413 if (SE->Scalars.erase(U))
4414 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
4416 Worklist.push_back(*UI);
4419 if (PHINode *PN = dyn_cast<PHINode>(Old))
4420 SE->ConstantEvolutionLoopExitValue.erase(PN);
4421 if (Instruction *I = dyn_cast<Instruction>(Old))
4422 SE->ValuesAtScopes.erase(I);
4423 SE->Scalars.erase(Old);
4424 // this now dangles!
4429 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
4430 : CallbackVH(V), SE(se) {}
4432 //===----------------------------------------------------------------------===//
4433 // ScalarEvolution Class Implementation
4434 //===----------------------------------------------------------------------===//
4436 ScalarEvolution::ScalarEvolution()
4437 : FunctionPass(&ID) {
4440 bool ScalarEvolution::runOnFunction(Function &F) {
4442 LI = &getAnalysis<LoopInfo>();
4443 TD = getAnalysisIfAvailable<TargetData>();
4447 void ScalarEvolution::releaseMemory() {
4449 BackedgeTakenCounts.clear();
4450 ConstantEvolutionLoopExitValue.clear();
4451 ValuesAtScopes.clear();
4452 UniqueSCEVs.clear();
4453 SCEVAllocator.Reset();
4456 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
4457 AU.setPreservesAll();
4458 AU.addRequiredTransitive<LoopInfo>();
4461 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
4462 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
4465 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
4467 // Print all inner loops first
4468 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4469 PrintLoopInfo(OS, SE, *I);
4471 OS << "Loop " << L->getHeader()->getName() << ": ";
4473 SmallVector<BasicBlock*, 8> ExitBlocks;
4474 L->getExitBlocks(ExitBlocks);
4475 if (ExitBlocks.size() != 1)
4476 OS << "<multiple exits> ";
4478 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
4479 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
4481 OS << "Unpredictable backedge-taken count. ";
4485 OS << "Loop " << L->getHeader()->getName() << ": ";
4487 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
4488 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
4490 OS << "Unpredictable max backedge-taken count. ";
4496 void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
4497 // ScalarEvolution's implementaiton of the print method is to print
4498 // out SCEV values of all instructions that are interesting. Doing
4499 // this potentially causes it to create new SCEV objects though,
4500 // which technically conflicts with the const qualifier. This isn't
4501 // observable from outside the class though (the hasSCEV function
4502 // notwithstanding), so casting away the const isn't dangerous.
4503 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
4505 OS << "Classifying expressions for: " << F->getName() << "\n";
4506 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
4507 if (isSCEVable(I->getType())) {
4510 const SCEV* SV = SE.getSCEV(&*I);
4513 const Loop *L = LI->getLoopFor((*I).getParent());
4515 const SCEV* AtUse = SE.getSCEVAtScope(SV, L);
4522 OS << "\t\t" "Exits: ";
4523 const SCEV* ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
4524 if (!ExitValue->isLoopInvariant(L)) {
4525 OS << "<<Unknown>>";
4534 OS << "Determining loop execution counts for: " << F->getName() << "\n";
4535 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
4536 PrintLoopInfo(OS, &SE, *I);
4539 void ScalarEvolution::print(std::ostream &o, const Module *M) const {
4540 raw_os_ostream OS(o);