1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the implementation of the scalar evolution analysis
11 // engine, which is used primarily to analyze expressions involving induction
12 // variables in loops.
14 // There are several aspects to this library. First is the representation of
15 // scalar expressions, which are represented as subclasses of the SCEV class.
16 // These classes are used to represent certain types of subexpressions that we
17 // can handle. These classes are reference counted, managed by the SCEVHandle
18 // class. We only create one SCEV of a particular shape, so pointer-comparisons
19 // for equality are legal.
21 // One important aspect of the SCEV objects is that they are never cyclic, even
22 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If
23 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
24 // recurrence) then we represent it directly as a recurrence node, otherwise we
25 // represent it as a SCEVUnknown node.
27 // In addition to being able to represent expressions of various types, we also
28 // have folders that are used to build the *canonical* representation for a
29 // particular expression. These folders are capable of using a variety of
30 // rewrite rules to simplify the expressions.
32 // Once the folders are defined, we can implement the more interesting
33 // higher-level code, such as the code that recognizes PHI nodes of various
34 // types, computes the execution count of a loop, etc.
36 // TODO: We should use these routines and value representations to implement
37 // dependence analysis!
39 //===----------------------------------------------------------------------===//
41 // There are several good references for the techniques used in this analysis.
43 // Chains of recurrences -- a method to expedite the evaluation
44 // of closed-form functions
45 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima
47 // On computational properties of chains of recurrences
50 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization
51 // Robert A. van Engelen
53 // Efficient Symbolic Analysis for Optimizing Compilers
54 // Robert A. van Engelen
56 // Using the chains of recurrences algebra for data dependence testing and
57 // induction variable substitution
58 // MS Thesis, Johnie Birch
60 //===----------------------------------------------------------------------===//
62 #define DEBUG_TYPE "scalar-evolution"
63 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
64 #include "llvm/Constants.h"
65 #include "llvm/DerivedTypes.h"
66 #include "llvm/GlobalVariable.h"
67 #include "llvm/Instructions.h"
68 #include "llvm/Analysis/ConstantFolding.h"
69 #include "llvm/Analysis/Dominators.h"
70 #include "llvm/Analysis/LoopInfo.h"
71 #include "llvm/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/ManagedStatic.h"
80 #include "llvm/Support/MathExtras.h"
81 #include "llvm/Support/raw_ostream.h"
82 #include "llvm/ADT/Statistic.h"
83 #include "llvm/ADT/STLExtras.h"
87 STATISTIC(NumArrayLenItCounts,
88 "Number of trip counts computed with array length");
89 STATISTIC(NumTripCountsComputed,
90 "Number of loops with predictable loop counts");
91 STATISTIC(NumTripCountsNotComputed,
92 "Number of loops without predictable loop counts");
93 STATISTIC(NumBruteForceTripCountsComputed,
94 "Number of loops with trip counts computed by force");
96 static cl::opt<unsigned>
97 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
98 cl::desc("Maximum number of iterations SCEV will "
99 "symbolically execute a constant derived loop"),
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 SCEVCouldNotCompute::SCEVCouldNotCompute(const ScalarEvolution* p) :
137 SCEV(scCouldNotCompute, p) {}
138 SCEVCouldNotCompute::~SCEVCouldNotCompute() {}
140 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
141 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
145 const Type *SCEVCouldNotCompute::getType() const {
146 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
150 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
151 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
155 SCEVHandle SCEVCouldNotCompute::
156 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
157 const SCEVHandle &Conc,
158 ScalarEvolution &SE) const {
162 void SCEVCouldNotCompute::print(raw_ostream &OS) const {
163 OS << "***COULDNOTCOMPUTE***";
166 bool SCEVCouldNotCompute::classof(const SCEV *S) {
167 return S->getSCEVType() == scCouldNotCompute;
171 // SCEVConstants - Only allow the creation of one SCEVConstant for any
172 // particular value. Don't use a SCEVHandle here, or else the object will
174 static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
177 SCEVConstant::~SCEVConstant() {
178 SCEVConstants->erase(V);
181 SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
182 SCEVConstant *&R = (*SCEVConstants)[V];
183 if (R == 0) R = new SCEVConstant(V, this);
187 SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
188 return getConstant(ConstantInt::get(Val));
192 ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
193 return getConstant(ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
196 const Type *SCEVConstant::getType() const { return V->getType(); }
198 void SCEVConstant::print(raw_ostream &OS) const {
199 WriteAsOperand(OS, V, false);
202 SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
203 const SCEVHandle &op, const Type *ty,
204 const ScalarEvolution* p)
205 : SCEV(SCEVTy, p), Op(op), Ty(ty) {}
207 SCEVCastExpr::~SCEVCastExpr() {}
209 bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
210 return Op->dominates(BB, DT);
213 // SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
214 // particular input. Don't use a SCEVHandle here, or else the object will
216 static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
217 SCEVTruncateExpr*> > SCEVTruncates;
219 SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty,
220 const ScalarEvolution* p)
221 : SCEVCastExpr(scTruncate, op, ty, p) {
222 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
223 (Ty->isInteger() || isa<PointerType>(Ty)) &&
224 "Cannot truncate non-integer value!");
227 SCEVTruncateExpr::~SCEVTruncateExpr() {
228 SCEVTruncates->erase(std::make_pair(Op, Ty));
231 void SCEVTruncateExpr::print(raw_ostream &OS) const {
232 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
235 // SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
236 // particular input. Don't use a SCEVHandle here, or else the object will never
238 static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
239 SCEVZeroExtendExpr*> > SCEVZeroExtends;
241 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty,
242 const ScalarEvolution* p)
243 : SCEVCastExpr(scZeroExtend, op, ty, p) {
244 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
245 (Ty->isInteger() || isa<PointerType>(Ty)) &&
246 "Cannot zero extend non-integer value!");
249 SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
250 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
253 void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
254 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
257 // SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
258 // particular input. Don't use a SCEVHandle here, or else the object will never
260 static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
261 SCEVSignExtendExpr*> > SCEVSignExtends;
263 SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty,
264 const ScalarEvolution* p)
265 : SCEVCastExpr(scSignExtend, op, ty, p) {
266 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
267 (Ty->isInteger() || isa<PointerType>(Ty)) &&
268 "Cannot sign extend non-integer value!");
271 SCEVSignExtendExpr::~SCEVSignExtendExpr() {
272 SCEVSignExtends->erase(std::make_pair(Op, Ty));
275 void SCEVSignExtendExpr::print(raw_ostream &OS) const {
276 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
279 // SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
280 // particular input. Don't use a SCEVHandle here, or else the object will never
282 static ManagedStatic<std::map<std::pair<unsigned, std::vector<const SCEV*> >,
283 SCEVCommutativeExpr*> > SCEVCommExprs;
285 SCEVCommutativeExpr::~SCEVCommutativeExpr() {
286 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
287 SCEVCommExprs->erase(std::make_pair(getSCEVType(), SCEVOps));
290 void SCEVCommutativeExpr::print(raw_ostream &OS) const {
291 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
292 const char *OpStr = getOperationStr();
293 OS << "(" << *Operands[0];
294 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
295 OS << OpStr << *Operands[i];
299 SCEVHandle SCEVCommutativeExpr::
300 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
301 const SCEVHandle &Conc,
302 ScalarEvolution &SE) const {
303 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
305 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
306 if (H != getOperand(i)) {
307 SmallVector<SCEVHandle, 8> NewOps;
308 NewOps.reserve(getNumOperands());
309 for (unsigned j = 0; j != i; ++j)
310 NewOps.push_back(getOperand(j));
312 for (++i; i != e; ++i)
313 NewOps.push_back(getOperand(i)->
314 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
316 if (isa<SCEVAddExpr>(this))
317 return SE.getAddExpr(NewOps);
318 else if (isa<SCEVMulExpr>(this))
319 return SE.getMulExpr(NewOps);
320 else if (isa<SCEVSMaxExpr>(this))
321 return SE.getSMaxExpr(NewOps);
322 else if (isa<SCEVUMaxExpr>(this))
323 return SE.getUMaxExpr(NewOps);
325 assert(0 && "Unknown commutative expr!");
331 bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
332 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
333 if (!getOperand(i)->dominates(BB, DT))
340 // SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
341 // input. Don't use a SCEVHandle here, or else the object will never be
343 static ManagedStatic<std::map<std::pair<const SCEV*, const SCEV*>,
344 SCEVUDivExpr*> > SCEVUDivs;
346 SCEVUDivExpr::~SCEVUDivExpr() {
347 SCEVUDivs->erase(std::make_pair(LHS, RHS));
350 bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
351 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
354 void SCEVUDivExpr::print(raw_ostream &OS) const {
355 OS << "(" << *LHS << " /u " << *RHS << ")";
358 const Type *SCEVUDivExpr::getType() const {
359 // In most cases the types of LHS and RHS will be the same, but in some
360 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
361 // depend on the type for correctness, but handling types carefully can
362 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
363 // a pointer type than the RHS, so use the RHS' type here.
364 return RHS->getType();
367 // SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
368 // particular input. Don't use a SCEVHandle here, or else the object will never
370 static ManagedStatic<std::map<std::pair<const Loop *,
371 std::vector<const SCEV*> >,
372 SCEVAddRecExpr*> > SCEVAddRecExprs;
374 SCEVAddRecExpr::~SCEVAddRecExpr() {
375 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
376 SCEVAddRecExprs->erase(std::make_pair(L, SCEVOps));
379 SCEVHandle SCEVAddRecExpr::
380 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
381 const SCEVHandle &Conc,
382 ScalarEvolution &SE) const {
383 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
385 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
386 if (H != getOperand(i)) {
387 SmallVector<SCEVHandle, 8> NewOps;
388 NewOps.reserve(getNumOperands());
389 for (unsigned j = 0; j != i; ++j)
390 NewOps.push_back(getOperand(j));
392 for (++i; i != e; ++i)
393 NewOps.push_back(getOperand(i)->
394 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
396 return SE.getAddRecExpr(NewOps, L);
403 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
404 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
405 // contain L and if the start is invariant.
406 // Add recurrences are never invariant in the function-body (null loop).
408 !QueryLoop->contains(L->getHeader()) &&
409 getOperand(0)->isLoopInvariant(QueryLoop);
413 void SCEVAddRecExpr::print(raw_ostream &OS) const {
414 OS << "{" << *Operands[0];
415 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
416 OS << ",+," << *Operands[i];
417 OS << "}<" << L->getHeader()->getName() + ">";
420 // SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
421 // value. Don't use a SCEVHandle here, or else the object will never be
423 static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
425 SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
427 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
428 // All non-instruction values are loop invariant. All instructions are loop
429 // invariant if they are not contained in the specified loop.
430 // Instructions are never considered invariant in the function body
431 // (null loop) because they are defined within the "loop".
432 if (Instruction *I = dyn_cast<Instruction>(V))
433 return L && !L->contains(I->getParent());
437 bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
438 if (Instruction *I = dyn_cast<Instruction>(getValue()))
439 return DT->dominates(I->getParent(), BB);
443 const Type *SCEVUnknown::getType() const {
447 void SCEVUnknown::print(raw_ostream &OS) const {
448 WriteAsOperand(OS, V, false);
451 //===----------------------------------------------------------------------===//
453 //===----------------------------------------------------------------------===//
456 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
457 /// than the complexity of the RHS. This comparator is used to canonicalize
459 class VISIBILITY_HIDDEN SCEVComplexityCompare {
462 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
464 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
465 // Primarily, sort the SCEVs by their getSCEVType().
466 if (LHS->getSCEVType() != RHS->getSCEVType())
467 return LHS->getSCEVType() < RHS->getSCEVType();
469 // Aside from the getSCEVType() ordering, the particular ordering
470 // isn't very important except that it's beneficial to be consistent,
471 // so that (a + b) and (b + a) don't end up as different expressions.
473 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
474 // not as complete as it could be.
475 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
476 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
478 // Order pointer values after integer values. This helps SCEVExpander
480 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
482 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
485 // Compare getValueID values.
486 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
487 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
489 // Sort arguments by their position.
490 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
491 const Argument *RA = cast<Argument>(RU->getValue());
492 return LA->getArgNo() < RA->getArgNo();
495 // For instructions, compare their loop depth, and their opcode.
496 // This is pretty loose.
497 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
498 Instruction *RV = cast<Instruction>(RU->getValue());
500 // Compare loop depths.
501 if (LI->getLoopDepth(LV->getParent()) !=
502 LI->getLoopDepth(RV->getParent()))
503 return LI->getLoopDepth(LV->getParent()) <
504 LI->getLoopDepth(RV->getParent());
507 if (LV->getOpcode() != RV->getOpcode())
508 return LV->getOpcode() < RV->getOpcode();
510 // Compare the number of operands.
511 if (LV->getNumOperands() != RV->getNumOperands())
512 return LV->getNumOperands() < RV->getNumOperands();
518 // Compare constant values.
519 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
520 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
521 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
524 // Compare addrec loop depths.
525 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
526 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
527 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
528 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
531 // Lexicographically compare n-ary expressions.
532 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
533 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
534 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
535 if (i >= RC->getNumOperands())
537 if (operator()(LC->getOperand(i), RC->getOperand(i)))
539 if (operator()(RC->getOperand(i), LC->getOperand(i)))
542 return LC->getNumOperands() < RC->getNumOperands();
545 // Lexicographically compare udiv expressions.
546 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
547 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
548 if (operator()(LC->getLHS(), RC->getLHS()))
550 if (operator()(RC->getLHS(), LC->getLHS()))
552 if (operator()(LC->getRHS(), RC->getRHS()))
554 if (operator()(RC->getRHS(), LC->getRHS()))
559 // Compare cast expressions by operand.
560 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
561 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
562 return operator()(LC->getOperand(), RC->getOperand());
565 assert(0 && "Unknown SCEV kind!");
571 /// GroupByComplexity - Given a list of SCEV objects, order them by their
572 /// complexity, and group objects of the same complexity together by value.
573 /// When this routine is finished, we know that any duplicates in the vector are
574 /// consecutive and that complexity is monotonically increasing.
576 /// Note that we go take special precautions to ensure that we get determinstic
577 /// results from this routine. In other words, we don't want the results of
578 /// this to depend on where the addresses of various SCEV objects happened to
581 static void GroupByComplexity(SmallVectorImpl<SCEVHandle> &Ops,
583 if (Ops.size() < 2) return; // Noop
584 if (Ops.size() == 2) {
585 // This is the common case, which also happens to be trivially simple.
587 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
588 std::swap(Ops[0], Ops[1]);
592 // Do the rough sort by complexity.
593 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
595 // Now that we are sorted by complexity, group elements of the same
596 // complexity. Note that this is, at worst, N^2, but the vector is likely to
597 // be extremely short in practice. Note that we take this approach because we
598 // do not want to depend on the addresses of the objects we are grouping.
599 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
600 const SCEV *S = Ops[i];
601 unsigned Complexity = S->getSCEVType();
603 // If there are any objects of the same complexity and same value as this
605 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
606 if (Ops[j] == S) { // Found a duplicate.
607 // Move it to immediately after i'th element.
608 std::swap(Ops[i+1], Ops[j]);
609 ++i; // no need to rescan it.
610 if (i == e-2) return; // Done!
618 //===----------------------------------------------------------------------===//
619 // Simple SCEV method implementations
620 //===----------------------------------------------------------------------===//
622 /// BinomialCoefficient - Compute BC(It, K). The result has width W.
624 static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
626 const Type* ResultTy) {
627 // Handle the simplest case efficiently.
629 return SE.getTruncateOrZeroExtend(It, ResultTy);
631 // We are using the following formula for BC(It, K):
633 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
635 // Suppose, W is the bitwidth of the return value. We must be prepared for
636 // overflow. Hence, we must assure that the result of our computation is
637 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
638 // safe in modular arithmetic.
640 // However, this code doesn't use exactly that formula; the formula it uses
641 // is something like the following, where T is the number of factors of 2 in
642 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
645 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
647 // This formula is trivially equivalent to the previous formula. However,
648 // this formula can be implemented much more efficiently. The trick is that
649 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
650 // arithmetic. To do exact division in modular arithmetic, all we have
651 // to do is multiply by the inverse. Therefore, this step can be done at
654 // The next issue is how to safely do the division by 2^T. The way this
655 // is done is by doing the multiplication step at a width of at least W + T
656 // bits. This way, the bottom W+T bits of the product are accurate. Then,
657 // when we perform the division by 2^T (which is equivalent to a right shift
658 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
659 // truncated out after the division by 2^T.
661 // In comparison to just directly using the first formula, this technique
662 // is much more efficient; using the first formula requires W * K bits,
663 // but this formula less than W + K bits. Also, the first formula requires
664 // a division step, whereas this formula only requires multiplies and shifts.
666 // It doesn't matter whether the subtraction step is done in the calculation
667 // width or the input iteration count's width; if the subtraction overflows,
668 // the result must be zero anyway. We prefer here to do it in the width of
669 // the induction variable because it helps a lot for certain cases; CodeGen
670 // isn't smart enough to ignore the overflow, which leads to much less
671 // efficient code if the width of the subtraction is wider than the native
674 // (It's possible to not widen at all by pulling out factors of 2 before
675 // the multiplication; for example, K=2 can be calculated as
676 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
677 // extra arithmetic, so it's not an obvious win, and it gets
678 // much more complicated for K > 3.)
680 // Protection from insane SCEVs; this bound is conservative,
681 // but it probably doesn't matter.
683 return SE.getCouldNotCompute();
685 unsigned W = SE.getTypeSizeInBits(ResultTy);
687 // Calculate K! / 2^T and T; we divide out the factors of two before
688 // multiplying for calculating K! / 2^T to avoid overflow.
689 // Other overflow doesn't matter because we only care about the bottom
690 // W bits of the result.
691 APInt OddFactorial(W, 1);
693 for (unsigned i = 3; i <= K; ++i) {
695 unsigned TwoFactors = Mult.countTrailingZeros();
697 Mult = Mult.lshr(TwoFactors);
698 OddFactorial *= Mult;
701 // We need at least W + T bits for the multiplication step
702 unsigned CalculationBits = W + T;
704 // Calcuate 2^T, at width T+W.
705 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
707 // Calculate the multiplicative inverse of K! / 2^T;
708 // this multiplication factor will perform the exact division by
710 APInt Mod = APInt::getSignedMinValue(W+1);
711 APInt MultiplyFactor = OddFactorial.zext(W+1);
712 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
713 MultiplyFactor = MultiplyFactor.trunc(W);
715 // Calculate the product, at width T+W
716 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
717 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
718 for (unsigned i = 1; i != K; ++i) {
719 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
720 Dividend = SE.getMulExpr(Dividend,
721 SE.getTruncateOrZeroExtend(S, CalculationTy));
725 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
727 // Truncate the result, and divide by K! / 2^T.
729 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
730 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
733 /// evaluateAtIteration - Return the value of this chain of recurrences at
734 /// the specified iteration number. We can evaluate this recurrence by
735 /// multiplying each element in the chain by the binomial coefficient
736 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
738 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
740 /// where BC(It, k) stands for binomial coefficient.
742 SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
743 ScalarEvolution &SE) const {
744 SCEVHandle Result = getStart();
745 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
746 // The computation is correct in the face of overflow provided that the
747 // multiplication is performed _after_ the evaluation of the binomial
749 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
750 if (isa<SCEVCouldNotCompute>(Coeff))
753 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
758 //===----------------------------------------------------------------------===//
759 // SCEV Expression folder implementations
760 //===----------------------------------------------------------------------===//
762 SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op,
764 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
765 "This is not a truncating conversion!");
766 assert(isSCEVable(Ty) &&
767 "This is not a conversion to a SCEVable type!");
768 Ty = getEffectiveSCEVType(Ty);
770 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
772 ConstantExpr::getTrunc(SC->getValue(), Ty));
774 // trunc(trunc(x)) --> trunc(x)
775 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
776 return getTruncateExpr(ST->getOperand(), Ty);
778 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
779 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
780 return getTruncateOrSignExtend(SS->getOperand(), Ty);
782 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
783 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
784 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
786 // If the input value is a chrec scev, truncate the chrec's operands.
787 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
788 SmallVector<SCEVHandle, 4> Operands;
789 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
790 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
791 return getAddRecExpr(Operands, AddRec->getLoop());
794 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
795 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty, this);
799 SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
801 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
802 "This is not an extending conversion!");
803 assert(isSCEVable(Ty) &&
804 "This is not a conversion to a SCEVable type!");
805 Ty = getEffectiveSCEVType(Ty);
807 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
808 const Type *IntTy = getEffectiveSCEVType(Ty);
809 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
810 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
811 return getUnknown(C);
814 // zext(zext(x)) --> zext(x)
815 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
816 return getZeroExtendExpr(SZ->getOperand(), Ty);
818 // If the input value is a chrec scev, and we can prove that the value
819 // did not overflow the old, smaller, value, we can zero extend all of the
820 // operands (often constants). This allows analysis of something like
821 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
822 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
823 if (AR->isAffine()) {
824 // Check whether the backedge-taken count is SCEVCouldNotCompute.
825 // Note that this serves two purposes: It filters out loops that are
826 // simply not analyzable, and it covers the case where this code is
827 // being called from within backedge-taken count analysis, such that
828 // attempting to ask for the backedge-taken count would likely result
829 // in infinite recursion. In the later case, the analysis code will
830 // cope with a conservative value, and it will take care to purge
831 // that value once it has finished.
832 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
833 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
834 // Manually compute the final value for AR, checking for
836 SCEVHandle Start = AR->getStart();
837 SCEVHandle Step = AR->getStepRecurrence(*this);
839 // Check whether the backedge-taken count can be losslessly casted to
840 // the addrec's type. The count is always unsigned.
841 SCEVHandle CastedMaxBECount =
842 getTruncateOrZeroExtend(MaxBECount, Start->getType());
843 SCEVHandle RecastedMaxBECount =
844 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
845 if (MaxBECount == RecastedMaxBECount) {
847 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
848 // Check whether Start+Step*MaxBECount has no unsigned overflow.
850 getMulExpr(CastedMaxBECount,
851 getTruncateOrZeroExtend(Step, Start->getType()));
852 SCEVHandle Add = getAddExpr(Start, ZMul);
853 SCEVHandle OperandExtendedAdd =
854 getAddExpr(getZeroExtendExpr(Start, WideTy),
855 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
856 getZeroExtendExpr(Step, WideTy)));
857 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
858 // Return the expression with the addrec on the outside.
859 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
860 getZeroExtendExpr(Step, Ty),
863 // Similar to above, only this time treat the step value as signed.
864 // This covers loops that count down.
866 getMulExpr(CastedMaxBECount,
867 getTruncateOrSignExtend(Step, Start->getType()));
868 Add = getAddExpr(Start, SMul);
870 getAddExpr(getZeroExtendExpr(Start, WideTy),
871 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
872 getSignExtendExpr(Step, WideTy)));
873 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
874 // Return the expression with the addrec on the outside.
875 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
876 getSignExtendExpr(Step, Ty),
882 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
883 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty, this);
887 SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op,
889 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
890 "This is not an extending conversion!");
891 assert(isSCEVable(Ty) &&
892 "This is not a conversion to a SCEVable type!");
893 Ty = getEffectiveSCEVType(Ty);
895 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
896 const Type *IntTy = getEffectiveSCEVType(Ty);
897 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
898 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
899 return getUnknown(C);
902 // sext(sext(x)) --> sext(x)
903 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
904 return getSignExtendExpr(SS->getOperand(), Ty);
906 // If the input value is a chrec scev, and we can prove that the value
907 // did not overflow the old, smaller, value, we can sign extend all of the
908 // operands (often constants). This allows analysis of something like
909 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
910 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
911 if (AR->isAffine()) {
912 // Check whether the backedge-taken count is SCEVCouldNotCompute.
913 // Note that this serves two purposes: It filters out loops that are
914 // simply not analyzable, and it covers the case where this code is
915 // being called from within backedge-taken count analysis, such that
916 // attempting to ask for the backedge-taken count would likely result
917 // in infinite recursion. In the later case, the analysis code will
918 // cope with a conservative value, and it will take care to purge
919 // that value once it has finished.
920 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
921 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
922 // Manually compute the final value for AR, checking for
924 SCEVHandle Start = AR->getStart();
925 SCEVHandle Step = AR->getStepRecurrence(*this);
927 // Check whether the backedge-taken count can be losslessly casted to
928 // the addrec's type. The count is always unsigned.
929 SCEVHandle CastedMaxBECount =
930 getTruncateOrZeroExtend(MaxBECount, Start->getType());
931 SCEVHandle RecastedMaxBECount =
932 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
933 if (MaxBECount == RecastedMaxBECount) {
935 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
936 // Check whether Start+Step*MaxBECount has no signed overflow.
938 getMulExpr(CastedMaxBECount,
939 getTruncateOrSignExtend(Step, Start->getType()));
940 SCEVHandle Add = getAddExpr(Start, SMul);
941 SCEVHandle OperandExtendedAdd =
942 getAddExpr(getSignExtendExpr(Start, WideTy),
943 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
944 getSignExtendExpr(Step, WideTy)));
945 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
946 // Return the expression with the addrec on the outside.
947 return getAddRecExpr(getSignExtendExpr(Start, Ty),
948 getSignExtendExpr(Step, Ty),
954 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
955 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty, this);
959 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
960 /// unspecified bits out to the given type.
962 SCEVHandle ScalarEvolution::getAnyExtendExpr(const SCEVHandle &Op,
964 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
965 "This is not an extending conversion!");
966 assert(isSCEVable(Ty) &&
967 "This is not a conversion to a SCEVable type!");
968 Ty = getEffectiveSCEVType(Ty);
970 // Sign-extend negative constants.
971 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
972 if (SC->getValue()->getValue().isNegative())
973 return getSignExtendExpr(Op, Ty);
975 // Peel off a truncate cast.
976 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
977 SCEVHandle NewOp = T->getOperand();
978 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
979 return getAnyExtendExpr(NewOp, Ty);
980 return getTruncateOrNoop(NewOp, Ty);
983 // Next try a zext cast. If the cast is folded, use it.
984 SCEVHandle ZExt = getZeroExtendExpr(Op, Ty);
985 if (!isa<SCEVZeroExtendExpr>(ZExt))
988 // Next try a sext cast. If the cast is folded, use it.
989 SCEVHandle SExt = getSignExtendExpr(Op, Ty);
990 if (!isa<SCEVSignExtendExpr>(SExt))
993 // If the expression is obviously signed, use the sext cast value.
994 if (isa<SCEVSMaxExpr>(Op))
997 // Absent any other information, use the zext cast value.
1001 /// CollectAddOperandsWithScales - Process the given Ops list, which is
1002 /// a list of operands to be added under the given scale, update the given
1003 /// map. This is a helper function for getAddRecExpr. As an example of
1004 /// what it does, given a sequence of operands that would form an add
1005 /// expression like this:
1007 /// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1009 /// where A and B are constants, update the map with these values:
1011 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1013 /// and add 13 + A*B*29 to AccumulatedConstant.
1014 /// This will allow getAddRecExpr to produce this:
1016 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1018 /// This form often exposes folding opportunities that are hidden in
1019 /// the original operand list.
1021 /// Return true iff it appears that any interesting folding opportunities
1022 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
1023 /// the common case where no interesting opportunities are present, and
1024 /// is also used as a check to avoid infinite recursion.
1027 CollectAddOperandsWithScales(DenseMap<SCEVHandle, APInt> &M,
1028 SmallVector<SCEVHandle, 8> &NewOps,
1029 APInt &AccumulatedConstant,
1030 const SmallVectorImpl<SCEVHandle> &Ops,
1032 ScalarEvolution &SE) {
1033 bool Interesting = false;
1035 // Iterate over the add operands.
1036 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1037 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1038 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1040 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1041 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1042 // A multiplication of a constant with another add; recurse.
1044 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1045 cast<SCEVAddExpr>(Mul->getOperand(1))
1049 // A multiplication of a constant with some other value. Update
1051 SmallVector<SCEVHandle, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1052 SCEVHandle Key = SE.getMulExpr(MulOps);
1053 std::pair<DenseMap<SCEVHandle, APInt>::iterator, bool> Pair =
1054 M.insert(std::make_pair(Key, APInt()));
1056 Pair.first->second = NewScale;
1057 NewOps.push_back(Pair.first->first);
1059 Pair.first->second += NewScale;
1060 // The map already had an entry for this value, which may indicate
1061 // a folding opportunity.
1065 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1066 // Pull a buried constant out to the outside.
1067 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1069 AccumulatedConstant += Scale * C->getValue()->getValue();
1071 // An ordinary operand. Update the map.
1072 std::pair<DenseMap<SCEVHandle, APInt>::iterator, bool> Pair =
1073 M.insert(std::make_pair(Ops[i], APInt()));
1075 Pair.first->second = Scale;
1076 NewOps.push_back(Pair.first->first);
1078 Pair.first->second += Scale;
1079 // The map already had an entry for this value, which may indicate
1080 // a folding opportunity.
1090 struct APIntCompare {
1091 bool operator()(const APInt &LHS, const APInt &RHS) const {
1092 return LHS.ult(RHS);
1097 /// getAddExpr - Get a canonical add expression, or something simpler if
1099 SCEVHandle ScalarEvolution::getAddExpr(SmallVectorImpl<SCEVHandle> &Ops) {
1100 assert(!Ops.empty() && "Cannot get empty add!");
1101 if (Ops.size() == 1) return Ops[0];
1103 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1104 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1105 getEffectiveSCEVType(Ops[0]->getType()) &&
1106 "SCEVAddExpr operand types don't match!");
1109 // Sort by complexity, this groups all similar expression types together.
1110 GroupByComplexity(Ops, LI);
1112 // If there are any constants, fold them together.
1114 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1116 assert(Idx < Ops.size());
1117 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1118 // We found two constants, fold them together!
1119 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1120 RHSC->getValue()->getValue());
1121 if (Ops.size() == 2) return Ops[0];
1122 Ops.erase(Ops.begin()+1); // Erase the folded element
1123 LHSC = cast<SCEVConstant>(Ops[0]);
1126 // If we are left with a constant zero being added, strip it off.
1127 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1128 Ops.erase(Ops.begin());
1133 if (Ops.size() == 1) return Ops[0];
1135 // Okay, check to see if the same value occurs in the operand list twice. If
1136 // so, merge them together into an multiply expression. Since we sorted the
1137 // list, these values are required to be adjacent.
1138 const Type *Ty = Ops[0]->getType();
1139 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1140 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1141 // Found a match, merge the two values into a multiply, and add any
1142 // remaining values to the result.
1143 SCEVHandle Two = getIntegerSCEV(2, Ty);
1144 SCEVHandle Mul = getMulExpr(Ops[i], Two);
1145 if (Ops.size() == 2)
1147 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1149 return getAddExpr(Ops);
1152 // Check for truncates. If all the operands are truncated from the same
1153 // type, see if factoring out the truncate would permit the result to be
1154 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1155 // if the contents of the resulting outer trunc fold to something simple.
1156 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1157 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1158 const Type *DstType = Trunc->getType();
1159 const Type *SrcType = Trunc->getOperand()->getType();
1160 SmallVector<SCEVHandle, 8> LargeOps;
1162 // Check all the operands to see if they can be represented in the
1163 // source type of the truncate.
1164 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1165 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1166 if (T->getOperand()->getType() != SrcType) {
1170 LargeOps.push_back(T->getOperand());
1171 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1172 // This could be either sign or zero extension, but sign extension
1173 // is much more likely to be foldable here.
1174 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1175 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
1176 SmallVector<SCEVHandle, 8> LargeMulOps;
1177 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1178 if (const SCEVTruncateExpr *T =
1179 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1180 if (T->getOperand()->getType() != SrcType) {
1184 LargeMulOps.push_back(T->getOperand());
1185 } else if (const SCEVConstant *C =
1186 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1187 // This could be either sign or zero extension, but sign extension
1188 // is much more likely to be foldable here.
1189 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1196 LargeOps.push_back(getMulExpr(LargeMulOps));
1203 // Evaluate the expression in the larger type.
1204 SCEVHandle Fold = getAddExpr(LargeOps);
1205 // If it folds to something simple, use it. Otherwise, don't.
1206 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1207 return getTruncateExpr(Fold, DstType);
1211 // Skip past any other cast SCEVs.
1212 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1215 // If there are add operands they would be next.
1216 if (Idx < Ops.size()) {
1217 bool DeletedAdd = false;
1218 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
1219 // If we have an add, expand the add operands onto the end of the operands
1221 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1222 Ops.erase(Ops.begin()+Idx);
1226 // If we deleted at least one add, we added operands to the end of the list,
1227 // and they are not necessarily sorted. Recurse to resort and resimplify
1228 // any operands we just aquired.
1230 return getAddExpr(Ops);
1233 // Skip over the add expression until we get to a multiply.
1234 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1237 // Check to see if there are any folding opportunities present with
1238 // operands multiplied by constant values.
1239 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1240 uint64_t BitWidth = getTypeSizeInBits(Ty);
1241 DenseMap<SCEVHandle, APInt> M;
1242 SmallVector<SCEVHandle, 8> NewOps;
1243 APInt AccumulatedConstant(BitWidth, 0);
1244 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1245 Ops, APInt(BitWidth, 1), *this)) {
1246 // Some interesting folding opportunity is present, so its worthwhile to
1247 // re-generate the operands list. Group the operands by constant scale,
1248 // to avoid multiplying by the same constant scale multiple times.
1249 std::map<APInt, SmallVector<SCEVHandle, 4>, APIntCompare> MulOpLists;
1250 for (SmallVector<SCEVHandle, 8>::iterator I = NewOps.begin(),
1251 E = NewOps.end(); I != E; ++I)
1252 MulOpLists[M.find(*I)->second].push_back(*I);
1253 // Re-generate the operands list.
1255 if (AccumulatedConstant != 0)
1256 Ops.push_back(getConstant(AccumulatedConstant));
1257 for (std::map<APInt, SmallVector<SCEVHandle, 4>, APIntCompare>::iterator I =
1258 MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
1260 Ops.push_back(getMulExpr(getConstant(I->first), getAddExpr(I->second)));
1262 return getIntegerSCEV(0, Ty);
1263 if (Ops.size() == 1)
1265 return getAddExpr(Ops);
1269 // If we are adding something to a multiply expression, make sure the
1270 // something is not already an operand of the multiply. If so, merge it into
1272 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
1273 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
1274 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
1275 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
1276 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
1277 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
1278 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1279 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
1280 if (Mul->getNumOperands() != 2) {
1281 // If the multiply has more than two operands, we must get the
1283 SmallVector<SCEVHandle, 4> MulOps(Mul->op_begin(), Mul->op_end());
1284 MulOps.erase(MulOps.begin()+MulOp);
1285 InnerMul = getMulExpr(MulOps);
1287 SCEVHandle One = getIntegerSCEV(1, Ty);
1288 SCEVHandle AddOne = getAddExpr(InnerMul, One);
1289 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
1290 if (Ops.size() == 2) return OuterMul;
1292 Ops.erase(Ops.begin()+AddOp);
1293 Ops.erase(Ops.begin()+Idx-1);
1295 Ops.erase(Ops.begin()+Idx);
1296 Ops.erase(Ops.begin()+AddOp-1);
1298 Ops.push_back(OuterMul);
1299 return getAddExpr(Ops);
1302 // Check this multiply against other multiplies being added together.
1303 for (unsigned OtherMulIdx = Idx+1;
1304 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1306 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
1307 // If MulOp occurs in OtherMul, we can fold the two multiplies
1309 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1310 OMulOp != e; ++OMulOp)
1311 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1312 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1313 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
1314 if (Mul->getNumOperands() != 2) {
1315 SmallVector<SCEVHandle, 4> MulOps(Mul->op_begin(), Mul->op_end());
1316 MulOps.erase(MulOps.begin()+MulOp);
1317 InnerMul1 = getMulExpr(MulOps);
1319 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1320 if (OtherMul->getNumOperands() != 2) {
1321 SmallVector<SCEVHandle, 4> MulOps(OtherMul->op_begin(),
1322 OtherMul->op_end());
1323 MulOps.erase(MulOps.begin()+OMulOp);
1324 InnerMul2 = getMulExpr(MulOps);
1326 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1327 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
1328 if (Ops.size() == 2) return OuterMul;
1329 Ops.erase(Ops.begin()+Idx);
1330 Ops.erase(Ops.begin()+OtherMulIdx-1);
1331 Ops.push_back(OuterMul);
1332 return getAddExpr(Ops);
1338 // If there are any add recurrences in the operands list, see if any other
1339 // added values are loop invariant. If so, we can fold them into the
1341 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1344 // Scan over all recurrences, trying to fold loop invariants into them.
1345 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1346 // Scan all of the other operands to this add and add them to the vector if
1347 // they are loop invariant w.r.t. the recurrence.
1348 SmallVector<SCEVHandle, 8> LIOps;
1349 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1350 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1351 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1352 LIOps.push_back(Ops[i]);
1353 Ops.erase(Ops.begin()+i);
1357 // If we found some loop invariants, fold them into the recurrence.
1358 if (!LIOps.empty()) {
1359 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
1360 LIOps.push_back(AddRec->getStart());
1362 SmallVector<SCEVHandle, 4> AddRecOps(AddRec->op_begin(),
1364 AddRecOps[0] = getAddExpr(LIOps);
1366 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
1367 // If all of the other operands were loop invariant, we are done.
1368 if (Ops.size() == 1) return NewRec;
1370 // Otherwise, add the folded AddRec by the non-liv parts.
1371 for (unsigned i = 0;; ++i)
1372 if (Ops[i] == AddRec) {
1376 return getAddExpr(Ops);
1379 // Okay, if there weren't any loop invariants to be folded, check to see if
1380 // there are multiple AddRec's with the same loop induction variable being
1381 // added together. If so, we can fold them.
1382 for (unsigned OtherIdx = Idx+1;
1383 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1384 if (OtherIdx != Idx) {
1385 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1386 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1387 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1388 SmallVector<SCEVHandle, 4> NewOps(AddRec->op_begin(), AddRec->op_end());
1389 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1390 if (i >= NewOps.size()) {
1391 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1392 OtherAddRec->op_end());
1395 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
1397 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
1399 if (Ops.size() == 2) return NewAddRec;
1401 Ops.erase(Ops.begin()+Idx);
1402 Ops.erase(Ops.begin()+OtherIdx-1);
1403 Ops.push_back(NewAddRec);
1404 return getAddExpr(Ops);
1408 // Otherwise couldn't fold anything into this recurrence. Move onto the
1412 // Okay, it looks like we really DO need an add expr. Check to see if we
1413 // already have one, otherwise create a new one.
1414 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
1415 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
1417 if (Result == 0) Result = new SCEVAddExpr(Ops, this);
1422 /// getMulExpr - Get a canonical multiply expression, or something simpler if
1424 SCEVHandle ScalarEvolution::getMulExpr(SmallVectorImpl<SCEVHandle> &Ops) {
1425 assert(!Ops.empty() && "Cannot get empty mul!");
1427 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1428 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1429 getEffectiveSCEVType(Ops[0]->getType()) &&
1430 "SCEVMulExpr operand types don't match!");
1433 // Sort by complexity, this groups all similar expression types together.
1434 GroupByComplexity(Ops, LI);
1436 // If there are any constants, fold them together.
1438 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1440 // C1*(C2+V) -> C1*C2 + C1*V
1441 if (Ops.size() == 2)
1442 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1443 if (Add->getNumOperands() == 2 &&
1444 isa<SCEVConstant>(Add->getOperand(0)))
1445 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1446 getMulExpr(LHSC, Add->getOperand(1)));
1450 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1451 // We found two constants, fold them together!
1452 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1453 RHSC->getValue()->getValue());
1454 Ops[0] = getConstant(Fold);
1455 Ops.erase(Ops.begin()+1); // Erase the folded element
1456 if (Ops.size() == 1) return Ops[0];
1457 LHSC = cast<SCEVConstant>(Ops[0]);
1460 // If we are left with a constant one being multiplied, strip it off.
1461 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1462 Ops.erase(Ops.begin());
1464 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1465 // If we have a multiply of zero, it will always be zero.
1470 // Skip over the add expression until we get to a multiply.
1471 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1474 if (Ops.size() == 1)
1477 // If there are mul operands inline them all into this expression.
1478 if (Idx < Ops.size()) {
1479 bool DeletedMul = false;
1480 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1481 // If we have an mul, expand the mul operands onto the end of the operands
1483 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1484 Ops.erase(Ops.begin()+Idx);
1488 // If we deleted at least one mul, we added operands to the end of the list,
1489 // and they are not necessarily sorted. Recurse to resort and resimplify
1490 // any operands we just aquired.
1492 return getMulExpr(Ops);
1495 // If there are any add recurrences in the operands list, see if any other
1496 // added values are loop invariant. If so, we can fold them into the
1498 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1501 // Scan over all recurrences, trying to fold loop invariants into them.
1502 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1503 // Scan all of the other operands to this mul and add them to the vector if
1504 // they are loop invariant w.r.t. the recurrence.
1505 SmallVector<SCEVHandle, 8> LIOps;
1506 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1507 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1508 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1509 LIOps.push_back(Ops[i]);
1510 Ops.erase(Ops.begin()+i);
1514 // If we found some loop invariants, fold them into the recurrence.
1515 if (!LIOps.empty()) {
1516 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
1517 SmallVector<SCEVHandle, 4> NewOps;
1518 NewOps.reserve(AddRec->getNumOperands());
1519 if (LIOps.size() == 1) {
1520 const SCEV *Scale = LIOps[0];
1521 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1522 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1524 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1525 SmallVector<SCEVHandle, 4> MulOps(LIOps.begin(), LIOps.end());
1526 MulOps.push_back(AddRec->getOperand(i));
1527 NewOps.push_back(getMulExpr(MulOps));
1531 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
1533 // If all of the other operands were loop invariant, we are done.
1534 if (Ops.size() == 1) return NewRec;
1536 // Otherwise, multiply the folded AddRec by the non-liv parts.
1537 for (unsigned i = 0;; ++i)
1538 if (Ops[i] == AddRec) {
1542 return getMulExpr(Ops);
1545 // Okay, if there weren't any loop invariants to be folded, check to see if
1546 // there are multiple AddRec's with the same loop induction variable being
1547 // multiplied together. If so, we can fold them.
1548 for (unsigned OtherIdx = Idx+1;
1549 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1550 if (OtherIdx != Idx) {
1551 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1552 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1553 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1554 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1555 SCEVHandle NewStart = getMulExpr(F->getStart(),
1557 SCEVHandle B = F->getStepRecurrence(*this);
1558 SCEVHandle D = G->getStepRecurrence(*this);
1559 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1562 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1564 if (Ops.size() == 2) return NewAddRec;
1566 Ops.erase(Ops.begin()+Idx);
1567 Ops.erase(Ops.begin()+OtherIdx-1);
1568 Ops.push_back(NewAddRec);
1569 return getMulExpr(Ops);
1573 // Otherwise couldn't fold anything into this recurrence. Move onto the
1577 // Okay, it looks like we really DO need an mul expr. Check to see if we
1578 // already have one, otherwise create a new one.
1579 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
1580 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1583 Result = new SCEVMulExpr(Ops, this);
1587 /// getUDivExpr - Get a canonical multiply expression, or something simpler if
1589 SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS,
1590 const SCEVHandle &RHS) {
1591 assert(getEffectiveSCEVType(LHS->getType()) ==
1592 getEffectiveSCEVType(RHS->getType()) &&
1593 "SCEVUDivExpr operand types don't match!");
1595 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1596 if (RHSC->getValue()->equalsInt(1))
1597 return LHS; // X udiv 1 --> x
1599 return getIntegerSCEV(0, LHS->getType()); // value is undefined
1601 // Determine if the division can be folded into the operands of
1603 // TODO: Generalize this to non-constants by using known-bits information.
1604 const Type *Ty = LHS->getType();
1605 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1606 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1607 // For non-power-of-two values, effectively round the value up to the
1608 // nearest power of two.
1609 if (!RHSC->getValue()->getValue().isPowerOf2())
1611 const IntegerType *ExtTy =
1612 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1613 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1614 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1615 if (const SCEVConstant *Step =
1616 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1617 if (!Step->getValue()->getValue()
1618 .urem(RHSC->getValue()->getValue()) &&
1619 getZeroExtendExpr(AR, ExtTy) ==
1620 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1621 getZeroExtendExpr(Step, ExtTy),
1623 SmallVector<SCEVHandle, 4> Operands;
1624 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1625 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1626 return getAddRecExpr(Operands, AR->getLoop());
1628 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1629 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1630 SmallVector<SCEVHandle, 4> Operands;
1631 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1632 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1633 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
1634 // Find an operand that's safely divisible.
1635 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1636 SCEVHandle Op = M->getOperand(i);
1637 SCEVHandle Div = getUDivExpr(Op, RHSC);
1638 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1639 const SmallVectorImpl<SCEVHandle> &MOperands = M->getOperands();
1640 Operands = SmallVector<SCEVHandle, 4>(MOperands.begin(),
1643 return getMulExpr(Operands);
1647 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
1648 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1649 SmallVector<SCEVHandle, 4> Operands;
1650 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1651 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1652 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1654 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1655 SCEVHandle Op = getUDivExpr(A->getOperand(i), RHS);
1656 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1658 Operands.push_back(Op);
1660 if (Operands.size() == A->getNumOperands())
1661 return getAddExpr(Operands);
1665 // Fold if both operands are constant.
1666 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1667 Constant *LHSCV = LHSC->getValue();
1668 Constant *RHSCV = RHSC->getValue();
1669 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
1673 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1674 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS, this);
1679 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1680 /// Simplify the expression as much as possible.
1681 SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
1682 const SCEVHandle &Step, const Loop *L) {
1683 SmallVector<SCEVHandle, 4> Operands;
1684 Operands.push_back(Start);
1685 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1686 if (StepChrec->getLoop() == L) {
1687 Operands.insert(Operands.end(), StepChrec->op_begin(),
1688 StepChrec->op_end());
1689 return getAddRecExpr(Operands, L);
1692 Operands.push_back(Step);
1693 return getAddRecExpr(Operands, L);
1696 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1697 /// Simplify the expression as much as possible.
1698 SCEVHandle ScalarEvolution::getAddRecExpr(SmallVectorImpl<SCEVHandle> &Operands,
1700 if (Operands.size() == 1) return Operands[0];
1702 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1703 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1704 getEffectiveSCEVType(Operands[0]->getType()) &&
1705 "SCEVAddRecExpr operand types don't match!");
1708 if (Operands.back()->isZero()) {
1709 Operands.pop_back();
1710 return getAddRecExpr(Operands, L); // {X,+,0} --> X
1713 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1714 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1715 const Loop* NestedLoop = NestedAR->getLoop();
1716 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1717 SmallVector<SCEVHandle, 4> NestedOperands(NestedAR->op_begin(),
1718 NestedAR->op_end());
1719 SCEVHandle NestedARHandle(NestedAR);
1720 Operands[0] = NestedAR->getStart();
1721 NestedOperands[0] = getAddRecExpr(Operands, L);
1722 return getAddRecExpr(NestedOperands, NestedLoop);
1726 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
1727 SCEVAddRecExpr *&Result = (*SCEVAddRecExprs)[std::make_pair(L, SCEVOps)];
1728 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L, this);
1732 SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1733 const SCEVHandle &RHS) {
1734 SmallVector<SCEVHandle, 2> Ops;
1737 return getSMaxExpr(Ops);
1741 ScalarEvolution::getSMaxExpr(SmallVectorImpl<SCEVHandle> &Ops) {
1742 assert(!Ops.empty() && "Cannot get empty smax!");
1743 if (Ops.size() == 1) return Ops[0];
1745 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1746 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1747 getEffectiveSCEVType(Ops[0]->getType()) &&
1748 "SCEVSMaxExpr operand types don't match!");
1751 // Sort by complexity, this groups all similar expression types together.
1752 GroupByComplexity(Ops, LI);
1754 // If there are any constants, fold them together.
1756 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1758 assert(Idx < Ops.size());
1759 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1760 // We found two constants, fold them together!
1761 ConstantInt *Fold = ConstantInt::get(
1762 APIntOps::smax(LHSC->getValue()->getValue(),
1763 RHSC->getValue()->getValue()));
1764 Ops[0] = getConstant(Fold);
1765 Ops.erase(Ops.begin()+1); // Erase the folded element
1766 if (Ops.size() == 1) return Ops[0];
1767 LHSC = cast<SCEVConstant>(Ops[0]);
1770 // If we are left with a constant -inf, strip it off.
1771 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1772 Ops.erase(Ops.begin());
1777 if (Ops.size() == 1) return Ops[0];
1779 // Find the first SMax
1780 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1783 // Check to see if one of the operands is an SMax. If so, expand its operands
1784 // onto our operand list, and recurse to simplify.
1785 if (Idx < Ops.size()) {
1786 bool DeletedSMax = false;
1787 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1788 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1789 Ops.erase(Ops.begin()+Idx);
1794 return getSMaxExpr(Ops);
1797 // Okay, check to see if the same value occurs in the operand list twice. If
1798 // so, delete one. Since we sorted the list, these values are required to
1800 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1801 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1802 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1806 if (Ops.size() == 1) return Ops[0];
1808 assert(!Ops.empty() && "Reduced smax down to nothing!");
1810 // Okay, it looks like we really DO need an smax expr. Check to see if we
1811 // already have one, otherwise create a new one.
1812 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
1813 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1815 if (Result == 0) Result = new SCEVSMaxExpr(Ops, this);
1819 SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1820 const SCEVHandle &RHS) {
1821 SmallVector<SCEVHandle, 2> Ops;
1824 return getUMaxExpr(Ops);
1828 ScalarEvolution::getUMaxExpr(SmallVectorImpl<SCEVHandle> &Ops) {
1829 assert(!Ops.empty() && "Cannot get empty umax!");
1830 if (Ops.size() == 1) return Ops[0];
1832 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1833 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1834 getEffectiveSCEVType(Ops[0]->getType()) &&
1835 "SCEVUMaxExpr operand types don't match!");
1838 // Sort by complexity, this groups all similar expression types together.
1839 GroupByComplexity(Ops, LI);
1841 // If there are any constants, fold them together.
1843 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1845 assert(Idx < Ops.size());
1846 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1847 // We found two constants, fold them together!
1848 ConstantInt *Fold = ConstantInt::get(
1849 APIntOps::umax(LHSC->getValue()->getValue(),
1850 RHSC->getValue()->getValue()));
1851 Ops[0] = getConstant(Fold);
1852 Ops.erase(Ops.begin()+1); // Erase the folded element
1853 if (Ops.size() == 1) return Ops[0];
1854 LHSC = cast<SCEVConstant>(Ops[0]);
1857 // If we are left with a constant zero, strip it off.
1858 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1859 Ops.erase(Ops.begin());
1864 if (Ops.size() == 1) return Ops[0];
1866 // Find the first UMax
1867 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1870 // Check to see if one of the operands is a UMax. If so, expand its operands
1871 // onto our operand list, and recurse to simplify.
1872 if (Idx < Ops.size()) {
1873 bool DeletedUMax = false;
1874 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1875 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1876 Ops.erase(Ops.begin()+Idx);
1881 return getUMaxExpr(Ops);
1884 // Okay, check to see if the same value occurs in the operand list twice. If
1885 // so, delete one. Since we sorted the list, these values are required to
1887 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1888 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1889 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1893 if (Ops.size() == 1) return Ops[0];
1895 assert(!Ops.empty() && "Reduced umax down to nothing!");
1897 // Okay, it looks like we really DO need a umax expr. Check to see if we
1898 // already have one, otherwise create a new one.
1899 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
1900 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1902 if (Result == 0) Result = new SCEVUMaxExpr(Ops, this);
1906 SCEVHandle ScalarEvolution::getUnknown(Value *V) {
1907 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1908 return getConstant(CI);
1909 if (isa<ConstantPointerNull>(V))
1910 return getIntegerSCEV(0, V->getType());
1911 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1912 if (Result == 0) Result = new SCEVUnknown(V, this);
1916 //===----------------------------------------------------------------------===//
1917 // Basic SCEV Analysis and PHI Idiom Recognition Code
1920 /// isSCEVable - Test if values of the given type are analyzable within
1921 /// the SCEV framework. This primarily includes integer types, and it
1922 /// can optionally include pointer types if the ScalarEvolution class
1923 /// has access to target-specific information.
1924 bool ScalarEvolution::isSCEVable(const Type *Ty) const {
1925 // Integers are always SCEVable.
1926 if (Ty->isInteger())
1929 // Pointers are SCEVable if TargetData information is available
1930 // to provide pointer size information.
1931 if (isa<PointerType>(Ty))
1934 // Otherwise it's not SCEVable.
1938 /// getTypeSizeInBits - Return the size in bits of the specified type,
1939 /// for which isSCEVable must return true.
1940 uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
1941 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1943 // If we have a TargetData, use it!
1945 return TD->getTypeSizeInBits(Ty);
1947 // Otherwise, we support only integer types.
1948 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1949 return Ty->getPrimitiveSizeInBits();
1952 /// getEffectiveSCEVType - Return a type with the same bitwidth as
1953 /// the given type and which represents how SCEV will treat the given
1954 /// type, for which isSCEVable must return true. For pointer types,
1955 /// this is the pointer-sized integer type.
1956 const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
1957 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1959 if (Ty->isInteger())
1962 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1963 return TD->getIntPtrType();
1966 SCEVHandle ScalarEvolution::getCouldNotCompute() {
1967 return CouldNotCompute;
1970 /// hasSCEV - Return true if the SCEV for this value has already been
1972 bool ScalarEvolution::hasSCEV(Value *V) const {
1973 return Scalars.count(V);
1976 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1977 /// expression and create a new one.
1978 SCEVHandle ScalarEvolution::getSCEV(Value *V) {
1979 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
1981 std::map<SCEVCallbackVH, SCEVHandle>::iterator I = Scalars.find(V);
1982 if (I != Scalars.end()) return I->second;
1983 SCEVHandle S = createSCEV(V);
1984 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
1988 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
1989 /// specified signed integer value and return a SCEV for the constant.
1990 SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1991 Ty = getEffectiveSCEVType(Ty);
1994 C = Constant::getNullValue(Ty);
1995 else if (Ty->isFloatingPoint())
1996 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1997 APFloat::IEEEdouble, Val));
1999 C = ConstantInt::get(Ty, Val);
2000 return getUnknown(C);
2003 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2005 SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
2006 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2007 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
2009 const Type *Ty = V->getType();
2010 Ty = getEffectiveSCEVType(Ty);
2011 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
2014 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
2015 SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
2016 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2017 return getUnknown(ConstantExpr::getNot(VC->getValue()));
2019 const Type *Ty = V->getType();
2020 Ty = getEffectiveSCEVType(Ty);
2021 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
2022 return getMinusSCEV(AllOnes, V);
2025 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2027 SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
2028 const SCEVHandle &RHS) {
2030 return getAddExpr(LHS, getNegativeSCEV(RHS));
2033 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2034 /// input value to the specified type. If the type must be extended, it is zero
2037 ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
2039 const Type *SrcTy = V->getType();
2040 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2041 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2042 "Cannot truncate or zero extend with non-integer arguments!");
2043 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2044 return V; // No conversion
2045 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2046 return getTruncateExpr(V, Ty);
2047 return getZeroExtendExpr(V, Ty);
2050 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2051 /// input value to the specified type. If the type must be extended, it is sign
2054 ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
2056 const Type *SrcTy = V->getType();
2057 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2058 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2059 "Cannot truncate or zero extend with non-integer arguments!");
2060 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2061 return V; // No conversion
2062 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2063 return getTruncateExpr(V, Ty);
2064 return getSignExtendExpr(V, Ty);
2067 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2068 /// input value to the specified type. If the type must be extended, it is zero
2069 /// extended. The conversion must not be narrowing.
2071 ScalarEvolution::getNoopOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
2072 const Type *SrcTy = V->getType();
2073 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2074 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2075 "Cannot noop or zero extend with non-integer arguments!");
2076 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2077 "getNoopOrZeroExtend cannot truncate!");
2078 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2079 return V; // No conversion
2080 return getZeroExtendExpr(V, Ty);
2083 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2084 /// input value to the specified type. If the type must be extended, it is sign
2085 /// extended. The conversion must not be narrowing.
2087 ScalarEvolution::getNoopOrSignExtend(const SCEVHandle &V, const Type *Ty) {
2088 const Type *SrcTy = V->getType();
2089 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2090 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2091 "Cannot noop or sign extend with non-integer arguments!");
2092 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2093 "getNoopOrSignExtend cannot truncate!");
2094 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2095 return V; // No conversion
2096 return getSignExtendExpr(V, Ty);
2099 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2100 /// the input value to the specified type. If the type must be extended,
2101 /// it is extended with unspecified bits. The conversion must not be
2104 ScalarEvolution::getNoopOrAnyExtend(const SCEVHandle &V, const Type *Ty) {
2105 const Type *SrcTy = V->getType();
2106 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2107 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2108 "Cannot noop or any extend with non-integer arguments!");
2109 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2110 "getNoopOrAnyExtend cannot truncate!");
2111 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2112 return V; // No conversion
2113 return getAnyExtendExpr(V, Ty);
2116 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2117 /// input value to the specified type. The conversion must not be widening.
2119 ScalarEvolution::getTruncateOrNoop(const SCEVHandle &V, const Type *Ty) {
2120 const Type *SrcTy = V->getType();
2121 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2122 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2123 "Cannot truncate or noop with non-integer arguments!");
2124 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2125 "getTruncateOrNoop cannot extend!");
2126 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2127 return V; // No conversion
2128 return getTruncateExpr(V, Ty);
2131 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2132 /// the types using zero-extension, and then perform a umax operation
2134 SCEVHandle ScalarEvolution::getUMaxFromMismatchedTypes(const SCEVHandle &LHS,
2135 const SCEVHandle &RHS) {
2136 SCEVHandle PromotedLHS = LHS;
2137 SCEVHandle PromotedRHS = RHS;
2139 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2140 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2142 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2144 return getUMaxExpr(PromotedLHS, PromotedRHS);
2147 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
2148 /// the specified instruction and replaces any references to the symbolic value
2149 /// SymName with the specified value. This is used during PHI resolution.
2150 void ScalarEvolution::
2151 ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
2152 const SCEVHandle &NewVal) {
2153 std::map<SCEVCallbackVH, SCEVHandle>::iterator SI =
2154 Scalars.find(SCEVCallbackVH(I, this));
2155 if (SI == Scalars.end()) return;
2158 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
2159 if (NV == SI->second) return; // No change.
2161 SI->second = NV; // Update the scalars map!
2163 // Any instruction values that use this instruction might also need to be
2165 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2167 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
2170 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2171 /// a loop header, making it a potential recurrence, or it doesn't.
2173 SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
2174 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
2175 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2176 if (L->getHeader() == PN->getParent()) {
2177 // If it lives in the loop header, it has two incoming values, one
2178 // from outside the loop, and one from inside.
2179 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2180 unsigned BackEdge = IncomingEdge^1;
2182 // While we are analyzing this PHI node, handle its value symbolically.
2183 SCEVHandle SymbolicName = getUnknown(PN);
2184 assert(Scalars.find(PN) == Scalars.end() &&
2185 "PHI node already processed?");
2186 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
2188 // Using this symbolic name for the PHI, analyze the value coming around
2190 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
2192 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2193 // has a special value for the first iteration of the loop.
2195 // If the value coming around the backedge is an add with the symbolic
2196 // value we just inserted, then we found a simple induction variable!
2197 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
2198 // If there is a single occurrence of the symbolic value, replace it
2199 // with a recurrence.
2200 unsigned FoundIndex = Add->getNumOperands();
2201 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2202 if (Add->getOperand(i) == SymbolicName)
2203 if (FoundIndex == e) {
2208 if (FoundIndex != Add->getNumOperands()) {
2209 // Create an add with everything but the specified operand.
2210 SmallVector<SCEVHandle, 8> Ops;
2211 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2212 if (i != FoundIndex)
2213 Ops.push_back(Add->getOperand(i));
2214 SCEVHandle Accum = getAddExpr(Ops);
2216 // This is not a valid addrec if the step amount is varying each
2217 // loop iteration, but is not itself an addrec in this loop.
2218 if (Accum->isLoopInvariant(L) ||
2219 (isa<SCEVAddRecExpr>(Accum) &&
2220 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
2221 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
2222 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L);
2224 // Okay, for the entire analysis of this edge we assumed the PHI
2225 // to be symbolic. We now need to go back and update all of the
2226 // entries for the scalars that use the PHI (except for the PHI
2227 // itself) to use the new analyzed value instead of the "symbolic"
2229 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2233 } else if (const SCEVAddRecExpr *AddRec =
2234 dyn_cast<SCEVAddRecExpr>(BEValue)) {
2235 // Otherwise, this could be a loop like this:
2236 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2237 // In this case, j = {1,+,1} and BEValue is j.
2238 // Because the other in-value of i (0) fits the evolution of BEValue
2239 // i really is an addrec evolution.
2240 if (AddRec->getLoop() == L && AddRec->isAffine()) {
2241 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
2243 // If StartVal = j.start - j.stride, we can use StartVal as the
2244 // initial step of the addrec evolution.
2245 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
2246 AddRec->getOperand(1))) {
2247 SCEVHandle PHISCEV =
2248 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
2250 // Okay, for the entire analysis of this edge we assumed the PHI
2251 // to be symbolic. We now need to go back and update all of the
2252 // entries for the scalars that use the PHI (except for the PHI
2253 // itself) to use the new analyzed value instead of the "symbolic"
2255 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2261 return SymbolicName;
2264 // If it's not a loop phi, we can't handle it yet.
2265 return getUnknown(PN);
2268 /// createNodeForGEP - Expand GEP instructions into add and multiply
2269 /// operations. This allows them to be analyzed by regular SCEV code.
2271 SCEVHandle ScalarEvolution::createNodeForGEP(User *GEP) {
2273 const Type *IntPtrTy = TD->getIntPtrType();
2274 Value *Base = GEP->getOperand(0);
2275 // Don't attempt to analyze GEPs over unsized objects.
2276 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2277 return getUnknown(GEP);
2278 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
2279 gep_type_iterator GTI = gep_type_begin(GEP);
2280 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2284 // Compute the (potentially symbolic) offset in bytes for this index.
2285 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2286 // For a struct, add the member offset.
2287 const StructLayout &SL = *TD->getStructLayout(STy);
2288 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2289 uint64_t Offset = SL.getElementOffset(FieldNo);
2290 TotalOffset = getAddExpr(TotalOffset,
2291 getIntegerSCEV(Offset, IntPtrTy));
2293 // For an array, add the element offset, explicitly scaled.
2294 SCEVHandle LocalOffset = getSCEV(Index);
2295 if (!isa<PointerType>(LocalOffset->getType()))
2296 // Getelementptr indicies are signed.
2297 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2300 getMulExpr(LocalOffset,
2301 getIntegerSCEV(TD->getTypeAllocSize(*GTI),
2303 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2306 return getAddExpr(getSCEV(Base), TotalOffset);
2309 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2310 /// guaranteed to end in (at every loop iteration). It is, at the same time,
2311 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2312 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
2314 ScalarEvolution::GetMinTrailingZeros(const SCEVHandle &S) {
2315 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2316 return C->getValue()->getValue().countTrailingZeros();
2318 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
2319 return std::min(GetMinTrailingZeros(T->getOperand()),
2320 (uint32_t)getTypeSizeInBits(T->getType()));
2322 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
2323 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2324 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2325 getTypeSizeInBits(E->getType()) : OpRes;
2328 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
2329 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2330 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2331 getTypeSizeInBits(E->getType()) : OpRes;
2334 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
2335 // The result is the min of all operands results.
2336 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2337 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2338 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2342 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
2343 // The result is the sum of all operands results.
2344 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2345 uint32_t BitWidth = getTypeSizeInBits(M->getType());
2346 for (unsigned i = 1, e = M->getNumOperands();
2347 SumOpRes != BitWidth && i != e; ++i)
2348 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
2353 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
2354 // The result is the min of all operands results.
2355 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2356 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2357 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2361 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
2362 // The result is the min of all operands results.
2363 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2364 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2365 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2369 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
2370 // The result is the min of all operands results.
2371 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2372 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2373 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2377 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2378 // For a SCEVUnknown, ask ValueTracking.
2379 unsigned BitWidth = getTypeSizeInBits(U->getType());
2380 APInt Mask = APInt::getAllOnesValue(BitWidth);
2381 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2382 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2383 return Zeros.countTrailingOnes();
2391 ScalarEvolution::GetMinLeadingZeros(const SCEVHandle &S) {
2392 // TODO: Handle other SCEV expression types here.
2394 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2395 return C->getValue()->getValue().countLeadingZeros();
2397 if (const SCEVZeroExtendExpr *C = dyn_cast<SCEVZeroExtendExpr>(S)) {
2398 // A zero-extension cast adds zero bits.
2399 return GetMinLeadingZeros(C->getOperand()) +
2400 (getTypeSizeInBits(C->getType()) -
2401 getTypeSizeInBits(C->getOperand()->getType()));
2404 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2405 // For a SCEVUnknown, ask ValueTracking.
2406 unsigned BitWidth = getTypeSizeInBits(U->getType());
2407 APInt Mask = APInt::getAllOnesValue(BitWidth);
2408 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2409 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
2410 return Zeros.countLeadingOnes();
2417 ScalarEvolution::GetMinSignBits(const SCEVHandle &S) {
2418 // TODO: Handle other SCEV expression types here.
2420 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
2421 const APInt &A = C->getValue()->getValue();
2422 return A.isNegative() ? A.countLeadingOnes() :
2423 A.countLeadingZeros();
2426 if (const SCEVSignExtendExpr *C = dyn_cast<SCEVSignExtendExpr>(S)) {
2427 // A sign-extension cast adds sign bits.
2428 return GetMinSignBits(C->getOperand()) +
2429 (getTypeSizeInBits(C->getType()) -
2430 getTypeSizeInBits(C->getOperand()->getType()));
2433 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2434 // For a SCEVUnknown, ask ValueTracking.
2435 return ComputeNumSignBits(U->getValue(), TD);
2441 /// createSCEV - We know that there is no SCEV for the specified value.
2442 /// Analyze the expression.
2444 SCEVHandle ScalarEvolution::createSCEV(Value *V) {
2445 if (!isSCEVable(V->getType()))
2446 return getUnknown(V);
2448 unsigned Opcode = Instruction::UserOp1;
2449 if (Instruction *I = dyn_cast<Instruction>(V))
2450 Opcode = I->getOpcode();
2451 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2452 Opcode = CE->getOpcode();
2454 return getUnknown(V);
2456 User *U = cast<User>(V);
2458 case Instruction::Add:
2459 return getAddExpr(getSCEV(U->getOperand(0)),
2460 getSCEV(U->getOperand(1)));
2461 case Instruction::Mul:
2462 return getMulExpr(getSCEV(U->getOperand(0)),
2463 getSCEV(U->getOperand(1)));
2464 case Instruction::UDiv:
2465 return getUDivExpr(getSCEV(U->getOperand(0)),
2466 getSCEV(U->getOperand(1)));
2467 case Instruction::Sub:
2468 return getMinusSCEV(getSCEV(U->getOperand(0)),
2469 getSCEV(U->getOperand(1)));
2470 case Instruction::And:
2471 // For an expression like x&255 that merely masks off the high bits,
2472 // use zext(trunc(x)) as the SCEV expression.
2473 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2474 if (CI->isNullValue())
2475 return getSCEV(U->getOperand(1));
2476 if (CI->isAllOnesValue())
2477 return getSCEV(U->getOperand(0));
2478 const APInt &A = CI->getValue();
2480 // Instcombine's ShrinkDemandedConstant may strip bits out of
2481 // constants, obscuring what would otherwise be a low-bits mask.
2482 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2483 // knew about to reconstruct a low-bits mask value.
2484 unsigned LZ = A.countLeadingZeros();
2485 unsigned BitWidth = A.getBitWidth();
2486 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2487 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2488 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2490 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2492 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
2494 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
2495 IntegerType::get(BitWidth - LZ)),
2500 case Instruction::Or:
2501 // If the RHS of the Or is a constant, we may have something like:
2502 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2503 // optimizations will transparently handle this case.
2505 // In order for this transformation to be safe, the LHS must be of the
2506 // form X*(2^n) and the Or constant must be less than 2^n.
2507 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2508 SCEVHandle LHS = getSCEV(U->getOperand(0));
2509 const APInt &CIVal = CI->getValue();
2510 if (GetMinTrailingZeros(LHS) >=
2511 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
2512 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
2515 case Instruction::Xor:
2516 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2517 // If the RHS of the xor is a signbit, then this is just an add.
2518 // Instcombine turns add of signbit into xor as a strength reduction step.
2519 if (CI->getValue().isSignBit())
2520 return getAddExpr(getSCEV(U->getOperand(0)),
2521 getSCEV(U->getOperand(1)));
2523 // If the RHS of xor is -1, then this is a not operation.
2524 if (CI->isAllOnesValue())
2525 return getNotSCEV(getSCEV(U->getOperand(0)));
2527 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2528 // This is a variant of the check for xor with -1, and it handles
2529 // the case where instcombine has trimmed non-demanded bits out
2530 // of an xor with -1.
2531 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2532 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2533 if (BO->getOpcode() == Instruction::And &&
2534 LCI->getValue() == CI->getValue())
2535 if (const SCEVZeroExtendExpr *Z =
2536 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
2537 const Type *UTy = U->getType();
2538 SCEVHandle Z0 = Z->getOperand();
2539 const Type *Z0Ty = Z0->getType();
2540 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
2542 // If C is a low-bits mask, the zero extend is zerving to
2543 // mask off the high bits. Complement the operand and
2544 // re-apply the zext.
2545 if (APIntOps::isMask(Z0TySize, CI->getValue()))
2546 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
2548 // If C is a single bit, it may be in the sign-bit position
2549 // before the zero-extend. In this case, represent the xor
2550 // using an add, which is equivalent, and re-apply the zext.
2551 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
2552 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
2554 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
2560 case Instruction::Shl:
2561 // Turn shift left of a constant amount into a multiply.
2562 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2563 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2564 Constant *X = ConstantInt::get(
2565 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
2566 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
2570 case Instruction::LShr:
2571 // Turn logical shift right of a constant into a unsigned divide.
2572 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2573 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2574 Constant *X = ConstantInt::get(
2575 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
2576 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
2580 case Instruction::AShr:
2581 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2582 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2583 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2584 if (L->getOpcode() == Instruction::Shl &&
2585 L->getOperand(1) == U->getOperand(1)) {
2586 unsigned BitWidth = getTypeSizeInBits(U->getType());
2587 uint64_t Amt = BitWidth - CI->getZExtValue();
2588 if (Amt == BitWidth)
2589 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2591 return getIntegerSCEV(0, U->getType()); // value is undefined
2593 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
2594 IntegerType::get(Amt)),
2599 case Instruction::Trunc:
2600 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
2602 case Instruction::ZExt:
2603 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
2605 case Instruction::SExt:
2606 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
2608 case Instruction::BitCast:
2609 // BitCasts are no-op casts so we just eliminate the cast.
2610 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
2611 return getSCEV(U->getOperand(0));
2614 case Instruction::IntToPtr:
2615 if (!TD) break; // Without TD we can't analyze pointers.
2616 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2617 TD->getIntPtrType());
2619 case Instruction::PtrToInt:
2620 if (!TD) break; // Without TD we can't analyze pointers.
2621 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2624 case Instruction::GetElementPtr:
2625 if (!TD) break; // Without TD we can't analyze pointers.
2626 return createNodeForGEP(U);
2628 case Instruction::PHI:
2629 return createNodeForPHI(cast<PHINode>(U));
2631 case Instruction::Select:
2632 // This could be a smax or umax that was lowered earlier.
2633 // Try to recover it.
2634 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2635 Value *LHS = ICI->getOperand(0);
2636 Value *RHS = ICI->getOperand(1);
2637 switch (ICI->getPredicate()) {
2638 case ICmpInst::ICMP_SLT:
2639 case ICmpInst::ICMP_SLE:
2640 std::swap(LHS, RHS);
2642 case ICmpInst::ICMP_SGT:
2643 case ICmpInst::ICMP_SGE:
2644 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2645 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
2646 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2647 // ~smax(~x, ~y) == smin(x, y).
2648 return getNotSCEV(getSMaxExpr(
2649 getNotSCEV(getSCEV(LHS)),
2650 getNotSCEV(getSCEV(RHS))));
2652 case ICmpInst::ICMP_ULT:
2653 case ICmpInst::ICMP_ULE:
2654 std::swap(LHS, RHS);
2656 case ICmpInst::ICMP_UGT:
2657 case ICmpInst::ICMP_UGE:
2658 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2659 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
2660 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2661 // ~umax(~x, ~y) == umin(x, y)
2662 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)),
2663 getNotSCEV(getSCEV(RHS))));
2665 case ICmpInst::ICMP_NE:
2666 // n != 0 ? n : 1 -> umax(n, 1)
2667 if (LHS == U->getOperand(1) &&
2668 isa<ConstantInt>(U->getOperand(2)) &&
2669 cast<ConstantInt>(U->getOperand(2))->isOne() &&
2670 isa<ConstantInt>(RHS) &&
2671 cast<ConstantInt>(RHS)->isZero())
2672 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
2674 case ICmpInst::ICMP_EQ:
2675 // n == 0 ? 1 : n -> umax(n, 1)
2676 if (LHS == U->getOperand(2) &&
2677 isa<ConstantInt>(U->getOperand(1)) &&
2678 cast<ConstantInt>(U->getOperand(1))->isOne() &&
2679 isa<ConstantInt>(RHS) &&
2680 cast<ConstantInt>(RHS)->isZero())
2681 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
2688 default: // We cannot analyze this expression.
2692 return getUnknown(V);
2697 //===----------------------------------------------------------------------===//
2698 // Iteration Count Computation Code
2701 /// getBackedgeTakenCount - If the specified loop has a predictable
2702 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2703 /// object. The backedge-taken count is the number of times the loop header
2704 /// will be branched to from within the loop. This is one less than the
2705 /// trip count of the loop, since it doesn't count the first iteration,
2706 /// when the header is branched to from outside the loop.
2708 /// Note that it is not valid to call this method on a loop without a
2709 /// loop-invariant backedge-taken count (see
2710 /// hasLoopInvariantBackedgeTakenCount).
2712 SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
2713 return getBackedgeTakenInfo(L).Exact;
2716 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2717 /// return the least SCEV value that is known never to be less than the
2718 /// actual backedge taken count.
2719 SCEVHandle ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
2720 return getBackedgeTakenInfo(L).Max;
2723 const ScalarEvolution::BackedgeTakenInfo &
2724 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
2725 // Initially insert a CouldNotCompute for this loop. If the insertion
2726 // succeeds, procede to actually compute a backedge-taken count and
2727 // update the value. The temporary CouldNotCompute value tells SCEV
2728 // code elsewhere that it shouldn't attempt to request a new
2729 // backedge-taken count, which could result in infinite recursion.
2730 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
2731 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2733 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
2734 if (ItCount.Exact != CouldNotCompute) {
2735 assert(ItCount.Exact->isLoopInvariant(L) &&
2736 ItCount.Max->isLoopInvariant(L) &&
2737 "Computed trip count isn't loop invariant for loop!");
2738 ++NumTripCountsComputed;
2740 // Update the value in the map.
2741 Pair.first->second = ItCount;
2743 if (ItCount.Max != CouldNotCompute)
2744 // Update the value in the map.
2745 Pair.first->second = ItCount;
2746 if (isa<PHINode>(L->getHeader()->begin()))
2747 // Only count loops that have phi nodes as not being computable.
2748 ++NumTripCountsNotComputed;
2751 // Now that we know more about the trip count for this loop, forget any
2752 // existing SCEV values for PHI nodes in this loop since they are only
2753 // conservative estimates made without the benefit
2754 // of trip count information.
2755 if (ItCount.hasAnyInfo())
2758 return Pair.first->second;
2761 /// forgetLoopBackedgeTakenCount - This method should be called by the
2762 /// client when it has changed a loop in a way that may effect
2763 /// ScalarEvolution's ability to compute a trip count, or if the loop
2765 void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
2766 BackedgeTakenCounts.erase(L);
2770 /// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2771 /// PHI nodes in the given loop. This is used when the trip count of
2772 /// the loop may have changed.
2773 void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
2774 BasicBlock *Header = L->getHeader();
2776 // Push all Loop-header PHIs onto the Worklist stack, except those
2777 // that are presently represented via a SCEVUnknown. SCEVUnknown for
2778 // a PHI either means that it has an unrecognized structure, or it's
2779 // a PHI that's in the progress of being computed by createNodeForPHI.
2780 // In the former case, additional loop trip count information isn't
2781 // going to change anything. In the later case, createNodeForPHI will
2782 // perform the necessary updates on its own when it gets to that point.
2783 SmallVector<Instruction *, 16> Worklist;
2784 for (BasicBlock::iterator I = Header->begin();
2785 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
2786 std::map<SCEVCallbackVH, SCEVHandle>::iterator It = Scalars.find((Value*)I);
2787 if (It != Scalars.end() && !isa<SCEVUnknown>(It->second))
2788 Worklist.push_back(PN);
2791 while (!Worklist.empty()) {
2792 Instruction *I = Worklist.pop_back_val();
2793 if (Scalars.erase(I))
2794 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2796 Worklist.push_back(cast<Instruction>(UI));
2800 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
2801 /// of the specified loop will execute.
2802 ScalarEvolution::BackedgeTakenInfo
2803 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
2804 SmallVector<BasicBlock*, 8> ExitingBlocks;
2805 L->getExitingBlocks(ExitingBlocks);
2807 // Examine all exits and pick the most conservative values.
2808 SCEVHandle BECount = CouldNotCompute;
2809 SCEVHandle MaxBECount = CouldNotCompute;
2810 bool CouldNotComputeBECount = false;
2811 bool CouldNotComputeMaxBECount = false;
2812 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
2813 BackedgeTakenInfo NewBTI =
2814 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
2816 if (NewBTI.Exact == CouldNotCompute) {
2817 // We couldn't compute an exact value for this exit, so
2818 // we don't be able to compute an exact value for the loop.
2819 CouldNotComputeBECount = true;
2820 BECount = CouldNotCompute;
2821 } else if (!CouldNotComputeBECount) {
2822 if (BECount == CouldNotCompute)
2823 BECount = NewBTI.Exact;
2825 // TODO: More analysis could be done here. For example, a
2826 // loop with a short-circuiting && operator has an exact count
2827 // of the min of both sides.
2828 CouldNotComputeBECount = true;
2829 BECount = CouldNotCompute;
2832 if (NewBTI.Max == CouldNotCompute) {
2833 // We couldn't compute an maximum value for this exit, so
2834 // we don't be able to compute an maximum value for the loop.
2835 CouldNotComputeMaxBECount = true;
2836 MaxBECount = CouldNotCompute;
2837 } else if (!CouldNotComputeMaxBECount) {
2838 if (MaxBECount == CouldNotCompute)
2839 MaxBECount = NewBTI.Max;
2841 MaxBECount = getUMaxFromMismatchedTypes(MaxBECount, NewBTI.Max);
2845 return BackedgeTakenInfo(BECount, MaxBECount);
2848 /// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
2849 /// of the specified loop will execute if it exits via the specified block.
2850 ScalarEvolution::BackedgeTakenInfo
2851 ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
2852 BasicBlock *ExitingBlock) {
2854 // Okay, we've chosen an exiting block. See what condition causes us to
2855 // exit at this block.
2857 // FIXME: we should be able to handle switch instructions (with a single exit)
2858 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2859 if (ExitBr == 0) return CouldNotCompute;
2860 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2862 // At this point, we know we have a conditional branch that determines whether
2863 // the loop is exited. However, we don't know if the branch is executed each
2864 // time through the loop. If not, then the execution count of the branch will
2865 // not be equal to the trip count of the loop.
2867 // Currently we check for this by checking to see if the Exit branch goes to
2868 // the loop header. If so, we know it will always execute the same number of
2869 // times as the loop. We also handle the case where the exit block *is* the
2870 // loop header. This is common for un-rotated loops.
2872 // If both of those tests fail, walk up the unique predecessor chain to the
2873 // header, stopping if there is an edge that doesn't exit the loop. If the
2874 // header is reached, the execution count of the branch will be equal to the
2875 // trip count of the loop.
2877 // More extensive analysis could be done to handle more cases here.
2879 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2880 ExitBr->getSuccessor(1) != L->getHeader() &&
2881 ExitBr->getParent() != L->getHeader()) {
2882 // The simple checks failed, try climbing the unique predecessor chain
2883 // up to the header.
2885 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
2886 BasicBlock *Pred = BB->getUniquePredecessor();
2888 return CouldNotCompute;
2889 TerminatorInst *PredTerm = Pred->getTerminator();
2890 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
2891 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
2894 // If the predecessor has a successor that isn't BB and isn't
2895 // outside the loop, assume the worst.
2896 if (L->contains(PredSucc))
2897 return CouldNotCompute;
2899 if (Pred == L->getHeader()) {
2906 return CouldNotCompute;
2909 // Procede to the next level to examine the exit condition expression.
2910 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
2911 ExitBr->getSuccessor(0),
2912 ExitBr->getSuccessor(1));
2915 /// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
2916 /// backedge of the specified loop will execute if its exit condition
2917 /// were a conditional branch of ExitCond, TBB, and FBB.
2918 ScalarEvolution::BackedgeTakenInfo
2919 ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
2923 // Check if the controlling expression for this loop is an and or or. In
2924 // such cases, an exact backedge-taken count may be infeasible, but a
2925 // maximum count may still be feasible.
2926 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
2927 if (BO->getOpcode() == Instruction::And) {
2928 // Recurse on the operands of the and.
2929 BackedgeTakenInfo BTI0 =
2930 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
2931 BackedgeTakenInfo BTI1 =
2932 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
2933 SCEVHandle BECount = CouldNotCompute;
2934 SCEVHandle MaxBECount = CouldNotCompute;
2935 if (L->contains(TBB)) {
2936 // Both conditions must be true for the loop to continue executing.
2937 // Choose the less conservative count.
2938 // TODO: Take the minimum of the exact counts.
2939 if (BTI0.Exact == BTI1.Exact)
2940 BECount = BTI0.Exact;
2941 // TODO: Take the minimum of the maximum counts.
2942 if (BTI0.Max == CouldNotCompute)
2943 MaxBECount = BTI1.Max;
2944 else if (BTI1.Max == CouldNotCompute)
2945 MaxBECount = BTI0.Max;
2946 else if (const SCEVConstant *C0 = dyn_cast<SCEVConstant>(BTI0.Max))
2947 if (const SCEVConstant *C1 = dyn_cast<SCEVConstant>(BTI1.Max))
2948 MaxBECount = getConstant(APIntOps::umin(C0->getValue()->getValue(),
2949 C1->getValue()->getValue()));
2951 // Both conditions must be true for the loop to exit.
2952 assert(L->contains(FBB) && "Loop block has no successor in loop!");
2953 if (BTI0.Exact != CouldNotCompute && BTI1.Exact != CouldNotCompute)
2954 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
2955 if (BTI0.Max != CouldNotCompute && BTI1.Max != CouldNotCompute)
2956 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
2959 return BackedgeTakenInfo(BECount, MaxBECount);
2961 if (BO->getOpcode() == Instruction::Or) {
2962 // Recurse on the operands of the or.
2963 BackedgeTakenInfo BTI0 =
2964 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
2965 BackedgeTakenInfo BTI1 =
2966 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
2967 SCEVHandle BECount = CouldNotCompute;
2968 SCEVHandle MaxBECount = CouldNotCompute;
2969 if (L->contains(FBB)) {
2970 // Both conditions must be false for the loop to continue executing.
2971 // Choose the less conservative count.
2972 // TODO: Take the minimum of the exact counts.
2973 if (BTI0.Exact == BTI1.Exact)
2974 BECount = BTI0.Exact;
2975 // TODO: Take the minimum of the maximum counts.
2976 if (BTI0.Max == CouldNotCompute)
2977 MaxBECount = BTI1.Max;
2978 else if (BTI1.Max == CouldNotCompute)
2979 MaxBECount = BTI0.Max;
2980 else if (const SCEVConstant *C0 = dyn_cast<SCEVConstant>(BTI0.Max))
2981 if (const SCEVConstant *C1 = dyn_cast<SCEVConstant>(BTI1.Max))
2982 MaxBECount = getConstant(APIntOps::umin(C0->getValue()->getValue(),
2983 C1->getValue()->getValue()));
2985 // Both conditions must be false for the loop to exit.
2986 assert(L->contains(TBB) && "Loop block has no successor in loop!");
2987 if (BTI0.Exact != CouldNotCompute && BTI1.Exact != CouldNotCompute)
2988 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
2989 if (BTI0.Max != CouldNotCompute && BTI1.Max != CouldNotCompute)
2990 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
2993 return BackedgeTakenInfo(BECount, MaxBECount);
2997 // With an icmp, it may be feasible to compute an exact backedge-taken count.
2998 // Procede to the next level to examine the icmp.
2999 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3000 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
3002 // If it's not an integer or pointer comparison then compute it the hard way.
3003 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3006 /// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3007 /// backedge of the specified loop will execute if its exit condition
3008 /// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3009 ScalarEvolution::BackedgeTakenInfo
3010 ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3015 // If the condition was exit on true, convert the condition to exit on false
3016 ICmpInst::Predicate Cond;
3017 if (!L->contains(FBB))
3018 Cond = ExitCond->getPredicate();
3020 Cond = ExitCond->getInversePredicate();
3022 // Handle common loops like: for (X = "string"; *X; ++X)
3023 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3024 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
3026 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
3027 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
3028 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
3029 return BackedgeTakenInfo(ItCnt,
3030 isa<SCEVConstant>(ItCnt) ? ItCnt :
3031 getConstant(APInt::getMaxValue(BitWidth)-1));
3035 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
3036 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
3038 // Try to evaluate any dependencies out of the loop.
3039 LHS = getSCEVAtScope(LHS, L);
3040 RHS = getSCEVAtScope(RHS, L);
3042 // At this point, we would like to compute how many iterations of the
3043 // loop the predicate will return true for these inputs.
3044 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3045 // If there is a loop-invariant, force it into the RHS.
3046 std::swap(LHS, RHS);
3047 Cond = ICmpInst::getSwappedPredicate(Cond);
3050 // If we have a comparison of a chrec against a constant, try to use value
3051 // ranges to answer this query.
3052 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3053 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
3054 if (AddRec->getLoop() == L) {
3055 // Form the constant range.
3056 ConstantRange CompRange(
3057 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
3059 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
3060 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
3064 case ICmpInst::ICMP_NE: { // while (X != Y)
3065 // Convert to: while (X-Y != 0)
3066 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
3067 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3070 case ICmpInst::ICMP_EQ: {
3071 // Convert to: while (X-Y == 0) // while (X == Y)
3072 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
3073 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3076 case ICmpInst::ICMP_SLT: {
3077 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3078 if (BTI.hasAnyInfo()) return BTI;
3081 case ICmpInst::ICMP_SGT: {
3082 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3083 getNotSCEV(RHS), L, true);
3084 if (BTI.hasAnyInfo()) return BTI;
3087 case ICmpInst::ICMP_ULT: {
3088 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3089 if (BTI.hasAnyInfo()) return BTI;
3092 case ICmpInst::ICMP_UGT: {
3093 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3094 getNotSCEV(RHS), L, false);
3095 if (BTI.hasAnyInfo()) return BTI;
3100 errs() << "ComputeBackedgeTakenCount ";
3101 if (ExitCond->getOperand(0)->getType()->isUnsigned())
3102 errs() << "[unsigned] ";
3103 errs() << *LHS << " "
3104 << Instruction::getOpcodeName(Instruction::ICmp)
3105 << " " << *RHS << "\n";
3110 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3113 static ConstantInt *
3114 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3115 ScalarEvolution &SE) {
3116 SCEVHandle InVal = SE.getConstant(C);
3117 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
3118 assert(isa<SCEVConstant>(Val) &&
3119 "Evaluation of SCEV at constant didn't fold correctly?");
3120 return cast<SCEVConstant>(Val)->getValue();
3123 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
3124 /// and a GEP expression (missing the pointer index) indexing into it, return
3125 /// the addressed element of the initializer or null if the index expression is
3128 GetAddressedElementFromGlobal(GlobalVariable *GV,
3129 const std::vector<ConstantInt*> &Indices) {
3130 Constant *Init = GV->getInitializer();
3131 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
3132 uint64_t Idx = Indices[i]->getZExtValue();
3133 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3134 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3135 Init = cast<Constant>(CS->getOperand(Idx));
3136 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3137 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3138 Init = cast<Constant>(CA->getOperand(Idx));
3139 } else if (isa<ConstantAggregateZero>(Init)) {
3140 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3141 assert(Idx < STy->getNumElements() && "Bad struct index!");
3142 Init = Constant::getNullValue(STy->getElementType(Idx));
3143 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3144 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
3145 Init = Constant::getNullValue(ATy->getElementType());
3147 assert(0 && "Unknown constant aggregate type!");
3151 return 0; // Unknown initializer type
3157 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3158 /// 'icmp op load X, cst', try to see if we can compute the backedge
3159 /// execution count.
3160 SCEVHandle ScalarEvolution::
3161 ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
3163 ICmpInst::Predicate predicate) {
3164 if (LI->isVolatile()) return CouldNotCompute;
3166 // Check to see if the loaded pointer is a getelementptr of a global.
3167 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
3168 if (!GEP) return CouldNotCompute;
3170 // Make sure that it is really a constant global we are gepping, with an
3171 // initializer, and make sure the first IDX is really 0.
3172 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
3173 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
3174 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3175 !cast<Constant>(GEP->getOperand(1))->isNullValue())
3176 return CouldNotCompute;
3178 // Okay, we allow one non-constant index into the GEP instruction.
3180 std::vector<ConstantInt*> Indexes;
3181 unsigned VarIdxNum = 0;
3182 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3183 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3184 Indexes.push_back(CI);
3185 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
3186 if (VarIdx) return CouldNotCompute; // Multiple non-constant idx's.
3187 VarIdx = GEP->getOperand(i);
3189 Indexes.push_back(0);
3192 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3193 // Check to see if X is a loop variant variable value now.
3194 SCEVHandle Idx = getSCEV(VarIdx);
3195 Idx = getSCEVAtScope(Idx, L);
3197 // We can only recognize very limited forms of loop index expressions, in
3198 // particular, only affine AddRec's like {C1,+,C2}.
3199 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
3200 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3201 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3202 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
3203 return CouldNotCompute;
3205 unsigned MaxSteps = MaxBruteForceIterations;
3206 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
3207 ConstantInt *ItCst =
3208 ConstantInt::get(cast<IntegerType>(IdxExpr->getType()), IterationNum);
3209 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
3211 // Form the GEP offset.
3212 Indexes[VarIdxNum] = Val;
3214 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
3215 if (Result == 0) break; // Cannot compute!
3217 // Evaluate the condition for this iteration.
3218 Result = ConstantExpr::getICmp(predicate, Result, RHS);
3219 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
3220 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
3222 errs() << "\n***\n*** Computed loop count " << *ItCst
3223 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3226 ++NumArrayLenItCounts;
3227 return getConstant(ItCst); // Found terminating iteration!
3230 return CouldNotCompute;
3234 /// CanConstantFold - Return true if we can constant fold an instruction of the
3235 /// specified type, assuming that all operands were constants.
3236 static bool CanConstantFold(const Instruction *I) {
3237 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
3238 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3241 if (const CallInst *CI = dyn_cast<CallInst>(I))
3242 if (const Function *F = CI->getCalledFunction())
3243 return canConstantFoldCallTo(F);
3247 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3248 /// in the loop that V is derived from. We allow arbitrary operations along the
3249 /// way, but the operands of an operation must either be constants or a value
3250 /// derived from a constant PHI. If this expression does not fit with these
3251 /// constraints, return null.
3252 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3253 // If this is not an instruction, or if this is an instruction outside of the
3254 // loop, it can't be derived from a loop PHI.
3255 Instruction *I = dyn_cast<Instruction>(V);
3256 if (I == 0 || !L->contains(I->getParent())) return 0;
3258 if (PHINode *PN = dyn_cast<PHINode>(I)) {
3259 if (L->getHeader() == I->getParent())
3262 // We don't currently keep track of the control flow needed to evaluate
3263 // PHIs, so we cannot handle PHIs inside of loops.
3267 // If we won't be able to constant fold this expression even if the operands
3268 // are constants, return early.
3269 if (!CanConstantFold(I)) return 0;
3271 // Otherwise, we can evaluate this instruction if all of its operands are
3272 // constant or derived from a PHI node themselves.
3274 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3275 if (!(isa<Constant>(I->getOperand(Op)) ||
3276 isa<GlobalValue>(I->getOperand(Op)))) {
3277 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3278 if (P == 0) return 0; // Not evolving from PHI
3282 return 0; // Evolving from multiple different PHIs.
3285 // This is a expression evolving from a constant PHI!
3289 /// EvaluateExpression - Given an expression that passes the
3290 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3291 /// in the loop has the value PHIVal. If we can't fold this expression for some
3292 /// reason, return null.
3293 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3294 if (isa<PHINode>(V)) return PHIVal;
3295 if (Constant *C = dyn_cast<Constant>(V)) return C;
3296 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
3297 Instruction *I = cast<Instruction>(V);
3299 std::vector<Constant*> Operands;
3300 Operands.resize(I->getNumOperands());
3302 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3303 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3304 if (Operands[i] == 0) return 0;
3307 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3308 return ConstantFoldCompareInstOperands(CI->getPredicate(),
3309 &Operands[0], Operands.size());
3311 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3312 &Operands[0], Operands.size());
3315 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3316 /// in the header of its containing loop, we know the loop executes a
3317 /// constant number of times, and the PHI node is just a recurrence
3318 /// involving constants, fold it.
3319 Constant *ScalarEvolution::
3320 getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
3321 std::map<PHINode*, Constant*>::iterator I =
3322 ConstantEvolutionLoopExitValue.find(PN);
3323 if (I != ConstantEvolutionLoopExitValue.end())
3326 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
3327 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3329 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3331 // Since the loop is canonicalized, the PHI node must have two entries. One
3332 // entry must be a constant (coming in from outside of the loop), and the
3333 // second must be derived from the same PHI.
3334 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3335 Constant *StartCST =
3336 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3338 return RetVal = 0; // Must be a constant.
3340 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3341 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3343 return RetVal = 0; // Not derived from same PHI.
3345 // Execute the loop symbolically to determine the exit value.
3346 if (BEs.getActiveBits() >= 32)
3347 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
3349 unsigned NumIterations = BEs.getZExtValue(); // must be in range
3350 unsigned IterationNum = 0;
3351 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3352 if (IterationNum == NumIterations)
3353 return RetVal = PHIVal; // Got exit value!
3355 // Compute the value of the PHI node for the next iteration.
3356 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3357 if (NextPHI == PHIVal)
3358 return RetVal = NextPHI; // Stopped evolving!
3360 return 0; // Couldn't evaluate!
3365 /// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
3366 /// constant number of times (the condition evolves only from constants),
3367 /// try to evaluate a few iterations of the loop until we get the exit
3368 /// condition gets a value of ExitWhen (true or false). If we cannot
3369 /// evaluate the trip count of the loop, return CouldNotCompute.
3370 SCEVHandle ScalarEvolution::
3371 ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
3372 PHINode *PN = getConstantEvolvingPHI(Cond, L);
3373 if (PN == 0) return CouldNotCompute;
3375 // Since the loop is canonicalized, the PHI node must have two entries. One
3376 // entry must be a constant (coming in from outside of the loop), and the
3377 // second must be derived from the same PHI.
3378 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3379 Constant *StartCST =
3380 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3381 if (StartCST == 0) return CouldNotCompute; // Must be a constant.
3383 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3384 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3385 if (PN2 != PN) return CouldNotCompute; // Not derived from same PHI.
3387 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3388 // the loop symbolically to determine when the condition gets a value of
3390 unsigned IterationNum = 0;
3391 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3392 for (Constant *PHIVal = StartCST;
3393 IterationNum != MaxIterations; ++IterationNum) {
3394 ConstantInt *CondVal =
3395 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
3397 // Couldn't symbolically evaluate.
3398 if (!CondVal) return CouldNotCompute;
3400 if (CondVal->getValue() == uint64_t(ExitWhen)) {
3401 ConstantEvolutionLoopExitValue[PN] = PHIVal;
3402 ++NumBruteForceTripCountsComputed;
3403 return getConstant(Type::Int32Ty, IterationNum);
3406 // Compute the value of the PHI node for the next iteration.
3407 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3408 if (NextPHI == 0 || NextPHI == PHIVal)
3409 return CouldNotCompute; // Couldn't evaluate or not making progress...
3413 // Too many iterations were needed to evaluate.
3414 return CouldNotCompute;
3417 /// getSCEVAtScope - Return a SCEV expression handle for the specified value
3418 /// at the specified scope in the program. The L value specifies a loop
3419 /// nest to evaluate the expression at, where null is the top-level or a
3420 /// specified loop is immediately inside of the loop.
3422 /// This method can be used to compute the exit value for a variable defined
3423 /// in a loop by querying what the value will hold in the parent loop.
3425 /// In the case that a relevant loop exit value cannot be computed, the
3426 /// original value V is returned.
3427 SCEVHandle ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
3428 // FIXME: this should be turned into a virtual method on SCEV!
3430 if (isa<SCEVConstant>(V)) return V;
3432 // If this instruction is evolved from a constant-evolving PHI, compute the
3433 // exit value from the loop without using SCEVs.
3434 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
3435 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
3436 const Loop *LI = (*this->LI)[I->getParent()];
3437 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3438 if (PHINode *PN = dyn_cast<PHINode>(I))
3439 if (PN->getParent() == LI->getHeader()) {
3440 // Okay, there is no closed form solution for the PHI node. Check
3441 // to see if the loop that contains it has a known backedge-taken
3442 // count. If so, we may be able to force computation of the exit
3444 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
3445 if (const SCEVConstant *BTCC =
3446 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
3447 // Okay, we know how many times the containing loop executes. If
3448 // this is a constant evolving PHI node, get the final value at
3449 // the specified iteration number.
3450 Constant *RV = getConstantEvolutionLoopExitValue(PN,
3451 BTCC->getValue()->getValue(),
3453 if (RV) return getUnknown(RV);
3457 // Okay, this is an expression that we cannot symbolically evaluate
3458 // into a SCEV. Check to see if it's possible to symbolically evaluate
3459 // the arguments into constants, and if so, try to constant propagate the
3460 // result. This is particularly useful for computing loop exit values.
3461 if (CanConstantFold(I)) {
3462 // Check to see if we've folded this instruction at this loop before.
3463 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3464 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3465 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3467 return Pair.first->second ? &*getUnknown(Pair.first->second) : V;
3469 std::vector<Constant*> Operands;
3470 Operands.reserve(I->getNumOperands());
3471 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3472 Value *Op = I->getOperand(i);
3473 if (Constant *C = dyn_cast<Constant>(Op)) {
3474 Operands.push_back(C);
3476 // If any of the operands is non-constant and if they are
3477 // non-integer and non-pointer, don't even try to analyze them
3478 // with scev techniques.
3479 if (!isSCEVable(Op->getType()))
3482 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
3483 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
3484 Constant *C = SC->getValue();
3485 if (C->getType() != Op->getType())
3486 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3490 Operands.push_back(C);
3491 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
3492 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3493 if (C->getType() != Op->getType())
3495 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3499 Operands.push_back(C);
3509 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3510 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
3511 &Operands[0], Operands.size());
3513 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3514 &Operands[0], Operands.size());
3515 Pair.first->second = C;
3516 return getUnknown(C);
3520 // This is some other type of SCEVUnknown, just return it.
3524 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
3525 // Avoid performing the look-up in the common case where the specified
3526 // expression has no loop-variant portions.
3527 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
3528 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
3529 if (OpAtScope != Comm->getOperand(i)) {
3530 // Okay, at least one of these operands is loop variant but might be
3531 // foldable. Build a new instance of the folded commutative expression.
3532 SmallVector<SCEVHandle, 8> NewOps(Comm->op_begin(), Comm->op_begin()+i);
3533 NewOps.push_back(OpAtScope);
3535 for (++i; i != e; ++i) {
3536 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
3537 NewOps.push_back(OpAtScope);
3539 if (isa<SCEVAddExpr>(Comm))
3540 return getAddExpr(NewOps);
3541 if (isa<SCEVMulExpr>(Comm))
3542 return getMulExpr(NewOps);
3543 if (isa<SCEVSMaxExpr>(Comm))
3544 return getSMaxExpr(NewOps);
3545 if (isa<SCEVUMaxExpr>(Comm))
3546 return getUMaxExpr(NewOps);
3547 assert(0 && "Unknown commutative SCEV type!");
3550 // If we got here, all operands are loop invariant.
3554 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
3555 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
3556 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
3557 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3558 return Div; // must be loop invariant
3559 return getUDivExpr(LHS, RHS);
3562 // If this is a loop recurrence for a loop that does not contain L, then we
3563 // are dealing with the final value computed by the loop.
3564 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
3565 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3566 // To evaluate this recurrence, we need to know how many times the AddRec
3567 // loop iterates. Compute this now.
3568 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
3569 if (BackedgeTakenCount == CouldNotCompute) return AddRec;
3571 // Then, evaluate the AddRec.
3572 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
3577 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
3578 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
3579 if (Op == Cast->getOperand())
3580 return Cast; // must be loop invariant
3581 return getZeroExtendExpr(Op, Cast->getType());
3584 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
3585 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
3586 if (Op == Cast->getOperand())
3587 return Cast; // must be loop invariant
3588 return getSignExtendExpr(Op, Cast->getType());
3591 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
3592 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
3593 if (Op == Cast->getOperand())
3594 return Cast; // must be loop invariant
3595 return getTruncateExpr(Op, Cast->getType());
3598 assert(0 && "Unknown SCEV type!");
3602 /// getSCEVAtScope - This is a convenience function which does
3603 /// getSCEVAtScope(getSCEV(V), L).
3604 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
3605 return getSCEVAtScope(getSCEV(V), L);
3608 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3609 /// following equation:
3611 /// A * X = B (mod N)
3613 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3614 /// A and B isn't important.
3616 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
3617 static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
3618 ScalarEvolution &SE) {
3619 uint32_t BW = A.getBitWidth();
3620 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3621 assert(A != 0 && "A must be non-zero.");
3625 // The gcd of A and N may have only one prime factor: 2. The number of
3626 // trailing zeros in A is its multiplicity
3627 uint32_t Mult2 = A.countTrailingZeros();
3630 // 2. Check if B is divisible by D.
3632 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3633 // is not less than multiplicity of this prime factor for D.
3634 if (B.countTrailingZeros() < Mult2)
3635 return SE.getCouldNotCompute();
3637 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3640 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3641 // bit width during computations.
3642 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3643 APInt Mod(BW + 1, 0);
3644 Mod.set(BW - Mult2); // Mod = N / D
3645 APInt I = AD.multiplicativeInverse(Mod);
3647 // 4. Compute the minimum unsigned root of the equation:
3648 // I * (B / D) mod (N / D)
3649 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
3651 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
3653 return SE.getConstant(Result.trunc(BW));
3656 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
3657 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
3658 /// might be the same) or two SCEVCouldNotCompute objects.
3660 static std::pair<SCEVHandle,SCEVHandle>
3661 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
3662 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
3663 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
3664 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
3665 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
3667 // We currently can only solve this if the coefficients are constants.
3668 if (!LC || !MC || !NC) {
3669 const SCEV *CNC = SE.getCouldNotCompute();
3670 return std::make_pair(CNC, CNC);
3673 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
3674 const APInt &L = LC->getValue()->getValue();
3675 const APInt &M = MC->getValue()->getValue();
3676 const APInt &N = NC->getValue()->getValue();
3677 APInt Two(BitWidth, 2);
3678 APInt Four(BitWidth, 4);
3681 using namespace APIntOps;
3683 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
3684 // The B coefficient is M-N/2
3688 // The A coefficient is N/2
3689 APInt A(N.sdiv(Two));
3691 // Compute the B^2-4ac term.
3694 SqrtTerm -= Four * (A * C);
3696 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
3697 // integer value or else APInt::sqrt() will assert.
3698 APInt SqrtVal(SqrtTerm.sqrt());
3700 // Compute the two solutions for the quadratic formula.
3701 // The divisions must be performed as signed divisions.
3703 APInt TwoA( A << 1 );
3704 if (TwoA.isMinValue()) {
3705 const SCEV *CNC = SE.getCouldNotCompute();
3706 return std::make_pair(CNC, CNC);
3709 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
3710 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
3712 return std::make_pair(SE.getConstant(Solution1),
3713 SE.getConstant(Solution2));
3714 } // end APIntOps namespace
3717 /// HowFarToZero - Return the number of times a backedge comparing the specified
3718 /// value to zero will execute. If not computable, return CouldNotCompute.
3719 SCEVHandle ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
3720 // If the value is a constant
3721 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
3722 // If the value is already zero, the branch will execute zero times.
3723 if (C->getValue()->isZero()) return C;
3724 return CouldNotCompute; // Otherwise it will loop infinitely.
3727 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
3728 if (!AddRec || AddRec->getLoop() != L)
3729 return CouldNotCompute;
3731 if (AddRec->isAffine()) {
3732 // If this is an affine expression, the execution count of this branch is
3733 // the minimum unsigned root of the following equation:
3735 // Start + Step*N = 0 (mod 2^BW)
3739 // Step*N = -Start (mod 2^BW)
3741 // where BW is the common bit width of Start and Step.
3743 // Get the initial value for the loop.
3744 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
3745 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
3747 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
3748 // For now we handle only constant steps.
3750 // First, handle unitary steps.
3751 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
3752 return getNegativeSCEV(Start); // N = -Start (as unsigned)
3753 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
3754 return Start; // N = Start (as unsigned)
3756 // Then, try to solve the above equation provided that Start is constant.
3757 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
3758 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
3759 -StartC->getValue()->getValue(),
3762 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
3763 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
3764 // the quadratic equation to solve it.
3765 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
3767 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3768 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3771 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3772 << " sol#2: " << *R2 << "\n";
3774 // Pick the smallest positive root value.
3775 if (ConstantInt *CB =
3776 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3777 R1->getValue(), R2->getValue()))) {
3778 if (CB->getZExtValue() == false)
3779 std::swap(R1, R2); // R1 is the minimum root now.
3781 // We can only use this value if the chrec ends up with an exact zero
3782 // value at this index. When solving for "X*X != 5", for example, we
3783 // should not accept a root of 2.
3784 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
3786 return R1; // We found a quadratic root!
3791 return CouldNotCompute;
3794 /// HowFarToNonZero - Return the number of times a backedge checking the
3795 /// specified value for nonzero will execute. If not computable, return
3797 SCEVHandle ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
3798 // Loops that look like: while (X == 0) are very strange indeed. We don't
3799 // handle them yet except for the trivial case. This could be expanded in the
3800 // future as needed.
3802 // If the value is a constant, check to see if it is known to be non-zero
3803 // already. If so, the backedge will execute zero times.
3804 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
3805 if (!C->getValue()->isNullValue())
3806 return getIntegerSCEV(0, C->getType());
3807 return CouldNotCompute; // Otherwise it will loop infinitely.
3810 // We could implement others, but I really doubt anyone writes loops like
3811 // this, and if they did, they would already be constant folded.
3812 return CouldNotCompute;
3815 /// getLoopPredecessor - If the given loop's header has exactly one unique
3816 /// predecessor outside the loop, return it. Otherwise return null.
3818 BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
3819 BasicBlock *Header = L->getHeader();
3820 BasicBlock *Pred = 0;
3821 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
3823 if (!L->contains(*PI)) {
3824 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
3830 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
3831 /// (which may not be an immediate predecessor) which has exactly one
3832 /// successor from which BB is reachable, or null if no such block is
3836 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
3837 // If the block has a unique predecessor, then there is no path from the
3838 // predecessor to the block that does not go through the direct edge
3839 // from the predecessor to the block.
3840 if (BasicBlock *Pred = BB->getSinglePredecessor())
3843 // A loop's header is defined to be a block that dominates the loop.
3844 // If the header has a unique predecessor outside the loop, it must be
3845 // a block that has exactly one successor that can reach the loop.
3846 if (Loop *L = LI->getLoopFor(BB))
3847 return getLoopPredecessor(L);
3852 /// HasSameValue - SCEV structural equivalence is usually sufficient for
3853 /// testing whether two expressions are equal, however for the purposes of
3854 /// looking for a condition guarding a loop, it can be useful to be a little
3855 /// more general, since a front-end may have replicated the controlling
3858 static bool HasSameValue(const SCEVHandle &A, const SCEVHandle &B) {
3859 // Quick check to see if they are the same SCEV.
3860 if (A == B) return true;
3862 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
3863 // two different instructions with the same value. Check for this case.
3864 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
3865 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
3866 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
3867 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
3868 if (AI->isIdenticalTo(BI))
3871 // Otherwise assume they may have a different value.
3875 /// isLoopGuardedByCond - Test whether entry to the loop is protected by
3876 /// a conditional between LHS and RHS. This is used to help avoid max
3877 /// expressions in loop trip counts.
3878 bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
3879 ICmpInst::Predicate Pred,
3880 const SCEV *LHS, const SCEV *RHS) {
3881 // Interpret a null as meaning no loop, where there is obviously no guard
3882 // (interprocedural conditions notwithstanding).
3883 if (!L) return false;
3885 BasicBlock *Predecessor = getLoopPredecessor(L);
3886 BasicBlock *PredecessorDest = L->getHeader();
3888 // Starting at the loop predecessor, climb up the predecessor chain, as long
3889 // as there are predecessors that can be found that have unique successors
3890 // leading to the original header.
3892 PredecessorDest = Predecessor,
3893 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
3895 BranchInst *LoopEntryPredicate =
3896 dyn_cast<BranchInst>(Predecessor->getTerminator());
3897 if (!LoopEntryPredicate ||
3898 LoopEntryPredicate->isUnconditional())
3901 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3904 // Now that we found a conditional branch that dominates the loop, check to
3905 // see if it is the comparison we are looking for.
3906 Value *PreCondLHS = ICI->getOperand(0);
3907 Value *PreCondRHS = ICI->getOperand(1);
3908 ICmpInst::Predicate Cond;
3909 if (LoopEntryPredicate->getSuccessor(0) == PredecessorDest)
3910 Cond = ICI->getPredicate();
3912 Cond = ICI->getInversePredicate();
3915 ; // An exact match.
3916 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3917 ; // The actual condition is beyond sufficient.
3919 // Check a few special cases.
3921 case ICmpInst::ICMP_UGT:
3922 if (Pred == ICmpInst::ICMP_ULT) {
3923 std::swap(PreCondLHS, PreCondRHS);
3924 Cond = ICmpInst::ICMP_ULT;
3928 case ICmpInst::ICMP_SGT:
3929 if (Pred == ICmpInst::ICMP_SLT) {
3930 std::swap(PreCondLHS, PreCondRHS);
3931 Cond = ICmpInst::ICMP_SLT;
3935 case ICmpInst::ICMP_NE:
3936 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3937 // so check for this case by checking if the NE is comparing against
3938 // a minimum or maximum constant.
3939 if (!ICmpInst::isTrueWhenEqual(Pred))
3940 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3941 const APInt &A = CI->getValue();
3943 case ICmpInst::ICMP_SLT:
3944 if (A.isMaxSignedValue()) break;
3946 case ICmpInst::ICMP_SGT:
3947 if (A.isMinSignedValue()) break;
3949 case ICmpInst::ICMP_ULT:
3950 if (A.isMaxValue()) break;
3952 case ICmpInst::ICMP_UGT:
3953 if (A.isMinValue()) break;
3958 Cond = ICmpInst::ICMP_NE;
3959 // NE is symmetric but the original comparison may not be. Swap
3960 // the operands if necessary so that they match below.
3961 if (isa<SCEVConstant>(LHS))
3962 std::swap(PreCondLHS, PreCondRHS);
3967 // We weren't able to reconcile the condition.
3971 if (!PreCondLHS->getType()->isInteger()) continue;
3973 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3974 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3975 if ((HasSameValue(LHS, PreCondLHSSCEV) &&
3976 HasSameValue(RHS, PreCondRHSSCEV)) ||
3977 (HasSameValue(LHS, getNotSCEV(PreCondRHSSCEV)) &&
3978 HasSameValue(RHS, getNotSCEV(PreCondLHSSCEV))))
3985 /// getBECount - Subtract the end and start values and divide by the step,
3986 /// rounding up, to get the number of times the backedge is executed. Return
3987 /// CouldNotCompute if an intermediate computation overflows.
3988 SCEVHandle ScalarEvolution::getBECount(const SCEVHandle &Start,
3989 const SCEVHandle &End,
3990 const SCEVHandle &Step) {
3991 const Type *Ty = Start->getType();
3992 SCEVHandle NegOne = getIntegerSCEV(-1, Ty);
3993 SCEVHandle Diff = getMinusSCEV(End, Start);
3994 SCEVHandle RoundUp = getAddExpr(Step, NegOne);
3996 // Add an adjustment to the difference between End and Start so that
3997 // the division will effectively round up.
3998 SCEVHandle Add = getAddExpr(Diff, RoundUp);
4000 // Check Add for unsigned overflow.
4001 // TODO: More sophisticated things could be done here.
4002 const Type *WideTy = IntegerType::get(getTypeSizeInBits(Ty) + 1);
4003 SCEVHandle OperandExtendedAdd =
4004 getAddExpr(getZeroExtendExpr(Diff, WideTy),
4005 getZeroExtendExpr(RoundUp, WideTy));
4006 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
4007 return CouldNotCompute;
4009 return getUDivExpr(Add, Step);
4012 /// HowManyLessThans - Return the number of times a backedge containing the
4013 /// specified less-than comparison will execute. If not computable, return
4014 /// CouldNotCompute.
4015 ScalarEvolution::BackedgeTakenInfo ScalarEvolution::
4016 HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
4017 const Loop *L, bool isSigned) {
4018 // Only handle: "ADDREC < LoopInvariant".
4019 if (!RHS->isLoopInvariant(L)) return CouldNotCompute;
4021 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
4022 if (!AddRec || AddRec->getLoop() != L)
4023 return CouldNotCompute;
4025 if (AddRec->isAffine()) {
4026 // FORNOW: We only support unit strides.
4027 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
4028 SCEVHandle Step = AddRec->getStepRecurrence(*this);
4030 // TODO: handle non-constant strides.
4031 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
4032 if (!CStep || CStep->isZero())
4033 return CouldNotCompute;
4034 if (CStep->isOne()) {
4035 // With unit stride, the iteration never steps past the limit value.
4036 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
4037 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
4038 // Test whether a positive iteration iteration can step past the limit
4039 // value and past the maximum value for its type in a single step.
4041 APInt Max = APInt::getSignedMaxValue(BitWidth);
4042 if ((Max - CStep->getValue()->getValue())
4043 .slt(CLimit->getValue()->getValue()))
4044 return CouldNotCompute;
4046 APInt Max = APInt::getMaxValue(BitWidth);
4047 if ((Max - CStep->getValue()->getValue())
4048 .ult(CLimit->getValue()->getValue()))
4049 return CouldNotCompute;
4052 // TODO: handle non-constant limit values below.
4053 return CouldNotCompute;
4055 // TODO: handle negative strides below.
4056 return CouldNotCompute;
4058 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
4059 // m. So, we count the number of iterations in which {n,+,s} < m is true.
4060 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
4061 // treat m-n as signed nor unsigned due to overflow possibility.
4063 // First, we get the value of the LHS in the first iteration: n
4064 SCEVHandle Start = AddRec->getOperand(0);
4066 // Determine the minimum constant start value.
4067 SCEVHandle MinStart = isa<SCEVConstant>(Start) ? Start :
4068 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
4069 APInt::getMinValue(BitWidth));
4071 // If we know that the condition is true in order to enter the loop,
4072 // then we know that it will run exactly (m-n)/s times. Otherwise, we
4073 // only know that it will execute (max(m,n)-n)/s times. In both cases,
4074 // the division must round up.
4075 SCEVHandle End = RHS;
4076 if (!isLoopGuardedByCond(L,
4077 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
4078 getMinusSCEV(Start, Step), RHS))
4079 End = isSigned ? getSMaxExpr(RHS, Start)
4080 : getUMaxExpr(RHS, Start);
4082 // Determine the maximum constant end value.
4084 isa<SCEVConstant>(End) ? End :
4085 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth)
4086 .ashr(GetMinSignBits(End) - 1) :
4087 APInt::getMaxValue(BitWidth)
4088 .lshr(GetMinLeadingZeros(End)));
4090 // Finally, we subtract these two values and divide, rounding up, to get
4091 // the number of times the backedge is executed.
4092 SCEVHandle BECount = getBECount(Start, End, Step);
4094 // The maximum backedge count is similar, except using the minimum start
4095 // value and the maximum end value.
4096 SCEVHandle MaxBECount = getBECount(MinStart, MaxEnd, Step);;
4098 return BackedgeTakenInfo(BECount, MaxBECount);
4101 return CouldNotCompute;
4104 /// getNumIterationsInRange - Return the number of iterations of this loop that
4105 /// produce values in the specified constant range. Another way of looking at
4106 /// this is that it returns the first iteration number where the value is not in
4107 /// the condition, thus computing the exit count. If the iteration count can't
4108 /// be computed, an instance of SCEVCouldNotCompute is returned.
4109 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
4110 ScalarEvolution &SE) const {
4111 if (Range.isFullSet()) // Infinite loop.
4112 return SE.getCouldNotCompute();
4114 // If the start is a non-zero constant, shift the range to simplify things.
4115 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
4116 if (!SC->getValue()->isZero()) {
4117 SmallVector<SCEVHandle, 4> Operands(op_begin(), op_end());
4118 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
4119 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
4120 if (const SCEVAddRecExpr *ShiftedAddRec =
4121 dyn_cast<SCEVAddRecExpr>(Shifted))
4122 return ShiftedAddRec->getNumIterationsInRange(
4123 Range.subtract(SC->getValue()->getValue()), SE);
4124 // This is strange and shouldn't happen.
4125 return SE.getCouldNotCompute();
4128 // The only time we can solve this is when we have all constant indices.
4129 // Otherwise, we cannot determine the overflow conditions.
4130 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4131 if (!isa<SCEVConstant>(getOperand(i)))
4132 return SE.getCouldNotCompute();
4135 // Okay at this point we know that all elements of the chrec are constants and
4136 // that the start element is zero.
4138 // First check to see if the range contains zero. If not, the first
4140 unsigned BitWidth = SE.getTypeSizeInBits(getType());
4141 if (!Range.contains(APInt(BitWidth, 0)))
4142 return SE.getIntegerSCEV(0, getType());
4145 // If this is an affine expression then we have this situation:
4146 // Solve {0,+,A} in Range === Ax in Range
4148 // We know that zero is in the range. If A is positive then we know that
4149 // the upper value of the range must be the first possible exit value.
4150 // If A is negative then the lower of the range is the last possible loop
4151 // value. Also note that we already checked for a full range.
4152 APInt One(BitWidth,1);
4153 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
4154 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
4156 // The exit value should be (End+A)/A.
4157 APInt ExitVal = (End + A).udiv(A);
4158 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
4160 // Evaluate at the exit value. If we really did fall out of the valid
4161 // range, then we computed our trip count, otherwise wrap around or other
4162 // things must have happened.
4163 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
4164 if (Range.contains(Val->getValue()))
4165 return SE.getCouldNotCompute(); // Something strange happened
4167 // Ensure that the previous value is in the range. This is a sanity check.
4168 assert(Range.contains(
4169 EvaluateConstantChrecAtConstant(this,
4170 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
4171 "Linear scev computation is off in a bad way!");
4172 return SE.getConstant(ExitValue);
4173 } else if (isQuadratic()) {
4174 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
4175 // quadratic equation to solve it. To do this, we must frame our problem in
4176 // terms of figuring out when zero is crossed, instead of when
4177 // Range.getUpper() is crossed.
4178 SmallVector<SCEVHandle, 4> NewOps(op_begin(), op_end());
4179 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
4180 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
4182 // Next, solve the constructed addrec
4183 std::pair<SCEVHandle,SCEVHandle> Roots =
4184 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
4185 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4186 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
4188 // Pick the smallest positive root value.
4189 if (ConstantInt *CB =
4190 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
4191 R1->getValue(), R2->getValue()))) {
4192 if (CB->getZExtValue() == false)
4193 std::swap(R1, R2); // R1 is the minimum root now.
4195 // Make sure the root is not off by one. The returned iteration should
4196 // not be in the range, but the previous one should be. When solving
4197 // for "X*X < 5", for example, we should not return a root of 2.
4198 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
4201 if (Range.contains(R1Val->getValue())) {
4202 // The next iteration must be out of the range...
4203 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
4205 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
4206 if (!Range.contains(R1Val->getValue()))
4207 return SE.getConstant(NextVal);
4208 return SE.getCouldNotCompute(); // Something strange happened
4211 // If R1 was not in the range, then it is a good return value. Make
4212 // sure that R1-1 WAS in the range though, just in case.
4213 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
4214 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
4215 if (Range.contains(R1Val->getValue()))
4217 return SE.getCouldNotCompute(); // Something strange happened
4222 return SE.getCouldNotCompute();
4227 //===----------------------------------------------------------------------===//
4228 // SCEVCallbackVH Class Implementation
4229 //===----------------------------------------------------------------------===//
4231 void ScalarEvolution::SCEVCallbackVH::deleted() {
4232 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4233 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
4234 SE->ConstantEvolutionLoopExitValue.erase(PN);
4235 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
4236 SE->ValuesAtScopes.erase(I);
4237 SE->Scalars.erase(getValPtr());
4238 // this now dangles!
4241 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
4242 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4244 // Forget all the expressions associated with users of the old value,
4245 // so that future queries will recompute the expressions using the new
4247 SmallVector<User *, 16> Worklist;
4248 Value *Old = getValPtr();
4249 bool DeleteOld = false;
4250 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
4252 Worklist.push_back(*UI);
4253 while (!Worklist.empty()) {
4254 User *U = Worklist.pop_back_val();
4255 // Deleting the Old value will cause this to dangle. Postpone
4256 // that until everything else is done.
4261 if (PHINode *PN = dyn_cast<PHINode>(U))
4262 SE->ConstantEvolutionLoopExitValue.erase(PN);
4263 if (Instruction *I = dyn_cast<Instruction>(U))
4264 SE->ValuesAtScopes.erase(I);
4265 if (SE->Scalars.erase(U))
4266 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
4268 Worklist.push_back(*UI);
4271 if (PHINode *PN = dyn_cast<PHINode>(Old))
4272 SE->ConstantEvolutionLoopExitValue.erase(PN);
4273 if (Instruction *I = dyn_cast<Instruction>(Old))
4274 SE->ValuesAtScopes.erase(I);
4275 SE->Scalars.erase(Old);
4276 // this now dangles!
4281 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
4282 : CallbackVH(V), SE(se) {}
4284 //===----------------------------------------------------------------------===//
4285 // ScalarEvolution Class Implementation
4286 //===----------------------------------------------------------------------===//
4288 ScalarEvolution::ScalarEvolution()
4289 : FunctionPass(&ID), CouldNotCompute(new SCEVCouldNotCompute(0)) {
4292 bool ScalarEvolution::runOnFunction(Function &F) {
4294 LI = &getAnalysis<LoopInfo>();
4295 TD = getAnalysisIfAvailable<TargetData>();
4299 void ScalarEvolution::releaseMemory() {
4301 BackedgeTakenCounts.clear();
4302 ConstantEvolutionLoopExitValue.clear();
4303 ValuesAtScopes.clear();
4306 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
4307 AU.setPreservesAll();
4308 AU.addRequiredTransitive<LoopInfo>();
4311 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
4312 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
4315 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
4317 // Print all inner loops first
4318 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4319 PrintLoopInfo(OS, SE, *I);
4321 OS << "Loop " << L->getHeader()->getName() << ": ";
4323 SmallVector<BasicBlock*, 8> ExitBlocks;
4324 L->getExitBlocks(ExitBlocks);
4325 if (ExitBlocks.size() != 1)
4326 OS << "<multiple exits> ";
4328 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
4329 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
4331 OS << "Unpredictable backedge-taken count. ";
4337 void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
4338 // ScalarEvolution's implementaiton of the print method is to print
4339 // out SCEV values of all instructions that are interesting. Doing
4340 // this potentially causes it to create new SCEV objects though,
4341 // which technically conflicts with the const qualifier. This isn't
4342 // observable from outside the class though (the hasSCEV function
4343 // notwithstanding), so casting away the const isn't dangerous.
4344 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
4346 OS << "Classifying expressions for: " << F->getName() << "\n";
4347 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
4348 if (isSCEVable(I->getType())) {
4351 SCEVHandle SV = SE.getSCEV(&*I);
4354 const Loop *L = LI->getLoopFor((*I).getParent());
4356 SCEVHandle AtUse = SE.getSCEVAtScope(SV, L);
4363 OS << "\t\t" "Exits: ";
4364 SCEVHandle ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
4365 if (!ExitValue->isLoopInvariant(L)) {
4366 OS << "<<Unknown>>";
4375 OS << "Determining loop execution counts for: " << F->getName() << "\n";
4376 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
4377 PrintLoopInfo(OS, &SE, *I);
4380 void ScalarEvolution::print(std::ostream &o, const Module *M) const {
4381 raw_os_ostream OS(o);