1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
63 #include "llvm/Constants.h"
64 #include "llvm/DerivedTypes.h"
65 #include "llvm/Instructions.h"
66 #include "llvm/Type.h"
67 #include "llvm/Value.h"
68 #include "llvm/Analysis/LoopInfo.h"
69 #include "llvm/Assembly/Writer.h"
70 #include "llvm/Transforms/Scalar.h"
71 #include "llvm/Transforms/Utils/Local.h"
72 #include "llvm/Support/CFG.h"
73 #include "llvm/Support/ConstantRange.h"
74 #include "llvm/Support/InstIterator.h"
75 #include "Support/CommandLine.h"
76 #include "Support/Statistic.h"
81 RegisterAnalysis<ScalarEvolution>
82 R("scalar-evolution", "Scalar Evolution Analysis");
85 NumBruteForceEvaluations("scalar-evolution",
86 "Number of brute force evaluations needed to calculate high-order polynomial exit values");
88 NumTripCountsComputed("scalar-evolution",
89 "Number of loops with predictable loop counts");
91 NumTripCountsNotComputed("scalar-evolution",
92 "Number of loops without predictable loop counts");
94 NumBruteForceTripCountsComputed("scalar-evolution",
95 "Number of loops with trip counts computed by force");
98 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
99 cl::desc("Maximum number of iterations SCEV will symbolically execute a constant derived loop"),
103 //===----------------------------------------------------------------------===//
104 // SCEV class definitions
105 //===----------------------------------------------------------------------===//
107 //===----------------------------------------------------------------------===//
108 // Implementation of the SCEV class.
111 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
112 /// than the complexity of the RHS. If the SCEVs have identical complexity,
113 /// order them by their addresses. This comparator is used to canonicalize
115 struct SCEVComplexityCompare {
116 bool operator()(SCEV *LHS, SCEV *RHS) {
117 if (LHS->getSCEVType() < RHS->getSCEVType())
119 if (LHS->getSCEVType() == RHS->getSCEVType())
127 void SCEV::dump() const {
131 /// getValueRange - Return the tightest constant bounds that this value is
132 /// known to have. This method is only valid on integer SCEV objects.
133 ConstantRange SCEV::getValueRange() const {
134 const Type *Ty = getType();
135 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
136 Ty = Ty->getUnsignedVersion();
137 // Default to a full range if no better information is available.
138 return ConstantRange(getType());
142 SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
144 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
145 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
149 const Type *SCEVCouldNotCompute::getType() const {
150 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
154 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
155 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
159 void SCEVCouldNotCompute::print(std::ostream &OS) const {
160 OS << "***COULDNOTCOMPUTE***";
163 bool SCEVCouldNotCompute::classof(const SCEV *S) {
164 return S->getSCEVType() == scCouldNotCompute;
168 // SCEVConstants - Only allow the creation of one SCEVConstant for any
169 // particular value. Don't use a SCEVHandle here, or else the object will
171 static std::map<ConstantInt*, SCEVConstant*> SCEVConstants;
174 SCEVConstant::~SCEVConstant() {
175 SCEVConstants.erase(V);
178 SCEVHandle SCEVConstant::get(ConstantInt *V) {
179 // Make sure that SCEVConstant instances are all unsigned.
180 if (V->getType()->isSigned()) {
181 const Type *NewTy = V->getType()->getUnsignedVersion();
182 V = cast<ConstantUInt>(ConstantExpr::getCast(V, NewTy));
185 SCEVConstant *&R = SCEVConstants[V];
186 if (R == 0) R = new SCEVConstant(V);
190 ConstantRange SCEVConstant::getValueRange() const {
191 return ConstantRange(V);
194 const Type *SCEVConstant::getType() const { return V->getType(); }
196 void SCEVConstant::print(std::ostream &OS) const {
197 WriteAsOperand(OS, V, false);
200 // SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
201 // particular input. Don't use a SCEVHandle here, or else the object will
203 static std::map<std::pair<SCEV*, const Type*>, SCEVTruncateExpr*> SCEVTruncates;
205 SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
206 : SCEV(scTruncate), Op(op), Ty(ty) {
207 assert(Op->getType()->isInteger() && Ty->isInteger() &&
209 "Cannot truncate non-integer value!");
210 assert(Op->getType()->getPrimitiveSize() > Ty->getPrimitiveSize() &&
211 "This is not a truncating conversion!");
214 SCEVTruncateExpr::~SCEVTruncateExpr() {
215 SCEVTruncates.erase(std::make_pair(Op, Ty));
218 ConstantRange SCEVTruncateExpr::getValueRange() const {
219 return getOperand()->getValueRange().truncate(getType());
222 void SCEVTruncateExpr::print(std::ostream &OS) const {
223 OS << "(truncate " << *Op << " to " << *Ty << ")";
226 // SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
227 // particular input. Don't use a SCEVHandle here, or else the object will never
229 static std::map<std::pair<SCEV*, const Type*>,
230 SCEVZeroExtendExpr*> SCEVZeroExtends;
232 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
233 : SCEV(scTruncate), Op(Op), Ty(ty) {
234 assert(Op->getType()->isInteger() && Ty->isInteger() &&
236 "Cannot zero extend non-integer value!");
237 assert(Op->getType()->getPrimitiveSize() < Ty->getPrimitiveSize() &&
238 "This is not an extending conversion!");
241 SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
242 SCEVZeroExtends.erase(std::make_pair(Op, Ty));
245 ConstantRange SCEVZeroExtendExpr::getValueRange() const {
246 return getOperand()->getValueRange().zeroExtend(getType());
249 void SCEVZeroExtendExpr::print(std::ostream &OS) const {
250 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
253 // SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
254 // particular input. Don't use a SCEVHandle here, or else the object will never
256 static std::map<std::pair<unsigned, std::vector<SCEV*> >,
257 SCEVCommutativeExpr*> SCEVCommExprs;
259 SCEVCommutativeExpr::~SCEVCommutativeExpr() {
260 SCEVCommExprs.erase(std::make_pair(getSCEVType(),
261 std::vector<SCEV*>(Operands.begin(),
265 void SCEVCommutativeExpr::print(std::ostream &OS) const {
266 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
267 const char *OpStr = getOperationStr();
268 OS << "(" << *Operands[0];
269 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
270 OS << OpStr << *Operands[i];
274 // SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
275 // input. Don't use a SCEVHandle here, or else the object will never be
277 static std::map<std::pair<SCEV*, SCEV*>, SCEVUDivExpr*> SCEVUDivs;
279 SCEVUDivExpr::~SCEVUDivExpr() {
280 SCEVUDivs.erase(std::make_pair(LHS, RHS));
283 void SCEVUDivExpr::print(std::ostream &OS) const {
284 OS << "(" << *LHS << " /u " << *RHS << ")";
287 const Type *SCEVUDivExpr::getType() const {
288 const Type *Ty = LHS->getType();
289 if (Ty->isSigned()) Ty = Ty->getUnsignedVersion();
293 // SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
294 // particular input. Don't use a SCEVHandle here, or else the object will never
296 static std::map<std::pair<const Loop *, std::vector<SCEV*> >,
297 SCEVAddRecExpr*> SCEVAddRecExprs;
299 SCEVAddRecExpr::~SCEVAddRecExpr() {
300 SCEVAddRecExprs.erase(std::make_pair(L,
301 std::vector<SCEV*>(Operands.begin(),
305 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
306 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
308 return !QueryLoop->contains(L->getHeader());
312 void SCEVAddRecExpr::print(std::ostream &OS) const {
313 OS << "{" << *Operands[0];
314 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
315 OS << ",+," << *Operands[i];
316 OS << "}<" << L->getHeader()->getName() + ">";
319 // SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
320 // value. Don't use a SCEVHandle here, or else the object will never be
322 static std::map<Value*, SCEVUnknown*> SCEVUnknowns;
324 SCEVUnknown::~SCEVUnknown() { SCEVUnknowns.erase(V); }
326 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
327 // All non-instruction values are loop invariant. All instructions are loop
328 // invariant if they are not contained in the specified loop.
329 if (Instruction *I = dyn_cast<Instruction>(V))
330 return !L->contains(I->getParent());
334 const Type *SCEVUnknown::getType() const {
338 void SCEVUnknown::print(std::ostream &OS) const {
339 WriteAsOperand(OS, V, false);
344 //===----------------------------------------------------------------------===//
345 // Simple SCEV method implementations
346 //===----------------------------------------------------------------------===//
348 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
349 /// specified signed integer value and return a SCEV for the constant.
350 SCEVHandle SCEVUnknown::getIntegerSCEV(int Val, const Type *Ty) {
353 C = Constant::getNullValue(Ty);
354 else if (Ty->isFloatingPoint())
355 C = ConstantFP::get(Ty, Val);
356 else if (Ty->isSigned())
357 C = ConstantSInt::get(Ty, Val);
359 C = ConstantSInt::get(Ty->getSignedVersion(), Val);
360 C = ConstantExpr::getCast(C, Ty);
362 return SCEVUnknown::get(C);
365 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
366 /// input value to the specified type. If the type must be extended, it is zero
368 static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
369 const Type *SrcTy = V->getType();
370 assert(SrcTy->isInteger() && Ty->isInteger() &&
371 "Cannot truncate or zero extend with non-integer arguments!");
372 if (SrcTy->getPrimitiveSize() == Ty->getPrimitiveSize())
373 return V; // No conversion
374 if (SrcTy->getPrimitiveSize() > Ty->getPrimitiveSize())
375 return SCEVTruncateExpr::get(V, Ty);
376 return SCEVZeroExtendExpr::get(V, Ty);
379 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
381 static SCEVHandle getNegativeSCEV(const SCEVHandle &V) {
382 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
383 return SCEVUnknown::get(ConstantExpr::getNeg(VC->getValue()));
385 return SCEVMulExpr::get(V, SCEVUnknown::getIntegerSCEV(-1, V->getType()));
388 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
390 static SCEVHandle getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS) {
392 return SCEVAddExpr::get(LHS, getNegativeSCEV(RHS));
396 /// Binomial - Evaluate N!/((N-M)!*M!) . Note that N is often large and M is
397 /// often very small, so we try to reduce the number of N! terms we need to
398 /// evaluate by evaluating this as (N!/(N-M)!)/M!
399 static ConstantInt *Binomial(ConstantInt *N, unsigned M) {
400 uint64_t NVal = N->getRawValue();
401 uint64_t FirstTerm = 1;
402 for (unsigned i = 0; i != M; ++i)
405 unsigned MFactorial = 1;
409 Constant *Result = ConstantUInt::get(Type::ULongTy, FirstTerm/MFactorial);
410 Result = ConstantExpr::getCast(Result, N->getType());
411 assert(isa<ConstantInt>(Result) && "Cast of integer not folded??");
412 return cast<ConstantInt>(Result);
415 /// PartialFact - Compute V!/(V-NumSteps)!
416 static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps) {
417 // Handle this case efficiently, it is common to have constant iteration
418 // counts while computing loop exit values.
419 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
420 uint64_t Val = SC->getValue()->getRawValue();
422 for (; NumSteps; --NumSteps)
423 Result *= Val-(NumSteps-1);
424 Constant *Res = ConstantUInt::get(Type::ULongTy, Result);
425 return SCEVUnknown::get(ConstantExpr::getCast(Res, V->getType()));
428 const Type *Ty = V->getType();
430 return SCEVUnknown::getIntegerSCEV(1, Ty);
432 SCEVHandle Result = V;
433 for (unsigned i = 1; i != NumSteps; ++i)
434 Result = SCEVMulExpr::get(Result, getMinusSCEV(V,
435 SCEVUnknown::getIntegerSCEV(i, Ty)));
440 /// evaluateAtIteration - Return the value of this chain of recurrences at
441 /// the specified iteration number. We can evaluate this recurrence by
442 /// multiplying each element in the chain by the binomial coefficient
443 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
445 /// A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3)
447 /// FIXME/VERIFY: I don't trust that this is correct in the face of overflow.
448 /// Is the binomial equation safe using modular arithmetic??
450 SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It) const {
451 SCEVHandle Result = getStart();
453 const Type *Ty = It->getType();
454 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
455 SCEVHandle BC = PartialFact(It, i);
457 SCEVHandle Val = SCEVUDivExpr::get(SCEVMulExpr::get(BC, getOperand(i)),
458 SCEVUnknown::getIntegerSCEV(Divisor,Ty));
459 Result = SCEVAddExpr::get(Result, Val);
465 //===----------------------------------------------------------------------===//
466 // SCEV Expression folder implementations
467 //===----------------------------------------------------------------------===//
469 SCEVHandle SCEVTruncateExpr::get(const SCEVHandle &Op, const Type *Ty) {
470 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
471 return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty));
473 // If the input value is a chrec scev made out of constants, truncate
474 // all of the constants.
475 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
476 std::vector<SCEVHandle> Operands;
477 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
478 // FIXME: This should allow truncation of other expression types!
479 if (isa<SCEVConstant>(AddRec->getOperand(i)))
480 Operands.push_back(get(AddRec->getOperand(i), Ty));
483 if (Operands.size() == AddRec->getNumOperands())
484 return SCEVAddRecExpr::get(Operands, AddRec->getLoop());
487 SCEVTruncateExpr *&Result = SCEVTruncates[std::make_pair(Op, Ty)];
488 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
492 SCEVHandle SCEVZeroExtendExpr::get(const SCEVHandle &Op, const Type *Ty) {
493 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
494 return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty));
496 // FIXME: If the input value is a chrec scev, and we can prove that the value
497 // did not overflow the old, smaller, value, we can zero extend all of the
498 // operands (often constants). This would allow analysis of something like
499 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
501 SCEVZeroExtendExpr *&Result = SCEVZeroExtends[std::make_pair(Op, Ty)];
502 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
506 // get - Get a canonical add expression, or something simpler if possible.
507 SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) {
508 assert(!Ops.empty() && "Cannot get empty add!");
509 if (Ops.size() == 1) return Ops[0];
511 // Sort by complexity, this groups all similar expression types together.
512 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
514 // If there are any constants, fold them together.
516 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
518 assert(Idx < Ops.size());
519 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
520 // We found two constants, fold them together!
521 Constant *Fold = ConstantExpr::getAdd(LHSC->getValue(), RHSC->getValue());
522 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
523 Ops[0] = SCEVConstant::get(CI);
524 Ops.erase(Ops.begin()+1); // Erase the folded element
525 if (Ops.size() == 1) return Ops[0];
527 // If we couldn't fold the expression, move to the next constant. Note
528 // that this is impossible to happen in practice because we always
529 // constant fold constant ints to constant ints.
534 // If we are left with a constant zero being added, strip it off.
535 if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
536 Ops.erase(Ops.begin());
541 if (Ops.size() == 1) return Ops[0];
543 // Okay, check to see if the same value occurs in the operand list twice. If
544 // so, merge them together into an multiply expression. Since we sorted the
545 // list, these values are required to be adjacent.
546 const Type *Ty = Ops[0]->getType();
547 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
548 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
549 // Found a match, merge the two values into a multiply, and add any
550 // remaining values to the result.
551 SCEVHandle Two = SCEVUnknown::getIntegerSCEV(2, Ty);
552 SCEVHandle Mul = SCEVMulExpr::get(Ops[i], Two);
555 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
557 return SCEVAddExpr::get(Ops);
560 // Okay, now we know the first non-constant operand. If there are add
561 // operands they would be next.
562 if (Idx < Ops.size()) {
563 bool DeletedAdd = false;
564 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
565 // If we have an add, expand the add operands onto the end of the operands
567 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
568 Ops.erase(Ops.begin()+Idx);
572 // If we deleted at least one add, we added operands to the end of the list,
573 // and they are not necessarily sorted. Recurse to resort and resimplify
574 // any operands we just aquired.
579 // Skip over the add expression until we get to a multiply.
580 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
583 // If we are adding something to a multiply expression, make sure the
584 // something is not already an operand of the multiply. If so, merge it into
586 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
587 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
588 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
589 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
590 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
591 if (MulOpSCEV == Ops[AddOp] &&
592 (Mul->getNumOperands() != 2 || !isa<SCEVConstant>(MulOpSCEV))) {
593 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
594 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
595 if (Mul->getNumOperands() != 2) {
596 // If the multiply has more than two operands, we must get the
598 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
599 MulOps.erase(MulOps.begin()+MulOp);
600 InnerMul = SCEVMulExpr::get(MulOps);
602 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, Ty);
603 SCEVHandle AddOne = SCEVAddExpr::get(InnerMul, One);
604 SCEVHandle OuterMul = SCEVMulExpr::get(AddOne, Ops[AddOp]);
605 if (Ops.size() == 2) return OuterMul;
607 Ops.erase(Ops.begin()+AddOp);
608 Ops.erase(Ops.begin()+Idx-1);
610 Ops.erase(Ops.begin()+Idx);
611 Ops.erase(Ops.begin()+AddOp-1);
613 Ops.push_back(OuterMul);
614 return SCEVAddExpr::get(Ops);
617 // Check this multiply against other multiplies being added together.
618 for (unsigned OtherMulIdx = Idx+1;
619 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
621 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
622 // If MulOp occurs in OtherMul, we can fold the two multiplies
624 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
625 OMulOp != e; ++OMulOp)
626 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
627 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
628 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
629 if (Mul->getNumOperands() != 2) {
630 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
631 MulOps.erase(MulOps.begin()+MulOp);
632 InnerMul1 = SCEVMulExpr::get(MulOps);
634 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
635 if (OtherMul->getNumOperands() != 2) {
636 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
638 MulOps.erase(MulOps.begin()+OMulOp);
639 InnerMul2 = SCEVMulExpr::get(MulOps);
641 SCEVHandle InnerMulSum = SCEVAddExpr::get(InnerMul1,InnerMul2);
642 SCEVHandle OuterMul = SCEVMulExpr::get(MulOpSCEV, InnerMulSum);
643 if (Ops.size() == 2) return OuterMul;
644 Ops.erase(Ops.begin()+Idx);
645 Ops.erase(Ops.begin()+OtherMulIdx-1);
646 Ops.push_back(OuterMul);
647 return SCEVAddExpr::get(Ops);
653 // If there are any add recurrences in the operands list, see if any other
654 // added values are loop invariant. If so, we can fold them into the
656 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
659 // Scan over all recurrences, trying to fold loop invariants into them.
660 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
661 // Scan all of the other operands to this add and add them to the vector if
662 // they are loop invariant w.r.t. the recurrence.
663 std::vector<SCEVHandle> LIOps;
664 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
665 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
666 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
667 LIOps.push_back(Ops[i]);
668 Ops.erase(Ops.begin()+i);
672 // If we found some loop invariants, fold them into the recurrence.
673 if (!LIOps.empty()) {
674 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
675 LIOps.push_back(AddRec->getStart());
677 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
678 AddRecOps[0] = SCEVAddExpr::get(LIOps);
680 SCEVHandle NewRec = SCEVAddRecExpr::get(AddRecOps, AddRec->getLoop());
681 // If all of the other operands were loop invariant, we are done.
682 if (Ops.size() == 1) return NewRec;
684 // Otherwise, add the folded AddRec by the non-liv parts.
685 for (unsigned i = 0;; ++i)
686 if (Ops[i] == AddRec) {
690 return SCEVAddExpr::get(Ops);
693 // Okay, if there weren't any loop invariants to be folded, check to see if
694 // there are multiple AddRec's with the same loop induction variable being
695 // added together. If so, we can fold them.
696 for (unsigned OtherIdx = Idx+1;
697 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
698 if (OtherIdx != Idx) {
699 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
700 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
701 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
702 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
703 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
704 if (i >= NewOps.size()) {
705 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
706 OtherAddRec->op_end());
709 NewOps[i] = SCEVAddExpr::get(NewOps[i], OtherAddRec->getOperand(i));
711 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
713 if (Ops.size() == 2) return NewAddRec;
715 Ops.erase(Ops.begin()+Idx);
716 Ops.erase(Ops.begin()+OtherIdx-1);
717 Ops.push_back(NewAddRec);
718 return SCEVAddExpr::get(Ops);
722 // Otherwise couldn't fold anything into this recurrence. Move onto the
726 // Okay, it looks like we really DO need an add expr. Check to see if we
727 // already have one, otherwise create a new one.
728 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
729 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scAddExpr,
731 if (Result == 0) Result = new SCEVAddExpr(Ops);
736 SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) {
737 assert(!Ops.empty() && "Cannot get empty mul!");
739 // Sort by complexity, this groups all similar expression types together.
740 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
742 // If there are any constants, fold them together.
744 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
746 // C1*(C2+V) -> C1*C2 + C1*V
748 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
749 if (Add->getNumOperands() == 2 &&
750 isa<SCEVConstant>(Add->getOperand(0)))
751 return SCEVAddExpr::get(SCEVMulExpr::get(LHSC, Add->getOperand(0)),
752 SCEVMulExpr::get(LHSC, Add->getOperand(1)));
756 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
757 // We found two constants, fold them together!
758 Constant *Fold = ConstantExpr::getMul(LHSC->getValue(), RHSC->getValue());
759 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
760 Ops[0] = SCEVConstant::get(CI);
761 Ops.erase(Ops.begin()+1); // Erase the folded element
762 if (Ops.size() == 1) return Ops[0];
764 // If we couldn't fold the expression, move to the next constant. Note
765 // that this is impossible to happen in practice because we always
766 // constant fold constant ints to constant ints.
771 // If we are left with a constant one being multiplied, strip it off.
772 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
773 Ops.erase(Ops.begin());
775 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
776 // If we have a multiply of zero, it will always be zero.
781 // Skip over the add expression until we get to a multiply.
782 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
788 // If there are mul operands inline them all into this expression.
789 if (Idx < Ops.size()) {
790 bool DeletedMul = false;
791 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
792 // If we have an mul, expand the mul operands onto the end of the operands
794 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
795 Ops.erase(Ops.begin()+Idx);
799 // If we deleted at least one mul, we added operands to the end of the list,
800 // and they are not necessarily sorted. Recurse to resort and resimplify
801 // any operands we just aquired.
806 // If there are any add recurrences in the operands list, see if any other
807 // added values are loop invariant. If so, we can fold them into the
809 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
812 // Scan over all recurrences, trying to fold loop invariants into them.
813 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
814 // Scan all of the other operands to this mul and add them to the vector if
815 // they are loop invariant w.r.t. the recurrence.
816 std::vector<SCEVHandle> LIOps;
817 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
818 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
819 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
820 LIOps.push_back(Ops[i]);
821 Ops.erase(Ops.begin()+i);
825 // If we found some loop invariants, fold them into the recurrence.
826 if (!LIOps.empty()) {
827 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
828 std::vector<SCEVHandle> NewOps;
829 NewOps.reserve(AddRec->getNumOperands());
830 if (LIOps.size() == 1) {
831 SCEV *Scale = LIOps[0];
832 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
833 NewOps.push_back(SCEVMulExpr::get(Scale, AddRec->getOperand(i)));
835 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
836 std::vector<SCEVHandle> MulOps(LIOps);
837 MulOps.push_back(AddRec->getOperand(i));
838 NewOps.push_back(SCEVMulExpr::get(MulOps));
842 SCEVHandle NewRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
844 // If all of the other operands were loop invariant, we are done.
845 if (Ops.size() == 1) return NewRec;
847 // Otherwise, multiply the folded AddRec by the non-liv parts.
848 for (unsigned i = 0;; ++i)
849 if (Ops[i] == AddRec) {
853 return SCEVMulExpr::get(Ops);
856 // Okay, if there weren't any loop invariants to be folded, check to see if
857 // there are multiple AddRec's with the same loop induction variable being
858 // multiplied together. If so, we can fold them.
859 for (unsigned OtherIdx = Idx+1;
860 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
861 if (OtherIdx != Idx) {
862 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
863 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
864 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
865 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
866 SCEVHandle NewStart = SCEVMulExpr::get(F->getStart(),
868 SCEVHandle B = F->getStepRecurrence();
869 SCEVHandle D = G->getStepRecurrence();
870 SCEVHandle NewStep = SCEVAddExpr::get(SCEVMulExpr::get(F, D),
871 SCEVMulExpr::get(G, B),
872 SCEVMulExpr::get(B, D));
873 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewStart, NewStep,
875 if (Ops.size() == 2) return NewAddRec;
877 Ops.erase(Ops.begin()+Idx);
878 Ops.erase(Ops.begin()+OtherIdx-1);
879 Ops.push_back(NewAddRec);
880 return SCEVMulExpr::get(Ops);
884 // Otherwise couldn't fold anything into this recurrence. Move onto the
888 // Okay, it looks like we really DO need an mul expr. Check to see if we
889 // already have one, otherwise create a new one.
890 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
891 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scMulExpr,
893 if (Result == 0) Result = new SCEVMulExpr(Ops);
897 SCEVHandle SCEVUDivExpr::get(const SCEVHandle &LHS, const SCEVHandle &RHS) {
898 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
899 if (RHSC->getValue()->equalsInt(1))
900 return LHS; // X /u 1 --> x
901 if (RHSC->getValue()->isAllOnesValue())
902 return getNegativeSCEV(LHS); // X /u -1 --> -x
904 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
905 Constant *LHSCV = LHSC->getValue();
906 Constant *RHSCV = RHSC->getValue();
907 if (LHSCV->getType()->isSigned())
908 LHSCV = ConstantExpr::getCast(LHSCV,
909 LHSCV->getType()->getUnsignedVersion());
910 if (RHSCV->getType()->isSigned())
911 RHSCV = ConstantExpr::getCast(RHSCV, LHSCV->getType());
912 return SCEVUnknown::get(ConstantExpr::getDiv(LHSCV, RHSCV));
916 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
918 SCEVUDivExpr *&Result = SCEVUDivs[std::make_pair(LHS, RHS)];
919 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
924 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
925 /// specified loop. Simplify the expression as much as possible.
926 SCEVHandle SCEVAddRecExpr::get(const SCEVHandle &Start,
927 const SCEVHandle &Step, const Loop *L) {
928 std::vector<SCEVHandle> Operands;
929 Operands.push_back(Start);
930 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
931 if (StepChrec->getLoop() == L) {
932 Operands.insert(Operands.end(), StepChrec->op_begin(),
933 StepChrec->op_end());
934 return get(Operands, L);
937 Operands.push_back(Step);
938 return get(Operands, L);
941 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
942 /// specified loop. Simplify the expression as much as possible.
943 SCEVHandle SCEVAddRecExpr::get(std::vector<SCEVHandle> &Operands,
945 if (Operands.size() == 1) return Operands[0];
947 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
948 if (StepC->getValue()->isNullValue()) {
950 return get(Operands, L); // { X,+,0 } --> X
953 SCEVAddRecExpr *&Result =
954 SCEVAddRecExprs[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
956 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
960 SCEVHandle SCEVUnknown::get(Value *V) {
961 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
962 return SCEVConstant::get(CI);
963 SCEVUnknown *&Result = SCEVUnknowns[V];
964 if (Result == 0) Result = new SCEVUnknown(V);
969 //===----------------------------------------------------------------------===//
970 // ScalarEvolutionsImpl Definition and Implementation
971 //===----------------------------------------------------------------------===//
973 /// ScalarEvolutionsImpl - This class implements the main driver for the scalar
977 struct ScalarEvolutionsImpl {
978 /// F - The function we are analyzing.
982 /// LI - The loop information for the function we are currently analyzing.
986 /// UnknownValue - This SCEV is used to represent unknown trip counts and
988 SCEVHandle UnknownValue;
990 /// Scalars - This is a cache of the scalars we have analyzed so far.
992 std::map<Value*, SCEVHandle> Scalars;
994 /// IterationCounts - Cache the iteration count of the loops for this
995 /// function as they are computed.
996 std::map<const Loop*, SCEVHandle> IterationCounts;
998 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
999 /// the PHI instructions that we attempt to compute constant evolutions for.
1000 /// This allows us to avoid potentially expensive recomputation of these
1001 /// properties. An instruction maps to null if we are unable to compute its
1003 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
1006 ScalarEvolutionsImpl(Function &f, LoopInfo &li)
1007 : F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1009 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1010 /// expression and create a new one.
1011 SCEVHandle getSCEV(Value *V);
1013 /// getSCEVAtScope - Compute the value of the specified expression within
1014 /// the indicated loop (which may be null to indicate in no loop). If the
1015 /// expression cannot be evaluated, return UnknownValue itself.
1016 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1019 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1020 /// an analyzable loop-invariant iteration count.
1021 bool hasLoopInvariantIterationCount(const Loop *L);
1023 /// getIterationCount - If the specified loop has a predictable iteration
1024 /// count, return it. Note that it is not valid to call this method on a
1025 /// loop without a loop-invariant iteration count.
1026 SCEVHandle getIterationCount(const Loop *L);
1028 /// deleteInstructionFromRecords - This method should be called by the
1029 /// client before it removes an instruction from the program, to make sure
1030 /// that no dangling references are left around.
1031 void deleteInstructionFromRecords(Instruction *I);
1034 /// createSCEV - We know that there is no SCEV for the specified value.
1035 /// Analyze the expression.
1036 SCEVHandle createSCEV(Value *V);
1037 SCEVHandle createNodeForCast(CastInst *CI);
1039 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1041 SCEVHandle createNodeForPHI(PHINode *PN);
1042 void UpdatePHIUserScalarEntries(Instruction *I, PHINode *PN,
1043 std::set<Instruction*> &UpdatedInsts);
1045 /// ComputeIterationCount - Compute the number of times the specified loop
1047 SCEVHandle ComputeIterationCount(const Loop *L);
1049 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1050 /// constant number of times (the condition evolves only from constants),
1051 /// try to evaluate a few iterations of the loop until we get the exit
1052 /// condition gets a value of ExitWhen (true or false). If we cannot
1053 /// evaluate the trip count of the loop, return UnknownValue.
1054 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1057 /// HowFarToZero - Return the number of times a backedge comparing the
1058 /// specified value to zero will execute. If not computable, return
1060 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1062 /// HowFarToNonZero - Return the number of times a backedge checking the
1063 /// specified value for nonzero will execute. If not computable, return
1065 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
1067 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1068 /// in the header of its containing loop, we know the loop executes a
1069 /// constant number of times, and the PHI node is just a recurrence
1070 /// involving constants, fold it.
1071 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its,
1076 //===----------------------------------------------------------------------===//
1077 // Basic SCEV Analysis and PHI Idiom Recognition Code
1080 /// deleteInstructionFromRecords - This method should be called by the
1081 /// client before it removes an instruction from the program, to make sure
1082 /// that no dangling references are left around.
1083 void ScalarEvolutionsImpl::deleteInstructionFromRecords(Instruction *I) {
1085 if (PHINode *PN = dyn_cast<PHINode>(I))
1086 ConstantEvolutionLoopExitValue.erase(PN);
1090 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1091 /// expression and create a new one.
1092 SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1093 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1095 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1096 if (I != Scalars.end()) return I->second;
1097 SCEVHandle S = createSCEV(V);
1098 Scalars.insert(std::make_pair(V, S));
1103 /// UpdatePHIUserScalarEntries - After PHI node analysis, we have a bunch of
1104 /// entries in the scalar map that refer to the "symbolic" PHI value instead of
1105 /// the recurrence value. After we resolve the PHI we must loop over all of the
1106 /// using instructions that have scalar map entries and update them.
1107 void ScalarEvolutionsImpl::UpdatePHIUserScalarEntries(Instruction *I,
1109 std::set<Instruction*> &UpdatedInsts) {
1110 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1111 if (SI == Scalars.end()) return; // This scalar wasn't previous processed.
1112 if (UpdatedInsts.insert(I).second) {
1113 Scalars.erase(SI); // Remove the old entry
1114 getSCEV(I); // Calculate the new entry
1116 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1118 UpdatePHIUserScalarEntries(cast<Instruction>(*UI), PN, UpdatedInsts);
1123 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1124 /// a loop header, making it a potential recurrence, or it doesn't.
1126 SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1127 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1128 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1129 if (L->getHeader() == PN->getParent()) {
1130 // If it lives in the loop header, it has two incoming values, one
1131 // from outside the loop, and one from inside.
1132 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1133 unsigned BackEdge = IncomingEdge^1;
1135 // While we are analyzing this PHI node, handle its value symbolically.
1136 SCEVHandle SymbolicName = SCEVUnknown::get(PN);
1137 assert(Scalars.find(PN) == Scalars.end() &&
1138 "PHI node already processed?");
1139 Scalars.insert(std::make_pair(PN, SymbolicName));
1141 // Using this symbolic name for the PHI, analyze the value coming around
1143 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1145 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1146 // has a special value for the first iteration of the loop.
1148 // If the value coming around the backedge is an add with the symbolic
1149 // value we just inserted, then we found a simple induction variable!
1150 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1151 // If there is a single occurrence of the symbolic value, replace it
1152 // with a recurrence.
1153 unsigned FoundIndex = Add->getNumOperands();
1154 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1155 if (Add->getOperand(i) == SymbolicName)
1156 if (FoundIndex == e) {
1161 if (FoundIndex != Add->getNumOperands()) {
1162 // Create an add with everything but the specified operand.
1163 std::vector<SCEVHandle> Ops;
1164 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1165 if (i != FoundIndex)
1166 Ops.push_back(Add->getOperand(i));
1167 SCEVHandle Accum = SCEVAddExpr::get(Ops);
1169 // This is not a valid addrec if the step amount is varying each
1170 // loop iteration, but is not itself an addrec in this loop.
1171 if (Accum->isLoopInvariant(L) ||
1172 (isa<SCEVAddRecExpr>(Accum) &&
1173 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1174 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1175 SCEVHandle PHISCEV = SCEVAddRecExpr::get(StartVal, Accum, L);
1177 // Okay, for the entire analysis of this edge we assumed the PHI
1178 // to be symbolic. We now need to go back and update all of the
1179 // entries for the scalars that use the PHI (except for the PHI
1180 // itself) to use the new analyzed value instead of the "symbolic"
1182 Scalars.find(PN)->second = PHISCEV; // Update the PHI value
1183 std::set<Instruction*> UpdatedInsts;
1184 UpdatedInsts.insert(PN);
1185 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
1187 UpdatePHIUserScalarEntries(cast<Instruction>(*UI), PN,
1194 return SymbolicName;
1197 // If it's not a loop phi, we can't handle it yet.
1198 return SCEVUnknown::get(PN);
1201 /// createNodeForCast - Handle the various forms of casts that we support.
1203 SCEVHandle ScalarEvolutionsImpl::createNodeForCast(CastInst *CI) {
1204 const Type *SrcTy = CI->getOperand(0)->getType();
1205 const Type *DestTy = CI->getType();
1207 // If this is a noop cast (ie, conversion from int to uint), ignore it.
1208 if (SrcTy->isLosslesslyConvertibleTo(DestTy))
1209 return getSCEV(CI->getOperand(0));
1211 if (SrcTy->isInteger() && DestTy->isInteger()) {
1212 // Otherwise, if this is a truncating integer cast, we can represent this
1214 if (SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize())
1215 return SCEVTruncateExpr::get(getSCEV(CI->getOperand(0)),
1216 CI->getType()->getUnsignedVersion());
1217 if (SrcTy->isUnsigned() &&
1218 SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize())
1219 return SCEVZeroExtendExpr::get(getSCEV(CI->getOperand(0)),
1220 CI->getType()->getUnsignedVersion());
1223 // If this is an sign or zero extending cast and we can prove that the value
1224 // will never overflow, we could do similar transformations.
1226 // Otherwise, we can't handle this cast!
1227 return SCEVUnknown::get(CI);
1231 /// createSCEV - We know that there is no SCEV for the specified value.
1232 /// Analyze the expression.
1234 SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1235 if (Instruction *I = dyn_cast<Instruction>(V)) {
1236 switch (I->getOpcode()) {
1237 case Instruction::Add:
1238 return SCEVAddExpr::get(getSCEV(I->getOperand(0)),
1239 getSCEV(I->getOperand(1)));
1240 case Instruction::Mul:
1241 return SCEVMulExpr::get(getSCEV(I->getOperand(0)),
1242 getSCEV(I->getOperand(1)));
1243 case Instruction::Div:
1244 if (V->getType()->isInteger() && V->getType()->isUnsigned())
1245 return SCEVUDivExpr::get(getSCEV(I->getOperand(0)),
1246 getSCEV(I->getOperand(1)));
1249 case Instruction::Sub:
1250 return getMinusSCEV(getSCEV(I->getOperand(0)), getSCEV(I->getOperand(1)));
1252 case Instruction::Shl:
1253 // Turn shift left of a constant amount into a multiply.
1254 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1255 Constant *X = ConstantInt::get(V->getType(), 1);
1256 X = ConstantExpr::getShl(X, SA);
1257 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1261 case Instruction::Shr:
1262 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
1263 if (V->getType()->isUnsigned()) {
1264 Constant *X = ConstantInt::get(V->getType(), 1);
1265 X = ConstantExpr::getShl(X, SA);
1266 return SCEVUDivExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1270 case Instruction::Cast:
1271 return createNodeForCast(cast<CastInst>(I));
1273 case Instruction::PHI:
1274 return createNodeForPHI(cast<PHINode>(I));
1276 default: // We cannot analyze this expression.
1281 return SCEVUnknown::get(V);
1286 //===----------------------------------------------------------------------===//
1287 // Iteration Count Computation Code
1290 /// getIterationCount - If the specified loop has a predictable iteration
1291 /// count, return it. Note that it is not valid to call this method on a
1292 /// loop without a loop-invariant iteration count.
1293 SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1294 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1295 if (I == IterationCounts.end()) {
1296 SCEVHandle ItCount = ComputeIterationCount(L);
1297 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1298 if (ItCount != UnknownValue) {
1299 assert(ItCount->isLoopInvariant(L) &&
1300 "Computed trip count isn't loop invariant for loop!");
1301 ++NumTripCountsComputed;
1302 } else if (isa<PHINode>(L->getHeader()->begin())) {
1303 // Only count loops that have phi nodes as not being computable.
1304 ++NumTripCountsNotComputed;
1310 /// ComputeIterationCount - Compute the number of times the specified loop
1312 SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1313 // If the loop has a non-one exit block count, we can't analyze it.
1314 std::vector<BasicBlock*> ExitBlocks;
1315 L->getExitBlocks(ExitBlocks);
1316 if (ExitBlocks.size() != 1) return UnknownValue;
1318 // Okay, there is one exit block. Try to find the condition that causes the
1319 // loop to be exited.
1320 BasicBlock *ExitBlock = ExitBlocks[0];
1322 BasicBlock *ExitingBlock = 0;
1323 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1325 if (L->contains(*PI)) {
1326 if (ExitingBlock == 0)
1329 return UnknownValue; // More than one block exiting!
1331 assert(ExitingBlock && "No exits from loop, something is broken!");
1333 // Okay, we've computed the exiting block. See what condition causes us to
1336 // FIXME: we should be able to handle switch instructions (with a single exit)
1337 // FIXME: We should handle cast of int to bool as well
1338 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1339 if (ExitBr == 0) return UnknownValue;
1340 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1341 SetCondInst *ExitCond = dyn_cast<SetCondInst>(ExitBr->getCondition());
1342 if (ExitCond == 0) // Not a setcc
1343 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1344 ExitBr->getSuccessor(0) == ExitBlock);
1346 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1347 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1349 // Try to evaluate any dependencies out of the loop.
1350 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1351 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1352 Tmp = getSCEVAtScope(RHS, L);
1353 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1355 // If the condition was exit on true, convert the condition to exit on false.
1356 Instruction::BinaryOps Cond;
1357 if (ExitBr->getSuccessor(1) == ExitBlock)
1358 Cond = ExitCond->getOpcode();
1360 Cond = ExitCond->getInverseCondition();
1362 // At this point, we would like to compute how many iterations of the loop the
1363 // predicate will return true for these inputs.
1364 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1365 // If there is a constant, force it into the RHS.
1366 std::swap(LHS, RHS);
1367 Cond = SetCondInst::getSwappedCondition(Cond);
1370 // FIXME: think about handling pointer comparisons! i.e.:
1371 // while (P != P+100) ++P;
1373 // If we have a comparison of a chrec against a constant, try to use value
1374 // ranges to answer this query.
1375 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1376 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1377 if (AddRec->getLoop() == L) {
1378 // Form the comparison range using the constant of the correct type so
1379 // that the ConstantRange class knows to do a signed or unsigned
1381 ConstantInt *CompVal = RHSC->getValue();
1382 const Type *RealTy = ExitCond->getOperand(0)->getType();
1383 CompVal = dyn_cast<ConstantInt>(ConstantExpr::getCast(CompVal, RealTy));
1385 // Form the constant range.
1386 ConstantRange CompRange(Cond, CompVal);
1388 // Now that we have it, if it's signed, convert it to an unsigned
1390 if (CompRange.getLower()->getType()->isSigned()) {
1391 const Type *NewTy = RHSC->getValue()->getType();
1392 Constant *NewL = ConstantExpr::getCast(CompRange.getLower(), NewTy);
1393 Constant *NewU = ConstantExpr::getCast(CompRange.getUpper(), NewTy);
1394 CompRange = ConstantRange(NewL, NewU);
1397 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange);
1398 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1403 case Instruction::SetNE: // while (X != Y)
1404 // Convert to: while (X-Y != 0)
1405 if (LHS->getType()->isInteger()) {
1406 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
1407 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1410 case Instruction::SetEQ:
1411 // Convert to: while (X-Y == 0) // while (X == Y)
1412 if (LHS->getType()->isInteger()) {
1413 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
1414 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1419 std::cerr << "ComputeIterationCount ";
1420 if (ExitCond->getOperand(0)->getType()->isUnsigned())
1421 std::cerr << "[unsigned] ";
1422 std::cerr << *LHS << " "
1423 << Instruction::getOpcodeName(Cond) << " " << *RHS << "\n";
1428 return ComputeIterationCountExhaustively(L, ExitCond,
1429 ExitBr->getSuccessor(0) == ExitBlock);
1432 /// CanConstantFold - Return true if we can constant fold an instruction of the
1433 /// specified type, assuming that all operands were constants.
1434 static bool CanConstantFold(const Instruction *I) {
1435 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I) ||
1436 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
1439 if (const CallInst *CI = dyn_cast<CallInst>(I))
1440 if (const Function *F = CI->getCalledFunction())
1441 return canConstantFoldCallTo((Function*)F); // FIXME: elim cast
1445 /// ConstantFold - Constant fold an instruction of the specified type with the
1446 /// specified constant operands. This function may modify the operands vector.
1447 static Constant *ConstantFold(const Instruction *I,
1448 std::vector<Constant*> &Operands) {
1449 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
1450 return ConstantExpr::get(I->getOpcode(), Operands[0], Operands[1]);
1452 switch (I->getOpcode()) {
1453 case Instruction::Cast:
1454 return ConstantExpr::getCast(Operands[0], I->getType());
1455 case Instruction::Select:
1456 return ConstantExpr::getSelect(Operands[0], Operands[1], Operands[2]);
1457 case Instruction::Call:
1458 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Operands[0])) {
1459 Operands.erase(Operands.begin());
1460 return ConstantFoldCall(cast<Function>(CPR->getValue()), Operands);
1464 case Instruction::GetElementPtr:
1465 Constant *Base = Operands[0];
1466 Operands.erase(Operands.begin());
1467 return ConstantExpr::getGetElementPtr(Base, Operands);
1473 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
1474 /// in the loop that V is derived from. We allow arbitrary operations along the
1475 /// way, but the operands of an operation must either be constants or a value
1476 /// derived from a constant PHI. If this expression does not fit with these
1477 /// constraints, return null.
1478 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
1479 // If this is not an instruction, or if this is an instruction outside of the
1480 // loop, it can't be derived from a loop PHI.
1481 Instruction *I = dyn_cast<Instruction>(V);
1482 if (I == 0 || !L->contains(I->getParent())) return 0;
1484 if (PHINode *PN = dyn_cast<PHINode>(I))
1485 if (L->getHeader() == I->getParent())
1488 // We don't currently keep track of the control flow needed to evaluate
1489 // PHIs, so we cannot handle PHIs inside of loops.
1492 // If we won't be able to constant fold this expression even if the operands
1493 // are constants, return early.
1494 if (!CanConstantFold(I)) return 0;
1496 // Otherwise, we can evaluate this instruction if all of its operands are
1497 // constant or derived from a PHI node themselves.
1499 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
1500 if (!(isa<Constant>(I->getOperand(Op)) ||
1501 isa<GlobalValue>(I->getOperand(Op)))) {
1502 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
1503 if (P == 0) return 0; // Not evolving from PHI
1507 return 0; // Evolving from multiple different PHIs.
1510 // This is a expression evolving from a constant PHI!
1514 /// EvaluateExpression - Given an expression that passes the
1515 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
1516 /// in the loop has the value PHIVal. If we can't fold this expression for some
1517 /// reason, return null.
1518 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
1519 if (isa<PHINode>(V)) return PHIVal;
1520 if (Constant *C = dyn_cast<Constant>(V)) return C;
1521 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
1522 return ConstantPointerRef::get(GV);
1523 Instruction *I = cast<Instruction>(V);
1525 std::vector<Constant*> Operands;
1526 Operands.resize(I->getNumOperands());
1528 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1529 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
1530 if (Operands[i] == 0) return 0;
1533 return ConstantFold(I, Operands);
1536 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1537 /// in the header of its containing loop, we know the loop executes a
1538 /// constant number of times, and the PHI node is just a recurrence
1539 /// involving constants, fold it.
1540 Constant *ScalarEvolutionsImpl::
1541 getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its, const Loop *L) {
1542 std::map<PHINode*, Constant*>::iterator I =
1543 ConstantEvolutionLoopExitValue.find(PN);
1544 if (I != ConstantEvolutionLoopExitValue.end())
1547 if (Its > MaxBruteForceIterations)
1548 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
1550 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
1552 // Since the loop is canonicalized, the PHI node must have two entries. One
1553 // entry must be a constant (coming in from outside of the loop), and the
1554 // second must be derived from the same PHI.
1555 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1556 Constant *StartCST =
1557 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1559 return RetVal = 0; // Must be a constant.
1561 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1562 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1564 return RetVal = 0; // Not derived from same PHI.
1566 // Execute the loop symbolically to determine the exit value.
1567 unsigned IterationNum = 0;
1568 unsigned NumIterations = Its;
1569 if (NumIterations != Its)
1570 return RetVal = 0; // More than 2^32 iterations??
1572 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
1573 if (IterationNum == NumIterations)
1574 return RetVal = PHIVal; // Got exit value!
1576 // Compute the value of the PHI node for the next iteration.
1577 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1578 if (NextPHI == PHIVal)
1579 return RetVal = NextPHI; // Stopped evolving!
1581 return 0; // Couldn't evaluate!
1586 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1587 /// constant number of times (the condition evolves only from constants),
1588 /// try to evaluate a few iterations of the loop until we get the exit
1589 /// condition gets a value of ExitWhen (true or false). If we cannot
1590 /// evaluate the trip count of the loop, return UnknownValue.
1591 SCEVHandle ScalarEvolutionsImpl::
1592 ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
1593 PHINode *PN = getConstantEvolvingPHI(Cond, L);
1594 if (PN == 0) return UnknownValue;
1596 // Since the loop is canonicalized, the PHI node must have two entries. One
1597 // entry must be a constant (coming in from outside of the loop), and the
1598 // second must be derived from the same PHI.
1599 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1600 Constant *StartCST =
1601 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1602 if (StartCST == 0) return UnknownValue; // Must be a constant.
1604 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1605 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1606 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
1608 // Okay, we find a PHI node that defines the trip count of this loop. Execute
1609 // the loop symbolically to determine when the condition gets a value of
1611 unsigned IterationNum = 0;
1612 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
1613 for (Constant *PHIVal = StartCST;
1614 IterationNum != MaxIterations; ++IterationNum) {
1615 ConstantBool *CondVal =
1616 dyn_cast_or_null<ConstantBool>(EvaluateExpression(Cond, PHIVal));
1617 if (!CondVal) return UnknownValue; // Couldn't symbolically evaluate.
1619 if (CondVal->getValue() == ExitWhen) {
1620 ConstantEvolutionLoopExitValue[PN] = PHIVal;
1621 ++NumBruteForceTripCountsComputed;
1622 return SCEVConstant::get(ConstantUInt::get(Type::UIntTy, IterationNum));
1625 // Compute the value of the PHI node for the next iteration.
1626 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1627 if (NextPHI == 0 || NextPHI == PHIVal)
1628 return UnknownValue; // Couldn't evaluate or not making progress...
1632 // Too many iterations were needed to evaluate.
1633 return UnknownValue;
1636 /// getSCEVAtScope - Compute the value of the specified expression within the
1637 /// indicated loop (which may be null to indicate in no loop). If the
1638 /// expression cannot be evaluated, return UnknownValue.
1639 SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
1640 // FIXME: this should be turned into a virtual method on SCEV!
1642 if (isa<SCEVConstant>(V)) return V;
1644 // If this instruction is evolves from a constant-evolving PHI, compute the
1645 // exit value from the loop without using SCEVs.
1646 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
1647 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
1648 const Loop *LI = this->LI[I->getParent()];
1649 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
1650 if (PHINode *PN = dyn_cast<PHINode>(I))
1651 if (PN->getParent() == LI->getHeader()) {
1652 // Okay, there is no closed form solution for the PHI node. Check
1653 // to see if the loop that contains it has a known iteration count.
1654 // If so, we may be able to force computation of the exit value.
1655 SCEVHandle IterationCount = getIterationCount(LI);
1656 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
1657 // Okay, we know how many times the containing loop executes. If
1658 // this is a constant evolving PHI node, get the final value at
1659 // the specified iteration number.
1660 Constant *RV = getConstantEvolutionLoopExitValue(PN,
1661 ICC->getValue()->getRawValue(),
1663 if (RV) return SCEVUnknown::get(RV);
1667 // Okay, this is a some expression that we cannot symbolically evaluate
1668 // into a SCEV. Check to see if it's possible to symbolically evaluate
1669 // the arguments into constants, and if see, try to constant propagate the
1670 // result. This is particularly useful for computing loop exit values.
1671 if (CanConstantFold(I)) {
1672 std::vector<Constant*> Operands;
1673 Operands.reserve(I->getNumOperands());
1674 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1675 Value *Op = I->getOperand(i);
1676 if (Constant *C = dyn_cast<Constant>(Op)) {
1677 Operands.push_back(C);
1678 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Op)) {
1679 Operands.push_back(ConstantPointerRef::get(GV));
1681 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
1682 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
1683 Operands.push_back(ConstantExpr::getCast(SC->getValue(),
1685 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
1686 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
1687 Operands.push_back(ConstantExpr::getCast(C, Op->getType()));
1695 return SCEVUnknown::get(ConstantFold(I, Operands));
1699 // This is some other type of SCEVUnknown, just return it.
1703 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
1704 // Avoid performing the look-up in the common case where the specified
1705 // expression has no loop-variant portions.
1706 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
1707 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1708 if (OpAtScope != Comm->getOperand(i)) {
1709 if (OpAtScope == UnknownValue) return UnknownValue;
1710 // Okay, at least one of these operands is loop variant but might be
1711 // foldable. Build a new instance of the folded commutative expression.
1712 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
1713 NewOps.push_back(OpAtScope);
1715 for (++i; i != e; ++i) {
1716 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1717 if (OpAtScope == UnknownValue) return UnknownValue;
1718 NewOps.push_back(OpAtScope);
1720 if (isa<SCEVAddExpr>(Comm))
1721 return SCEVAddExpr::get(NewOps);
1722 assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
1723 return SCEVMulExpr::get(NewOps);
1726 // If we got here, all operands are loop invariant.
1730 if (SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(V)) {
1731 SCEVHandle LHS = getSCEVAtScope(UDiv->getLHS(), L);
1732 if (LHS == UnknownValue) return LHS;
1733 SCEVHandle RHS = getSCEVAtScope(UDiv->getRHS(), L);
1734 if (RHS == UnknownValue) return RHS;
1735 if (LHS == UDiv->getLHS() && RHS == UDiv->getRHS())
1736 return UDiv; // must be loop invariant
1737 return SCEVUDivExpr::get(LHS, RHS);
1740 // If this is a loop recurrence for a loop that does not contain L, then we
1741 // are dealing with the final value computed by the loop.
1742 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
1743 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
1744 // To evaluate this recurrence, we need to know how many times the AddRec
1745 // loop iterates. Compute this now.
1746 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
1747 if (IterationCount == UnknownValue) return UnknownValue;
1748 IterationCount = getTruncateOrZeroExtend(IterationCount,
1751 // If the value is affine, simplify the expression evaluation to just
1752 // Start + Step*IterationCount.
1753 if (AddRec->isAffine())
1754 return SCEVAddExpr::get(AddRec->getStart(),
1755 SCEVMulExpr::get(IterationCount,
1756 AddRec->getOperand(1)));
1758 // Otherwise, evaluate it the hard way.
1759 return AddRec->evaluateAtIteration(IterationCount);
1761 return UnknownValue;
1764 //assert(0 && "Unknown SCEV type!");
1765 return UnknownValue;
1769 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
1770 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
1771 /// might be the same) or two SCEVCouldNotCompute objects.
1773 static std::pair<SCEVHandle,SCEVHandle>
1774 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) {
1775 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
1776 SCEVConstant *L = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
1777 SCEVConstant *M = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
1778 SCEVConstant *N = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
1780 // We currently can only solve this if the coefficients are constants.
1781 if (!L || !M || !N) {
1782 SCEV *CNC = new SCEVCouldNotCompute();
1783 return std::make_pair(CNC, CNC);
1786 Constant *Two = ConstantInt::get(L->getValue()->getType(), 2);
1788 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
1789 Constant *C = L->getValue();
1790 // The B coefficient is M-N/2
1791 Constant *B = ConstantExpr::getSub(M->getValue(),
1792 ConstantExpr::getDiv(N->getValue(),
1794 // The A coefficient is N/2
1795 Constant *A = ConstantExpr::getDiv(N->getValue(), Two);
1797 // Compute the B^2-4ac term.
1798 Constant *SqrtTerm =
1799 ConstantExpr::getMul(ConstantInt::get(C->getType(), 4),
1800 ConstantExpr::getMul(A, C));
1801 SqrtTerm = ConstantExpr::getSub(ConstantExpr::getMul(B, B), SqrtTerm);
1803 // Compute floor(sqrt(B^2-4ac))
1804 ConstantUInt *SqrtVal =
1805 cast<ConstantUInt>(ConstantExpr::getCast(SqrtTerm,
1806 SqrtTerm->getType()->getUnsignedVersion()));
1807 uint64_t SqrtValV = SqrtVal->getValue();
1808 uint64_t SqrtValV2 = (uint64_t)sqrt(SqrtValV);
1809 // The square root might not be precise for arbitrary 64-bit integer
1810 // values. Do some sanity checks to ensure it's correct.
1811 if (SqrtValV2*SqrtValV2 > SqrtValV ||
1812 (SqrtValV2+1)*(SqrtValV2+1) <= SqrtValV) {
1813 SCEV *CNC = new SCEVCouldNotCompute();
1814 return std::make_pair(CNC, CNC);
1817 SqrtVal = ConstantUInt::get(Type::ULongTy, SqrtValV2);
1818 SqrtTerm = ConstantExpr::getCast(SqrtVal, SqrtTerm->getType());
1820 Constant *NegB = ConstantExpr::getNeg(B);
1821 Constant *TwoA = ConstantExpr::getMul(A, Two);
1823 // The divisions must be performed as signed divisions.
1824 const Type *SignedTy = NegB->getType()->getSignedVersion();
1825 NegB = ConstantExpr::getCast(NegB, SignedTy);
1826 TwoA = ConstantExpr::getCast(TwoA, SignedTy);
1827 SqrtTerm = ConstantExpr::getCast(SqrtTerm, SignedTy);
1829 Constant *Solution1 =
1830 ConstantExpr::getDiv(ConstantExpr::getAdd(NegB, SqrtTerm), TwoA);
1831 Constant *Solution2 =
1832 ConstantExpr::getDiv(ConstantExpr::getSub(NegB, SqrtTerm), TwoA);
1833 return std::make_pair(SCEVUnknown::get(Solution1),
1834 SCEVUnknown::get(Solution2));
1837 /// HowFarToZero - Return the number of times a backedge comparing the specified
1838 /// value to zero will execute. If not computable, return UnknownValue
1839 SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
1840 // If the value is a constant
1841 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
1842 // If the value is already zero, the branch will execute zero times.
1843 if (C->getValue()->isNullValue()) return C;
1844 return UnknownValue; // Otherwise it will loop infinitely.
1847 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
1848 if (!AddRec || AddRec->getLoop() != L)
1849 return UnknownValue;
1851 if (AddRec->isAffine()) {
1852 // If this is an affine expression the execution count of this branch is
1855 // (0 - Start/Step) iff Start % Step == 0
1857 // Get the initial value for the loop.
1858 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
1859 SCEVHandle Step = AddRec->getOperand(1);
1861 Step = getSCEVAtScope(Step, L->getParentLoop());
1863 // Figure out if Start % Step == 0.
1864 // FIXME: We should add DivExpr and RemExpr operations to our AST.
1865 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
1866 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
1867 return getNegativeSCEV(Start); // 0 - Start/1 == -Start
1868 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
1869 return Start; // 0 - Start/-1 == Start
1871 // Check to see if Start is divisible by SC with no remainder.
1872 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
1873 ConstantInt *StartCC = StartC->getValue();
1874 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
1875 Constant *Rem = ConstantExpr::getRem(StartNegC, StepC->getValue());
1876 if (Rem->isNullValue()) {
1877 Constant *Result =ConstantExpr::getDiv(StartNegC,StepC->getValue());
1878 return SCEVUnknown::get(Result);
1882 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
1883 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
1884 // the quadratic equation to solve it.
1885 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec);
1886 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
1887 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
1890 std::cerr << "HFTZ: " << *V << " - sol#1: " << *R1
1891 << " sol#2: " << *R2 << "\n";
1893 // Pick the smallest positive root value.
1894 assert(R1->getType()->isUnsigned()&&"Didn't canonicalize to unsigned?");
1895 if (ConstantBool *CB =
1896 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
1898 if (CB != ConstantBool::True)
1899 std::swap(R1, R2); // R1 is the minimum root now.
1901 // We can only use this value if the chrec ends up with an exact zero
1902 // value at this index. When solving for "X*X != 5", for example, we
1903 // should not accept a root of 2.
1904 SCEVHandle Val = AddRec->evaluateAtIteration(R1);
1905 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
1906 if (EvalVal->getValue()->isNullValue())
1907 return R1; // We found a quadratic root!
1912 return UnknownValue;
1915 /// HowFarToNonZero - Return the number of times a backedge checking the
1916 /// specified value for nonzero will execute. If not computable, return
1918 SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
1919 // Loops that look like: while (X == 0) are very strange indeed. We don't
1920 // handle them yet except for the trivial case. This could be expanded in the
1921 // future as needed.
1923 // If the value is a constant, check to see if it is known to be non-zero
1924 // already. If so, the backedge will execute zero times.
1925 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
1926 Constant *Zero = Constant::getNullValue(C->getValue()->getType());
1927 Constant *NonZero = ConstantExpr::getSetNE(C->getValue(), Zero);
1928 if (NonZero == ConstantBool::True)
1929 return getSCEV(Zero);
1930 return UnknownValue; // Otherwise it will loop infinitely.
1933 // We could implement others, but I really doubt anyone writes loops like
1934 // this, and if they did, they would already be constant folded.
1935 return UnknownValue;
1938 static ConstantInt *
1939 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) {
1940 SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C));
1941 SCEVHandle Val = AddRec->evaluateAtIteration(InVal);
1942 assert(isa<SCEVConstant>(Val) &&
1943 "Evaluation of SCEV at constant didn't fold correctly?");
1944 return cast<SCEVConstant>(Val)->getValue();
1948 /// getNumIterationsInRange - Return the number of iterations of this loop that
1949 /// produce values in the specified constant range. Another way of looking at
1950 /// this is that it returns the first iteration number where the value is not in
1951 /// the condition, thus computing the exit count. If the iteration count can't
1952 /// be computed, an instance of SCEVCouldNotCompute is returned.
1953 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range) const {
1954 if (Range.isFullSet()) // Infinite loop.
1955 return new SCEVCouldNotCompute();
1957 // If the start is a non-zero constant, shift the range to simplify things.
1958 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
1959 if (!SC->getValue()->isNullValue()) {
1960 std::vector<SCEVHandle> Operands(op_begin(), op_end());
1961 Operands[0] = SCEVUnknown::getIntegerSCEV(0, SC->getType());
1962 SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop());
1963 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
1964 return ShiftedAddRec->getNumIterationsInRange(
1965 Range.subtract(SC->getValue()));
1966 // This is strange and shouldn't happen.
1967 return new SCEVCouldNotCompute();
1970 // The only time we can solve this is when we have all constant indices.
1971 // Otherwise, we cannot determine the overflow conditions.
1972 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1973 if (!isa<SCEVConstant>(getOperand(i)))
1974 return new SCEVCouldNotCompute();
1977 // Okay at this point we know that all elements of the chrec are constants and
1978 // that the start element is zero.
1980 // First check to see if the range contains zero. If not, the first
1982 ConstantInt *Zero = ConstantInt::get(getType(), 0);
1983 if (!Range.contains(Zero)) return SCEVConstant::get(Zero);
1986 // If this is an affine expression then we have this situation:
1987 // Solve {0,+,A} in Range === Ax in Range
1989 // Since we know that zero is in the range, we know that the upper value of
1990 // the range must be the first possible exit value. Also note that we
1991 // already checked for a full range.
1992 ConstantInt *Upper = cast<ConstantInt>(Range.getUpper());
1993 ConstantInt *A = cast<SCEVConstant>(getOperand(1))->getValue();
1994 ConstantInt *One = ConstantInt::get(getType(), 1);
1996 // The exit value should be (Upper+A-1)/A.
1997 Constant *ExitValue = Upper;
1999 ExitValue = ConstantExpr::getSub(ConstantExpr::getAdd(Upper, A), One);
2000 ExitValue = ConstantExpr::getDiv(ExitValue, A);
2002 assert(isa<ConstantInt>(ExitValue) &&
2003 "Constant folding of integers not implemented?");
2005 // Evaluate at the exit value. If we really did fall out of the valid
2006 // range, then we computed our trip count, otherwise wrap around or other
2007 // things must have happened.
2008 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue);
2009 if (Range.contains(Val))
2010 return new SCEVCouldNotCompute(); // Something strange happened
2012 // Ensure that the previous value is in the range. This is a sanity check.
2013 assert(Range.contains(EvaluateConstantChrecAtConstant(this,
2014 ConstantExpr::getSub(ExitValue, One))) &&
2015 "Linear scev computation is off in a bad way!");
2016 return SCEVConstant::get(cast<ConstantInt>(ExitValue));
2017 } else if (isQuadratic()) {
2018 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2019 // quadratic equation to solve it. To do this, we must frame our problem in
2020 // terms of figuring out when zero is crossed, instead of when
2021 // Range.getUpper() is crossed.
2022 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
2023 NewOps[0] = getNegativeSCEV(SCEVUnknown::get(Range.getUpper()));
2024 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop());
2026 // Next, solve the constructed addrec
2027 std::pair<SCEVHandle,SCEVHandle> Roots =
2028 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec));
2029 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2030 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2032 // Pick the smallest positive root value.
2033 assert(R1->getType()->isUnsigned() && "Didn't canonicalize to unsigned?");
2034 if (ConstantBool *CB =
2035 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2037 if (CB != ConstantBool::True)
2038 std::swap(R1, R2); // R1 is the minimum root now.
2040 // Make sure the root is not off by one. The returned iteration should
2041 // not be in the range, but the previous one should be. When solving
2042 // for "X*X < 5", for example, we should not return a root of 2.
2043 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2045 if (Range.contains(R1Val)) {
2046 // The next iteration must be out of the range...
2048 ConstantExpr::getAdd(R1->getValue(),
2049 ConstantInt::get(R1->getType(), 1));
2051 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2052 if (!Range.contains(R1Val))
2053 return SCEVUnknown::get(NextVal);
2054 return new SCEVCouldNotCompute(); // Something strange happened
2057 // If R1 was not in the range, then it is a good return value. Make
2058 // sure that R1-1 WAS in the range though, just in case.
2060 ConstantExpr::getSub(R1->getValue(),
2061 ConstantInt::get(R1->getType(), 1));
2062 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2063 if (Range.contains(R1Val))
2065 return new SCEVCouldNotCompute(); // Something strange happened
2070 // Fallback, if this is a general polynomial, figure out the progression
2071 // through brute force: evaluate until we find an iteration that fails the
2072 // test. This is likely to be slow, but getting an accurate trip count is
2073 // incredibly important, we will be able to simplify the exit test a lot, and
2074 // we are almost guaranteed to get a trip count in this case.
2075 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2076 ConstantInt *One = ConstantInt::get(getType(), 1);
2077 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2079 ++NumBruteForceEvaluations;
2080 SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal));
2081 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2082 return new SCEVCouldNotCompute();
2084 // Check to see if we found the value!
2085 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()))
2086 return SCEVConstant::get(TestVal);
2088 // Increment to test the next index.
2089 TestVal = cast<ConstantInt>(ConstantExpr::getAdd(TestVal, One));
2090 } while (TestVal != EndVal);
2092 return new SCEVCouldNotCompute();
2097 //===----------------------------------------------------------------------===//
2098 // ScalarEvolution Class Implementation
2099 //===----------------------------------------------------------------------===//
2101 bool ScalarEvolution::runOnFunction(Function &F) {
2102 Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>());
2106 void ScalarEvolution::releaseMemory() {
2107 delete (ScalarEvolutionsImpl*)Impl;
2111 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2112 AU.setPreservesAll();
2113 AU.addRequiredID(LoopSimplifyID);
2114 AU.addRequiredTransitive<LoopInfo>();
2117 SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2118 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2121 SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2122 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2125 bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2126 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2129 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2130 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2133 void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const {
2134 return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I);
2138 /// shouldSubstituteIndVar - Return true if we should perform induction variable
2139 /// substitution for this variable. This is a hack because we don't have a
2140 /// strength reduction pass yet. When we do we will promote all vars, because
2141 /// we can strength reduce them later as desired.
2142 bool ScalarEvolution::shouldSubstituteIndVar(const SCEV *S) const {
2143 // Don't substitute high degree polynomials.
2144 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S))
2145 if (AddRec->getNumOperands() > 3) return false;
2150 static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
2152 // Print all inner loops first
2153 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2154 PrintLoopInfo(OS, SE, *I);
2156 std::cerr << "Loop " << L->getHeader()->getName() << ": ";
2158 std::vector<BasicBlock*> ExitBlocks;
2159 L->getExitBlocks(ExitBlocks);
2160 if (ExitBlocks.size() != 1)
2161 std::cerr << "<multiple exits> ";
2163 if (SE->hasLoopInvariantIterationCount(L)) {
2164 std::cerr << *SE->getIterationCount(L) << " iterations! ";
2166 std::cerr << "Unpredictable iteration count. ";
2172 void ScalarEvolution::print(std::ostream &OS) const {
2173 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2174 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2176 OS << "Classifying expressions for: " << F.getName() << "\n";
2177 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
2178 if ((*I)->getType()->isInteger()) {
2181 SCEVHandle SV = getSCEV(*I);
2185 if ((*I)->getType()->isIntegral()) {
2186 ConstantRange Bounds = SV->getValueRange();
2187 if (!Bounds.isFullSet())
2188 OS << "Bounds: " << Bounds << " ";
2191 if (const Loop *L = LI.getLoopFor((*I)->getParent())) {
2193 SCEVHandle ExitValue = getSCEVAtScope(*I, L->getParentLoop());
2194 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2195 OS << "<<Unknown>>";
2205 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2206 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2207 PrintLoopInfo(OS, this, *I);