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 // Orthogonal to the analysis of code above, this file also implements the
37 // ScalarEvolutionRewriter class, which is used to emit code that represents the
38 // various recurrences present in a loop, in canonical forms.
40 // TODO: We should use these routines and value representations to implement
41 // dependence analysis!
43 //===----------------------------------------------------------------------===//
45 // There are several good references for the techniques used in this analysis.
47 // Chains of recurrences -- a method to expedite the evaluation
48 // of closed-form functions
49 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima
51 // On computational properties of chains of recurrences
54 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization
55 // Robert A. van Engelen
57 // Efficient Symbolic Analysis for Optimizing Compilers
58 // Robert A. van Engelen
60 // Using the chains of recurrences algebra for data dependence testing and
61 // induction variable substitution
62 // MS Thesis, Johnie Birch
64 //===----------------------------------------------------------------------===//
66 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
67 #include "llvm/Constants.h"
68 #include "llvm/DerivedTypes.h"
69 #include "llvm/Instructions.h"
70 #include "llvm/Type.h"
71 #include "llvm/Value.h"
72 #include "llvm/Analysis/LoopInfo.h"
73 #include "llvm/Assembly/Writer.h"
74 #include "llvm/Transforms/Scalar.h"
75 #include "llvm/Support/CFG.h"
76 #include "llvm/Support/ConstantRange.h"
77 #include "llvm/Support/InstIterator.h"
78 #include "Support/Statistic.h"
82 RegisterAnalysis<ScalarEvolution>
83 R("scalar-evolution", "Scalar Evolution Analysis Printer");
86 NumBruteForceEvaluations("scalar-evolution",
87 "Number of brute force evaluations needed to calculate high-order polynomial exit values");
89 NumTripCountsComputed("scalar-evolution",
90 "Number of loops with predictable loop counts");
92 NumTripCountsNotComputed("scalar-evolution",
93 "Number of loops without predictable loop counts");
96 //===----------------------------------------------------------------------===//
97 // SCEV class definitions
98 //===----------------------------------------------------------------------===//
100 //===----------------------------------------------------------------------===//
101 // Implementation of the SCEV class.
104 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
105 /// than the complexity of the RHS. If the SCEVs have identical complexity,
106 /// order them by their addresses. This comparator is used to canonicalize
108 struct SCEVComplexityCompare {
109 bool operator()(SCEV *LHS, SCEV *RHS) {
110 if (LHS->getSCEVType() < RHS->getSCEVType())
112 if (LHS->getSCEVType() == RHS->getSCEVType())
120 void SCEV::dump() const {
124 /// getValueRange - Return the tightest constant bounds that this value is
125 /// known to have. This method is only valid on integer SCEV objects.
126 ConstantRange SCEV::getValueRange() const {
127 const Type *Ty = getType();
128 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
129 Ty = Ty->getUnsignedVersion();
130 // Default to a full range if no better information is available.
131 return ConstantRange(getType());
135 SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
137 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
138 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
142 const Type *SCEVCouldNotCompute::getType() const {
143 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
147 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
148 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
152 Value *SCEVCouldNotCompute::expandCodeFor(ScalarEvolutionRewriter &SER,
153 Instruction *InsertPt) {
154 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 static SCEVHandle 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, 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 getIntegerSCEV(1, Ty);
432 SCEVHandle Result = V;
433 for (unsigned i = 1; i != NumSteps; ++i)
434 Result = SCEVMulExpr::get(Result, getMinusSCEV(V, getIntegerSCEV(i, Ty)));
439 /// evaluateAtIteration - Return the value of this chain of recurrences at
440 /// the specified iteration number. We can evaluate this recurrence by
441 /// multiplying each element in the chain by the binomial coefficient
442 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
444 /// A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3)
446 /// FIXME/VERIFY: I don't trust that this is correct in the face of overflow.
447 /// Is the binomial equation safe using modular arithmetic??
449 SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It) const {
450 SCEVHandle Result = getStart();
452 const Type *Ty = It->getType();
453 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
454 SCEVHandle BC = PartialFact(It, i);
456 SCEVHandle Val = SCEVUDivExpr::get(SCEVMulExpr::get(BC, getOperand(i)),
457 getIntegerSCEV(Divisor, Ty));
458 Result = SCEVAddExpr::get(Result, Val);
464 //===----------------------------------------------------------------------===//
465 // SCEV Expression folder implementations
466 //===----------------------------------------------------------------------===//
468 SCEVHandle SCEVTruncateExpr::get(const SCEVHandle &Op, const Type *Ty) {
469 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
470 return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty));
472 // If the input value is a chrec scev made out of constants, truncate
473 // all of the constants.
474 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
475 std::vector<SCEVHandle> Operands;
476 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
477 // FIXME: This should allow truncation of other expression types!
478 if (isa<SCEVConstant>(AddRec->getOperand(i)))
479 Operands.push_back(get(AddRec->getOperand(i), Ty));
482 if (Operands.size() == AddRec->getNumOperands())
483 return SCEVAddRecExpr::get(Operands, AddRec->getLoop());
486 SCEVTruncateExpr *&Result = SCEVTruncates[std::make_pair(Op, Ty)];
487 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
491 SCEVHandle SCEVZeroExtendExpr::get(const SCEVHandle &Op, const Type *Ty) {
492 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
493 return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty));
495 // FIXME: If the input value is a chrec scev, and we can prove that the value
496 // did not overflow the old, smaller, value, we can zero extend all of the
497 // operands (often constants). This would allow analysis of something like
498 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
500 SCEVZeroExtendExpr *&Result = SCEVZeroExtends[std::make_pair(Op, Ty)];
501 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
505 // get - Get a canonical add expression, or something simpler if possible.
506 SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) {
507 assert(!Ops.empty() && "Cannot get empty add!");
508 if (Ops.size() == 1) return Ops[0];
510 // Sort by complexity, this groups all similar expression types together.
511 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
513 // If there are any constants, fold them together.
515 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
517 assert(Idx < Ops.size());
518 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
519 // We found two constants, fold them together!
520 Constant *Fold = ConstantExpr::getAdd(LHSC->getValue(), RHSC->getValue());
521 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
522 Ops[0] = SCEVConstant::get(CI);
523 Ops.erase(Ops.begin()+1); // Erase the folded element
524 if (Ops.size() == 1) return Ops[0];
526 // If we couldn't fold the expression, move to the next constant. Note
527 // that this is impossible to happen in practice because we always
528 // constant fold constant ints to constant ints.
533 // If we are left with a constant zero being added, strip it off.
534 if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
535 Ops.erase(Ops.begin());
540 if (Ops.size() == 1) return Ops[0];
542 // Okay, check to see if the same value occurs in the operand list twice. If
543 // so, merge them together into an multiply expression. Since we sorted the
544 // list, these values are required to be adjacent.
545 const Type *Ty = Ops[0]->getType();
546 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
547 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
548 // Found a match, merge the two values into a multiply, and add any
549 // remaining values to the result.
550 SCEVHandle Two = getIntegerSCEV(2, Ty);
551 SCEVHandle Mul = SCEVMulExpr::get(Ops[i], Two);
554 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
556 return SCEVAddExpr::get(Ops);
559 // Okay, now we know the first non-constant operand. If there are add
560 // operands they would be next.
561 if (Idx < Ops.size()) {
562 bool DeletedAdd = false;
563 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
564 // If we have an add, expand the add operands onto the end of the operands
566 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
567 Ops.erase(Ops.begin()+Idx);
571 // If we deleted at least one add, we added operands to the end of the list,
572 // and they are not necessarily sorted. Recurse to resort and resimplify
573 // any operands we just aquired.
578 // Skip over the add expression until we get to a multiply.
579 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
582 // If we are adding something to a multiply expression, make sure the
583 // something is not already an operand of the multiply. If so, merge it into
585 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
586 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
587 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
588 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
589 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
590 if (MulOpSCEV == Ops[AddOp] &&
591 (Mul->getNumOperands() != 2 || !isa<SCEVConstant>(MulOpSCEV))) {
592 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
593 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
594 if (Mul->getNumOperands() != 2) {
595 // If the multiply has more than two operands, we must get the
597 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
598 MulOps.erase(MulOps.begin()+MulOp);
599 InnerMul = SCEVMulExpr::get(MulOps);
601 SCEVHandle One = getIntegerSCEV(1, Ty);
602 SCEVHandle AddOne = SCEVAddExpr::get(InnerMul, One);
603 SCEVHandle OuterMul = SCEVMulExpr::get(AddOne, Ops[AddOp]);
604 if (Ops.size() == 2) return OuterMul;
606 Ops.erase(Ops.begin()+AddOp);
607 Ops.erase(Ops.begin()+Idx-1);
609 Ops.erase(Ops.begin()+Idx);
610 Ops.erase(Ops.begin()+AddOp-1);
612 Ops.push_back(OuterMul);
613 return SCEVAddExpr::get(Ops);
616 // Check this multiply against other multiplies being added together.
617 for (unsigned OtherMulIdx = Idx+1;
618 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
620 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
621 // If MulOp occurs in OtherMul, we can fold the two multiplies
623 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
624 OMulOp != e; ++OMulOp)
625 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
626 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
627 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
628 if (Mul->getNumOperands() != 2) {
629 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
630 MulOps.erase(MulOps.begin()+MulOp);
631 InnerMul1 = SCEVMulExpr::get(MulOps);
633 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
634 if (OtherMul->getNumOperands() != 2) {
635 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
637 MulOps.erase(MulOps.begin()+OMulOp);
638 InnerMul2 = SCEVMulExpr::get(MulOps);
640 SCEVHandle InnerMulSum = SCEVAddExpr::get(InnerMul1,InnerMul2);
641 SCEVHandle OuterMul = SCEVMulExpr::get(MulOpSCEV, InnerMulSum);
642 if (Ops.size() == 2) return OuterMul;
643 Ops.erase(Ops.begin()+Idx);
644 Ops.erase(Ops.begin()+OtherMulIdx-1);
645 Ops.push_back(OuterMul);
646 return SCEVAddExpr::get(Ops);
652 // If there are any add recurrences in the operands list, see if any other
653 // added values are loop invariant. If so, we can fold them into the
655 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
658 // Scan over all recurrences, trying to fold loop invariants into them.
659 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
660 // Scan all of the other operands to this add and add them to the vector if
661 // they are loop invariant w.r.t. the recurrence.
662 std::vector<SCEVHandle> LIOps;
663 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
664 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
665 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
666 LIOps.push_back(Ops[i]);
667 Ops.erase(Ops.begin()+i);
671 // If we found some loop invariants, fold them into the recurrence.
672 if (!LIOps.empty()) {
673 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
674 LIOps.push_back(AddRec->getStart());
676 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
677 AddRecOps[0] = SCEVAddExpr::get(LIOps);
679 SCEVHandle NewRec = SCEVAddRecExpr::get(AddRecOps, AddRec->getLoop());
680 // If all of the other operands were loop invariant, we are done.
681 if (Ops.size() == 1) return NewRec;
683 // Otherwise, add the folded AddRec by the non-liv parts.
684 for (unsigned i = 0;; ++i)
685 if (Ops[i] == AddRec) {
689 return SCEVAddExpr::get(Ops);
692 // Okay, if there weren't any loop invariants to be folded, check to see if
693 // there are multiple AddRec's with the same loop induction variable being
694 // added together. If so, we can fold them.
695 for (unsigned OtherIdx = Idx+1;
696 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
697 if (OtherIdx != Idx) {
698 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
699 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
700 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
701 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
702 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
703 if (i >= NewOps.size()) {
704 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
705 OtherAddRec->op_end());
708 NewOps[i] = SCEVAddExpr::get(NewOps[i], OtherAddRec->getOperand(i));
710 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
712 if (Ops.size() == 2) return NewAddRec;
714 Ops.erase(Ops.begin()+Idx);
715 Ops.erase(Ops.begin()+OtherIdx-1);
716 Ops.push_back(NewAddRec);
717 return SCEVAddExpr::get(Ops);
721 // Otherwise couldn't fold anything into this recurrence. Move onto the
725 // Okay, it looks like we really DO need an add expr. Check to see if we
726 // already have one, otherwise create a new one.
727 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
728 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scAddExpr,
730 if (Result == 0) Result = new SCEVAddExpr(Ops);
735 SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) {
736 assert(!Ops.empty() && "Cannot get empty mul!");
738 // Sort by complexity, this groups all similar expression types together.
739 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
741 // If there are any constants, fold them together.
743 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
745 // C1*(C2+V) -> C1*C2 + C1*V
747 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
748 if (Add->getNumOperands() == 2 &&
749 isa<SCEVConstant>(Add->getOperand(0)))
750 return SCEVAddExpr::get(SCEVMulExpr::get(LHSC, Add->getOperand(0)),
751 SCEVMulExpr::get(LHSC, Add->getOperand(1)));
755 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
756 // We found two constants, fold them together!
757 Constant *Fold = ConstantExpr::getMul(LHSC->getValue(), RHSC->getValue());
758 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
759 Ops[0] = SCEVConstant::get(CI);
760 Ops.erase(Ops.begin()+1); // Erase the folded element
761 if (Ops.size() == 1) return Ops[0];
763 // If we couldn't fold the expression, move to the next constant. Note
764 // that this is impossible to happen in practice because we always
765 // constant fold constant ints to constant ints.
770 // If we are left with a constant one being multiplied, strip it off.
771 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
772 Ops.erase(Ops.begin());
774 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
775 // If we have a multiply of zero, it will always be zero.
780 // Skip over the add expression until we get to a multiply.
781 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
787 // If there are mul operands inline them all into this expression.
788 if (Idx < Ops.size()) {
789 bool DeletedMul = false;
790 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
791 // If we have an mul, expand the mul operands onto the end of the operands
793 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
794 Ops.erase(Ops.begin()+Idx);
798 // If we deleted at least one mul, we added operands to the end of the list,
799 // and they are not necessarily sorted. Recurse to resort and resimplify
800 // any operands we just aquired.
805 // If there are any add recurrences in the operands list, see if any other
806 // added values are loop invariant. If so, we can fold them into the
808 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
811 // Scan over all recurrences, trying to fold loop invariants into them.
812 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
813 // Scan all of the other operands to this mul and add them to the vector if
814 // they are loop invariant w.r.t. the recurrence.
815 std::vector<SCEVHandle> LIOps;
816 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
817 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
818 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
819 LIOps.push_back(Ops[i]);
820 Ops.erase(Ops.begin()+i);
824 // If we found some loop invariants, fold them into the recurrence.
825 if (!LIOps.empty()) {
826 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
827 std::vector<SCEVHandle> NewOps;
828 NewOps.reserve(AddRec->getNumOperands());
829 if (LIOps.size() == 1) {
830 SCEV *Scale = LIOps[0];
831 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
832 NewOps.push_back(SCEVMulExpr::get(Scale, AddRec->getOperand(i)));
834 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
835 std::vector<SCEVHandle> MulOps(LIOps);
836 MulOps.push_back(AddRec->getOperand(i));
837 NewOps.push_back(SCEVMulExpr::get(MulOps));
841 SCEVHandle NewRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
843 // If all of the other operands were loop invariant, we are done.
844 if (Ops.size() == 1) return NewRec;
846 // Otherwise, multiply the folded AddRec by the non-liv parts.
847 for (unsigned i = 0;; ++i)
848 if (Ops[i] == AddRec) {
852 return SCEVMulExpr::get(Ops);
855 // Okay, if there weren't any loop invariants to be folded, check to see if
856 // there are multiple AddRec's with the same loop induction variable being
857 // multiplied together. If so, we can fold them.
858 for (unsigned OtherIdx = Idx+1;
859 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
860 if (OtherIdx != Idx) {
861 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
862 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
863 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
864 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
865 SCEVHandle NewStart = SCEVMulExpr::get(F->getStart(),
867 SCEVHandle B = F->getStepRecurrence();
868 SCEVHandle D = G->getStepRecurrence();
869 SCEVHandle NewStep = SCEVAddExpr::get(SCEVMulExpr::get(F, D),
870 SCEVMulExpr::get(G, B),
871 SCEVMulExpr::get(B, D));
872 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewStart, NewStep,
874 if (Ops.size() == 2) return NewAddRec;
876 Ops.erase(Ops.begin()+Idx);
877 Ops.erase(Ops.begin()+OtherIdx-1);
878 Ops.push_back(NewAddRec);
879 return SCEVMulExpr::get(Ops);
883 // Otherwise couldn't fold anything into this recurrence. Move onto the
887 // Okay, it looks like we really DO need an mul expr. Check to see if we
888 // already have one, otherwise create a new one.
889 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
890 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scMulExpr,
892 if (Result == 0) Result = new SCEVMulExpr(Ops);
896 SCEVHandle SCEVUDivExpr::get(const SCEVHandle &LHS, const SCEVHandle &RHS) {
897 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
898 if (RHSC->getValue()->equalsInt(1))
899 return LHS; // X /u 1 --> x
900 if (RHSC->getValue()->isAllOnesValue())
901 return getNegativeSCEV(LHS); // X /u -1 --> -x
903 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
904 Constant *LHSCV = LHSC->getValue();
905 Constant *RHSCV = RHSC->getValue();
906 if (LHSCV->getType()->isSigned())
907 LHSCV = ConstantExpr::getCast(LHSCV,
908 LHSCV->getType()->getUnsignedVersion());
909 if (RHSCV->getType()->isSigned())
910 RHSCV = ConstantExpr::getCast(RHSCV, LHSCV->getType());
911 return SCEVUnknown::get(ConstantExpr::getDiv(LHSCV, RHSCV));
915 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
917 SCEVUDivExpr *&Result = SCEVUDivs[std::make_pair(LHS, RHS)];
918 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
923 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
924 /// specified loop. Simplify the expression as much as possible.
925 SCEVHandle SCEVAddRecExpr::get(const SCEVHandle &Start,
926 const SCEVHandle &Step, const Loop *L) {
927 std::vector<SCEVHandle> Operands;
928 Operands.push_back(Start);
929 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
930 if (StepChrec->getLoop() == L) {
931 Operands.insert(Operands.end(), StepChrec->op_begin(),
932 StepChrec->op_end());
933 return get(Operands, L);
936 Operands.push_back(Step);
937 return get(Operands, L);
940 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
941 /// specified loop. Simplify the expression as much as possible.
942 SCEVHandle SCEVAddRecExpr::get(std::vector<SCEVHandle> &Operands,
944 if (Operands.size() == 1) return Operands[0];
946 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
947 if (StepC->getValue()->isNullValue()) {
949 return get(Operands, L); // { X,+,0 } --> X
952 SCEVAddRecExpr *&Result =
953 SCEVAddRecExprs[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
955 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
959 SCEVHandle SCEVUnknown::get(Value *V) {
960 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
961 return SCEVConstant::get(CI);
962 SCEVUnknown *&Result = SCEVUnknowns[V];
963 if (Result == 0) Result = new SCEVUnknown(V);
968 //===----------------------------------------------------------------------===//
969 // Non-trivial closed-form SCEV Expanders
970 //===----------------------------------------------------------------------===//
972 Value *SCEVTruncateExpr::expandCodeFor(ScalarEvolutionRewriter &SER,
973 Instruction *InsertPt) {
974 Value *V = SER.ExpandCodeFor(getOperand(), InsertPt);
975 return new CastInst(V, getType(), "tmp.", InsertPt);
978 Value *SCEVZeroExtendExpr::expandCodeFor(ScalarEvolutionRewriter &SER,
979 Instruction *InsertPt) {
980 Value *V = SER.ExpandCodeFor(getOperand(), InsertPt,
981 getOperand()->getType()->getUnsignedVersion());
982 return new CastInst(V, getType(), "tmp.", InsertPt);
985 Value *SCEVAddExpr::expandCodeFor(ScalarEvolutionRewriter &SER,
986 Instruction *InsertPt) {
987 const Type *Ty = getType();
988 Value *V = SER.ExpandCodeFor(getOperand(getNumOperands()-1), InsertPt, Ty);
990 // Emit a bunch of add instructions
991 for (int i = getNumOperands()-2; i >= 0; --i)
992 V = BinaryOperator::create(Instruction::Add, V,
993 SER.ExpandCodeFor(getOperand(i), InsertPt, Ty),
998 Value *SCEVMulExpr::expandCodeFor(ScalarEvolutionRewriter &SER,
999 Instruction *InsertPt) {
1000 const Type *Ty = getType();
1001 int FirstOp = 0; // Set if we should emit a subtract.
1002 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getOperand(0)))
1003 if (SC->getValue()->isAllOnesValue())
1006 int i = getNumOperands()-2;
1007 Value *V = SER.ExpandCodeFor(getOperand(i+1), InsertPt, Ty);
1009 // Emit a bunch of multiply instructions
1010 for (; i >= FirstOp; --i)
1011 V = BinaryOperator::create(Instruction::Mul, V,
1012 SER.ExpandCodeFor(getOperand(i), InsertPt, Ty),
1014 // -1 * ... ---> 0 - ...
1016 V = BinaryOperator::create(Instruction::Sub, Constant::getNullValue(Ty), V,
1021 Value *SCEVUDivExpr::expandCodeFor(ScalarEvolutionRewriter &SER,
1022 Instruction *InsertPt) {
1023 const Type *Ty = getType();
1024 Value *LHS = SER.ExpandCodeFor(getLHS(), InsertPt, Ty);
1025 Value *RHS = SER.ExpandCodeFor(getRHS(), InsertPt, Ty);
1026 return BinaryOperator::create(Instruction::Div, LHS, RHS, "tmp.", InsertPt);
1029 Value *SCEVAddRecExpr::expandCodeFor(ScalarEvolutionRewriter &SER,
1030 Instruction *InsertPt) {
1031 const Type *Ty = getType();
1032 // We cannot yet do fp recurrences, e.g. the xform of {X,+,F} --> X+{0,+,F}
1033 assert(Ty->isIntegral() && "Cannot expand fp recurrences yet!");
1035 // {X,+,F} --> X + {0,+,F}
1036 if (!isa<SCEVConstant>(getStart()) ||
1037 !cast<SCEVConstant>(getStart())->getValue()->isNullValue()) {
1038 Value *Start = SER.ExpandCodeFor(getStart(), InsertPt, Ty);
1039 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
1040 NewOps[0] = getIntegerSCEV(0, getType());
1041 Value *Rest = SER.ExpandCodeFor(SCEVAddRecExpr::get(NewOps, getLoop()),
1042 InsertPt, getType());
1044 // FIXME: look for an existing add to use.
1045 return BinaryOperator::create(Instruction::Add, Rest, Start, "tmp.",
1049 // {0,+,1} --> Insert a canonical induction variable into the loop!
1050 if (getNumOperands() == 2 && getOperand(1) == getIntegerSCEV(1, getType())) {
1051 // Create and insert the PHI node for the induction variable in the
1053 BasicBlock *Header = getLoop()->getHeader();
1054 PHINode *PN = new PHINode(Ty, "indvar", Header->begin());
1055 PN->addIncoming(Constant::getNullValue(Ty), L->getLoopPreheader());
1057 pred_iterator HPI = pred_begin(Header);
1058 assert(HPI != pred_end(Header) && "Loop with zero preds???");
1059 if (!getLoop()->contains(*HPI)) ++HPI;
1060 assert(HPI != pred_end(Header) && getLoop()->contains(*HPI) &&
1061 "No backedge in loop?");
1063 // Insert a unit add instruction right before the terminator corresponding
1064 // to the back-edge.
1065 Constant *One = Ty->isFloatingPoint() ? (Constant*)ConstantFP::get(Ty, 1.0)
1066 : (Constant*)ConstantInt::get(Ty, 1);
1067 Instruction *Add = BinaryOperator::create(Instruction::Add, PN, One,
1069 (*HPI)->getTerminator());
1071 pred_iterator PI = pred_begin(Header);
1072 if (*PI == L->getLoopPreheader())
1074 PN->addIncoming(Add, *PI);
1078 // Get the canonical induction variable I for this loop.
1079 Value *I = SER.GetOrInsertCanonicalInductionVariable(getLoop(), Ty);
1081 if (getNumOperands() == 2) { // {0,+,F} --> i*F
1082 Value *F = SER.ExpandCodeFor(getOperand(1), InsertPt, Ty);
1083 return BinaryOperator::create(Instruction::Mul, I, F, "tmp.", InsertPt);
1086 // If this is a chain of recurrences, turn it into a closed form, using the
1087 // folders, then expandCodeFor the closed form. This allows the folders to
1088 // simplify the expression without having to build a bunch of special code
1089 // into this folder.
1090 SCEVHandle IH = SCEVUnknown::get(I); // Get I as a "symbolic" SCEV.
1092 SCEVHandle V = evaluateAtIteration(IH);
1093 //std::cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
1095 return SER.ExpandCodeFor(V, InsertPt, Ty);
1099 //===----------------------------------------------------------------------===//
1100 // ScalarEvolutionsImpl Definition and Implementation
1101 //===----------------------------------------------------------------------===//
1103 /// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1107 struct ScalarEvolutionsImpl {
1108 /// F - The function we are analyzing.
1112 /// LI - The loop information for the function we are currently analyzing.
1116 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1118 SCEVHandle UnknownValue;
1120 /// Scalars - This is a cache of the scalars we have analyzed so far.
1122 std::map<Value*, SCEVHandle> Scalars;
1124 /// IterationCounts - Cache the iteration count of the loops for this
1125 /// function as they are computed.
1126 std::map<const Loop*, SCEVHandle> IterationCounts;
1129 ScalarEvolutionsImpl(Function &f, LoopInfo &li)
1130 : F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1132 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1133 /// expression and create a new one.
1134 SCEVHandle getSCEV(Value *V);
1136 /// getSCEVAtScope - Compute the value of the specified expression within
1137 /// the indicated loop (which may be null to indicate in no loop). If the
1138 /// expression cannot be evaluated, return UnknownValue itself.
1139 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1142 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1143 /// an analyzable loop-invariant iteration count.
1144 bool hasLoopInvariantIterationCount(const Loop *L);
1146 /// getIterationCount - If the specified loop has a predictable iteration
1147 /// count, return it. Note that it is not valid to call this method on a
1148 /// loop without a loop-invariant iteration count.
1149 SCEVHandle getIterationCount(const Loop *L);
1151 /// deleteInstructionFromRecords - This method should be called by the
1152 /// client before it removes an instruction from the program, to make sure
1153 /// that no dangling references are left around.
1154 void deleteInstructionFromRecords(Instruction *I);
1157 /// createSCEV - We know that there is no SCEV for the specified value.
1158 /// Analyze the expression.
1159 SCEVHandle createSCEV(Value *V);
1160 SCEVHandle createNodeForCast(CastInst *CI);
1162 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1164 SCEVHandle createNodeForPHI(PHINode *PN);
1165 void UpdatePHIUserScalarEntries(Instruction *I, PHINode *PN,
1166 std::set<Instruction*> &UpdatedInsts);
1168 /// ComputeIterationCount - Compute the number of times the specified loop
1170 SCEVHandle ComputeIterationCount(const Loop *L);
1172 /// HowFarToZero - Return the number of times a backedge comparing the
1173 /// specified value to zero will execute. If not computable, return
1175 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1177 /// HowFarToNonZero - Return the number of times a backedge checking the
1178 /// specified value for nonzero will execute. If not computable, return
1180 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
1184 //===----------------------------------------------------------------------===//
1185 // Basic SCEV Analysis and PHI Idiom Recognition Code
1188 /// deleteInstructionFromRecords - This method should be called by the
1189 /// client before it removes an instruction from the program, to make sure
1190 /// that no dangling references are left around.
1191 void ScalarEvolutionsImpl::deleteInstructionFromRecords(Instruction *I) {
1196 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1197 /// expression and create a new one.
1198 SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1199 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1201 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1202 if (I != Scalars.end()) return I->second;
1203 SCEVHandle S = createSCEV(V);
1204 Scalars.insert(std::make_pair(V, S));
1209 /// UpdatePHIUserScalarEntries - After PHI node analysis, we have a bunch of
1210 /// entries in the scalar map that refer to the "symbolic" PHI value instead of
1211 /// the recurrence value. After we resolve the PHI we must loop over all of the
1212 /// using instructions that have scalar map entries and update them.
1213 void ScalarEvolutionsImpl::UpdatePHIUserScalarEntries(Instruction *I,
1215 std::set<Instruction*> &UpdatedInsts) {
1216 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1217 if (SI == Scalars.end()) return; // This scalar wasn't previous processed.
1218 if (UpdatedInsts.insert(I).second) {
1219 Scalars.erase(SI); // Remove the old entry
1220 getSCEV(I); // Calculate the new entry
1222 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1224 UpdatePHIUserScalarEntries(cast<Instruction>(*UI), PN, UpdatedInsts);
1229 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1230 /// a loop header, making it a potential recurrence, or it doesn't.
1232 SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1233 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1234 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1235 if (L->getHeader() == PN->getParent()) {
1236 // If it lives in the loop header, it has two incoming values, one
1237 // from outside the loop, and one from inside.
1238 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1239 unsigned BackEdge = IncomingEdge^1;
1241 // While we are analyzing this PHI node, handle its value symbolically.
1242 SCEVHandle SymbolicName = SCEVUnknown::get(PN);
1243 assert(Scalars.find(PN) == Scalars.end() &&
1244 "PHI node already processed?");
1245 Scalars.insert(std::make_pair(PN, SymbolicName));
1247 // Using this symbolic name for the PHI, analyze the value coming around
1249 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1251 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1252 // has a special value for the first iteration of the loop.
1254 // If the value coming around the backedge is an add with the symbolic
1255 // value we just inserted, then we found a simple induction variable!
1256 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1257 // If there is a single occurrence of the symbolic value, replace it
1258 // with a recurrence.
1259 unsigned FoundIndex = Add->getNumOperands();
1260 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1261 if (Add->getOperand(i) == SymbolicName)
1262 if (FoundIndex == e) {
1267 if (FoundIndex != Add->getNumOperands()) {
1268 // Create an add with everything but the specified operand.
1269 std::vector<SCEVHandle> Ops;
1270 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1271 if (i != FoundIndex)
1272 Ops.push_back(Add->getOperand(i));
1273 SCEVHandle Accum = SCEVAddExpr::get(Ops);
1275 // This is not a valid addrec if the step amount is varying each
1276 // loop iteration, but is not itself an addrec in this loop.
1277 if (Accum->isLoopInvariant(L) ||
1278 (isa<SCEVAddRecExpr>(Accum) &&
1279 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1280 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1281 SCEVHandle PHISCEV = SCEVAddRecExpr::get(StartVal, Accum, L);
1283 // Okay, for the entire analysis of this edge we assumed the PHI
1284 // to be symbolic. We now need to go back and update all of the
1285 // entries for the scalars that use the PHI (except for the PHI
1286 // itself) to use the new analyzed value instead of the "symbolic"
1288 Scalars.find(PN)->second = PHISCEV; // Update the PHI value
1289 std::set<Instruction*> UpdatedInsts;
1290 UpdatedInsts.insert(PN);
1291 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
1293 UpdatePHIUserScalarEntries(cast<Instruction>(*UI), PN,
1300 return SymbolicName;
1303 // If it's not a loop phi, we can't handle it yet.
1304 return SCEVUnknown::get(PN);
1307 /// createNodeForCast - Handle the various forms of casts that we support.
1309 SCEVHandle ScalarEvolutionsImpl::createNodeForCast(CastInst *CI) {
1310 const Type *SrcTy = CI->getOperand(0)->getType();
1311 const Type *DestTy = CI->getType();
1313 // If this is a noop cast (ie, conversion from int to uint), ignore it.
1314 if (SrcTy->isLosslesslyConvertibleTo(DestTy))
1315 return getSCEV(CI->getOperand(0));
1317 if (SrcTy->isInteger() && DestTy->isInteger()) {
1318 // Otherwise, if this is a truncating integer cast, we can represent this
1320 if (SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize())
1321 return SCEVTruncateExpr::get(getSCEV(CI->getOperand(0)),
1322 CI->getType()->getUnsignedVersion());
1323 if (SrcTy->isUnsigned() &&
1324 SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize())
1325 return SCEVZeroExtendExpr::get(getSCEV(CI->getOperand(0)),
1326 CI->getType()->getUnsignedVersion());
1329 // If this is an sign or zero extending cast and we can prove that the value
1330 // will never overflow, we could do similar transformations.
1332 // Otherwise, we can't handle this cast!
1333 return SCEVUnknown::get(CI);
1337 /// createSCEV - We know that there is no SCEV for the specified value.
1338 /// Analyze the expression.
1340 SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1341 if (Instruction *I = dyn_cast<Instruction>(V)) {
1342 switch (I->getOpcode()) {
1343 case Instruction::Add:
1344 return SCEVAddExpr::get(getSCEV(I->getOperand(0)),
1345 getSCEV(I->getOperand(1)));
1346 case Instruction::Mul:
1347 return SCEVMulExpr::get(getSCEV(I->getOperand(0)),
1348 getSCEV(I->getOperand(1)));
1349 case Instruction::Div:
1350 if (V->getType()->isInteger() && V->getType()->isUnsigned())
1351 return SCEVUDivExpr::get(getSCEV(I->getOperand(0)),
1352 getSCEV(I->getOperand(1)));
1355 case Instruction::Sub:
1356 return getMinusSCEV(getSCEV(I->getOperand(0)), getSCEV(I->getOperand(1)));
1358 case Instruction::Shl:
1359 // Turn shift left of a constant amount into a multiply.
1360 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1361 Constant *X = ConstantInt::get(V->getType(), 1);
1362 X = ConstantExpr::getShl(X, SA);
1363 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1367 case Instruction::Shr:
1368 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
1369 if (V->getType()->isUnsigned()) {
1370 Constant *X = ConstantInt::get(V->getType(), 1);
1371 X = ConstantExpr::getShl(X, SA);
1372 return SCEVUDivExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1376 case Instruction::Cast:
1377 return createNodeForCast(cast<CastInst>(I));
1379 case Instruction::PHI:
1380 return createNodeForPHI(cast<PHINode>(I));
1382 default: // We cannot analyze this expression.
1387 return SCEVUnknown::get(V);
1392 //===----------------------------------------------------------------------===//
1393 // Iteration Count Computation Code
1396 /// getIterationCount - If the specified loop has a predictable iteration
1397 /// count, return it. Note that it is not valid to call this method on a
1398 /// loop without a loop-invariant iteration count.
1399 SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1400 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1401 if (I == IterationCounts.end()) {
1402 SCEVHandle ItCount = ComputeIterationCount(L);
1403 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1404 if (ItCount != UnknownValue) {
1405 assert(ItCount->isLoopInvariant(L) &&
1406 "Computed trip count isn't loop invariant for loop!");
1407 ++NumTripCountsComputed;
1408 } else if (isa<PHINode>(L->getHeader()->begin())) {
1409 // Only count loops that have phi nodes as not being computable.
1410 ++NumTripCountsNotComputed;
1416 /// ComputeIterationCount - Compute the number of times the specified loop
1418 SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1419 // If the loop has a non-one exit block count, we can't analyze it.
1420 if (L->getExitBlocks().size() != 1) return UnknownValue;
1422 // Okay, there is one exit block. Try to find the condition that causes the
1423 // loop to be exited.
1424 BasicBlock *ExitBlock = L->getExitBlocks()[0];
1426 BasicBlock *ExitingBlock = 0;
1427 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1429 if (L->contains(*PI)) {
1430 if (ExitingBlock == 0)
1433 return UnknownValue; // More than one block exiting!
1435 assert(ExitingBlock && "No exits from loop, something is broken!");
1437 // Okay, we've computed the exiting block. See what condition causes us to
1440 // FIXME: we should be able to handle switch instructions (with a single exit)
1441 // FIXME: We should handle cast of int to bool as well
1442 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1443 if (ExitBr == 0) return UnknownValue;
1444 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1445 SetCondInst *ExitCond = dyn_cast<SetCondInst>(ExitBr->getCondition());
1446 if (ExitCond == 0) return UnknownValue;
1448 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1449 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1451 // Try to evaluate any dependencies out of the loop.
1452 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1453 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1454 Tmp = getSCEVAtScope(RHS, L);
1455 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1457 // If the condition was exit on true, convert the condition to exit on false.
1458 Instruction::BinaryOps Cond;
1459 if (ExitBr->getSuccessor(1) == ExitBlock)
1460 Cond = ExitCond->getOpcode();
1462 Cond = ExitCond->getInverseCondition();
1464 // At this point, we would like to compute how many iterations of the loop the
1465 // predicate will return true for these inputs.
1466 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1467 // If there is a constant, force it into the RHS.
1468 std::swap(LHS, RHS);
1469 Cond = SetCondInst::getSwappedCondition(Cond);
1472 // FIXME: think about handling pointer comparisons! i.e.:
1473 // while (P != P+100) ++P;
1475 // If we have a comparison of a chrec against a constant, try to use value
1476 // ranges to answer this query.
1477 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1478 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1479 if (AddRec->getLoop() == L) {
1480 // Form the comparison range using the constant of the correct type so
1481 // that the ConstantRange class knows to do a signed or unsigned
1483 ConstantInt *CompVal = RHSC->getValue();
1484 const Type *RealTy = ExitCond->getOperand(0)->getType();
1485 CompVal = dyn_cast<ConstantInt>(ConstantExpr::getCast(CompVal, RealTy));
1487 // Form the constant range.
1488 ConstantRange CompRange(Cond, CompVal);
1490 // Now that we have it, if it's signed, convert it to an unsigned
1492 if (CompRange.getLower()->getType()->isSigned()) {
1493 const Type *NewTy = RHSC->getValue()->getType();
1494 Constant *NewL = ConstantExpr::getCast(CompRange.getLower(), NewTy);
1495 Constant *NewU = ConstantExpr::getCast(CompRange.getUpper(), NewTy);
1496 CompRange = ConstantRange(NewL, NewU);
1499 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange);
1500 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1505 case Instruction::SetNE: // while (X != Y)
1506 // Convert to: while (X-Y != 0)
1507 if (LHS->getType()->isInteger())
1508 return HowFarToZero(getMinusSCEV(LHS, RHS), L);
1510 case Instruction::SetEQ:
1511 // Convert to: while (X-Y == 0) // while (X == Y)
1512 if (LHS->getType()->isInteger())
1513 return HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
1517 std::cerr << "ComputeIterationCount ";
1518 if (ExitCond->getOperand(0)->getType()->isUnsigned())
1519 std::cerr << "[unsigned] ";
1520 std::cerr << *LHS << " "
1521 << Instruction::getOpcodeName(Cond) << " " << *RHS << "\n";
1525 return UnknownValue;
1528 /// getSCEVAtScope - Compute the value of the specified expression within the
1529 /// indicated loop (which may be null to indicate in no loop). If the
1530 /// expression cannot be evaluated, return UnknownValue.
1531 SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
1532 // FIXME: this should be turned into a virtual method on SCEV!
1534 if (isa<SCEVConstant>(V) || isa<SCEVUnknown>(V)) return V;
1535 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
1536 // Avoid performing the look-up in the common case where the specified
1537 // expression has no loop-variant portions.
1538 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
1539 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1540 if (OpAtScope != Comm->getOperand(i)) {
1541 if (OpAtScope == UnknownValue) return UnknownValue;
1542 // Okay, at least one of these operands is loop variant but might be
1543 // foldable. Build a new instance of the folded commutative expression.
1544 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i-1);
1545 NewOps.push_back(OpAtScope);
1547 for (++i; i != e; ++i) {
1548 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1549 if (OpAtScope == UnknownValue) return UnknownValue;
1550 NewOps.push_back(OpAtScope);
1552 if (isa<SCEVAddExpr>(Comm))
1553 return SCEVAddExpr::get(NewOps);
1554 assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
1555 return SCEVMulExpr::get(NewOps);
1558 // If we got here, all operands are loop invariant.
1562 if (SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(V)) {
1563 SCEVHandle LHS = getSCEVAtScope(UDiv->getLHS(), L);
1564 if (LHS == UnknownValue) return LHS;
1565 SCEVHandle RHS = getSCEVAtScope(UDiv->getRHS(), L);
1566 if (RHS == UnknownValue) return RHS;
1567 if (LHS == UDiv->getLHS() && RHS == UDiv->getRHS())
1568 return UDiv; // must be loop invariant
1569 return SCEVUDivExpr::get(LHS, RHS);
1572 // If this is a loop recurrence for a loop that does not contain L, then we
1573 // are dealing with the final value computed by the loop.
1574 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
1575 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
1576 // To evaluate this recurrence, we need to know how many times the AddRec
1577 // loop iterates. Compute this now.
1578 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
1579 if (IterationCount == UnknownValue) return UnknownValue;
1580 IterationCount = getTruncateOrZeroExtend(IterationCount,
1583 // If the value is affine, simplify the expression evaluation to just
1584 // Start + Step*IterationCount.
1585 if (AddRec->isAffine())
1586 return SCEVAddExpr::get(AddRec->getStart(),
1587 SCEVMulExpr::get(IterationCount,
1588 AddRec->getOperand(1)));
1590 // Otherwise, evaluate it the hard way.
1591 return AddRec->evaluateAtIteration(IterationCount);
1593 return UnknownValue;
1596 //assert(0 && "Unknown SCEV type!");
1597 return UnknownValue;
1601 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
1602 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
1603 /// might be the same) or two SCEVCouldNotCompute objects.
1605 static std::pair<SCEVHandle,SCEVHandle>
1606 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) {
1607 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
1608 SCEVConstant *L = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
1609 SCEVConstant *M = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
1610 SCEVConstant *N = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
1612 // We currently can only solve this if the coefficients are constants.
1613 if (!L || !M || !N) {
1614 SCEV *CNC = new SCEVCouldNotCompute();
1615 return std::make_pair(CNC, CNC);
1618 Constant *Two = ConstantInt::get(L->getValue()->getType(), 2);
1620 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
1621 Constant *C = L->getValue();
1622 // The B coefficient is M-N/2
1623 Constant *B = ConstantExpr::getSub(M->getValue(),
1624 ConstantExpr::getDiv(N->getValue(),
1626 // The A coefficient is N/2
1627 Constant *A = ConstantExpr::getDiv(N->getValue(), Two);
1629 // Compute the B^2-4ac term.
1630 Constant *SqrtTerm =
1631 ConstantExpr::getMul(ConstantInt::get(C->getType(), 4),
1632 ConstantExpr::getMul(A, C));
1633 SqrtTerm = ConstantExpr::getSub(ConstantExpr::getMul(B, B), SqrtTerm);
1635 // Compute floor(sqrt(B^2-4ac))
1636 ConstantUInt *SqrtVal =
1637 cast<ConstantUInt>(ConstantExpr::getCast(SqrtTerm,
1638 SqrtTerm->getType()->getUnsignedVersion()));
1639 uint64_t SqrtValV = SqrtVal->getValue();
1640 uint64_t SqrtValV2 = (uint64_t)sqrt(SqrtValV);
1641 // The square root might not be precise for arbitrary 64-bit integer
1642 // values. Do some sanity checks to ensure it's correct.
1643 if (SqrtValV2*SqrtValV2 > SqrtValV ||
1644 (SqrtValV2+1)*(SqrtValV2+1) <= SqrtValV) {
1645 SCEV *CNC = new SCEVCouldNotCompute();
1646 return std::make_pair(CNC, CNC);
1649 SqrtVal = ConstantUInt::get(Type::ULongTy, SqrtValV2);
1650 SqrtTerm = ConstantExpr::getCast(SqrtVal, SqrtTerm->getType());
1652 Constant *NegB = ConstantExpr::getNeg(B);
1653 Constant *TwoA = ConstantExpr::getMul(A, Two);
1655 // The divisions must be performed as signed divisions.
1656 const Type *SignedTy = NegB->getType()->getSignedVersion();
1657 NegB = ConstantExpr::getCast(NegB, SignedTy);
1658 TwoA = ConstantExpr::getCast(TwoA, SignedTy);
1659 SqrtTerm = ConstantExpr::getCast(SqrtTerm, SignedTy);
1661 Constant *Solution1 =
1662 ConstantExpr::getDiv(ConstantExpr::getAdd(NegB, SqrtTerm), TwoA);
1663 Constant *Solution2 =
1664 ConstantExpr::getDiv(ConstantExpr::getSub(NegB, SqrtTerm), TwoA);
1665 return std::make_pair(SCEVUnknown::get(Solution1),
1666 SCEVUnknown::get(Solution2));
1669 /// HowFarToZero - Return the number of times a backedge comparing the specified
1670 /// value to zero will execute. If not computable, return UnknownValue
1671 SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
1672 // If the value is a constant
1673 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
1674 // If the value is already zero, the branch will execute zero times.
1675 if (C->getValue()->isNullValue()) return C;
1676 return UnknownValue; // Otherwise it will loop infinitely.
1679 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
1680 if (!AddRec || AddRec->getLoop() != L)
1681 return UnknownValue;
1683 if (AddRec->isAffine()) {
1684 // If this is an affine expression the execution count of this branch is
1687 // (0 - Start/Step) iff Start % Step == 0
1689 // Get the initial value for the loop.
1690 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
1691 SCEVHandle Step = AddRec->getOperand(1);
1693 Step = getSCEVAtScope(Step, L->getParentLoop());
1695 // Figure out if Start % Step == 0.
1696 // FIXME: We should add DivExpr and RemExpr operations to our AST.
1697 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
1698 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
1699 return getNegativeSCEV(Start); // 0 - Start/1 == -Start
1700 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
1701 return Start; // 0 - Start/-1 == Start
1703 // Check to see if Start is divisible by SC with no remainder.
1704 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
1705 ConstantInt *StartCC = StartC->getValue();
1706 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
1707 Constant *Rem = ConstantExpr::getRem(StartNegC, StepC->getValue());
1708 if (Rem->isNullValue()) {
1709 Constant *Result =ConstantExpr::getDiv(StartNegC,StepC->getValue());
1710 return SCEVUnknown::get(Result);
1714 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
1715 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
1716 // the quadratic equation to solve it.
1717 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec);
1718 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
1719 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
1722 std::cerr << "HFTZ: " << *V << " - sol#1: " << *R1
1723 << " sol#2: " << *R2 << "\n";
1725 // Pick the smallest positive root value.
1726 assert(R1->getType()->isUnsigned()&&"Didn't canonicalize to unsigned?");
1727 if (ConstantBool *CB =
1728 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
1730 if (CB != ConstantBool::True)
1731 std::swap(R1, R2); // R1 is the minimum root now.
1733 // We can only use this value if the chrec ends up with an exact zero
1734 // value at this index. When solving for "X*X != 5", for example, we
1735 // should not accept a root of 2.
1736 SCEVHandle Val = AddRec->evaluateAtIteration(R1);
1737 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
1738 if (EvalVal->getValue()->isNullValue())
1739 return R1; // We found a quadratic root!
1744 return UnknownValue;
1747 /// HowFarToNonZero - Return the number of times a backedge checking the
1748 /// specified value for nonzero will execute. If not computable, return
1750 SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
1751 // Loops that look like: while (X == 0) are very strange indeed. We don't
1752 // handle them yet except for the trivial case. This could be expanded in the
1753 // future as needed.
1755 // If the value is a constant, check to see if it is known to be non-zero
1756 // already. If so, the backedge will execute zero times.
1757 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
1758 Constant *Zero = Constant::getNullValue(C->getValue()->getType());
1759 Constant *NonZero = ConstantExpr::getSetNE(C->getValue(), Zero);
1760 if (NonZero == ConstantBool::True)
1761 return getSCEV(Zero);
1762 return UnknownValue; // Otherwise it will loop infinitely.
1765 // We could implement others, but I really doubt anyone writes loops like
1766 // this, and if they did, they would already be constant folded.
1767 return UnknownValue;
1770 static ConstantInt *
1771 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) {
1772 SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C));
1773 SCEVHandle Val = AddRec->evaluateAtIteration(InVal);
1774 assert(isa<SCEVConstant>(Val) &&
1775 "Evaluation of SCEV at constant didn't fold correctly?");
1776 return cast<SCEVConstant>(Val)->getValue();
1780 /// getNumIterationsInRange - Return the number of iterations of this loop that
1781 /// produce values in the specified constant range. Another way of looking at
1782 /// this is that it returns the first iteration number where the value is not in
1783 /// the condition, thus computing the exit count. If the iteration count can't
1784 /// be computed, an instance of SCEVCouldNotCompute is returned.
1785 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range) const {
1786 if (Range.isFullSet()) // Infinite loop.
1787 return new SCEVCouldNotCompute();
1789 // If the start is a non-zero constant, shift the range to simplify things.
1790 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
1791 if (!SC->getValue()->isNullValue()) {
1792 std::vector<SCEVHandle> Operands(op_begin(), op_end());
1793 Operands[0] = getIntegerSCEV(0, SC->getType());
1794 SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop());
1795 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
1796 return ShiftedAddRec->getNumIterationsInRange(
1797 Range.subtract(SC->getValue()));
1798 // This is strange and shouldn't happen.
1799 return new SCEVCouldNotCompute();
1802 // The only time we can solve this is when we have all constant indices.
1803 // Otherwise, we cannot determine the overflow conditions.
1804 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1805 if (!isa<SCEVConstant>(getOperand(i)))
1806 return new SCEVCouldNotCompute();
1809 // Okay at this point we know that all elements of the chrec are constants and
1810 // that the start element is zero.
1812 // First check to see if the range contains zero. If not, the first
1814 ConstantInt *Zero = ConstantInt::get(getType(), 0);
1815 if (!Range.contains(Zero)) return SCEVConstant::get(Zero);
1818 // If this is an affine expression then we have this situation:
1819 // Solve {0,+,A} in Range === Ax in Range
1821 // Since we know that zero is in the range, we know that the upper value of
1822 // the range must be the first possible exit value. Also note that we
1823 // already checked for a full range.
1824 ConstantInt *Upper = cast<ConstantInt>(Range.getUpper());
1825 ConstantInt *A = cast<SCEVConstant>(getOperand(1))->getValue();
1826 ConstantInt *One = ConstantInt::get(getType(), 1);
1828 // The exit value should be (Upper+A-1)/A.
1829 Constant *ExitValue = Upper;
1831 ExitValue = ConstantExpr::getSub(ConstantExpr::getAdd(Upper, A), One);
1832 ExitValue = ConstantExpr::getDiv(ExitValue, A);
1834 assert(isa<ConstantInt>(ExitValue) &&
1835 "Constant folding of integers not implemented?");
1837 // Evaluate at the exit value. If we really did fall out of the valid
1838 // range, then we computed our trip count, otherwise wrap around or other
1839 // things must have happened.
1840 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue);
1841 if (Range.contains(Val))
1842 return new SCEVCouldNotCompute(); // Something strange happened
1844 // Ensure that the previous value is in the range. This is a sanity check.
1845 assert(Range.contains(EvaluateConstantChrecAtConstant(this,
1846 ConstantExpr::getSub(ExitValue, One))) &&
1847 "Linear scev computation is off in a bad way!");
1848 return SCEVConstant::get(cast<ConstantInt>(ExitValue));
1849 } else if (isQuadratic()) {
1850 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
1851 // quadratic equation to solve it. To do this, we must frame our problem in
1852 // terms of figuring out when zero is crossed, instead of when
1853 // Range.getUpper() is crossed.
1854 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
1855 NewOps[0] = getNegativeSCEV(SCEVUnknown::get(Range.getUpper()));
1856 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop());
1858 // Next, solve the constructed addrec
1859 std::pair<SCEVHandle,SCEVHandle> Roots =
1860 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec));
1861 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
1862 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
1864 // Pick the smallest positive root value.
1865 assert(R1->getType()->isUnsigned() && "Didn't canonicalize to unsigned?");
1866 if (ConstantBool *CB =
1867 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
1869 if (CB != ConstantBool::True)
1870 std::swap(R1, R2); // R1 is the minimum root now.
1872 // Make sure the root is not off by one. The returned iteration should
1873 // not be in the range, but the previous one should be. When solving
1874 // for "X*X < 5", for example, we should not return a root of 2.
1875 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
1877 if (Range.contains(R1Val)) {
1878 // The next iteration must be out of the range...
1880 ConstantExpr::getAdd(R1->getValue(),
1881 ConstantInt::get(R1->getType(), 1));
1883 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
1884 if (!Range.contains(R1Val))
1885 return SCEVUnknown::get(NextVal);
1886 return new SCEVCouldNotCompute(); // Something strange happened
1889 // If R1 was not in the range, then it is a good return value. Make
1890 // sure that R1-1 WAS in the range though, just in case.
1892 ConstantExpr::getSub(R1->getValue(),
1893 ConstantInt::get(R1->getType(), 1));
1894 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
1895 if (Range.contains(R1Val))
1897 return new SCEVCouldNotCompute(); // Something strange happened
1902 // Fallback, if this is a general polynomial, figure out the progression
1903 // through brute force: evaluate until we find an iteration that fails the
1904 // test. This is likely to be slow, but getting an accurate trip count is
1905 // incredibly important, we will be able to simplify the exit test a lot, and
1906 // we are almost guaranteed to get a trip count in this case.
1907 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
1908 ConstantInt *One = ConstantInt::get(getType(), 1);
1909 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
1911 ++NumBruteForceEvaluations;
1912 SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal));
1913 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
1914 return new SCEVCouldNotCompute();
1916 // Check to see if we found the value!
1917 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()))
1918 return SCEVConstant::get(TestVal);
1920 // Increment to test the next index.
1921 TestVal = cast<ConstantInt>(ConstantExpr::getAdd(TestVal, One));
1922 } while (TestVal != EndVal);
1924 return new SCEVCouldNotCompute();
1929 //===----------------------------------------------------------------------===//
1930 // ScalarEvolution Class Implementation
1931 //===----------------------------------------------------------------------===//
1933 bool ScalarEvolution::runOnFunction(Function &F) {
1934 Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>());
1938 void ScalarEvolution::releaseMemory() {
1939 delete (ScalarEvolutionsImpl*)Impl;
1943 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
1944 AU.setPreservesAll();
1945 AU.addRequiredID(LoopSimplifyID);
1946 AU.addRequiredTransitive<LoopInfo>();
1949 SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
1950 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
1953 SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
1954 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
1957 bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
1958 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
1961 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
1962 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
1965 void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const {
1966 return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I);
1970 /// shouldSubstituteIndVar - Return true if we should perform induction variable
1971 /// substitution for this variable. This is a hack because we don't have a
1972 /// strength reduction pass yet. When we do we will promote all vars, because
1973 /// we can strength reduce them later as desired.
1974 bool ScalarEvolution::shouldSubstituteIndVar(const SCEV *S) const {
1975 // Don't substitute high degree polynomials.
1976 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S))
1977 if (AddRec->getNumOperands() > 3) return false;
1982 static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
1984 // Print all inner loops first
1985 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
1986 PrintLoopInfo(OS, SE, *I);
1988 std::cerr << "Loop " << L->getHeader()->getName() << ": ";
1989 if (L->getExitBlocks().size() != 1)
1990 std::cerr << "<multiple exits> ";
1992 if (SE->hasLoopInvariantIterationCount(L)) {
1993 std::cerr << *SE->getIterationCount(L) << " iterations! ";
1995 std::cerr << "Unpredictable iteration count. ";
2001 void ScalarEvolution::print(std::ostream &OS) const {
2002 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2003 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2005 OS << "Classifying expressions for: " << F.getName() << "\n";
2006 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
2007 if ((*I)->getType()->isInteger()) {
2010 SCEVHandle SV = getSCEV(*I);
2014 if ((*I)->getType()->isIntegral()) {
2015 ConstantRange Bounds = SV->getValueRange();
2016 if (!Bounds.isFullSet())
2017 OS << "Bounds: " << Bounds << " ";
2020 if (const Loop *L = LI.getLoopFor((*I)->getParent())) {
2022 SCEVHandle ExitValue = getSCEVAtScope(*I, L->getParentLoop());
2023 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2024 OS << "<<Unknown>>";
2034 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2035 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2036 PrintLoopInfo(OS, this, *I);
2039 //===----------------------------------------------------------------------===//
2040 // ScalarEvolutionRewriter Class Implementation
2041 //===----------------------------------------------------------------------===//
2043 Value *ScalarEvolutionRewriter::
2044 GetOrInsertCanonicalInductionVariable(const Loop *L, const Type *Ty) {
2045 assert((Ty->isInteger() || Ty->isFloatingPoint()) &&
2046 "Can only insert integer or floating point induction variables!");
2048 // Check to see if we already inserted one.
2049 SCEVHandle H = SCEVAddRecExpr::get(getIntegerSCEV(0, Ty),
2050 getIntegerSCEV(1, Ty), L);
2051 return ExpandCodeFor(H, 0, Ty);
2054 /// ExpandCodeFor - Insert code to directly compute the specified SCEV
2055 /// expression into the program. The inserted code is inserted into the
2056 /// specified block.
2057 Value *ScalarEvolutionRewriter::ExpandCodeFor(SCEVHandle SH,
2058 Instruction *InsertPt,
2060 std::map<SCEVHandle, Value*>::iterator ExistVal =InsertedExpressions.find(SH);
2062 if (ExistVal != InsertedExpressions.end()) {
2063 V = ExistVal->second;
2065 // Ask the recurrence object to expand the code for itself.
2066 V = SH->expandCodeFor(*this, InsertPt);
2067 // Cache the generated result.
2068 InsertedExpressions.insert(std::make_pair(SH, V));
2071 if (Ty == 0 || V->getType() == Ty)
2073 if (Constant *C = dyn_cast<Constant>(V))
2074 return ConstantExpr::getCast(C, Ty);
2075 else if (Instruction *I = dyn_cast<Instruction>(V)) {
2076 // Check to see if there is already a cast. If there is, use it.
2077 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2079 if ((*UI)->getType() == Ty)
2080 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI))) {
2081 BasicBlock::iterator It = I; ++It;
2082 while (isa<PHINode>(It)) ++It;
2083 if (It != BasicBlock::iterator(CI)) {
2084 // Splice the cast immediately after the operand in question.
2085 I->getParent()->getInstList().splice(It,
2086 CI->getParent()->getInstList(),
2092 BasicBlock::iterator IP = I; ++IP;
2093 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
2094 IP = II->getNormalDest()->begin();
2095 while (isa<PHINode>(IP)) ++IP;
2096 return new CastInst(V, Ty, V->getName(), IP);
2098 // FIXME: check to see if there is already a cast!
2099 return new CastInst(V, Ty, V->getName(), InsertPt);