1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the implementation of the scalar evolution analysis
11 // engine, which is used primarily to analyze expressions involving induction
12 // variables in loops.
14 // There are several aspects to this library. First is the representation of
15 // scalar expressions, which are represented as subclasses of the SCEV class.
16 // These classes are used to represent certain types of subexpressions that we
17 // can handle. We only create one SCEV of a particular shape, so
18 // pointer-comparisons for equality are legal.
20 // One important aspect of the SCEV objects is that they are never cyclic, even
21 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If
22 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
23 // recurrence) then we represent it directly as a recurrence node, otherwise we
24 // represent it as a SCEVUnknown node.
26 // In addition to being able to represent expressions of various types, we also
27 // have folders that are used to build the *canonical* representation for a
28 // particular expression. These folders are capable of using a variety of
29 // rewrite rules to simplify the expressions.
31 // Once the folders are defined, we can implement the more interesting
32 // higher-level code, such as the code that recognizes PHI nodes of various
33 // types, computes the execution count of a loop, etc.
35 // TODO: We should use these routines and value representations to implement
36 // dependence analysis!
38 //===----------------------------------------------------------------------===//
40 // There are several good references for the techniques used in this analysis.
42 // Chains of recurrences -- a method to expedite the evaluation
43 // of closed-form functions
44 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima
46 // On computational properties of chains of recurrences
49 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50 // Robert A. van Engelen
52 // Efficient Symbolic Analysis for Optimizing Compilers
53 // Robert A. van Engelen
55 // Using the chains of recurrences algebra for data dependence testing and
56 // induction variable substitution
57 // MS Thesis, Johnie Birch
59 //===----------------------------------------------------------------------===//
61 #define DEBUG_TYPE "scalar-evolution"
62 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
63 #include "llvm/Constants.h"
64 #include "llvm/DerivedTypes.h"
65 #include "llvm/GlobalVariable.h"
66 #include "llvm/GlobalAlias.h"
67 #include "llvm/Instructions.h"
68 #include "llvm/LLVMContext.h"
69 #include "llvm/Operator.h"
70 #include "llvm/Analysis/ConstantFolding.h"
71 #include "llvm/Analysis/Dominators.h"
72 #include "llvm/Analysis/InstructionSimplify.h"
73 #include "llvm/Analysis/LoopInfo.h"
74 #include "llvm/Analysis/ValueTracking.h"
75 #include "llvm/Assembly/Writer.h"
76 #include "llvm/Target/TargetData.h"
77 #include "llvm/Support/CommandLine.h"
78 #include "llvm/Support/ConstantRange.h"
79 #include "llvm/Support/Debug.h"
80 #include "llvm/Support/ErrorHandling.h"
81 #include "llvm/Support/GetElementPtrTypeIterator.h"
82 #include "llvm/Support/InstIterator.h"
83 #include "llvm/Support/MathExtras.h"
84 #include "llvm/Support/raw_ostream.h"
85 #include "llvm/ADT/Statistic.h"
86 #include "llvm/ADT/STLExtras.h"
87 #include "llvm/ADT/SmallPtrSet.h"
91 STATISTIC(NumArrayLenItCounts,
92 "Number of trip counts computed with array length");
93 STATISTIC(NumTripCountsComputed,
94 "Number of loops with predictable loop counts");
95 STATISTIC(NumTripCountsNotComputed,
96 "Number of loops without predictable loop counts");
97 STATISTIC(NumBruteForceTripCountsComputed,
98 "Number of loops with trip counts computed by force");
100 static cl::opt<unsigned>
101 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
102 cl::desc("Maximum number of iterations SCEV will "
103 "symbolically execute a constant "
107 INITIALIZE_PASS_BEGIN(ScalarEvolution, "scalar-evolution",
108 "Scalar Evolution Analysis", false, true)
109 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
110 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
111 INITIALIZE_PASS_END(ScalarEvolution, "scalar-evolution",
112 "Scalar Evolution Analysis", false, true)
113 char ScalarEvolution::ID = 0;
115 //===----------------------------------------------------------------------===//
116 // SCEV class definitions
117 //===----------------------------------------------------------------------===//
119 //===----------------------------------------------------------------------===//
120 // Implementation of the SCEV class.
123 void SCEV::dump() const {
128 void SCEV::print(raw_ostream &OS) const {
129 switch (getSCEVType()) {
131 WriteAsOperand(OS, cast<SCEVConstant>(this)->getValue(), false);
134 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
135 const SCEV *Op = Trunc->getOperand();
136 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
137 << *Trunc->getType() << ")";
141 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
142 const SCEV *Op = ZExt->getOperand();
143 OS << "(zext " << *Op->getType() << " " << *Op << " to "
144 << *ZExt->getType() << ")";
148 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
149 const SCEV *Op = SExt->getOperand();
150 OS << "(sext " << *Op->getType() << " " << *Op << " to "
151 << *SExt->getType() << ")";
155 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
156 OS << "{" << *AR->getOperand(0);
157 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
158 OS << ",+," << *AR->getOperand(i);
160 if (AR->getNoWrapFlags(FlagNUW))
162 if (AR->getNoWrapFlags(FlagNSW))
164 if (AR->getNoWrapFlags(FlagNW) &&
165 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
167 WriteAsOperand(OS, AR->getLoop()->getHeader(), /*PrintType=*/false);
175 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
176 const char *OpStr = 0;
177 switch (NAry->getSCEVType()) {
178 case scAddExpr: OpStr = " + "; break;
179 case scMulExpr: OpStr = " * "; break;
180 case scUMaxExpr: OpStr = " umax "; break;
181 case scSMaxExpr: OpStr = " smax "; break;
184 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
187 if (llvm::next(I) != E)
194 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
195 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
199 const SCEVUnknown *U = cast<SCEVUnknown>(this);
201 if (U->isSizeOf(AllocTy)) {
202 OS << "sizeof(" << *AllocTy << ")";
205 if (U->isAlignOf(AllocTy)) {
206 OS << "alignof(" << *AllocTy << ")";
212 if (U->isOffsetOf(CTy, FieldNo)) {
213 OS << "offsetof(" << *CTy << ", ";
214 WriteAsOperand(OS, FieldNo, false);
219 // Otherwise just print it normally.
220 WriteAsOperand(OS, U->getValue(), false);
223 case scCouldNotCompute:
224 OS << "***COULDNOTCOMPUTE***";
228 llvm_unreachable("Unknown SCEV kind!");
231 Type *SCEV::getType() const {
232 switch (getSCEVType()) {
234 return cast<SCEVConstant>(this)->getType();
238 return cast<SCEVCastExpr>(this)->getType();
243 return cast<SCEVNAryExpr>(this)->getType();
245 return cast<SCEVAddExpr>(this)->getType();
247 return cast<SCEVUDivExpr>(this)->getType();
249 return cast<SCEVUnknown>(this)->getType();
250 case scCouldNotCompute:
251 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
255 llvm_unreachable("Unknown SCEV kind!");
259 bool SCEV::isZero() const {
260 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
261 return SC->getValue()->isZero();
265 bool SCEV::isOne() const {
266 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
267 return SC->getValue()->isOne();
271 bool SCEV::isAllOnesValue() const {
272 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
273 return SC->getValue()->isAllOnesValue();
277 SCEVCouldNotCompute::SCEVCouldNotCompute() :
278 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
280 bool SCEVCouldNotCompute::classof(const SCEV *S) {
281 return S->getSCEVType() == scCouldNotCompute;
284 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
286 ID.AddInteger(scConstant);
289 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
290 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
291 UniqueSCEVs.InsertNode(S, IP);
295 const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
296 return getConstant(ConstantInt::get(getContext(), Val));
300 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
301 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
302 return getConstant(ConstantInt::get(ITy, V, isSigned));
305 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
306 unsigned SCEVTy, const SCEV *op, Type *ty)
307 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
309 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
310 const SCEV *op, Type *ty)
311 : SCEVCastExpr(ID, scTruncate, op, ty) {
312 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
313 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
314 "Cannot truncate non-integer value!");
317 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
318 const SCEV *op, Type *ty)
319 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
320 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
321 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
322 "Cannot zero extend non-integer value!");
325 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
326 const SCEV *op, Type *ty)
327 : SCEVCastExpr(ID, scSignExtend, op, ty) {
328 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
329 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
330 "Cannot sign extend non-integer value!");
333 void SCEVUnknown::deleted() {
334 // Clear this SCEVUnknown from various maps.
335 SE->forgetMemoizedResults(this);
337 // Remove this SCEVUnknown from the uniquing map.
338 SE->UniqueSCEVs.RemoveNode(this);
340 // Release the value.
344 void SCEVUnknown::allUsesReplacedWith(Value *New) {
345 // Clear this SCEVUnknown from various maps.
346 SE->forgetMemoizedResults(this);
348 // Remove this SCEVUnknown from the uniquing map.
349 SE->UniqueSCEVs.RemoveNode(this);
351 // Update this SCEVUnknown to point to the new value. This is needed
352 // because there may still be outstanding SCEVs which still point to
357 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
358 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
359 if (VCE->getOpcode() == Instruction::PtrToInt)
360 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
361 if (CE->getOpcode() == Instruction::GetElementPtr &&
362 CE->getOperand(0)->isNullValue() &&
363 CE->getNumOperands() == 2)
364 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
366 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
374 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
375 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
376 if (VCE->getOpcode() == Instruction::PtrToInt)
377 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
378 if (CE->getOpcode() == Instruction::GetElementPtr &&
379 CE->getOperand(0)->isNullValue()) {
381 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
382 if (StructType *STy = dyn_cast<StructType>(Ty))
383 if (!STy->isPacked() &&
384 CE->getNumOperands() == 3 &&
385 CE->getOperand(1)->isNullValue()) {
386 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
388 STy->getNumElements() == 2 &&
389 STy->getElementType(0)->isIntegerTy(1)) {
390 AllocTy = STy->getElementType(1);
399 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
400 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
401 if (VCE->getOpcode() == Instruction::PtrToInt)
402 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
403 if (CE->getOpcode() == Instruction::GetElementPtr &&
404 CE->getNumOperands() == 3 &&
405 CE->getOperand(0)->isNullValue() &&
406 CE->getOperand(1)->isNullValue()) {
408 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
409 // Ignore vector types here so that ScalarEvolutionExpander doesn't
410 // emit getelementptrs that index into vectors.
411 if (Ty->isStructTy() || Ty->isArrayTy()) {
413 FieldNo = CE->getOperand(2);
421 //===----------------------------------------------------------------------===//
423 //===----------------------------------------------------------------------===//
426 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
427 /// than the complexity of the RHS. This comparator is used to canonicalize
429 class SCEVComplexityCompare {
430 const LoopInfo *const LI;
432 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
434 // Return true or false if LHS is less than, or at least RHS, respectively.
435 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
436 return compare(LHS, RHS) < 0;
439 // Return negative, zero, or positive, if LHS is less than, equal to, or
440 // greater than RHS, respectively. A three-way result allows recursive
441 // comparisons to be more efficient.
442 int compare(const SCEV *LHS, const SCEV *RHS) const {
443 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
447 // Primarily, sort the SCEVs by their getSCEVType().
448 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
450 return (int)LType - (int)RType;
452 // Aside from the getSCEVType() ordering, the particular ordering
453 // isn't very important except that it's beneficial to be consistent,
454 // so that (a + b) and (b + a) don't end up as different expressions.
457 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
458 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
460 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
461 // not as complete as it could be.
462 const Value *LV = LU->getValue(), *RV = RU->getValue();
464 // Order pointer values after integer values. This helps SCEVExpander
466 bool LIsPointer = LV->getType()->isPointerTy(),
467 RIsPointer = RV->getType()->isPointerTy();
468 if (LIsPointer != RIsPointer)
469 return (int)LIsPointer - (int)RIsPointer;
471 // Compare getValueID values.
472 unsigned LID = LV->getValueID(),
473 RID = RV->getValueID();
475 return (int)LID - (int)RID;
477 // Sort arguments by their position.
478 if (const Argument *LA = dyn_cast<Argument>(LV)) {
479 const Argument *RA = cast<Argument>(RV);
480 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
481 return (int)LArgNo - (int)RArgNo;
484 // For instructions, compare their loop depth, and their operand
485 // count. This is pretty loose.
486 if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
487 const Instruction *RInst = cast<Instruction>(RV);
489 // Compare loop depths.
490 const BasicBlock *LParent = LInst->getParent(),
491 *RParent = RInst->getParent();
492 if (LParent != RParent) {
493 unsigned LDepth = LI->getLoopDepth(LParent),
494 RDepth = LI->getLoopDepth(RParent);
495 if (LDepth != RDepth)
496 return (int)LDepth - (int)RDepth;
499 // Compare the number of operands.
500 unsigned LNumOps = LInst->getNumOperands(),
501 RNumOps = RInst->getNumOperands();
502 return (int)LNumOps - (int)RNumOps;
509 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
510 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
512 // Compare constant values.
513 const APInt &LA = LC->getValue()->getValue();
514 const APInt &RA = RC->getValue()->getValue();
515 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
516 if (LBitWidth != RBitWidth)
517 return (int)LBitWidth - (int)RBitWidth;
518 return LA.ult(RA) ? -1 : 1;
522 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
523 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
525 // Compare addrec loop depths.
526 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
527 if (LLoop != RLoop) {
528 unsigned LDepth = LLoop->getLoopDepth(),
529 RDepth = RLoop->getLoopDepth();
530 if (LDepth != RDepth)
531 return (int)LDepth - (int)RDepth;
534 // Addrec complexity grows with operand count.
535 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
536 if (LNumOps != RNumOps)
537 return (int)LNumOps - (int)RNumOps;
539 // Lexicographically compare.
540 for (unsigned i = 0; i != LNumOps; ++i) {
541 long X = compare(LA->getOperand(i), RA->getOperand(i));
553 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
554 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
556 // Lexicographically compare n-ary expressions.
557 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
558 for (unsigned i = 0; i != LNumOps; ++i) {
561 long X = compare(LC->getOperand(i), RC->getOperand(i));
565 return (int)LNumOps - (int)RNumOps;
569 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
570 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
572 // Lexicographically compare udiv expressions.
573 long X = compare(LC->getLHS(), RC->getLHS());
576 return compare(LC->getRHS(), RC->getRHS());
582 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
583 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
585 // Compare cast expressions by operand.
586 return compare(LC->getOperand(), RC->getOperand());
593 llvm_unreachable("Unknown SCEV kind!");
599 /// GroupByComplexity - Given a list of SCEV objects, order them by their
600 /// complexity, and group objects of the same complexity together by value.
601 /// When this routine is finished, we know that any duplicates in the vector are
602 /// consecutive and that complexity is monotonically increasing.
604 /// Note that we go take special precautions to ensure that we get deterministic
605 /// results from this routine. In other words, we don't want the results of
606 /// this to depend on where the addresses of various SCEV objects happened to
609 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
611 if (Ops.size() < 2) return; // Noop
612 if (Ops.size() == 2) {
613 // This is the common case, which also happens to be trivially simple.
615 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
616 if (SCEVComplexityCompare(LI)(RHS, LHS))
621 // Do the rough sort by complexity.
622 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
624 // Now that we are sorted by complexity, group elements of the same
625 // complexity. Note that this is, at worst, N^2, but the vector is likely to
626 // be extremely short in practice. Note that we take this approach because we
627 // do not want to depend on the addresses of the objects we are grouping.
628 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
629 const SCEV *S = Ops[i];
630 unsigned Complexity = S->getSCEVType();
632 // If there are any objects of the same complexity and same value as this
634 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
635 if (Ops[j] == S) { // Found a duplicate.
636 // Move it to immediately after i'th element.
637 std::swap(Ops[i+1], Ops[j]);
638 ++i; // no need to rescan it.
639 if (i == e-2) return; // Done!
647 //===----------------------------------------------------------------------===//
648 // Simple SCEV method implementations
649 //===----------------------------------------------------------------------===//
651 /// BinomialCoefficient - Compute BC(It, K). The result has width W.
653 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
656 // Handle the simplest case efficiently.
658 return SE.getTruncateOrZeroExtend(It, ResultTy);
660 // We are using the following formula for BC(It, K):
662 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
664 // Suppose, W is the bitwidth of the return value. We must be prepared for
665 // overflow. Hence, we must assure that the result of our computation is
666 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
667 // safe in modular arithmetic.
669 // However, this code doesn't use exactly that formula; the formula it uses
670 // is something like the following, where T is the number of factors of 2 in
671 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
674 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
676 // This formula is trivially equivalent to the previous formula. However,
677 // this formula can be implemented much more efficiently. The trick is that
678 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
679 // arithmetic. To do exact division in modular arithmetic, all we have
680 // to do is multiply by the inverse. Therefore, this step can be done at
683 // The next issue is how to safely do the division by 2^T. The way this
684 // is done is by doing the multiplication step at a width of at least W + T
685 // bits. This way, the bottom W+T bits of the product are accurate. Then,
686 // when we perform the division by 2^T (which is equivalent to a right shift
687 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
688 // truncated out after the division by 2^T.
690 // In comparison to just directly using the first formula, this technique
691 // is much more efficient; using the first formula requires W * K bits,
692 // but this formula less than W + K bits. Also, the first formula requires
693 // a division step, whereas this formula only requires multiplies and shifts.
695 // It doesn't matter whether the subtraction step is done in the calculation
696 // width or the input iteration count's width; if the subtraction overflows,
697 // the result must be zero anyway. We prefer here to do it in the width of
698 // the induction variable because it helps a lot for certain cases; CodeGen
699 // isn't smart enough to ignore the overflow, which leads to much less
700 // efficient code if the width of the subtraction is wider than the native
703 // (It's possible to not widen at all by pulling out factors of 2 before
704 // the multiplication; for example, K=2 can be calculated as
705 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
706 // extra arithmetic, so it's not an obvious win, and it gets
707 // much more complicated for K > 3.)
709 // Protection from insane SCEVs; this bound is conservative,
710 // but it probably doesn't matter.
712 return SE.getCouldNotCompute();
714 unsigned W = SE.getTypeSizeInBits(ResultTy);
716 // Calculate K! / 2^T and T; we divide out the factors of two before
717 // multiplying for calculating K! / 2^T to avoid overflow.
718 // Other overflow doesn't matter because we only care about the bottom
719 // W bits of the result.
720 APInt OddFactorial(W, 1);
722 for (unsigned i = 3; i <= K; ++i) {
724 unsigned TwoFactors = Mult.countTrailingZeros();
726 Mult = Mult.lshr(TwoFactors);
727 OddFactorial *= Mult;
730 // We need at least W + T bits for the multiplication step
731 unsigned CalculationBits = W + T;
733 // Calculate 2^T, at width T+W.
734 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
736 // Calculate the multiplicative inverse of K! / 2^T;
737 // this multiplication factor will perform the exact division by
739 APInt Mod = APInt::getSignedMinValue(W+1);
740 APInt MultiplyFactor = OddFactorial.zext(W+1);
741 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
742 MultiplyFactor = MultiplyFactor.trunc(W);
744 // Calculate the product, at width T+W
745 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
747 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
748 for (unsigned i = 1; i != K; ++i) {
749 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
750 Dividend = SE.getMulExpr(Dividend,
751 SE.getTruncateOrZeroExtend(S, CalculationTy));
755 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
757 // Truncate the result, and divide by K! / 2^T.
759 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
760 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
763 /// evaluateAtIteration - Return the value of this chain of recurrences at
764 /// the specified iteration number. We can evaluate this recurrence by
765 /// multiplying each element in the chain by the binomial coefficient
766 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
768 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
770 /// where BC(It, k) stands for binomial coefficient.
772 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
773 ScalarEvolution &SE) const {
774 const SCEV *Result = getStart();
775 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
776 // The computation is correct in the face of overflow provided that the
777 // multiplication is performed _after_ the evaluation of the binomial
779 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
780 if (isa<SCEVCouldNotCompute>(Coeff))
783 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
788 //===----------------------------------------------------------------------===//
789 // SCEV Expression folder implementations
790 //===----------------------------------------------------------------------===//
792 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
794 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
795 "This is not a truncating conversion!");
796 assert(isSCEVable(Ty) &&
797 "This is not a conversion to a SCEVable type!");
798 Ty = getEffectiveSCEVType(Ty);
801 ID.AddInteger(scTruncate);
805 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
807 // Fold if the operand is constant.
808 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
810 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(),
811 getEffectiveSCEVType(Ty))));
813 // trunc(trunc(x)) --> trunc(x)
814 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
815 return getTruncateExpr(ST->getOperand(), Ty);
817 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
818 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
819 return getTruncateOrSignExtend(SS->getOperand(), Ty);
821 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
822 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
823 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
825 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
826 // eliminate all the truncates.
827 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
828 SmallVector<const SCEV *, 4> Operands;
829 bool hasTrunc = false;
830 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
831 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
832 hasTrunc = isa<SCEVTruncateExpr>(S);
833 Operands.push_back(S);
836 return getAddExpr(Operands);
837 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
840 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
841 // eliminate all the truncates.
842 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
843 SmallVector<const SCEV *, 4> Operands;
844 bool hasTrunc = false;
845 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
846 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
847 hasTrunc = isa<SCEVTruncateExpr>(S);
848 Operands.push_back(S);
851 return getMulExpr(Operands);
852 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
855 // If the input value is a chrec scev, truncate the chrec's operands.
856 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
857 SmallVector<const SCEV *, 4> Operands;
858 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
859 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
860 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
863 // As a special case, fold trunc(undef) to undef. We don't want to
864 // know too much about SCEVUnknowns, but this special case is handy
866 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
867 if (isa<UndefValue>(U->getValue()))
868 return getSCEV(UndefValue::get(Ty));
870 // The cast wasn't folded; create an explicit cast node. We can reuse
871 // the existing insert position since if we get here, we won't have
872 // made any changes which would invalidate it.
873 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
875 UniqueSCEVs.InsertNode(S, IP);
879 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
881 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
882 "This is not an extending conversion!");
883 assert(isSCEVable(Ty) &&
884 "This is not a conversion to a SCEVable type!");
885 Ty = getEffectiveSCEVType(Ty);
887 // Fold if the operand is constant.
888 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
890 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(),
891 getEffectiveSCEVType(Ty))));
893 // zext(zext(x)) --> zext(x)
894 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
895 return getZeroExtendExpr(SZ->getOperand(), Ty);
897 // Before doing any expensive analysis, check to see if we've already
898 // computed a SCEV for this Op and Ty.
900 ID.AddInteger(scZeroExtend);
904 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
906 // zext(trunc(x)) --> zext(x) or x or trunc(x)
907 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
908 // It's possible the bits taken off by the truncate were all zero bits. If
909 // so, we should be able to simplify this further.
910 const SCEV *X = ST->getOperand();
911 ConstantRange CR = getUnsignedRange(X);
912 unsigned TruncBits = getTypeSizeInBits(ST->getType());
913 unsigned NewBits = getTypeSizeInBits(Ty);
914 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
915 CR.zextOrTrunc(NewBits)))
916 return getTruncateOrZeroExtend(X, Ty);
919 // If the input value is a chrec scev, and we can prove that the value
920 // did not overflow the old, smaller, value, we can zero extend all of the
921 // operands (often constants). This allows analysis of something like
922 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
923 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
924 if (AR->isAffine()) {
925 const SCEV *Start = AR->getStart();
926 const SCEV *Step = AR->getStepRecurrence(*this);
927 unsigned BitWidth = getTypeSizeInBits(AR->getType());
928 const Loop *L = AR->getLoop();
930 // If we have special knowledge that this addrec won't overflow,
931 // we don't need to do any further analysis.
932 if (AR->getNoWrapFlags(SCEV::FlagNUW))
933 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
934 getZeroExtendExpr(Step, Ty),
935 L, AR->getNoWrapFlags());
937 // Check whether the backedge-taken count is SCEVCouldNotCompute.
938 // Note that this serves two purposes: It filters out loops that are
939 // simply not analyzable, and it covers the case where this code is
940 // being called from within backedge-taken count analysis, such that
941 // attempting to ask for the backedge-taken count would likely result
942 // in infinite recursion. In the later case, the analysis code will
943 // cope with a conservative value, and it will take care to purge
944 // that value once it has finished.
945 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
946 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
947 // Manually compute the final value for AR, checking for
950 // Check whether the backedge-taken count can be losslessly casted to
951 // the addrec's type. The count is always unsigned.
952 const SCEV *CastedMaxBECount =
953 getTruncateOrZeroExtend(MaxBECount, Start->getType());
954 const SCEV *RecastedMaxBECount =
955 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
956 if (MaxBECount == RecastedMaxBECount) {
957 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
958 // Check whether Start+Step*MaxBECount has no unsigned overflow.
959 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
960 const SCEV *Add = getAddExpr(Start, ZMul);
961 const SCEV *OperandExtendedAdd =
962 getAddExpr(getZeroExtendExpr(Start, WideTy),
963 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
964 getZeroExtendExpr(Step, WideTy)));
965 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd) {
966 // Cache knowledge of AR NUW, which is propagated to this AddRec.
967 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
968 // Return the expression with the addrec on the outside.
969 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
970 getZeroExtendExpr(Step, Ty),
971 L, AR->getNoWrapFlags());
973 // Similar to above, only this time treat the step value as signed.
974 // This covers loops that count down.
975 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
976 Add = getAddExpr(Start, SMul);
978 getAddExpr(getZeroExtendExpr(Start, WideTy),
979 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
980 getSignExtendExpr(Step, WideTy)));
981 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd) {
982 // Cache knowledge of AR NW, which is propagated to this AddRec.
983 // Negative step causes unsigned wrap, but it still can't self-wrap.
984 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
985 // Return the expression with the addrec on the outside.
986 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
987 getSignExtendExpr(Step, Ty),
988 L, AR->getNoWrapFlags());
992 // If the backedge is guarded by a comparison with the pre-inc value
993 // the addrec is safe. Also, if the entry is guarded by a comparison
994 // with the start value and the backedge is guarded by a comparison
995 // with the post-inc value, the addrec is safe.
996 if (isKnownPositive(Step)) {
997 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
998 getUnsignedRange(Step).getUnsignedMax());
999 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1000 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
1001 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
1002 AR->getPostIncExpr(*this), N))) {
1003 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1004 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1005 // Return the expression with the addrec on the outside.
1006 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1007 getZeroExtendExpr(Step, Ty),
1008 L, AR->getNoWrapFlags());
1010 } else if (isKnownNegative(Step)) {
1011 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1012 getSignedRange(Step).getSignedMin());
1013 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1014 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
1015 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1016 AR->getPostIncExpr(*this), N))) {
1017 // Cache knowledge of AR NW, which is propagated to this AddRec.
1018 // Negative step causes unsigned wrap, but it still can't self-wrap.
1019 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1020 // Return the expression with the addrec on the outside.
1021 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1022 getSignExtendExpr(Step, Ty),
1023 L, AR->getNoWrapFlags());
1029 // The cast wasn't folded; create an explicit cast node.
1030 // Recompute the insert position, as it may have been invalidated.
1031 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1032 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1034 UniqueSCEVs.InsertNode(S, IP);
1038 // Get the limit of a recurrence such that incrementing by Step cannot cause
1039 // signed overflow as long as the value of the recurrence within the loop does
1040 // not exceed this limit before incrementing.
1041 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1042 ICmpInst::Predicate *Pred,
1043 ScalarEvolution *SE) {
1044 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1045 if (SE->isKnownPositive(Step)) {
1046 *Pred = ICmpInst::ICMP_SLT;
1047 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1048 SE->getSignedRange(Step).getSignedMax());
1050 if (SE->isKnownNegative(Step)) {
1051 *Pred = ICmpInst::ICMP_SGT;
1052 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1053 SE->getSignedRange(Step).getSignedMin());
1058 // The recurrence AR has been shown to have no signed wrap. Typically, if we can
1059 // prove NSW for AR, then we can just as easily prove NSW for its preincrement
1060 // or postincrement sibling. This allows normalizing a sign extended AddRec as
1061 // such: {sext(Step + Start),+,Step} => {(Step + sext(Start),+,Step} As a
1062 // result, the expression "Step + sext(PreIncAR)" is congruent with
1063 // "sext(PostIncAR)"
1064 static const SCEV *getPreStartForSignExtend(const SCEVAddRecExpr *AR,
1066 ScalarEvolution *SE) {
1067 const Loop *L = AR->getLoop();
1068 const SCEV *Start = AR->getStart();
1069 const SCEV *Step = AR->getStepRecurrence(*SE);
1071 // Check for a simple looking step prior to loop entry.
1072 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1073 if (!SA || SA->getNumOperands() != 2 || SA->getOperand(0) != Step)
1076 // This is a postinc AR. Check for overflow on the preinc recurrence using the
1077 // same three conditions that getSignExtendedExpr checks.
1079 // 1. NSW flags on the step increment.
1080 const SCEV *PreStart = SA->getOperand(1);
1081 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1082 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1084 if (PreAR && PreAR->getNoWrapFlags(SCEV::FlagNSW))
1087 // 2. Direct overflow check on the step operation's expression.
1088 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1089 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1090 const SCEV *OperandExtendedStart =
1091 SE->getAddExpr(SE->getSignExtendExpr(PreStart, WideTy),
1092 SE->getSignExtendExpr(Step, WideTy));
1093 if (SE->getSignExtendExpr(Start, WideTy) == OperandExtendedStart) {
1094 // Cache knowledge of PreAR NSW.
1096 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(SCEV::FlagNSW);
1097 // FIXME: this optimization needs a unit test
1098 DEBUG(dbgs() << "SCEV: untested prestart overflow check\n");
1102 // 3. Loop precondition.
1103 ICmpInst::Predicate Pred;
1104 const SCEV *OverflowLimit = getOverflowLimitForStep(Step, &Pred, SE);
1106 if (OverflowLimit &&
1107 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) {
1113 // Get the normalized sign-extended expression for this AddRec's Start.
1114 static const SCEV *getSignExtendAddRecStart(const SCEVAddRecExpr *AR,
1116 ScalarEvolution *SE) {
1117 const SCEV *PreStart = getPreStartForSignExtend(AR, Ty, SE);
1119 return SE->getSignExtendExpr(AR->getStart(), Ty);
1121 return SE->getAddExpr(SE->getSignExtendExpr(AR->getStepRecurrence(*SE), Ty),
1122 SE->getSignExtendExpr(PreStart, Ty));
1125 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
1127 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1128 "This is not an extending conversion!");
1129 assert(isSCEVable(Ty) &&
1130 "This is not a conversion to a SCEVable type!");
1131 Ty = getEffectiveSCEVType(Ty);
1133 // Fold if the operand is constant.
1134 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1136 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(),
1137 getEffectiveSCEVType(Ty))));
1139 // sext(sext(x)) --> sext(x)
1140 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1141 return getSignExtendExpr(SS->getOperand(), Ty);
1143 // sext(zext(x)) --> zext(x)
1144 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1145 return getZeroExtendExpr(SZ->getOperand(), Ty);
1147 // Before doing any expensive analysis, check to see if we've already
1148 // computed a SCEV for this Op and Ty.
1149 FoldingSetNodeID ID;
1150 ID.AddInteger(scSignExtend);
1154 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1156 // If the input value is provably positive, build a zext instead.
1157 if (isKnownNonNegative(Op))
1158 return getZeroExtendExpr(Op, Ty);
1160 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1161 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1162 // It's possible the bits taken off by the truncate were all sign bits. If
1163 // so, we should be able to simplify this further.
1164 const SCEV *X = ST->getOperand();
1165 ConstantRange CR = getSignedRange(X);
1166 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1167 unsigned NewBits = getTypeSizeInBits(Ty);
1168 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1169 CR.sextOrTrunc(NewBits)))
1170 return getTruncateOrSignExtend(X, Ty);
1173 // If the input value is a chrec scev, and we can prove that the value
1174 // did not overflow the old, smaller, value, we can sign extend all of the
1175 // operands (often constants). This allows analysis of something like
1176 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1177 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1178 if (AR->isAffine()) {
1179 const SCEV *Start = AR->getStart();
1180 const SCEV *Step = AR->getStepRecurrence(*this);
1181 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1182 const Loop *L = AR->getLoop();
1184 // If we have special knowledge that this addrec won't overflow,
1185 // we don't need to do any further analysis.
1186 if (AR->getNoWrapFlags(SCEV::FlagNSW))
1187 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
1188 getSignExtendExpr(Step, Ty),
1191 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1192 // Note that this serves two purposes: It filters out loops that are
1193 // simply not analyzable, and it covers the case where this code is
1194 // being called from within backedge-taken count analysis, such that
1195 // attempting to ask for the backedge-taken count would likely result
1196 // in infinite recursion. In the later case, the analysis code will
1197 // cope with a conservative value, and it will take care to purge
1198 // that value once it has finished.
1199 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1200 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1201 // Manually compute the final value for AR, checking for
1204 // Check whether the backedge-taken count can be losslessly casted to
1205 // the addrec's type. The count is always unsigned.
1206 const SCEV *CastedMaxBECount =
1207 getTruncateOrZeroExtend(MaxBECount, Start->getType());
1208 const SCEV *RecastedMaxBECount =
1209 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1210 if (MaxBECount == RecastedMaxBECount) {
1211 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1212 // Check whether Start+Step*MaxBECount has no signed overflow.
1213 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
1214 const SCEV *Add = getAddExpr(Start, SMul);
1215 const SCEV *OperandExtendedAdd =
1216 getAddExpr(getSignExtendExpr(Start, WideTy),
1217 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1218 getSignExtendExpr(Step, WideTy)));
1219 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd) {
1220 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1221 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1222 // Return the expression with the addrec on the outside.
1223 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
1224 getSignExtendExpr(Step, Ty),
1225 L, AR->getNoWrapFlags());
1227 // Similar to above, only this time treat the step value as unsigned.
1228 // This covers loops that count up with an unsigned step.
1229 const SCEV *UMul = getMulExpr(CastedMaxBECount, Step);
1230 Add = getAddExpr(Start, UMul);
1231 OperandExtendedAdd =
1232 getAddExpr(getSignExtendExpr(Start, WideTy),
1233 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1234 getZeroExtendExpr(Step, WideTy)));
1235 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd) {
1236 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1237 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1238 // Return the expression with the addrec on the outside.
1239 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
1240 getZeroExtendExpr(Step, Ty),
1241 L, AR->getNoWrapFlags());
1245 // If the backedge is guarded by a comparison with the pre-inc value
1246 // the addrec is safe. Also, if the entry is guarded by a comparison
1247 // with the start value and the backedge is guarded by a comparison
1248 // with the post-inc value, the addrec is safe.
1249 ICmpInst::Predicate Pred;
1250 const SCEV *OverflowLimit = getOverflowLimitForStep(Step, &Pred, this);
1251 if (OverflowLimit &&
1252 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1253 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1254 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1256 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1257 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1258 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
1259 getSignExtendExpr(Step, Ty),
1260 L, AR->getNoWrapFlags());
1265 // The cast wasn't folded; create an explicit cast node.
1266 // Recompute the insert position, as it may have been invalidated.
1267 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1268 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1270 UniqueSCEVs.InsertNode(S, IP);
1274 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1275 /// unspecified bits out to the given type.
1277 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1279 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1280 "This is not an extending conversion!");
1281 assert(isSCEVable(Ty) &&
1282 "This is not a conversion to a SCEVable type!");
1283 Ty = getEffectiveSCEVType(Ty);
1285 // Sign-extend negative constants.
1286 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1287 if (SC->getValue()->getValue().isNegative())
1288 return getSignExtendExpr(Op, Ty);
1290 // Peel off a truncate cast.
1291 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
1292 const SCEV *NewOp = T->getOperand();
1293 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1294 return getAnyExtendExpr(NewOp, Ty);
1295 return getTruncateOrNoop(NewOp, Ty);
1298 // Next try a zext cast. If the cast is folded, use it.
1299 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
1300 if (!isa<SCEVZeroExtendExpr>(ZExt))
1303 // Next try a sext cast. If the cast is folded, use it.
1304 const SCEV *SExt = getSignExtendExpr(Op, Ty);
1305 if (!isa<SCEVSignExtendExpr>(SExt))
1308 // Force the cast to be folded into the operands of an addrec.
1309 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1310 SmallVector<const SCEV *, 4> Ops;
1311 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
1313 Ops.push_back(getAnyExtendExpr(*I, Ty));
1314 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
1317 // As a special case, fold anyext(undef) to undef. We don't want to
1318 // know too much about SCEVUnknowns, but this special case is handy
1320 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
1321 if (isa<UndefValue>(U->getValue()))
1322 return getSCEV(UndefValue::get(Ty));
1324 // If the expression is obviously signed, use the sext cast value.
1325 if (isa<SCEVSMaxExpr>(Op))
1328 // Absent any other information, use the zext cast value.
1332 /// CollectAddOperandsWithScales - Process the given Ops list, which is
1333 /// a list of operands to be added under the given scale, update the given
1334 /// map. This is a helper function for getAddRecExpr. As an example of
1335 /// what it does, given a sequence of operands that would form an add
1336 /// expression like this:
1338 /// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1340 /// where A and B are constants, update the map with these values:
1342 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1344 /// and add 13 + A*B*29 to AccumulatedConstant.
1345 /// This will allow getAddRecExpr to produce this:
1347 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1349 /// This form often exposes folding opportunities that are hidden in
1350 /// the original operand list.
1352 /// Return true iff it appears that any interesting folding opportunities
1353 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
1354 /// the common case where no interesting opportunities are present, and
1355 /// is also used as a check to avoid infinite recursion.
1358 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1359 SmallVector<const SCEV *, 8> &NewOps,
1360 APInt &AccumulatedConstant,
1361 const SCEV *const *Ops, size_t NumOperands,
1363 ScalarEvolution &SE) {
1364 bool Interesting = false;
1366 // Iterate over the add operands. They are sorted, with constants first.
1368 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1370 // Pull a buried constant out to the outside.
1371 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1373 AccumulatedConstant += Scale * C->getValue()->getValue();
1376 // Next comes everything else. We're especially interested in multiplies
1377 // here, but they're in the middle, so just visit the rest with one loop.
1378 for (; i != NumOperands; ++i) {
1379 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1380 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1382 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1383 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1384 // A multiplication of a constant with another add; recurse.
1385 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
1387 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1388 Add->op_begin(), Add->getNumOperands(),
1391 // A multiplication of a constant with some other value. Update
1393 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1394 const SCEV *Key = SE.getMulExpr(MulOps);
1395 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1396 M.insert(std::make_pair(Key, NewScale));
1398 NewOps.push_back(Pair.first->first);
1400 Pair.first->second += NewScale;
1401 // The map already had an entry for this value, which may indicate
1402 // a folding opportunity.
1407 // An ordinary operand. Update the map.
1408 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1409 M.insert(std::make_pair(Ops[i], Scale));
1411 NewOps.push_back(Pair.first->first);
1413 Pair.first->second += Scale;
1414 // The map already had an entry for this value, which may indicate
1415 // a folding opportunity.
1425 struct APIntCompare {
1426 bool operator()(const APInt &LHS, const APInt &RHS) const {
1427 return LHS.ult(RHS);
1432 /// getAddExpr - Get a canonical add expression, or something simpler if
1434 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1435 SCEV::NoWrapFlags Flags) {
1436 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
1437 "only nuw or nsw allowed");
1438 assert(!Ops.empty() && "Cannot get empty add!");
1439 if (Ops.size() == 1) return Ops[0];
1441 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
1442 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1443 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
1444 "SCEVAddExpr operand types don't match!");
1447 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
1449 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
1450 SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
1451 if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
1453 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
1454 E = Ops.end(); I != E; ++I)
1455 if (!isKnownNonNegative(*I)) {
1459 if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
1462 // Sort by complexity, this groups all similar expression types together.
1463 GroupByComplexity(Ops, LI);
1465 // If there are any constants, fold them together.
1467 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1469 assert(Idx < Ops.size());
1470 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1471 // We found two constants, fold them together!
1472 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1473 RHSC->getValue()->getValue());
1474 if (Ops.size() == 2) return Ops[0];
1475 Ops.erase(Ops.begin()+1); // Erase the folded element
1476 LHSC = cast<SCEVConstant>(Ops[0]);
1479 // If we are left with a constant zero being added, strip it off.
1480 if (LHSC->getValue()->isZero()) {
1481 Ops.erase(Ops.begin());
1485 if (Ops.size() == 1) return Ops[0];
1488 // Okay, check to see if the same value occurs in the operand list more than
1489 // once. If so, merge them together into an multiply expression. Since we
1490 // sorted the list, these values are required to be adjacent.
1491 Type *Ty = Ops[0]->getType();
1492 bool FoundMatch = false;
1493 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
1494 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1495 // Scan ahead to count how many equal operands there are.
1497 while (i+Count != e && Ops[i+Count] == Ops[i])
1499 // Merge the values into a multiply.
1500 const SCEV *Scale = getConstant(Ty, Count);
1501 const SCEV *Mul = getMulExpr(Scale, Ops[i]);
1502 if (Ops.size() == Count)
1505 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
1506 --i; e -= Count - 1;
1510 return getAddExpr(Ops, Flags);
1512 // Check for truncates. If all the operands are truncated from the same
1513 // type, see if factoring out the truncate would permit the result to be
1514 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1515 // if the contents of the resulting outer trunc fold to something simple.
1516 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1517 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1518 Type *DstType = Trunc->getType();
1519 Type *SrcType = Trunc->getOperand()->getType();
1520 SmallVector<const SCEV *, 8> LargeOps;
1522 // Check all the operands to see if they can be represented in the
1523 // source type of the truncate.
1524 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1525 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1526 if (T->getOperand()->getType() != SrcType) {
1530 LargeOps.push_back(T->getOperand());
1531 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1532 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
1533 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
1534 SmallVector<const SCEV *, 8> LargeMulOps;
1535 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1536 if (const SCEVTruncateExpr *T =
1537 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1538 if (T->getOperand()->getType() != SrcType) {
1542 LargeMulOps.push_back(T->getOperand());
1543 } else if (const SCEVConstant *C =
1544 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1545 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
1552 LargeOps.push_back(getMulExpr(LargeMulOps));
1559 // Evaluate the expression in the larger type.
1560 const SCEV *Fold = getAddExpr(LargeOps, Flags);
1561 // If it folds to something simple, use it. Otherwise, don't.
1562 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1563 return getTruncateExpr(Fold, DstType);
1567 // Skip past any other cast SCEVs.
1568 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1571 // If there are add operands they would be next.
1572 if (Idx < Ops.size()) {
1573 bool DeletedAdd = false;
1574 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
1575 // If we have an add, expand the add operands onto the end of the operands
1577 Ops.erase(Ops.begin()+Idx);
1578 Ops.append(Add->op_begin(), Add->op_end());
1582 // If we deleted at least one add, we added operands to the end of the list,
1583 // and they are not necessarily sorted. Recurse to resort and resimplify
1584 // any operands we just acquired.
1586 return getAddExpr(Ops);
1589 // Skip over the add expression until we get to a multiply.
1590 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1593 // Check to see if there are any folding opportunities present with
1594 // operands multiplied by constant values.
1595 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1596 uint64_t BitWidth = getTypeSizeInBits(Ty);
1597 DenseMap<const SCEV *, APInt> M;
1598 SmallVector<const SCEV *, 8> NewOps;
1599 APInt AccumulatedConstant(BitWidth, 0);
1600 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1601 Ops.data(), Ops.size(),
1602 APInt(BitWidth, 1), *this)) {
1603 // Some interesting folding opportunity is present, so its worthwhile to
1604 // re-generate the operands list. Group the operands by constant scale,
1605 // to avoid multiplying by the same constant scale multiple times.
1606 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1607 for (SmallVector<const SCEV *, 8>::const_iterator I = NewOps.begin(),
1608 E = NewOps.end(); I != E; ++I)
1609 MulOpLists[M.find(*I)->second].push_back(*I);
1610 // Re-generate the operands list.
1612 if (AccumulatedConstant != 0)
1613 Ops.push_back(getConstant(AccumulatedConstant));
1614 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1615 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
1617 Ops.push_back(getMulExpr(getConstant(I->first),
1618 getAddExpr(I->second)));
1620 return getConstant(Ty, 0);
1621 if (Ops.size() == 1)
1623 return getAddExpr(Ops);
1627 // If we are adding something to a multiply expression, make sure the
1628 // something is not already an operand of the multiply. If so, merge it into
1630 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
1631 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
1632 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
1633 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
1634 if (isa<SCEVConstant>(MulOpSCEV))
1636 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
1637 if (MulOpSCEV == Ops[AddOp]) {
1638 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1639 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
1640 if (Mul->getNumOperands() != 2) {
1641 // If the multiply has more than two operands, we must get the
1643 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1644 Mul->op_begin()+MulOp);
1645 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
1646 InnerMul = getMulExpr(MulOps);
1648 const SCEV *One = getConstant(Ty, 1);
1649 const SCEV *AddOne = getAddExpr(One, InnerMul);
1650 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
1651 if (Ops.size() == 2) return OuterMul;
1653 Ops.erase(Ops.begin()+AddOp);
1654 Ops.erase(Ops.begin()+Idx-1);
1656 Ops.erase(Ops.begin()+Idx);
1657 Ops.erase(Ops.begin()+AddOp-1);
1659 Ops.push_back(OuterMul);
1660 return getAddExpr(Ops);
1663 // Check this multiply against other multiplies being added together.
1664 for (unsigned OtherMulIdx = Idx+1;
1665 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1667 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
1668 // If MulOp occurs in OtherMul, we can fold the two multiplies
1670 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1671 OMulOp != e; ++OMulOp)
1672 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1673 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1674 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
1675 if (Mul->getNumOperands() != 2) {
1676 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1677 Mul->op_begin()+MulOp);
1678 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
1679 InnerMul1 = getMulExpr(MulOps);
1681 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1682 if (OtherMul->getNumOperands() != 2) {
1683 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1684 OtherMul->op_begin()+OMulOp);
1685 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
1686 InnerMul2 = getMulExpr(MulOps);
1688 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1689 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
1690 if (Ops.size() == 2) return OuterMul;
1691 Ops.erase(Ops.begin()+Idx);
1692 Ops.erase(Ops.begin()+OtherMulIdx-1);
1693 Ops.push_back(OuterMul);
1694 return getAddExpr(Ops);
1700 // If there are any add recurrences in the operands list, see if any other
1701 // added values are loop invariant. If so, we can fold them into the
1703 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1706 // Scan over all recurrences, trying to fold loop invariants into them.
1707 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1708 // Scan all of the other operands to this add and add them to the vector if
1709 // they are loop invariant w.r.t. the recurrence.
1710 SmallVector<const SCEV *, 8> LIOps;
1711 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1712 const Loop *AddRecLoop = AddRec->getLoop();
1713 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1714 if (isLoopInvariant(Ops[i], AddRecLoop)) {
1715 LIOps.push_back(Ops[i]);
1716 Ops.erase(Ops.begin()+i);
1720 // If we found some loop invariants, fold them into the recurrence.
1721 if (!LIOps.empty()) {
1722 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
1723 LIOps.push_back(AddRec->getStart());
1725 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
1727 AddRecOps[0] = getAddExpr(LIOps);
1729 // Build the new addrec. Propagate the NUW and NSW flags if both the
1730 // outer add and the inner addrec are guaranteed to have no overflow.
1731 // Always propagate NW.
1732 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
1733 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
1735 // If all of the other operands were loop invariant, we are done.
1736 if (Ops.size() == 1) return NewRec;
1738 // Otherwise, add the folded AddRec by the non-liv parts.
1739 for (unsigned i = 0;; ++i)
1740 if (Ops[i] == AddRec) {
1744 return getAddExpr(Ops);
1747 // Okay, if there weren't any loop invariants to be folded, check to see if
1748 // there are multiple AddRec's with the same loop induction variable being
1749 // added together. If so, we can fold them.
1750 for (unsigned OtherIdx = Idx+1;
1751 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1753 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
1754 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
1755 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
1757 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1759 if (const SCEVAddRecExpr *OtherAddRec =
1760 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
1761 if (OtherAddRec->getLoop() == AddRecLoop) {
1762 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
1764 if (i >= AddRecOps.size()) {
1765 AddRecOps.append(OtherAddRec->op_begin()+i,
1766 OtherAddRec->op_end());
1769 AddRecOps[i] = getAddExpr(AddRecOps[i],
1770 OtherAddRec->getOperand(i));
1772 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
1774 // Step size has changed, so we cannot guarantee no self-wraparound.
1775 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
1776 return getAddExpr(Ops);
1779 // Otherwise couldn't fold anything into this recurrence. Move onto the
1783 // Okay, it looks like we really DO need an add expr. Check to see if we
1784 // already have one, otherwise create a new one.
1785 FoldingSetNodeID ID;
1786 ID.AddInteger(scAddExpr);
1787 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1788 ID.AddPointer(Ops[i]);
1791 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1793 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1794 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
1795 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
1797 UniqueSCEVs.InsertNode(S, IP);
1799 S->setNoWrapFlags(Flags);
1803 /// getMulExpr - Get a canonical multiply expression, or something simpler if
1805 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1806 SCEV::NoWrapFlags Flags) {
1807 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
1808 "only nuw or nsw allowed");
1809 assert(!Ops.empty() && "Cannot get empty mul!");
1810 if (Ops.size() == 1) return Ops[0];
1812 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
1813 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1814 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
1815 "SCEVMulExpr operand types don't match!");
1818 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
1820 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
1821 SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
1822 if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
1824 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
1825 E = Ops.end(); I != E; ++I)
1826 if (!isKnownNonNegative(*I)) {
1830 if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
1833 // Sort by complexity, this groups all similar expression types together.
1834 GroupByComplexity(Ops, LI);
1836 // If there are any constants, fold them together.
1838 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1840 // C1*(C2+V) -> C1*C2 + C1*V
1841 if (Ops.size() == 2)
1842 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1843 if (Add->getNumOperands() == 2 &&
1844 isa<SCEVConstant>(Add->getOperand(0)))
1845 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1846 getMulExpr(LHSC, Add->getOperand(1)));
1849 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1850 // We found two constants, fold them together!
1851 ConstantInt *Fold = ConstantInt::get(getContext(),
1852 LHSC->getValue()->getValue() *
1853 RHSC->getValue()->getValue());
1854 Ops[0] = getConstant(Fold);
1855 Ops.erase(Ops.begin()+1); // Erase the folded element
1856 if (Ops.size() == 1) return Ops[0];
1857 LHSC = cast<SCEVConstant>(Ops[0]);
1860 // If we are left with a constant one being multiplied, strip it off.
1861 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1862 Ops.erase(Ops.begin());
1864 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1865 // If we have a multiply of zero, it will always be zero.
1867 } else if (Ops[0]->isAllOnesValue()) {
1868 // If we have a mul by -1 of an add, try distributing the -1 among the
1870 if (Ops.size() == 2) {
1871 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1872 SmallVector<const SCEV *, 4> NewOps;
1873 bool AnyFolded = false;
1874 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(),
1875 E = Add->op_end(); I != E; ++I) {
1876 const SCEV *Mul = getMulExpr(Ops[0], *I);
1877 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1878 NewOps.push_back(Mul);
1881 return getAddExpr(NewOps);
1883 else if (const SCEVAddRecExpr *
1884 AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
1885 // Negation preserves a recurrence's no self-wrap property.
1886 SmallVector<const SCEV *, 4> Operands;
1887 for (SCEVAddRecExpr::op_iterator I = AddRec->op_begin(),
1888 E = AddRec->op_end(); I != E; ++I) {
1889 Operands.push_back(getMulExpr(Ops[0], *I));
1891 return getAddRecExpr(Operands, AddRec->getLoop(),
1892 AddRec->getNoWrapFlags(SCEV::FlagNW));
1897 if (Ops.size() == 1)
1901 // Skip over the add expression until we get to a multiply.
1902 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1905 // If there are mul operands inline them all into this expression.
1906 if (Idx < Ops.size()) {
1907 bool DeletedMul = false;
1908 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1909 // If we have an mul, expand the mul operands onto the end of the operands
1911 Ops.erase(Ops.begin()+Idx);
1912 Ops.append(Mul->op_begin(), Mul->op_end());
1916 // If we deleted at least one mul, we added operands to the end of the list,
1917 // and they are not necessarily sorted. Recurse to resort and resimplify
1918 // any operands we just acquired.
1920 return getMulExpr(Ops);
1923 // If there are any add recurrences in the operands list, see if any other
1924 // added values are loop invariant. If so, we can fold them into the
1926 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1929 // Scan over all recurrences, trying to fold loop invariants into them.
1930 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1931 // Scan all of the other operands to this mul and add them to the vector if
1932 // they are loop invariant w.r.t. the recurrence.
1933 SmallVector<const SCEV *, 8> LIOps;
1934 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1935 const Loop *AddRecLoop = AddRec->getLoop();
1936 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1937 if (isLoopInvariant(Ops[i], AddRecLoop)) {
1938 LIOps.push_back(Ops[i]);
1939 Ops.erase(Ops.begin()+i);
1943 // If we found some loop invariants, fold them into the recurrence.
1944 if (!LIOps.empty()) {
1945 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
1946 SmallVector<const SCEV *, 4> NewOps;
1947 NewOps.reserve(AddRec->getNumOperands());
1948 const SCEV *Scale = getMulExpr(LIOps);
1949 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1950 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1952 // Build the new addrec. Propagate the NUW and NSW flags if both the
1953 // outer mul and the inner addrec are guaranteed to have no overflow.
1955 // No self-wrap cannot be guaranteed after changing the step size, but
1956 // will be inferred if either NUW or NSW is true.
1957 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
1958 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
1960 // If all of the other operands were loop invariant, we are done.
1961 if (Ops.size() == 1) return NewRec;
1963 // Otherwise, multiply the folded AddRec by the non-liv parts.
1964 for (unsigned i = 0;; ++i)
1965 if (Ops[i] == AddRec) {
1969 return getMulExpr(Ops);
1972 // Okay, if there weren't any loop invariants to be folded, check to see if
1973 // there are multiple AddRec's with the same loop induction variable being
1974 // multiplied together. If so, we can fold them.
1975 for (unsigned OtherIdx = Idx+1;
1976 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1978 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
1979 // F * G, where F = {A,+,B}<L> and G = {C,+,D}<L> -->
1980 // {A*C,+,F*D + G*B + B*D}<L>
1981 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1983 if (const SCEVAddRecExpr *OtherAddRec =
1984 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
1985 if (OtherAddRec->getLoop() == AddRecLoop) {
1986 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1987 const SCEV *NewStart = getMulExpr(F->getStart(), G->getStart());
1988 const SCEV *B = F->getStepRecurrence(*this);
1989 const SCEV *D = G->getStepRecurrence(*this);
1990 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
1993 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
1996 if (Ops.size() == 2) return NewAddRec;
1997 Ops[Idx] = AddRec = cast<SCEVAddRecExpr>(NewAddRec);
1998 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2000 return getMulExpr(Ops);
2003 // Otherwise couldn't fold anything into this recurrence. Move onto the
2007 // Okay, it looks like we really DO need an mul expr. Check to see if we
2008 // already have one, otherwise create a new one.
2009 FoldingSetNodeID ID;
2010 ID.AddInteger(scMulExpr);
2011 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2012 ID.AddPointer(Ops[i]);
2015 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2017 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2018 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2019 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2021 UniqueSCEVs.InsertNode(S, IP);
2023 S->setNoWrapFlags(Flags);
2027 /// getUDivExpr - Get a canonical unsigned division expression, or something
2028 /// simpler if possible.
2029 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2031 assert(getEffectiveSCEVType(LHS->getType()) ==
2032 getEffectiveSCEVType(RHS->getType()) &&
2033 "SCEVUDivExpr operand types don't match!");
2035 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
2036 if (RHSC->getValue()->equalsInt(1))
2037 return LHS; // X udiv 1 --> x
2038 // If the denominator is zero, the result of the udiv is undefined. Don't
2039 // try to analyze it, because the resolution chosen here may differ from
2040 // the resolution chosen in other parts of the compiler.
2041 if (!RHSC->getValue()->isZero()) {
2042 // Determine if the division can be folded into the operands of
2044 // TODO: Generalize this to non-constants by using known-bits information.
2045 Type *Ty = LHS->getType();
2046 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
2047 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
2048 // For non-power-of-two values, effectively round the value up to the
2049 // nearest power of two.
2050 if (!RHSC->getValue()->getValue().isPowerOf2())
2052 IntegerType *ExtTy =
2053 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
2054 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2055 if (const SCEVConstant *Step =
2056 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2057 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
2058 const APInt &StepInt = Step->getValue()->getValue();
2059 const APInt &DivInt = RHSC->getValue()->getValue();
2060 if (!StepInt.urem(DivInt) &&
2061 getZeroExtendExpr(AR, ExtTy) ==
2062 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2063 getZeroExtendExpr(Step, ExtTy),
2064 AR->getLoop(), SCEV::FlagAnyWrap)) {
2065 SmallVector<const SCEV *, 4> Operands;
2066 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
2067 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
2068 return getAddRecExpr(Operands, AR->getLoop(),
2071 /// Get a canonical UDivExpr for a recurrence.
2072 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2073 // We can currently only fold X%N if X is constant.
2074 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2075 if (StartC && !DivInt.urem(StepInt) &&
2076 getZeroExtendExpr(AR, ExtTy) ==
2077 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2078 getZeroExtendExpr(Step, ExtTy),
2079 AR->getLoop(), SCEV::FlagAnyWrap)) {
2080 const APInt &StartInt = StartC->getValue()->getValue();
2081 const APInt &StartRem = StartInt.urem(StepInt);
2083 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2084 AR->getLoop(), SCEV::FlagNW);
2087 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2088 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2089 SmallVector<const SCEV *, 4> Operands;
2090 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
2091 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
2092 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2093 // Find an operand that's safely divisible.
2094 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2095 const SCEV *Op = M->getOperand(i);
2096 const SCEV *Div = getUDivExpr(Op, RHSC);
2097 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2098 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2101 return getMulExpr(Operands);
2105 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
2106 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
2107 SmallVector<const SCEV *, 4> Operands;
2108 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
2109 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
2110 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2112 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2113 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2114 if (isa<SCEVUDivExpr>(Op) ||
2115 getMulExpr(Op, RHS) != A->getOperand(i))
2117 Operands.push_back(Op);
2119 if (Operands.size() == A->getNumOperands())
2120 return getAddExpr(Operands);
2124 // Fold if both operands are constant.
2125 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2126 Constant *LHSCV = LHSC->getValue();
2127 Constant *RHSCV = RHSC->getValue();
2128 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2134 FoldingSetNodeID ID;
2135 ID.AddInteger(scUDivExpr);
2139 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2140 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2142 UniqueSCEVs.InsertNode(S, IP);
2147 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
2148 /// Simplify the expression as much as possible.
2149 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
2151 SCEV::NoWrapFlags Flags) {
2152 SmallVector<const SCEV *, 4> Operands;
2153 Operands.push_back(Start);
2154 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
2155 if (StepChrec->getLoop() == L) {
2156 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
2157 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
2160 Operands.push_back(Step);
2161 return getAddRecExpr(Operands, L, Flags);
2164 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
2165 /// Simplify the expression as much as possible.
2167 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
2168 const Loop *L, SCEV::NoWrapFlags Flags) {
2169 if (Operands.size() == 1) return Operands[0];
2171 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
2172 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
2173 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
2174 "SCEVAddRecExpr operand types don't match!");
2175 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2176 assert(isLoopInvariant(Operands[i], L) &&
2177 "SCEVAddRecExpr operand is not loop-invariant!");
2180 if (Operands.back()->isZero()) {
2181 Operands.pop_back();
2182 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
2185 // It's tempting to want to call getMaxBackedgeTakenCount count here and
2186 // use that information to infer NUW and NSW flags. However, computing a
2187 // BE count requires calling getAddRecExpr, so we may not yet have a
2188 // meaningful BE count at this point (and if we don't, we'd be stuck
2189 // with a SCEVCouldNotCompute as the cached BE count).
2191 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2193 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2194 SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
2195 if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
2197 for (SmallVectorImpl<const SCEV *>::const_iterator I = Operands.begin(),
2198 E = Operands.end(); I != E; ++I)
2199 if (!isKnownNonNegative(*I)) {
2203 if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2206 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
2207 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
2208 const Loop *NestedLoop = NestedAR->getLoop();
2209 if (L->contains(NestedLoop) ?
2210 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
2211 (!NestedLoop->contains(L) &&
2212 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
2213 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
2214 NestedAR->op_end());
2215 Operands[0] = NestedAR->getStart();
2216 // AddRecs require their operands be loop-invariant with respect to their
2217 // loops. Don't perform this transformation if it would break this
2219 bool AllInvariant = true;
2220 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2221 if (!isLoopInvariant(Operands[i], L)) {
2222 AllInvariant = false;
2226 // Create a recurrence for the outer loop with the same step size.
2228 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
2229 // inner recurrence has the same property.
2230 SCEV::NoWrapFlags OuterFlags =
2231 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
2233 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
2234 AllInvariant = true;
2235 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
2236 if (!isLoopInvariant(NestedOperands[i], NestedLoop)) {
2237 AllInvariant = false;
2241 // Ok, both add recurrences are valid after the transformation.
2243 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
2244 // the outer recurrence has the same property.
2245 SCEV::NoWrapFlags InnerFlags =
2246 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
2247 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
2250 // Reset Operands to its original state.
2251 Operands[0] = NestedAR;
2255 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2256 // already have one, otherwise create a new one.
2257 FoldingSetNodeID ID;
2258 ID.AddInteger(scAddRecExpr);
2259 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2260 ID.AddPointer(Operands[i]);
2264 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2266 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2267 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
2268 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2269 O, Operands.size(), L);
2270 UniqueSCEVs.InsertNode(S, IP);
2272 S->setNoWrapFlags(Flags);
2276 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2278 SmallVector<const SCEV *, 2> Ops;
2281 return getSMaxExpr(Ops);
2285 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2286 assert(!Ops.empty() && "Cannot get empty smax!");
2287 if (Ops.size() == 1) return Ops[0];
2289 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2290 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2291 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2292 "SCEVSMaxExpr operand types don't match!");
2295 // Sort by complexity, this groups all similar expression types together.
2296 GroupByComplexity(Ops, LI);
2298 // If there are any constants, fold them together.
2300 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2302 assert(Idx < Ops.size());
2303 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2304 // We found two constants, fold them together!
2305 ConstantInt *Fold = ConstantInt::get(getContext(),
2306 APIntOps::smax(LHSC->getValue()->getValue(),
2307 RHSC->getValue()->getValue()));
2308 Ops[0] = getConstant(Fold);
2309 Ops.erase(Ops.begin()+1); // Erase the folded element
2310 if (Ops.size() == 1) return Ops[0];
2311 LHSC = cast<SCEVConstant>(Ops[0]);
2314 // If we are left with a constant minimum-int, strip it off.
2315 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2316 Ops.erase(Ops.begin());
2318 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2319 // If we have an smax with a constant maximum-int, it will always be
2324 if (Ops.size() == 1) return Ops[0];
2327 // Find the first SMax
2328 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2331 // Check to see if one of the operands is an SMax. If so, expand its operands
2332 // onto our operand list, and recurse to simplify.
2333 if (Idx < Ops.size()) {
2334 bool DeletedSMax = false;
2335 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
2336 Ops.erase(Ops.begin()+Idx);
2337 Ops.append(SMax->op_begin(), SMax->op_end());
2342 return getSMaxExpr(Ops);
2345 // Okay, check to see if the same value occurs in the operand list twice. If
2346 // so, delete one. Since we sorted the list, these values are required to
2348 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2349 // X smax Y smax Y --> X smax Y
2350 // X smax Y --> X, if X is always greater than Y
2351 if (Ops[i] == Ops[i+1] ||
2352 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
2353 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2355 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
2356 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2360 if (Ops.size() == 1) return Ops[0];
2362 assert(!Ops.empty() && "Reduced smax down to nothing!");
2364 // Okay, it looks like we really DO need an smax expr. Check to see if we
2365 // already have one, otherwise create a new one.
2366 FoldingSetNodeID ID;
2367 ID.AddInteger(scSMaxExpr);
2368 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2369 ID.AddPointer(Ops[i]);
2371 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2372 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2373 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2374 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
2376 UniqueSCEVs.InsertNode(S, IP);
2380 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2382 SmallVector<const SCEV *, 2> Ops;
2385 return getUMaxExpr(Ops);
2389 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2390 assert(!Ops.empty() && "Cannot get empty umax!");
2391 if (Ops.size() == 1) return Ops[0];
2393 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2394 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2395 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2396 "SCEVUMaxExpr operand types don't match!");
2399 // Sort by complexity, this groups all similar expression types together.
2400 GroupByComplexity(Ops, LI);
2402 // If there are any constants, fold them together.
2404 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2406 assert(Idx < Ops.size());
2407 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2408 // We found two constants, fold them together!
2409 ConstantInt *Fold = ConstantInt::get(getContext(),
2410 APIntOps::umax(LHSC->getValue()->getValue(),
2411 RHSC->getValue()->getValue()));
2412 Ops[0] = getConstant(Fold);
2413 Ops.erase(Ops.begin()+1); // Erase the folded element
2414 if (Ops.size() == 1) return Ops[0];
2415 LHSC = cast<SCEVConstant>(Ops[0]);
2418 // If we are left with a constant minimum-int, strip it off.
2419 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2420 Ops.erase(Ops.begin());
2422 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2423 // If we have an umax with a constant maximum-int, it will always be
2428 if (Ops.size() == 1) return Ops[0];
2431 // Find the first UMax
2432 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2435 // Check to see if one of the operands is a UMax. If so, expand its operands
2436 // onto our operand list, and recurse to simplify.
2437 if (Idx < Ops.size()) {
2438 bool DeletedUMax = false;
2439 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
2440 Ops.erase(Ops.begin()+Idx);
2441 Ops.append(UMax->op_begin(), UMax->op_end());
2446 return getUMaxExpr(Ops);
2449 // Okay, check to see if the same value occurs in the operand list twice. If
2450 // so, delete one. Since we sorted the list, these values are required to
2452 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2453 // X umax Y umax Y --> X umax Y
2454 // X umax Y --> X, if X is always greater than Y
2455 if (Ops[i] == Ops[i+1] ||
2456 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
2457 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2459 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
2460 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2464 if (Ops.size() == 1) return Ops[0];
2466 assert(!Ops.empty() && "Reduced umax down to nothing!");
2468 // Okay, it looks like we really DO need a umax expr. Check to see if we
2469 // already have one, otherwise create a new one.
2470 FoldingSetNodeID ID;
2471 ID.AddInteger(scUMaxExpr);
2472 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2473 ID.AddPointer(Ops[i]);
2475 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2476 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2477 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2478 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
2480 UniqueSCEVs.InsertNode(S, IP);
2484 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2486 // ~smax(~x, ~y) == smin(x, y).
2487 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2490 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2492 // ~umax(~x, ~y) == umin(x, y)
2493 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2496 const SCEV *ScalarEvolution::getSizeOfExpr(Type *AllocTy) {
2497 // If we have TargetData, we can bypass creating a target-independent
2498 // constant expression and then folding it back into a ConstantInt.
2499 // This is just a compile-time optimization.
2501 return getConstant(TD->getIntPtrType(getContext()),
2502 TD->getTypeAllocSize(AllocTy));
2504 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2505 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2506 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2508 Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2509 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2512 const SCEV *ScalarEvolution::getAlignOfExpr(Type *AllocTy) {
2513 Constant *C = ConstantExpr::getAlignOf(AllocTy);
2514 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2515 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2517 Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2518 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2521 const SCEV *ScalarEvolution::getOffsetOfExpr(StructType *STy,
2523 // If we have TargetData, we can bypass creating a target-independent
2524 // constant expression and then folding it back into a ConstantInt.
2525 // This is just a compile-time optimization.
2527 return getConstant(TD->getIntPtrType(getContext()),
2528 TD->getStructLayout(STy)->getElementOffset(FieldNo));
2530 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2531 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2532 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2534 Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
2535 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2538 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *CTy,
2539 Constant *FieldNo) {
2540 Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
2541 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2542 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2544 Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
2545 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2548 const SCEV *ScalarEvolution::getUnknown(Value *V) {
2549 // Don't attempt to do anything other than create a SCEVUnknown object
2550 // here. createSCEV only calls getUnknown after checking for all other
2551 // interesting possibilities, and any other code that calls getUnknown
2552 // is doing so in order to hide a value from SCEV canonicalization.
2554 FoldingSetNodeID ID;
2555 ID.AddInteger(scUnknown);
2558 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
2559 assert(cast<SCEVUnknown>(S)->getValue() == V &&
2560 "Stale SCEVUnknown in uniquing map!");
2563 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
2565 FirstUnknown = cast<SCEVUnknown>(S);
2566 UniqueSCEVs.InsertNode(S, IP);
2570 //===----------------------------------------------------------------------===//
2571 // Basic SCEV Analysis and PHI Idiom Recognition Code
2574 /// isSCEVable - Test if values of the given type are analyzable within
2575 /// the SCEV framework. This primarily includes integer types, and it
2576 /// can optionally include pointer types if the ScalarEvolution class
2577 /// has access to target-specific information.
2578 bool ScalarEvolution::isSCEVable(Type *Ty) const {
2579 // Integers and pointers are always SCEVable.
2580 return Ty->isIntegerTy() || Ty->isPointerTy();
2583 /// getTypeSizeInBits - Return the size in bits of the specified type,
2584 /// for which isSCEVable must return true.
2585 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
2586 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2588 // If we have a TargetData, use it!
2590 return TD->getTypeSizeInBits(Ty);
2592 // Integer types have fixed sizes.
2593 if (Ty->isIntegerTy())
2594 return Ty->getPrimitiveSizeInBits();
2596 // The only other support type is pointer. Without TargetData, conservatively
2597 // assume pointers are 64-bit.
2598 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
2602 /// getEffectiveSCEVType - Return a type with the same bitwidth as
2603 /// the given type and which represents how SCEV will treat the given
2604 /// type, for which isSCEVable must return true. For pointer types,
2605 /// this is the pointer-sized integer type.
2606 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
2607 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2609 if (Ty->isIntegerTy())
2612 // The only other support type is pointer.
2613 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
2614 if (TD) return TD->getIntPtrType(getContext());
2616 // Without TargetData, conservatively assume pointers are 64-bit.
2617 return Type::getInt64Ty(getContext());
2620 const SCEV *ScalarEvolution::getCouldNotCompute() {
2621 return &CouldNotCompute;
2624 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2625 /// expression and create a new one.
2626 const SCEV *ScalarEvolution::getSCEV(Value *V) {
2627 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
2629 ValueExprMapType::const_iterator I = ValueExprMap.find(V);
2630 if (I != ValueExprMap.end()) return I->second;
2631 const SCEV *S = createSCEV(V);
2633 // The process of creating a SCEV for V may have caused other SCEVs
2634 // to have been created, so it's necessary to insert the new entry
2635 // from scratch, rather than trying to remember the insert position
2637 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(V, this), S));
2641 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2643 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
2644 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2646 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
2648 Type *Ty = V->getType();
2649 Ty = getEffectiveSCEVType(Ty);
2650 return getMulExpr(V,
2651 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
2654 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
2655 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
2656 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2658 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
2660 Type *Ty = V->getType();
2661 Ty = getEffectiveSCEVType(Ty);
2662 const SCEV *AllOnes =
2663 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
2664 return getMinusSCEV(AllOnes, V);
2667 /// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
2668 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
2669 SCEV::NoWrapFlags Flags) {
2670 assert(!maskFlags(Flags, SCEV::FlagNUW) && "subtraction does not have NUW");
2672 // Fast path: X - X --> 0.
2674 return getConstant(LHS->getType(), 0);
2677 return getAddExpr(LHS, getNegativeSCEV(RHS), Flags);
2680 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2681 /// input value to the specified type. If the type must be extended, it is zero
2684 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
2685 Type *SrcTy = V->getType();
2686 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2687 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2688 "Cannot truncate or zero extend with non-integer arguments!");
2689 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2690 return V; // No conversion
2691 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2692 return getTruncateExpr(V, Ty);
2693 return getZeroExtendExpr(V, Ty);
2696 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2697 /// input value to the specified type. If the type must be extended, it is sign
2700 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
2702 Type *SrcTy = V->getType();
2703 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2704 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2705 "Cannot truncate or zero extend with non-integer arguments!");
2706 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2707 return V; // No conversion
2708 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2709 return getTruncateExpr(V, Ty);
2710 return getSignExtendExpr(V, Ty);
2713 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2714 /// input value to the specified type. If the type must be extended, it is zero
2715 /// extended. The conversion must not be narrowing.
2717 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
2718 Type *SrcTy = V->getType();
2719 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2720 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2721 "Cannot noop or zero extend with non-integer arguments!");
2722 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2723 "getNoopOrZeroExtend cannot truncate!");
2724 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2725 return V; // No conversion
2726 return getZeroExtendExpr(V, Ty);
2729 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2730 /// input value to the specified type. If the type must be extended, it is sign
2731 /// extended. The conversion must not be narrowing.
2733 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
2734 Type *SrcTy = V->getType();
2735 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2736 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2737 "Cannot noop or sign extend with non-integer arguments!");
2738 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2739 "getNoopOrSignExtend cannot truncate!");
2740 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2741 return V; // No conversion
2742 return getSignExtendExpr(V, Ty);
2745 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2746 /// the input value to the specified type. If the type must be extended,
2747 /// it is extended with unspecified bits. The conversion must not be
2750 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
2751 Type *SrcTy = V->getType();
2752 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2753 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2754 "Cannot noop or any extend with non-integer arguments!");
2755 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2756 "getNoopOrAnyExtend cannot truncate!");
2757 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2758 return V; // No conversion
2759 return getAnyExtendExpr(V, Ty);
2762 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2763 /// input value to the specified type. The conversion must not be widening.
2765 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
2766 Type *SrcTy = V->getType();
2767 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2768 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2769 "Cannot truncate or noop with non-integer arguments!");
2770 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2771 "getTruncateOrNoop cannot extend!");
2772 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2773 return V; // No conversion
2774 return getTruncateExpr(V, Ty);
2777 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2778 /// the types using zero-extension, and then perform a umax operation
2780 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2782 const SCEV *PromotedLHS = LHS;
2783 const SCEV *PromotedRHS = RHS;
2785 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2786 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2788 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2790 return getUMaxExpr(PromotedLHS, PromotedRHS);
2793 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
2794 /// the types using zero-extension, and then perform a umin operation
2796 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2798 const SCEV *PromotedLHS = LHS;
2799 const SCEV *PromotedRHS = RHS;
2801 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2802 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2804 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2806 return getUMinExpr(PromotedLHS, PromotedRHS);
2809 /// getPointerBase - Transitively follow the chain of pointer-type operands
2810 /// until reaching a SCEV that does not have a single pointer operand. This
2811 /// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
2812 /// but corner cases do exist.
2813 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
2814 // A pointer operand may evaluate to a nonpointer expression, such as null.
2815 if (!V->getType()->isPointerTy())
2818 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
2819 return getPointerBase(Cast->getOperand());
2821 else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
2822 const SCEV *PtrOp = 0;
2823 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
2825 if ((*I)->getType()->isPointerTy()) {
2826 // Cannot find the base of an expression with multiple pointer operands.
2834 return getPointerBase(PtrOp);
2839 /// PushDefUseChildren - Push users of the given Instruction
2840 /// onto the given Worklist.
2842 PushDefUseChildren(Instruction *I,
2843 SmallVectorImpl<Instruction *> &Worklist) {
2844 // Push the def-use children onto the Worklist stack.
2845 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2847 Worklist.push_back(cast<Instruction>(*UI));
2850 /// ForgetSymbolicValue - This looks up computed SCEV values for all
2851 /// instructions that depend on the given instruction and removes them from
2852 /// the ValueExprMapType map if they reference SymName. This is used during PHI
2855 ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
2856 SmallVector<Instruction *, 16> Worklist;
2857 PushDefUseChildren(PN, Worklist);
2859 SmallPtrSet<Instruction *, 8> Visited;
2861 while (!Worklist.empty()) {
2862 Instruction *I = Worklist.pop_back_val();
2863 if (!Visited.insert(I)) continue;
2865 ValueExprMapType::iterator It =
2866 ValueExprMap.find(static_cast<Value *>(I));
2867 if (It != ValueExprMap.end()) {
2868 const SCEV *Old = It->second;
2870 // Short-circuit the def-use traversal if the symbolic name
2871 // ceases to appear in expressions.
2872 if (Old != SymName && !hasOperand(Old, SymName))
2875 // SCEVUnknown for a PHI either means that it has an unrecognized
2876 // structure, it's a PHI that's in the progress of being computed
2877 // by createNodeForPHI, or it's a single-value PHI. In the first case,
2878 // additional loop trip count information isn't going to change anything.
2879 // In the second case, createNodeForPHI will perform the necessary
2880 // updates on its own when it gets to that point. In the third, we do
2881 // want to forget the SCEVUnknown.
2882 if (!isa<PHINode>(I) ||
2883 !isa<SCEVUnknown>(Old) ||
2884 (I != PN && Old == SymName)) {
2885 forgetMemoizedResults(Old);
2886 ValueExprMap.erase(It);
2890 PushDefUseChildren(I, Worklist);
2894 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2895 /// a loop header, making it a potential recurrence, or it doesn't.
2897 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
2898 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2899 if (L->getHeader() == PN->getParent()) {
2900 // The loop may have multiple entrances or multiple exits; we can analyze
2901 // this phi as an addrec if it has a unique entry value and a unique
2903 Value *BEValueV = 0, *StartValueV = 0;
2904 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2905 Value *V = PN->getIncomingValue(i);
2906 if (L->contains(PN->getIncomingBlock(i))) {
2909 } else if (BEValueV != V) {
2913 } else if (!StartValueV) {
2915 } else if (StartValueV != V) {
2920 if (BEValueV && StartValueV) {
2921 // While we are analyzing this PHI node, handle its value symbolically.
2922 const SCEV *SymbolicName = getUnknown(PN);
2923 assert(ValueExprMap.find(PN) == ValueExprMap.end() &&
2924 "PHI node already processed?");
2925 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
2927 // Using this symbolic name for the PHI, analyze the value coming around
2929 const SCEV *BEValue = getSCEV(BEValueV);
2931 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2932 // has a special value for the first iteration of the loop.
2934 // If the value coming around the backedge is an add with the symbolic
2935 // value we just inserted, then we found a simple induction variable!
2936 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
2937 // If there is a single occurrence of the symbolic value, replace it
2938 // with a recurrence.
2939 unsigned FoundIndex = Add->getNumOperands();
2940 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2941 if (Add->getOperand(i) == SymbolicName)
2942 if (FoundIndex == e) {
2947 if (FoundIndex != Add->getNumOperands()) {
2948 // Create an add with everything but the specified operand.
2949 SmallVector<const SCEV *, 8> Ops;
2950 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2951 if (i != FoundIndex)
2952 Ops.push_back(Add->getOperand(i));
2953 const SCEV *Accum = getAddExpr(Ops);
2955 // This is not a valid addrec if the step amount is varying each
2956 // loop iteration, but is not itself an addrec in this loop.
2957 if (isLoopInvariant(Accum, L) ||
2958 (isa<SCEVAddRecExpr>(Accum) &&
2959 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
2960 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
2962 // If the increment doesn't overflow, then neither the addrec nor
2963 // the post-increment will overflow.
2964 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
2965 if (OBO->hasNoUnsignedWrap())
2966 Flags = setFlags(Flags, SCEV::FlagNUW);
2967 if (OBO->hasNoSignedWrap())
2968 Flags = setFlags(Flags, SCEV::FlagNSW);
2969 } else if (const GEPOperator *GEP =
2970 dyn_cast<GEPOperator>(BEValueV)) {
2971 // If the increment is an inbounds GEP, then we know the address
2972 // space cannot be wrapped around. We cannot make any guarantee
2973 // about signed or unsigned overflow because pointers are
2974 // unsigned but we may have a negative index from the base
2976 if (GEP->isInBounds())
2977 Flags = setFlags(Flags, SCEV::FlagNW);
2980 const SCEV *StartVal = getSCEV(StartValueV);
2981 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
2983 // Since the no-wrap flags are on the increment, they apply to the
2984 // post-incremented value as well.
2985 if (isLoopInvariant(Accum, L))
2986 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
2989 // Okay, for the entire analysis of this edge we assumed the PHI
2990 // to be symbolic. We now need to go back and purge all of the
2991 // entries for the scalars that use the symbolic expression.
2992 ForgetSymbolicName(PN, SymbolicName);
2993 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
2997 } else if (const SCEVAddRecExpr *AddRec =
2998 dyn_cast<SCEVAddRecExpr>(BEValue)) {
2999 // Otherwise, this could be a loop like this:
3000 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
3001 // In this case, j = {1,+,1} and BEValue is j.
3002 // Because the other in-value of i (0) fits the evolution of BEValue
3003 // i really is an addrec evolution.
3004 if (AddRec->getLoop() == L && AddRec->isAffine()) {
3005 const SCEV *StartVal = getSCEV(StartValueV);
3007 // If StartVal = j.start - j.stride, we can use StartVal as the
3008 // initial step of the addrec evolution.
3009 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
3010 AddRec->getOperand(1))) {
3011 // FIXME: For constant StartVal, we should be able to infer
3013 const SCEV *PHISCEV =
3014 getAddRecExpr(StartVal, AddRec->getOperand(1), L,
3017 // Okay, for the entire analysis of this edge we assumed the PHI
3018 // to be symbolic. We now need to go back and purge all of the
3019 // entries for the scalars that use the symbolic expression.
3020 ForgetSymbolicName(PN, SymbolicName);
3021 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
3029 // If the PHI has a single incoming value, follow that value, unless the
3030 // PHI's incoming blocks are in a different loop, in which case doing so
3031 // risks breaking LCSSA form. Instcombine would normally zap these, but
3032 // it doesn't have DominatorTree information, so it may miss cases.
3033 if (Value *V = SimplifyInstruction(PN, TD, DT))
3034 if (LI->replacementPreservesLCSSAForm(PN, V))
3037 // If it's not a loop phi, we can't handle it yet.
3038 return getUnknown(PN);
3041 /// createNodeForGEP - Expand GEP instructions into add and multiply
3042 /// operations. This allows them to be analyzed by regular SCEV code.
3044 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
3046 // Don't blindly transfer the inbounds flag from the GEP instruction to the
3047 // Add expression, because the Instruction may be guarded by control flow
3048 // and the no-overflow bits may not be valid for the expression in any
3050 bool isInBounds = GEP->isInBounds();
3052 Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
3053 Value *Base = GEP->getOperand(0);
3054 // Don't attempt to analyze GEPs over unsized objects.
3055 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
3056 return getUnknown(GEP);
3057 const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
3058 gep_type_iterator GTI = gep_type_begin(GEP);
3059 for (GetElementPtrInst::op_iterator I = llvm::next(GEP->op_begin()),
3063 // Compute the (potentially symbolic) offset in bytes for this index.
3064 if (StructType *STy = dyn_cast<StructType>(*GTI++)) {
3065 // For a struct, add the member offset.
3066 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
3067 const SCEV *FieldOffset = getOffsetOfExpr(STy, FieldNo);
3069 // Add the field offset to the running total offset.
3070 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3072 // For an array, add the element offset, explicitly scaled.
3073 const SCEV *ElementSize = getSizeOfExpr(*GTI);
3074 const SCEV *IndexS = getSCEV(Index);
3075 // Getelementptr indices are signed.
3076 IndexS = getTruncateOrSignExtend(IndexS, IntPtrTy);
3078 // Multiply the index by the element size to compute the element offset.
3079 const SCEV *LocalOffset = getMulExpr(IndexS, ElementSize,
3080 isInBounds ? SCEV::FlagNSW :
3083 // Add the element offset to the running total offset.
3084 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3088 // Get the SCEV for the GEP base.
3089 const SCEV *BaseS = getSCEV(Base);
3091 // Add the total offset from all the GEP indices to the base.
3092 return getAddExpr(BaseS, TotalOffset,
3093 isInBounds ? SCEV::FlagNSW : SCEV::FlagAnyWrap);
3096 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
3097 /// guaranteed to end in (at every loop iteration). It is, at the same time,
3098 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
3099 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
3101 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
3102 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
3103 return C->getValue()->getValue().countTrailingZeros();
3105 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
3106 return std::min(GetMinTrailingZeros(T->getOperand()),
3107 (uint32_t)getTypeSizeInBits(T->getType()));
3109 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
3110 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
3111 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
3112 getTypeSizeInBits(E->getType()) : OpRes;
3115 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
3116 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
3117 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
3118 getTypeSizeInBits(E->getType()) : OpRes;
3121 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
3122 // The result is the min of all operands results.
3123 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
3124 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
3125 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
3129 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
3130 // The result is the sum of all operands results.
3131 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
3132 uint32_t BitWidth = getTypeSizeInBits(M->getType());
3133 for (unsigned i = 1, e = M->getNumOperands();
3134 SumOpRes != BitWidth && i != e; ++i)
3135 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
3140 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
3141 // The result is the min of all operands results.
3142 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
3143 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
3144 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
3148 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
3149 // The result is the min of all operands results.
3150 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
3151 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
3152 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
3156 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
3157 // The result is the min of all operands results.
3158 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
3159 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
3160 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
3164 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3165 // For a SCEVUnknown, ask ValueTracking.
3166 unsigned BitWidth = getTypeSizeInBits(U->getType());
3167 APInt Mask = APInt::getAllOnesValue(BitWidth);
3168 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3169 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
3170 return Zeros.countTrailingOnes();
3177 /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
3180 ScalarEvolution::getUnsignedRange(const SCEV *S) {
3181 // See if we've computed this range already.
3182 DenseMap<const SCEV *, ConstantRange>::iterator I = UnsignedRanges.find(S);
3183 if (I != UnsignedRanges.end())
3186 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
3187 return setUnsignedRange(C, ConstantRange(C->getValue()->getValue()));
3189 unsigned BitWidth = getTypeSizeInBits(S->getType());
3190 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3192 // If the value has known zeros, the maximum unsigned value will have those
3193 // known zeros as well.
3194 uint32_t TZ = GetMinTrailingZeros(S);
3196 ConservativeResult =
3197 ConstantRange(APInt::getMinValue(BitWidth),
3198 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
3200 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3201 ConstantRange X = getUnsignedRange(Add->getOperand(0));
3202 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3203 X = X.add(getUnsignedRange(Add->getOperand(i)));
3204 return setUnsignedRange(Add, ConservativeResult.intersectWith(X));
3207 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3208 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
3209 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3210 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
3211 return setUnsignedRange(Mul, ConservativeResult.intersectWith(X));
3214 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3215 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
3216 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3217 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
3218 return setUnsignedRange(SMax, ConservativeResult.intersectWith(X));
3221 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3222 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
3223 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3224 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
3225 return setUnsignedRange(UMax, ConservativeResult.intersectWith(X));
3228 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3229 ConstantRange X = getUnsignedRange(UDiv->getLHS());
3230 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
3231 return setUnsignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
3234 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3235 ConstantRange X = getUnsignedRange(ZExt->getOperand());
3236 return setUnsignedRange(ZExt,
3237 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
3240 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3241 ConstantRange X = getUnsignedRange(SExt->getOperand());
3242 return setUnsignedRange(SExt,
3243 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
3246 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3247 ConstantRange X = getUnsignedRange(Trunc->getOperand());
3248 return setUnsignedRange(Trunc,
3249 ConservativeResult.intersectWith(X.truncate(BitWidth)));
3252 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
3253 // If there's no unsigned wrap, the value will never be less than its
3255 if (AddRec->getNoWrapFlags(SCEV::FlagNUW))
3256 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
3257 if (!C->getValue()->isZero())
3258 ConservativeResult =
3259 ConservativeResult.intersectWith(
3260 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0)));
3262 // TODO: non-affine addrec
3263 if (AddRec->isAffine()) {
3264 Type *Ty = AddRec->getType();
3265 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
3266 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3267 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
3268 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3270 const SCEV *Start = AddRec->getStart();
3271 const SCEV *Step = AddRec->getStepRecurrence(*this);
3273 ConstantRange StartRange = getUnsignedRange(Start);
3274 ConstantRange StepRange = getSignedRange(Step);
3275 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3276 ConstantRange EndRange =
3277 StartRange.add(MaxBECountRange.multiply(StepRange));
3279 // Check for overflow. This must be done with ConstantRange arithmetic
3280 // because we could be called from within the ScalarEvolution overflow
3282 ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
3283 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3284 ConstantRange ExtMaxBECountRange =
3285 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3286 ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
3287 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3289 return setUnsignedRange(AddRec, ConservativeResult);
3291 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
3292 EndRange.getUnsignedMin());
3293 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
3294 EndRange.getUnsignedMax());
3295 if (Min.isMinValue() && Max.isMaxValue())
3296 return setUnsignedRange(AddRec, ConservativeResult);
3297 return setUnsignedRange(AddRec,
3298 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
3302 return setUnsignedRange(AddRec, ConservativeResult);
3305 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3306 // For a SCEVUnknown, ask ValueTracking.
3307 APInt Mask = APInt::getAllOnesValue(BitWidth);
3308 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3309 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
3310 if (Ones == ~Zeros + 1)
3311 return setUnsignedRange(U, ConservativeResult);
3312 return setUnsignedRange(U,
3313 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)));
3316 return setUnsignedRange(S, ConservativeResult);
3319 /// getSignedRange - Determine the signed range for a particular SCEV.
3322 ScalarEvolution::getSignedRange(const SCEV *S) {
3323 // See if we've computed this range already.
3324 DenseMap<const SCEV *, ConstantRange>::iterator I = SignedRanges.find(S);
3325 if (I != SignedRanges.end())
3328 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
3329 return setSignedRange(C, ConstantRange(C->getValue()->getValue()));
3331 unsigned BitWidth = getTypeSizeInBits(S->getType());
3332 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3334 // If the value has known zeros, the maximum signed value will have those
3335 // known zeros as well.
3336 uint32_t TZ = GetMinTrailingZeros(S);
3338 ConservativeResult =
3339 ConstantRange(APInt::getSignedMinValue(BitWidth),
3340 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
3342 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3343 ConstantRange X = getSignedRange(Add->getOperand(0));
3344 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3345 X = X.add(getSignedRange(Add->getOperand(i)));
3346 return setSignedRange(Add, ConservativeResult.intersectWith(X));
3349 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3350 ConstantRange X = getSignedRange(Mul->getOperand(0));
3351 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3352 X = X.multiply(getSignedRange(Mul->getOperand(i)));
3353 return setSignedRange(Mul, ConservativeResult.intersectWith(X));
3356 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3357 ConstantRange X = getSignedRange(SMax->getOperand(0));
3358 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3359 X = X.smax(getSignedRange(SMax->getOperand(i)));
3360 return setSignedRange(SMax, ConservativeResult.intersectWith(X));
3363 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3364 ConstantRange X = getSignedRange(UMax->getOperand(0));
3365 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3366 X = X.umax(getSignedRange(UMax->getOperand(i)));
3367 return setSignedRange(UMax, ConservativeResult.intersectWith(X));
3370 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3371 ConstantRange X = getSignedRange(UDiv->getLHS());
3372 ConstantRange Y = getSignedRange(UDiv->getRHS());
3373 return setSignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
3376 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3377 ConstantRange X = getSignedRange(ZExt->getOperand());
3378 return setSignedRange(ZExt,
3379 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
3382 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3383 ConstantRange X = getSignedRange(SExt->getOperand());
3384 return setSignedRange(SExt,
3385 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
3388 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3389 ConstantRange X = getSignedRange(Trunc->getOperand());
3390 return setSignedRange(Trunc,
3391 ConservativeResult.intersectWith(X.truncate(BitWidth)));
3394 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
3395 // If there's no signed wrap, and all the operands have the same sign or
3396 // zero, the value won't ever change sign.
3397 if (AddRec->getNoWrapFlags(SCEV::FlagNSW)) {
3398 bool AllNonNeg = true;
3399 bool AllNonPos = true;
3400 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3401 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3402 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3405 ConservativeResult = ConservativeResult.intersectWith(
3406 ConstantRange(APInt(BitWidth, 0),
3407 APInt::getSignedMinValue(BitWidth)));
3409 ConservativeResult = ConservativeResult.intersectWith(
3410 ConstantRange(APInt::getSignedMinValue(BitWidth),
3411 APInt(BitWidth, 1)));
3414 // TODO: non-affine addrec
3415 if (AddRec->isAffine()) {
3416 Type *Ty = AddRec->getType();
3417 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
3418 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3419 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
3420 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3422 const SCEV *Start = AddRec->getStart();
3423 const SCEV *Step = AddRec->getStepRecurrence(*this);
3425 ConstantRange StartRange = getSignedRange(Start);
3426 ConstantRange StepRange = getSignedRange(Step);
3427 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3428 ConstantRange EndRange =
3429 StartRange.add(MaxBECountRange.multiply(StepRange));
3431 // Check for overflow. This must be done with ConstantRange arithmetic
3432 // because we could be called from within the ScalarEvolution overflow
3434 ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
3435 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3436 ConstantRange ExtMaxBECountRange =
3437 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3438 ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
3439 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3441 return setSignedRange(AddRec, ConservativeResult);
3443 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3444 EndRange.getSignedMin());
3445 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3446 EndRange.getSignedMax());
3447 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
3448 return setSignedRange(AddRec, ConservativeResult);
3449 return setSignedRange(AddRec,
3450 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
3454 return setSignedRange(AddRec, ConservativeResult);
3457 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3458 // For a SCEVUnknown, ask ValueTracking.
3459 if (!U->getValue()->getType()->isIntegerTy() && !TD)
3460 return setSignedRange(U, ConservativeResult);
3461 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3463 return setSignedRange(U, ConservativeResult);
3464 return setSignedRange(U, ConservativeResult.intersectWith(
3465 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
3466 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1)));
3469 return setSignedRange(S, ConservativeResult);
3472 /// createSCEV - We know that there is no SCEV for the specified value.
3473 /// Analyze the expression.
3475 const SCEV *ScalarEvolution::createSCEV(Value *V) {
3476 if (!isSCEVable(V->getType()))
3477 return getUnknown(V);
3479 unsigned Opcode = Instruction::UserOp1;
3480 if (Instruction *I = dyn_cast<Instruction>(V)) {
3481 Opcode = I->getOpcode();
3483 // Don't attempt to analyze instructions in blocks that aren't
3484 // reachable. Such instructions don't matter, and they aren't required
3485 // to obey basic rules for definitions dominating uses which this
3486 // analysis depends on.
3487 if (!DT->isReachableFromEntry(I->getParent()))
3488 return getUnknown(V);
3489 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
3490 Opcode = CE->getOpcode();
3491 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3492 return getConstant(CI);
3493 else if (isa<ConstantPointerNull>(V))
3494 return getConstant(V->getType(), 0);
3495 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3496 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
3498 return getUnknown(V);
3500 Operator *U = cast<Operator>(V);
3502 case Instruction::Add: {
3503 // The simple thing to do would be to just call getSCEV on both operands
3504 // and call getAddExpr with the result. However if we're looking at a
3505 // bunch of things all added together, this can be quite inefficient,
3506 // because it leads to N-1 getAddExpr calls for N ultimate operands.
3507 // Instead, gather up all the operands and make a single getAddExpr call.
3508 // LLVM IR canonical form means we need only traverse the left operands.
3509 SmallVector<const SCEV *, 4> AddOps;
3510 AddOps.push_back(getSCEV(U->getOperand(1)));
3511 for (Value *Op = U->getOperand(0); ; Op = U->getOperand(0)) {
3512 unsigned Opcode = Op->getValueID() - Value::InstructionVal;
3513 if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
3515 U = cast<Operator>(Op);
3516 const SCEV *Op1 = getSCEV(U->getOperand(1));
3517 if (Opcode == Instruction::Sub)
3518 AddOps.push_back(getNegativeSCEV(Op1));
3520 AddOps.push_back(Op1);
3522 AddOps.push_back(getSCEV(U->getOperand(0)));
3523 return getAddExpr(AddOps);
3525 case Instruction::Mul: {
3526 // See the Add code above.
3527 SmallVector<const SCEV *, 4> MulOps;
3528 MulOps.push_back(getSCEV(U->getOperand(1)));
3529 for (Value *Op = U->getOperand(0);
3530 Op->getValueID() == Instruction::Mul + Value::InstructionVal;
3531 Op = U->getOperand(0)) {
3532 U = cast<Operator>(Op);
3533 MulOps.push_back(getSCEV(U->getOperand(1)));
3535 MulOps.push_back(getSCEV(U->getOperand(0)));
3536 return getMulExpr(MulOps);
3538 case Instruction::UDiv:
3539 return getUDivExpr(getSCEV(U->getOperand(0)),
3540 getSCEV(U->getOperand(1)));
3541 case Instruction::Sub:
3542 return getMinusSCEV(getSCEV(U->getOperand(0)),
3543 getSCEV(U->getOperand(1)));
3544 case Instruction::And:
3545 // For an expression like x&255 that merely masks off the high bits,
3546 // use zext(trunc(x)) as the SCEV expression.
3547 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3548 if (CI->isNullValue())
3549 return getSCEV(U->getOperand(1));
3550 if (CI->isAllOnesValue())
3551 return getSCEV(U->getOperand(0));
3552 const APInt &A = CI->getValue();
3554 // Instcombine's ShrinkDemandedConstant may strip bits out of
3555 // constants, obscuring what would otherwise be a low-bits mask.
3556 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3557 // knew about to reconstruct a low-bits mask value.
3558 unsigned LZ = A.countLeadingZeros();
3559 unsigned BitWidth = A.getBitWidth();
3560 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3561 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3562 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3564 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3566 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
3568 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
3569 IntegerType::get(getContext(), BitWidth - LZ)),
3574 case Instruction::Or:
3575 // If the RHS of the Or is a constant, we may have something like:
3576 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3577 // optimizations will transparently handle this case.
3579 // In order for this transformation to be safe, the LHS must be of the
3580 // form X*(2^n) and the Or constant must be less than 2^n.
3581 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3582 const SCEV *LHS = getSCEV(U->getOperand(0));
3583 const APInt &CIVal = CI->getValue();
3584 if (GetMinTrailingZeros(LHS) >=
3585 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3586 // Build a plain add SCEV.
3587 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3588 // If the LHS of the add was an addrec and it has no-wrap flags,
3589 // transfer the no-wrap flags, since an or won't introduce a wrap.
3590 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3591 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
3592 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
3593 OldAR->getNoWrapFlags());
3599 case Instruction::Xor:
3600 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3601 // If the RHS of the xor is a signbit, then this is just an add.
3602 // Instcombine turns add of signbit into xor as a strength reduction step.
3603 if (CI->getValue().isSignBit())
3604 return getAddExpr(getSCEV(U->getOperand(0)),
3605 getSCEV(U->getOperand(1)));
3607 // If the RHS of xor is -1, then this is a not operation.
3608 if (CI->isAllOnesValue())
3609 return getNotSCEV(getSCEV(U->getOperand(0)));
3611 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3612 // This is a variant of the check for xor with -1, and it handles
3613 // the case where instcombine has trimmed non-demanded bits out
3614 // of an xor with -1.
3615 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3616 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3617 if (BO->getOpcode() == Instruction::And &&
3618 LCI->getValue() == CI->getValue())
3619 if (const SCEVZeroExtendExpr *Z =
3620 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
3621 Type *UTy = U->getType();
3622 const SCEV *Z0 = Z->getOperand();
3623 Type *Z0Ty = Z0->getType();
3624 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3626 // If C is a low-bits mask, the zero extend is serving to
3627 // mask off the high bits. Complement the operand and
3628 // re-apply the zext.
3629 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3630 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3632 // If C is a single bit, it may be in the sign-bit position
3633 // before the zero-extend. In this case, represent the xor
3634 // using an add, which is equivalent, and re-apply the zext.
3635 APInt Trunc = CI->getValue().trunc(Z0TySize);
3636 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3638 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3644 case Instruction::Shl:
3645 // Turn shift left of a constant amount into a multiply.
3646 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3647 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
3649 // If the shift count is not less than the bitwidth, the result of
3650 // the shift is undefined. Don't try to analyze it, because the
3651 // resolution chosen here may differ from the resolution chosen in
3652 // other parts of the compiler.
3653 if (SA->getValue().uge(BitWidth))
3656 Constant *X = ConstantInt::get(getContext(),
3657 APInt(BitWidth, 1).shl(SA->getZExtValue()));
3658 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3662 case Instruction::LShr:
3663 // Turn logical shift right of a constant into a unsigned divide.
3664 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3665 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
3667 // If the shift count is not less than the bitwidth, the result of
3668 // the shift is undefined. Don't try to analyze it, because the
3669 // resolution chosen here may differ from the resolution chosen in
3670 // other parts of the compiler.
3671 if (SA->getValue().uge(BitWidth))
3674 Constant *X = ConstantInt::get(getContext(),
3675 APInt(BitWidth, 1).shl(SA->getZExtValue()));
3676 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3680 case Instruction::AShr:
3681 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3682 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
3683 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
3684 if (L->getOpcode() == Instruction::Shl &&
3685 L->getOperand(1) == U->getOperand(1)) {
3686 uint64_t BitWidth = getTypeSizeInBits(U->getType());
3688 // If the shift count is not less than the bitwidth, the result of
3689 // the shift is undefined. Don't try to analyze it, because the
3690 // resolution chosen here may differ from the resolution chosen in
3691 // other parts of the compiler.
3692 if (CI->getValue().uge(BitWidth))
3695 uint64_t Amt = BitWidth - CI->getZExtValue();
3696 if (Amt == BitWidth)
3697 return getSCEV(L->getOperand(0)); // shift by zero --> noop
3699 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
3700 IntegerType::get(getContext(),
3706 case Instruction::Trunc:
3707 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
3709 case Instruction::ZExt:
3710 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3712 case Instruction::SExt:
3713 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3715 case Instruction::BitCast:
3716 // BitCasts are no-op casts so we just eliminate the cast.
3717 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
3718 return getSCEV(U->getOperand(0));
3721 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3722 // lead to pointer expressions which cannot safely be expanded to GEPs,
3723 // because ScalarEvolution doesn't respect the GEP aliasing rules when
3724 // simplifying integer expressions.
3726 case Instruction::GetElementPtr:
3727 return createNodeForGEP(cast<GEPOperator>(U));
3729 case Instruction::PHI:
3730 return createNodeForPHI(cast<PHINode>(U));
3732 case Instruction::Select:
3733 // This could be a smax or umax that was lowered earlier.
3734 // Try to recover it.
3735 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3736 Value *LHS = ICI->getOperand(0);
3737 Value *RHS = ICI->getOperand(1);
3738 switch (ICI->getPredicate()) {
3739 case ICmpInst::ICMP_SLT:
3740 case ICmpInst::ICMP_SLE:
3741 std::swap(LHS, RHS);
3743 case ICmpInst::ICMP_SGT:
3744 case ICmpInst::ICMP_SGE:
3745 // a >s b ? a+x : b+x -> smax(a, b)+x
3746 // a >s b ? b+x : a+x -> smin(a, b)+x
3747 if (LHS->getType() == U->getType()) {
3748 const SCEV *LS = getSCEV(LHS);
3749 const SCEV *RS = getSCEV(RHS);
3750 const SCEV *LA = getSCEV(U->getOperand(1));
3751 const SCEV *RA = getSCEV(U->getOperand(2));
3752 const SCEV *LDiff = getMinusSCEV(LA, LS);
3753 const SCEV *RDiff = getMinusSCEV(RA, RS);
3755 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
3756 LDiff = getMinusSCEV(LA, RS);
3757 RDiff = getMinusSCEV(RA, LS);
3759 return getAddExpr(getSMinExpr(LS, RS), LDiff);
3762 case ICmpInst::ICMP_ULT:
3763 case ICmpInst::ICMP_ULE:
3764 std::swap(LHS, RHS);
3766 case ICmpInst::ICMP_UGT:
3767 case ICmpInst::ICMP_UGE:
3768 // a >u b ? a+x : b+x -> umax(a, b)+x
3769 // a >u b ? b+x : a+x -> umin(a, b)+x
3770 if (LHS->getType() == U->getType()) {
3771 const SCEV *LS = getSCEV(LHS);
3772 const SCEV *RS = getSCEV(RHS);
3773 const SCEV *LA = getSCEV(U->getOperand(1));
3774 const SCEV *RA = getSCEV(U->getOperand(2));
3775 const SCEV *LDiff = getMinusSCEV(LA, LS);
3776 const SCEV *RDiff = getMinusSCEV(RA, RS);
3778 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
3779 LDiff = getMinusSCEV(LA, RS);
3780 RDiff = getMinusSCEV(RA, LS);
3782 return getAddExpr(getUMinExpr(LS, RS), LDiff);
3785 case ICmpInst::ICMP_NE:
3786 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
3787 if (LHS->getType() == U->getType() &&
3788 isa<ConstantInt>(RHS) &&
3789 cast<ConstantInt>(RHS)->isZero()) {
3790 const SCEV *One = getConstant(LHS->getType(), 1);
3791 const SCEV *LS = getSCEV(LHS);
3792 const SCEV *LA = getSCEV(U->getOperand(1));
3793 const SCEV *RA = getSCEV(U->getOperand(2));
3794 const SCEV *LDiff = getMinusSCEV(LA, LS);
3795 const SCEV *RDiff = getMinusSCEV(RA, One);
3797 return getAddExpr(getUMaxExpr(One, LS), LDiff);
3800 case ICmpInst::ICMP_EQ:
3801 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
3802 if (LHS->getType() == U->getType() &&
3803 isa<ConstantInt>(RHS) &&
3804 cast<ConstantInt>(RHS)->isZero()) {
3805 const SCEV *One = getConstant(LHS->getType(), 1);
3806 const SCEV *LS = getSCEV(LHS);
3807 const SCEV *LA = getSCEV(U->getOperand(1));
3808 const SCEV *RA = getSCEV(U->getOperand(2));
3809 const SCEV *LDiff = getMinusSCEV(LA, One);
3810 const SCEV *RDiff = getMinusSCEV(RA, LS);
3812 return getAddExpr(getUMaxExpr(One, LS), LDiff);
3820 default: // We cannot analyze this expression.
3824 return getUnknown(V);
3829 //===----------------------------------------------------------------------===//
3830 // Iteration Count Computation Code
3833 /// getSmallConstantTripCount - Returns the maximum trip count of this loop as a
3834 /// normal unsigned value, if possible. Returns 0 if the trip count is unknown
3835 /// or not constant. Will also return 0 if the maximum trip count is very large
3837 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L,
3838 BasicBlock *ExitBlock) {
3839 const SCEVConstant *ExitCount =
3840 dyn_cast<SCEVConstant>(getExitCount(L, ExitBlock));
3844 ConstantInt *ExitConst = ExitCount->getValue();
3846 // Guard against huge trip counts.
3847 if (ExitConst->getValue().getActiveBits() > 32)
3850 // In case of integer overflow, this returns 0, which is correct.
3851 return ((unsigned)ExitConst->getZExtValue()) + 1;
3854 /// getSmallConstantTripMultiple - Returns the largest constant divisor of the
3855 /// trip count of this loop as a normal unsigned value, if possible. This
3856 /// means that the actual trip count is always a multiple of the returned
3857 /// value (don't forget the trip count could very well be zero as well!).
3859 /// Returns 1 if the trip count is unknown or not guaranteed to be the
3860 /// multiple of a constant (which is also the case if the trip count is simply
3861 /// constant, use getSmallConstantTripCount for that case), Will also return 1
3862 /// if the trip count is very large (>= 2^32).
3863 unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L,
3864 BasicBlock *ExitBlock) {
3865 const SCEV *ExitCount = getExitCount(L, ExitBlock);
3866 if (ExitCount == getCouldNotCompute())
3869 // Get the trip count from the BE count by adding 1.
3870 const SCEV *TCMul = getAddExpr(ExitCount,
3871 getConstant(ExitCount->getType(), 1));
3872 // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt
3873 // to factor simple cases.
3874 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul))
3875 TCMul = Mul->getOperand(0);
3877 const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul);
3881 ConstantInt *Result = MulC->getValue();
3883 // Guard against huge trip counts.
3884 if (!Result || Result->getValue().getActiveBits() > 32)
3887 return (unsigned)Result->getZExtValue();
3890 // getExitCount - Get the expression for the number of loop iterations for which
3891 // this loop is guaranteed not to exit via ExitintBlock. Otherwise return
3892 // SCEVCouldNotCompute.
3893 const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) {
3894 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
3897 /// getBackedgeTakenCount - If the specified loop has a predictable
3898 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3899 /// object. The backedge-taken count is the number of times the loop header
3900 /// will be branched to from within the loop. This is one less than the
3901 /// trip count of the loop, since it doesn't count the first iteration,
3902 /// when the header is branched to from outside the loop.
3904 /// Note that it is not valid to call this method on a loop without a
3905 /// loop-invariant backedge-taken count (see
3906 /// hasLoopInvariantBackedgeTakenCount).
3908 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
3909 return getBackedgeTakenInfo(L).getExact(this);
3912 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3913 /// return the least SCEV value that is known never to be less than the
3914 /// actual backedge taken count.
3915 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
3916 return getBackedgeTakenInfo(L).getMax(this);
3919 /// PushLoopPHIs - Push PHI nodes in the header of the given loop
3920 /// onto the given Worklist.
3922 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3923 BasicBlock *Header = L->getHeader();
3925 // Push all Loop-header PHIs onto the Worklist stack.
3926 for (BasicBlock::iterator I = Header->begin();
3927 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3928 Worklist.push_back(PN);
3931 const ScalarEvolution::BackedgeTakenInfo &
3932 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
3933 // Initially insert an invalid entry for this loop. If the insertion
3934 // succeeds, proceed to actually compute a backedge-taken count and
3935 // update the value. The temporary CouldNotCompute value tells SCEV
3936 // code elsewhere that it shouldn't attempt to request a new
3937 // backedge-taken count, which could result in infinite recursion.
3938 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
3939 BackedgeTakenCounts.insert(std::make_pair(L, BackedgeTakenInfo()));
3941 return Pair.first->second;
3943 // ComputeBackedgeTakenCount may allocate memory for its result. Inserting it
3944 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
3945 // must be cleared in this scope.
3946 BackedgeTakenInfo Result = ComputeBackedgeTakenCount(L);
3948 if (Result.getExact(this) != getCouldNotCompute()) {
3949 assert(isLoopInvariant(Result.getExact(this), L) &&
3950 isLoopInvariant(Result.getMax(this), L) &&
3951 "Computed backedge-taken count isn't loop invariant for loop!");
3952 ++NumTripCountsComputed;
3954 else if (Result.getMax(this) == getCouldNotCompute() &&
3955 isa<PHINode>(L->getHeader()->begin())) {
3956 // Only count loops that have phi nodes as not being computable.
3957 ++NumTripCountsNotComputed;
3960 // Now that we know more about the trip count for this loop, forget any
3961 // existing SCEV values for PHI nodes in this loop since they are only
3962 // conservative estimates made without the benefit of trip count
3963 // information. This is similar to the code in forgetLoop, except that
3964 // it handles SCEVUnknown PHI nodes specially.
3965 if (Result.hasAnyInfo()) {
3966 SmallVector<Instruction *, 16> Worklist;
3967 PushLoopPHIs(L, Worklist);
3969 SmallPtrSet<Instruction *, 8> Visited;
3970 while (!Worklist.empty()) {
3971 Instruction *I = Worklist.pop_back_val();
3972 if (!Visited.insert(I)) continue;
3974 ValueExprMapType::iterator It =
3975 ValueExprMap.find(static_cast<Value *>(I));
3976 if (It != ValueExprMap.end()) {
3977 const SCEV *Old = It->second;
3979 // SCEVUnknown for a PHI either means that it has an unrecognized
3980 // structure, or it's a PHI that's in the progress of being computed
3981 // by createNodeForPHI. In the former case, additional loop trip
3982 // count information isn't going to change anything. In the later
3983 // case, createNodeForPHI will perform the necessary updates on its
3984 // own when it gets to that point.
3985 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
3986 forgetMemoizedResults(Old);
3987 ValueExprMap.erase(It);
3989 if (PHINode *PN = dyn_cast<PHINode>(I))
3990 ConstantEvolutionLoopExitValue.erase(PN);
3993 PushDefUseChildren(I, Worklist);
3997 // Re-lookup the insert position, since the call to
3998 // ComputeBackedgeTakenCount above could result in a
3999 // recusive call to getBackedgeTakenInfo (on a different
4000 // loop), which would invalidate the iterator computed
4002 return BackedgeTakenCounts.find(L)->second = Result;
4005 /// forgetLoop - This method should be called by the client when it has
4006 /// changed a loop in a way that may effect ScalarEvolution's ability to
4007 /// compute a trip count, or if the loop is deleted.
4008 void ScalarEvolution::forgetLoop(const Loop *L) {
4009 // Drop any stored trip count value.
4010 DenseMap<const Loop*, BackedgeTakenInfo>::iterator BTCPos =
4011 BackedgeTakenCounts.find(L);
4012 if (BTCPos != BackedgeTakenCounts.end()) {
4013 BTCPos->second.clear();
4014 BackedgeTakenCounts.erase(BTCPos);
4017 // Drop information about expressions based on loop-header PHIs.
4018 SmallVector<Instruction *, 16> Worklist;
4019 PushLoopPHIs(L, Worklist);
4021 SmallPtrSet<Instruction *, 8> Visited;
4022 while (!Worklist.empty()) {
4023 Instruction *I = Worklist.pop_back_val();
4024 if (!Visited.insert(I)) continue;
4026 ValueExprMapType::iterator It = ValueExprMap.find(static_cast<Value *>(I));
4027 if (It != ValueExprMap.end()) {
4028 forgetMemoizedResults(It->second);
4029 ValueExprMap.erase(It);
4030 if (PHINode *PN = dyn_cast<PHINode>(I))
4031 ConstantEvolutionLoopExitValue.erase(PN);
4034 PushDefUseChildren(I, Worklist);
4037 // Forget all contained loops too, to avoid dangling entries in the
4038 // ValuesAtScopes map.
4039 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4043 /// forgetValue - This method should be called by the client when it has
4044 /// changed a value in a way that may effect its value, or which may
4045 /// disconnect it from a def-use chain linking it to a loop.
4046 void ScalarEvolution::forgetValue(Value *V) {
4047 Instruction *I = dyn_cast<Instruction>(V);
4050 // Drop information about expressions based on loop-header PHIs.
4051 SmallVector<Instruction *, 16> Worklist;
4052 Worklist.push_back(I);
4054 SmallPtrSet<Instruction *, 8> Visited;
4055 while (!Worklist.empty()) {
4056 I = Worklist.pop_back_val();
4057 if (!Visited.insert(I)) continue;
4059 ValueExprMapType::iterator It = ValueExprMap.find(static_cast<Value *>(I));
4060 if (It != ValueExprMap.end()) {
4061 forgetMemoizedResults(It->second);
4062 ValueExprMap.erase(It);
4063 if (PHINode *PN = dyn_cast<PHINode>(I))
4064 ConstantEvolutionLoopExitValue.erase(PN);
4067 PushDefUseChildren(I, Worklist);
4071 /// getExact - Get the exact loop backedge taken count considering all loop
4072 /// exits. If all exits are computable, this is the minimum computed count.
4074 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE) const {
4075 // If any exits were not computable, the loop is not computable.
4076 if (!ExitNotTaken.isCompleteList()) return SE->getCouldNotCompute();
4078 // We need at least one computable exit.
4079 if (!ExitNotTaken.ExitingBlock) return SE->getCouldNotCompute();
4080 assert(ExitNotTaken.ExactNotTaken && "uninitialized not-taken info");
4082 const SCEV *BECount = 0;
4083 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
4084 ENT != 0; ENT = ENT->getNextExit()) {
4086 assert(ENT->ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
4089 BECount = ENT->ExactNotTaken;
4091 BECount = SE->getUMinFromMismatchedTypes(BECount, ENT->ExactNotTaken);
4093 assert(BECount && "Invalid not taken count for loop exit");
4097 /// getExact - Get the exact not taken count for this loop exit.
4099 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
4100 ScalarEvolution *SE) const {
4101 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
4102 ENT != 0; ENT = ENT->getNextExit()) {
4104 if (ENT->ExitingBlock == ExitingBlock)
4105 return ENT->ExactNotTaken;
4107 return SE->getCouldNotCompute();
4110 /// getMax - Get the max backedge taken count for the loop.
4112 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
4113 return Max ? Max : SE->getCouldNotCompute();
4116 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
4117 /// computable exit into a persistent ExitNotTakenInfo array.
4118 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
4119 SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts,
4120 bool Complete, const SCEV *MaxCount) : Max(MaxCount) {
4123 ExitNotTaken.setIncomplete();
4125 unsigned NumExits = ExitCounts.size();
4126 if (NumExits == 0) return;
4128 ExitNotTaken.ExitingBlock = ExitCounts[0].first;
4129 ExitNotTaken.ExactNotTaken = ExitCounts[0].second;
4130 if (NumExits == 1) return;
4132 // Handle the rare case of multiple computable exits.
4133 ExitNotTakenInfo *ENT = new ExitNotTakenInfo[NumExits-1];
4135 ExitNotTakenInfo *PrevENT = &ExitNotTaken;
4136 for (unsigned i = 1; i < NumExits; ++i, PrevENT = ENT, ++ENT) {
4137 PrevENT->setNextExit(ENT);
4138 ENT->ExitingBlock = ExitCounts[i].first;
4139 ENT->ExactNotTaken = ExitCounts[i].second;
4143 /// clear - Invalidate this result and free the ExitNotTakenInfo array.
4144 void ScalarEvolution::BackedgeTakenInfo::clear() {
4145 ExitNotTaken.ExitingBlock = 0;
4146 ExitNotTaken.ExactNotTaken = 0;
4147 delete[] ExitNotTaken.getNextExit();
4150 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
4151 /// of the specified loop will execute.
4152 ScalarEvolution::BackedgeTakenInfo
4153 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
4154 SmallVector<BasicBlock *, 8> ExitingBlocks;
4155 L->getExitingBlocks(ExitingBlocks);
4157 // Examine all exits and pick the most conservative values.
4158 const SCEV *MaxBECount = getCouldNotCompute();
4159 bool CouldComputeBECount = true;
4160 SmallVector<std::pair<BasicBlock *, const SCEV *>, 4> ExitCounts;
4161 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
4162 ExitLimit EL = ComputeExitLimit(L, ExitingBlocks[i]);
4163 if (EL.Exact == getCouldNotCompute())
4164 // We couldn't compute an exact value for this exit, so
4165 // we won't be able to compute an exact value for the loop.
4166 CouldComputeBECount = false;
4168 ExitCounts.push_back(std::make_pair(ExitingBlocks[i], EL.Exact));
4170 if (MaxBECount == getCouldNotCompute())
4171 MaxBECount = EL.Max;
4172 else if (EL.Max != getCouldNotCompute())
4173 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, EL.Max);
4176 return BackedgeTakenInfo(ExitCounts, CouldComputeBECount, MaxBECount);
4179 /// ComputeExitLimit - Compute the number of times the backedge of the specified
4180 /// loop will execute if it exits via the specified block.
4181 ScalarEvolution::ExitLimit
4182 ScalarEvolution::ComputeExitLimit(const Loop *L, BasicBlock *ExitingBlock) {
4184 // Okay, we've chosen an exiting block. See what condition causes us to
4185 // exit at this block.
4187 // FIXME: we should be able to handle switch instructions (with a single exit)
4188 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
4189 if (ExitBr == 0) return getCouldNotCompute();
4190 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
4192 // At this point, we know we have a conditional branch that determines whether
4193 // the loop is exited. However, we don't know if the branch is executed each
4194 // time through the loop. If not, then the execution count of the branch will
4195 // not be equal to the trip count of the loop.
4197 // Currently we check for this by checking to see if the Exit branch goes to
4198 // the loop header. If so, we know it will always execute the same number of
4199 // times as the loop. We also handle the case where the exit block *is* the
4200 // loop header. This is common for un-rotated loops.
4202 // If both of those tests fail, walk up the unique predecessor chain to the
4203 // header, stopping if there is an edge that doesn't exit the loop. If the
4204 // header is reached, the execution count of the branch will be equal to the
4205 // trip count of the loop.
4207 // More extensive analysis could be done to handle more cases here.
4209 if (ExitBr->getSuccessor(0) != L->getHeader() &&
4210 ExitBr->getSuccessor(1) != L->getHeader() &&
4211 ExitBr->getParent() != L->getHeader()) {
4212 // The simple checks failed, try climbing the unique predecessor chain
4213 // up to the header.
4215 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
4216 BasicBlock *Pred = BB->getUniquePredecessor();
4218 return getCouldNotCompute();
4219 TerminatorInst *PredTerm = Pred->getTerminator();
4220 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
4221 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
4224 // If the predecessor has a successor that isn't BB and isn't
4225 // outside the loop, assume the worst.
4226 if (L->contains(PredSucc))
4227 return getCouldNotCompute();
4229 if (Pred == L->getHeader()) {
4236 return getCouldNotCompute();
4239 // Proceed to the next level to examine the exit condition expression.
4240 return ComputeExitLimitFromCond(L, ExitBr->getCondition(),
4241 ExitBr->getSuccessor(0),
4242 ExitBr->getSuccessor(1));
4245 /// ComputeExitLimitFromCond - Compute the number of times the
4246 /// backedge of the specified loop will execute if its exit condition
4247 /// were a conditional branch of ExitCond, TBB, and FBB.
4248 ScalarEvolution::ExitLimit
4249 ScalarEvolution::ComputeExitLimitFromCond(const Loop *L,
4253 // Check if the controlling expression for this loop is an And or Or.
4254 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
4255 if (BO->getOpcode() == Instruction::And) {
4256 // Recurse on the operands of the and.
4257 ExitLimit EL0 = ComputeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB);
4258 ExitLimit EL1 = ComputeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB);
4259 const SCEV *BECount = getCouldNotCompute();
4260 const SCEV *MaxBECount = getCouldNotCompute();
4261 if (L->contains(TBB)) {
4262 // Both conditions must be true for the loop to continue executing.
4263 // Choose the less conservative count.
4264 if (EL0.Exact == getCouldNotCompute() ||
4265 EL1.Exact == getCouldNotCompute())
4266 BECount = getCouldNotCompute();
4268 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
4269 if (EL0.Max == getCouldNotCompute())
4270 MaxBECount = EL1.Max;
4271 else if (EL1.Max == getCouldNotCompute())
4272 MaxBECount = EL0.Max;
4274 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
4276 // Both conditions must be true at the same time for the loop to exit.
4277 // For now, be conservative.
4278 assert(L->contains(FBB) && "Loop block has no successor in loop!");
4279 if (EL0.Max == EL1.Max)
4280 MaxBECount = EL0.Max;
4281 if (EL0.Exact == EL1.Exact)
4282 BECount = EL0.Exact;
4285 return ExitLimit(BECount, MaxBECount);
4287 if (BO->getOpcode() == Instruction::Or) {
4288 // Recurse on the operands of the or.
4289 ExitLimit EL0 = ComputeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB);
4290 ExitLimit EL1 = ComputeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB);
4291 const SCEV *BECount = getCouldNotCompute();
4292 const SCEV *MaxBECount = getCouldNotCompute();
4293 if (L->contains(FBB)) {
4294 // Both conditions must be false for the loop to continue executing.
4295 // Choose the less conservative count.
4296 if (EL0.Exact == getCouldNotCompute() ||
4297 EL1.Exact == getCouldNotCompute())
4298 BECount = getCouldNotCompute();
4300 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
4301 if (EL0.Max == getCouldNotCompute())
4302 MaxBECount = EL1.Max;
4303 else if (EL1.Max == getCouldNotCompute())
4304 MaxBECount = EL0.Max;
4306 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
4308 // Both conditions must be false at the same time for the loop to exit.
4309 // For now, be conservative.
4310 assert(L->contains(TBB) && "Loop block has no successor in loop!");
4311 if (EL0.Max == EL1.Max)
4312 MaxBECount = EL0.Max;
4313 if (EL0.Exact == EL1.Exact)
4314 BECount = EL0.Exact;
4317 return ExitLimit(BECount, MaxBECount);
4321 // With an icmp, it may be feasible to compute an exact backedge-taken count.
4322 // Proceed to the next level to examine the icmp.
4323 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
4324 return ComputeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB);
4326 // Check for a constant condition. These are normally stripped out by
4327 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
4328 // preserve the CFG and is temporarily leaving constant conditions
4330 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
4331 if (L->contains(FBB) == !CI->getZExtValue())
4332 // The backedge is always taken.
4333 return getCouldNotCompute();
4335 // The backedge is never taken.
4336 return getConstant(CI->getType(), 0);
4339 // If it's not an integer or pointer comparison then compute it the hard way.
4340 return ComputeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
4343 /// ComputeExitLimitFromICmp - Compute the number of times the
4344 /// backedge of the specified loop will execute if its exit condition
4345 /// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
4346 ScalarEvolution::ExitLimit
4347 ScalarEvolution::ComputeExitLimitFromICmp(const Loop *L,
4352 // If the condition was exit on true, convert the condition to exit on false
4353 ICmpInst::Predicate Cond;
4354 if (!L->contains(FBB))
4355 Cond = ExitCond->getPredicate();
4357 Cond = ExitCond->getInversePredicate();
4359 // Handle common loops like: for (X = "string"; *X; ++X)
4360 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
4361 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
4363 ComputeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
4364 if (ItCnt.hasAnyInfo())
4368 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
4369 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
4371 // Try to evaluate any dependencies out of the loop.
4372 LHS = getSCEVAtScope(LHS, L);
4373 RHS = getSCEVAtScope(RHS, L);
4375 // At this point, we would like to compute how many iterations of the
4376 // loop the predicate will return true for these inputs.
4377 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
4378 // If there is a loop-invariant, force it into the RHS.
4379 std::swap(LHS, RHS);
4380 Cond = ICmpInst::getSwappedPredicate(Cond);
4383 // Simplify the operands before analyzing them.
4384 (void)SimplifyICmpOperands(Cond, LHS, RHS);
4386 // If we have a comparison of a chrec against a constant, try to use value
4387 // ranges to answer this query.
4388 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
4389 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
4390 if (AddRec->getLoop() == L) {
4391 // Form the constant range.
4392 ConstantRange CompRange(
4393 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
4395 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
4396 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
4400 case ICmpInst::ICMP_NE: { // while (X != Y)
4401 // Convert to: while (X-Y != 0)
4402 ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L);
4403 if (EL.hasAnyInfo()) return EL;
4406 case ICmpInst::ICMP_EQ: { // while (X == Y)
4407 // Convert to: while (X-Y == 0)
4408 ExitLimit EL = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
4409 if (EL.hasAnyInfo()) return EL;
4412 case ICmpInst::ICMP_SLT: {
4413 ExitLimit EL = HowManyLessThans(LHS, RHS, L, true);
4414 if (EL.hasAnyInfo()) return EL;
4417 case ICmpInst::ICMP_SGT: {
4418 ExitLimit EL = HowManyLessThans(getNotSCEV(LHS),
4419 getNotSCEV(RHS), L, true);
4420 if (EL.hasAnyInfo()) return EL;
4423 case ICmpInst::ICMP_ULT: {
4424 ExitLimit EL = HowManyLessThans(LHS, RHS, L, false);
4425 if (EL.hasAnyInfo()) return EL;
4428 case ICmpInst::ICMP_UGT: {
4429 ExitLimit EL = HowManyLessThans(getNotSCEV(LHS),
4430 getNotSCEV(RHS), L, false);
4431 if (EL.hasAnyInfo()) return EL;
4436 dbgs() << "ComputeBackedgeTakenCount ";
4437 if (ExitCond->getOperand(0)->getType()->isUnsigned())
4438 dbgs() << "[unsigned] ";
4439 dbgs() << *LHS << " "
4440 << Instruction::getOpcodeName(Instruction::ICmp)
4441 << " " << *RHS << "\n";
4445 return ComputeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
4448 static ConstantInt *
4449 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
4450 ScalarEvolution &SE) {
4451 const SCEV *InVal = SE.getConstant(C);
4452 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
4453 assert(isa<SCEVConstant>(Val) &&
4454 "Evaluation of SCEV at constant didn't fold correctly?");
4455 return cast<SCEVConstant>(Val)->getValue();
4458 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
4459 /// and a GEP expression (missing the pointer index) indexing into it, return
4460 /// the addressed element of the initializer or null if the index expression is
4463 GetAddressedElementFromGlobal(GlobalVariable *GV,
4464 const std::vector<ConstantInt*> &Indices) {
4465 Constant *Init = GV->getInitializer();
4466 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
4467 uint64_t Idx = Indices[i]->getZExtValue();
4468 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
4469 assert(Idx < CS->getNumOperands() && "Bad struct index!");
4470 Init = cast<Constant>(CS->getOperand(Idx));
4471 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
4472 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
4473 Init = cast<Constant>(CA->getOperand(Idx));
4474 } else if (isa<ConstantAggregateZero>(Init)) {
4475 if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
4476 assert(Idx < STy->getNumElements() && "Bad struct index!");
4477 Init = Constant::getNullValue(STy->getElementType(Idx));
4478 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
4479 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
4480 Init = Constant::getNullValue(ATy->getElementType());
4482 llvm_unreachable("Unknown constant aggregate type!");
4486 return 0; // Unknown initializer type
4492 /// ComputeLoadConstantCompareExitLimit - Given an exit condition of
4493 /// 'icmp op load X, cst', try to see if we can compute the backedge
4494 /// execution count.
4495 ScalarEvolution::ExitLimit
4496 ScalarEvolution::ComputeLoadConstantCompareExitLimit(
4500 ICmpInst::Predicate predicate) {
4502 if (LI->isVolatile()) return getCouldNotCompute();
4504 // Check to see if the loaded pointer is a getelementptr of a global.
4505 // TODO: Use SCEV instead of manually grubbing with GEPs.
4506 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
4507 if (!GEP) return getCouldNotCompute();
4509 // Make sure that it is really a constant global we are gepping, with an
4510 // initializer, and make sure the first IDX is really 0.
4511 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
4512 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
4513 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
4514 !cast<Constant>(GEP->getOperand(1))->isNullValue())
4515 return getCouldNotCompute();
4517 // Okay, we allow one non-constant index into the GEP instruction.
4519 std::vector<ConstantInt*> Indexes;
4520 unsigned VarIdxNum = 0;
4521 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
4522 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4523 Indexes.push_back(CI);
4524 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
4525 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
4526 VarIdx = GEP->getOperand(i);
4528 Indexes.push_back(0);
4531 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
4532 // Check to see if X is a loop variant variable value now.
4533 const SCEV *Idx = getSCEV(VarIdx);
4534 Idx = getSCEVAtScope(Idx, L);
4536 // We can only recognize very limited forms of loop index expressions, in
4537 // particular, only affine AddRec's like {C1,+,C2}.
4538 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
4539 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
4540 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
4541 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
4542 return getCouldNotCompute();
4544 unsigned MaxSteps = MaxBruteForceIterations;
4545 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
4546 ConstantInt *ItCst = ConstantInt::get(
4547 cast<IntegerType>(IdxExpr->getType()), IterationNum);
4548 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
4550 // Form the GEP offset.
4551 Indexes[VarIdxNum] = Val;
4553 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
4554 if (Result == 0) break; // Cannot compute!
4556 // Evaluate the condition for this iteration.
4557 Result = ConstantExpr::getICmp(predicate, Result, RHS);
4558 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
4559 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
4561 dbgs() << "\n***\n*** Computed loop count " << *ItCst
4562 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
4565 ++NumArrayLenItCounts;
4566 return getConstant(ItCst); // Found terminating iteration!
4569 return getCouldNotCompute();
4573 /// CanConstantFold - Return true if we can constant fold an instruction of the
4574 /// specified type, assuming that all operands were constants.
4575 static bool CanConstantFold(const Instruction *I) {
4576 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
4577 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
4580 if (const CallInst *CI = dyn_cast<CallInst>(I))
4581 if (const Function *F = CI->getCalledFunction())
4582 return canConstantFoldCallTo(F);
4586 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
4587 /// in the loop that V is derived from. We allow arbitrary operations along the
4588 /// way, but the operands of an operation must either be constants or a value
4589 /// derived from a constant PHI. If this expression does not fit with these
4590 /// constraints, return null.
4591 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
4592 // If this is not an instruction, or if this is an instruction outside of the
4593 // loop, it can't be derived from a loop PHI.
4594 Instruction *I = dyn_cast<Instruction>(V);
4595 if (I == 0 || !L->contains(I)) return 0;
4597 if (PHINode *PN = dyn_cast<PHINode>(I)) {
4598 if (L->getHeader() == I->getParent())
4601 // We don't currently keep track of the control flow needed to evaluate
4602 // PHIs, so we cannot handle PHIs inside of loops.
4606 // If we won't be able to constant fold this expression even if the operands
4607 // are constants, return early.
4608 if (!CanConstantFold(I)) return 0;
4610 // Otherwise, we can evaluate this instruction if all of its operands are
4611 // constant or derived from a PHI node themselves.
4613 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
4614 if (!isa<Constant>(I->getOperand(Op))) {
4615 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
4616 if (P == 0) return 0; // Not evolving from PHI
4620 return 0; // Evolving from multiple different PHIs.
4623 // This is a expression evolving from a constant PHI!
4627 /// EvaluateExpression - Given an expression that passes the
4628 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
4629 /// in the loop has the value PHIVal. If we can't fold this expression for some
4630 /// reason, return null.
4631 static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
4632 const TargetData *TD) {
4633 if (isa<PHINode>(V)) return PHIVal;
4634 if (Constant *C = dyn_cast<Constant>(V)) return C;
4635 Instruction *I = cast<Instruction>(V);
4637 std::vector<Constant*> Operands(I->getNumOperands());
4639 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4640 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
4641 if (Operands[i] == 0) return 0;
4644 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4645 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
4647 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Operands, TD);
4650 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
4651 /// in the header of its containing loop, we know the loop executes a
4652 /// constant number of times, and the PHI node is just a recurrence
4653 /// involving constants, fold it.
4655 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
4658 DenseMap<PHINode*, Constant*>::const_iterator I =
4659 ConstantEvolutionLoopExitValue.find(PN);
4660 if (I != ConstantEvolutionLoopExitValue.end())
4663 if (BEs.ugt(MaxBruteForceIterations))
4664 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
4666 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
4668 // Since the loop is canonicalized, the PHI node must have two entries. One
4669 // entry must be a constant (coming in from outside of the loop), and the
4670 // second must be derived from the same PHI.
4671 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4672 Constant *StartCST =
4673 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4675 return RetVal = 0; // Must be a constant.
4677 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4678 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4679 !isa<Constant>(BEValue))
4680 return RetVal = 0; // Not derived from same PHI.
4682 // Execute the loop symbolically to determine the exit value.
4683 if (BEs.getActiveBits() >= 32)
4684 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
4686 unsigned NumIterations = BEs.getZExtValue(); // must be in range
4687 unsigned IterationNum = 0;
4688 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
4689 if (IterationNum == NumIterations)
4690 return RetVal = PHIVal; // Got exit value!
4692 // Compute the value of the PHI node for the next iteration.
4693 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
4694 if (NextPHI == PHIVal)
4695 return RetVal = NextPHI; // Stopped evolving!
4697 return 0; // Couldn't evaluate!
4702 /// ComputeExitCountExhaustively - If the loop is known to execute a
4703 /// constant number of times (the condition evolves only from constants),
4704 /// try to evaluate a few iterations of the loop until we get the exit
4705 /// condition gets a value of ExitWhen (true or false). If we cannot
4706 /// evaluate the trip count of the loop, return getCouldNotCompute().
4707 const SCEV * ScalarEvolution::ComputeExitCountExhaustively(const Loop *L,
4710 PHINode *PN = getConstantEvolvingPHI(Cond, L);
4711 if (PN == 0) return getCouldNotCompute();
4713 // If the loop is canonicalized, the PHI will have exactly two entries.
4714 // That's the only form we support here.
4715 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
4717 // One entry must be a constant (coming in from outside of the loop), and the
4718 // second must be derived from the same PHI.
4719 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4720 Constant *StartCST =
4721 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4722 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
4724 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4725 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4726 !isa<Constant>(BEValue))
4727 return getCouldNotCompute(); // Not derived from same PHI.
4729 // Okay, we find a PHI node that defines the trip count of this loop. Execute
4730 // the loop symbolically to determine when the condition gets a value of
4732 unsigned IterationNum = 0;
4733 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
4734 for (Constant *PHIVal = StartCST;
4735 IterationNum != MaxIterations; ++IterationNum) {
4736 ConstantInt *CondVal =
4737 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
4739 // Couldn't symbolically evaluate.
4740 if (!CondVal) return getCouldNotCompute();
4742 if (CondVal->getValue() == uint64_t(ExitWhen)) {
4743 ++NumBruteForceTripCountsComputed;
4744 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
4747 // Compute the value of the PHI node for the next iteration.
4748 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
4749 if (NextPHI == 0 || NextPHI == PHIVal)
4750 return getCouldNotCompute();// Couldn't evaluate or not making progress...
4754 // Too many iterations were needed to evaluate.
4755 return getCouldNotCompute();
4758 /// getSCEVAtScope - Return a SCEV expression for the specified value
4759 /// at the specified scope in the program. The L value specifies a loop
4760 /// nest to evaluate the expression at, where null is the top-level or a
4761 /// specified loop is immediately inside of the loop.
4763 /// This method can be used to compute the exit value for a variable defined
4764 /// in a loop by querying what the value will hold in the parent loop.
4766 /// In the case that a relevant loop exit value cannot be computed, the
4767 /// original value V is returned.
4768 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
4769 // Check to see if we've folded this expression at this loop before.
4770 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4771 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4772 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4774 return Pair.first->second ? Pair.first->second : V;
4776 // Otherwise compute it.
4777 const SCEV *C = computeSCEVAtScope(V, L);
4778 ValuesAtScopes[V][L] = C;
4782 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
4783 if (isa<SCEVConstant>(V)) return V;
4785 // If this instruction is evolved from a constant-evolving PHI, compute the
4786 // exit value from the loop without using SCEVs.
4787 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
4788 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
4789 const Loop *LI = (*this->LI)[I->getParent()];
4790 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
4791 if (PHINode *PN = dyn_cast<PHINode>(I))
4792 if (PN->getParent() == LI->getHeader()) {
4793 // Okay, there is no closed form solution for the PHI node. Check
4794 // to see if the loop that contains it has a known backedge-taken
4795 // count. If so, we may be able to force computation of the exit
4797 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
4798 if (const SCEVConstant *BTCC =
4799 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
4800 // Okay, we know how many times the containing loop executes. If
4801 // this is a constant evolving PHI node, get the final value at
4802 // the specified iteration number.
4803 Constant *RV = getConstantEvolutionLoopExitValue(PN,
4804 BTCC->getValue()->getValue(),
4806 if (RV) return getSCEV(RV);
4810 // Okay, this is an expression that we cannot symbolically evaluate
4811 // into a SCEV. Check to see if it's possible to symbolically evaluate
4812 // the arguments into constants, and if so, try to constant propagate the
4813 // result. This is particularly useful for computing loop exit values.
4814 if (CanConstantFold(I)) {
4815 SmallVector<Constant *, 4> Operands;
4816 bool MadeImprovement = false;
4817 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4818 Value *Op = I->getOperand(i);
4819 if (Constant *C = dyn_cast<Constant>(Op)) {
4820 Operands.push_back(C);
4824 // If any of the operands is non-constant and if they are
4825 // non-integer and non-pointer, don't even try to analyze them
4826 // with scev techniques.
4827 if (!isSCEVable(Op->getType()))
4830 const SCEV *OrigV = getSCEV(Op);
4831 const SCEV *OpV = getSCEVAtScope(OrigV, L);
4832 MadeImprovement |= OrigV != OpV;
4835 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
4837 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV))
4838 C = dyn_cast<Constant>(SU->getValue());
4840 if (C->getType() != Op->getType())
4841 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4845 Operands.push_back(C);
4848 // Check to see if getSCEVAtScope actually made an improvement.
4849 if (MadeImprovement) {
4851 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4852 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
4853 Operands[0], Operands[1], TD);
4855 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4863 // This is some other type of SCEVUnknown, just return it.
4867 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
4868 // Avoid performing the look-up in the common case where the specified
4869 // expression has no loop-variant portions.
4870 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
4871 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
4872 if (OpAtScope != Comm->getOperand(i)) {
4873 // Okay, at least one of these operands is loop variant but might be
4874 // foldable. Build a new instance of the folded commutative expression.
4875 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4876 Comm->op_begin()+i);
4877 NewOps.push_back(OpAtScope);
4879 for (++i; i != e; ++i) {
4880 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
4881 NewOps.push_back(OpAtScope);
4883 if (isa<SCEVAddExpr>(Comm))
4884 return getAddExpr(NewOps);
4885 if (isa<SCEVMulExpr>(Comm))
4886 return getMulExpr(NewOps);
4887 if (isa<SCEVSMaxExpr>(Comm))
4888 return getSMaxExpr(NewOps);
4889 if (isa<SCEVUMaxExpr>(Comm))
4890 return getUMaxExpr(NewOps);
4891 llvm_unreachable("Unknown commutative SCEV type!");
4894 // If we got here, all operands are loop invariant.
4898 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
4899 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4900 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
4901 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4902 return Div; // must be loop invariant
4903 return getUDivExpr(LHS, RHS);
4906 // If this is a loop recurrence for a loop that does not contain L, then we
4907 // are dealing with the final value computed by the loop.
4908 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4909 // First, attempt to evaluate each operand.
4910 // Avoid performing the look-up in the common case where the specified
4911 // expression has no loop-variant portions.
4912 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4913 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
4914 if (OpAtScope == AddRec->getOperand(i))
4917 // Okay, at least one of these operands is loop variant but might be
4918 // foldable. Build a new instance of the folded commutative expression.
4919 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
4920 AddRec->op_begin()+i);
4921 NewOps.push_back(OpAtScope);
4922 for (++i; i != e; ++i)
4923 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
4925 const SCEV *FoldedRec =
4926 getAddRecExpr(NewOps, AddRec->getLoop(),
4927 AddRec->getNoWrapFlags(SCEV::FlagNW));
4928 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
4929 // The addrec may be folded to a nonrecurrence, for example, if the
4930 // induction variable is multiplied by zero after constant folding. Go
4931 // ahead and return the folded value.
4937 // If the scope is outside the addrec's loop, evaluate it by using the
4938 // loop exit value of the addrec.
4939 if (!AddRec->getLoop()->contains(L)) {
4940 // To evaluate this recurrence, we need to know how many times the AddRec
4941 // loop iterates. Compute this now.
4942 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
4943 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
4945 // Then, evaluate the AddRec.
4946 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
4952 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
4953 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4954 if (Op == Cast->getOperand())
4955 return Cast; // must be loop invariant
4956 return getZeroExtendExpr(Op, Cast->getType());
4959 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
4960 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4961 if (Op == Cast->getOperand())
4962 return Cast; // must be loop invariant
4963 return getSignExtendExpr(Op, Cast->getType());
4966 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
4967 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4968 if (Op == Cast->getOperand())
4969 return Cast; // must be loop invariant
4970 return getTruncateExpr(Op, Cast->getType());
4973 llvm_unreachable("Unknown SCEV type!");
4977 /// getSCEVAtScope - This is a convenience function which does
4978 /// getSCEVAtScope(getSCEV(V), L).
4979 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
4980 return getSCEVAtScope(getSCEV(V), L);
4983 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4984 /// following equation:
4986 /// A * X = B (mod N)
4988 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4989 /// A and B isn't important.
4991 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
4992 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
4993 ScalarEvolution &SE) {
4994 uint32_t BW = A.getBitWidth();
4995 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4996 assert(A != 0 && "A must be non-zero.");
5000 // The gcd of A and N may have only one prime factor: 2. The number of
5001 // trailing zeros in A is its multiplicity
5002 uint32_t Mult2 = A.countTrailingZeros();
5005 // 2. Check if B is divisible by D.
5007 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
5008 // is not less than multiplicity of this prime factor for D.
5009 if (B.countTrailingZeros() < Mult2)
5010 return SE.getCouldNotCompute();
5012 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
5015 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
5016 // bit width during computations.
5017 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
5018 APInt Mod(BW + 1, 0);
5019 Mod.setBit(BW - Mult2); // Mod = N / D
5020 APInt I = AD.multiplicativeInverse(Mod);
5022 // 4. Compute the minimum unsigned root of the equation:
5023 // I * (B / D) mod (N / D)
5024 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
5026 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
5028 return SE.getConstant(Result.trunc(BW));
5031 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
5032 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
5033 /// might be the same) or two SCEVCouldNotCompute objects.
5035 static std::pair<const SCEV *,const SCEV *>
5036 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
5037 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
5038 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
5039 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
5040 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
5042 // We currently can only solve this if the coefficients are constants.
5043 if (!LC || !MC || !NC) {
5044 const SCEV *CNC = SE.getCouldNotCompute();
5045 return std::make_pair(CNC, CNC);
5048 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
5049 const APInt &L = LC->getValue()->getValue();
5050 const APInt &M = MC->getValue()->getValue();
5051 const APInt &N = NC->getValue()->getValue();
5052 APInt Two(BitWidth, 2);
5053 APInt Four(BitWidth, 4);
5056 using namespace APIntOps;
5058 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
5059 // The B coefficient is M-N/2
5063 // The A coefficient is N/2
5064 APInt A(N.sdiv(Two));
5066 // Compute the B^2-4ac term.
5069 SqrtTerm -= Four * (A * C);
5071 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
5072 // integer value or else APInt::sqrt() will assert.
5073 APInt SqrtVal(SqrtTerm.sqrt());
5075 // Compute the two solutions for the quadratic formula.
5076 // The divisions must be performed as signed divisions.
5078 APInt TwoA( A << 1 );
5079 if (TwoA.isMinValue()) {
5080 const SCEV *CNC = SE.getCouldNotCompute();
5081 return std::make_pair(CNC, CNC);
5084 LLVMContext &Context = SE.getContext();
5086 ConstantInt *Solution1 =
5087 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
5088 ConstantInt *Solution2 =
5089 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
5091 return std::make_pair(SE.getConstant(Solution1),
5092 SE.getConstant(Solution2));
5093 } // end APIntOps namespace
5096 /// HowFarToZero - Return the number of times a backedge comparing the specified
5097 /// value to zero will execute. If not computable, return CouldNotCompute.
5099 /// This is only used for loops with a "x != y" exit test. The exit condition is
5100 /// now expressed as a single expression, V = x-y. So the exit test is
5101 /// effectively V != 0. We know and take advantage of the fact that this
5102 /// expression only being used in a comparison by zero context.
5103 ScalarEvolution::ExitLimit
5104 ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
5105 // If the value is a constant
5106 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
5107 // If the value is already zero, the branch will execute zero times.
5108 if (C->getValue()->isZero()) return C;
5109 return getCouldNotCompute(); // Otherwise it will loop infinitely.
5112 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
5113 if (!AddRec || AddRec->getLoop() != L)
5114 return getCouldNotCompute();
5116 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
5117 // the quadratic equation to solve it.
5118 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
5119 std::pair<const SCEV *,const SCEV *> Roots =
5120 SolveQuadraticEquation(AddRec, *this);
5121 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5122 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
5125 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
5126 << " sol#2: " << *R2 << "\n";
5128 // Pick the smallest positive root value.
5129 if (ConstantInt *CB =
5130 dyn_cast<ConstantInt>(ConstantExpr::getICmp(CmpInst::ICMP_ULT,
5133 if (CB->getZExtValue() == false)
5134 std::swap(R1, R2); // R1 is the minimum root now.
5136 // We can only use this value if the chrec ends up with an exact zero
5137 // value at this index. When solving for "X*X != 5", for example, we
5138 // should not accept a root of 2.
5139 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
5141 return R1; // We found a quadratic root!
5144 return getCouldNotCompute();
5147 // Otherwise we can only handle this if it is affine.
5148 if (!AddRec->isAffine())
5149 return getCouldNotCompute();
5151 // If this is an affine expression, the execution count of this branch is
5152 // the minimum unsigned root of the following equation:
5154 // Start + Step*N = 0 (mod 2^BW)
5158 // Step*N = -Start (mod 2^BW)
5160 // where BW is the common bit width of Start and Step.
5162 // Get the initial value for the loop.
5163 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
5164 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
5166 // For now we handle only constant steps.
5168 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
5169 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
5170 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
5171 // We have not yet seen any such cases.
5172 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
5174 return getCouldNotCompute();
5176 // For positive steps (counting up until unsigned overflow):
5177 // N = -Start/Step (as unsigned)
5178 // For negative steps (counting down to zero):
5180 // First compute the unsigned distance from zero in the direction of Step.
5181 bool CountDown = StepC->getValue()->getValue().isNegative();
5182 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
5184 // Handle unitary steps, which cannot wraparound.
5185 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
5186 // N = Distance (as unsigned)
5187 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
5188 ConstantRange CR = getUnsignedRange(Start);
5189 const SCEV *MaxBECount = getConstant(CountDown ? CR.getUnsignedMax()
5190 : ~CR.getUnsignedMin());
5191 return ExitLimit(Distance, MaxBECount);
5194 // If the recurrence is known not to wraparound, unsigned divide computes the
5195 // back edge count. We know that the value will either become zero (and thus
5196 // the loop terminates), that the loop will terminate through some other exit
5197 // condition first, or that the loop has undefined behavior. This means
5198 // we can't "miss" the exit value, even with nonunit stride.
5200 // FIXME: Prove that loops always exhibits *acceptable* undefined
5201 // behavior. Loops must exhibit defined behavior until a wrapped value is
5202 // actually used. So the trip count computed by udiv could be smaller than the
5203 // number of well-defined iterations.
5204 if (AddRec->getNoWrapFlags(SCEV::FlagNW))
5205 // FIXME: We really want an "isexact" bit for udiv.
5206 return getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
5208 // Then, try to solve the above equation provided that Start is constant.
5209 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
5210 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
5211 -StartC->getValue()->getValue(),
5213 return getCouldNotCompute();
5216 /// HowFarToNonZero - Return the number of times a backedge checking the
5217 /// specified value for nonzero will execute. If not computable, return
5219 ScalarEvolution::ExitLimit
5220 ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
5221 // Loops that look like: while (X == 0) are very strange indeed. We don't
5222 // handle them yet except for the trivial case. This could be expanded in the
5223 // future as needed.
5225 // If the value is a constant, check to see if it is known to be non-zero
5226 // already. If so, the backedge will execute zero times.
5227 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
5228 if (!C->getValue()->isNullValue())
5229 return getConstant(C->getType(), 0);
5230 return getCouldNotCompute(); // Otherwise it will loop infinitely.
5233 // We could implement others, but I really doubt anyone writes loops like
5234 // this, and if they did, they would already be constant folded.
5235 return getCouldNotCompute();
5238 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
5239 /// (which may not be an immediate predecessor) which has exactly one
5240 /// successor from which BB is reachable, or null if no such block is
5243 std::pair<BasicBlock *, BasicBlock *>
5244 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
5245 // If the block has a unique predecessor, then there is no path from the
5246 // predecessor to the block that does not go through the direct edge
5247 // from the predecessor to the block.
5248 if (BasicBlock *Pred = BB->getSinglePredecessor())
5249 return std::make_pair(Pred, BB);
5251 // A loop's header is defined to be a block that dominates the loop.
5252 // If the header has a unique predecessor outside the loop, it must be
5253 // a block that has exactly one successor that can reach the loop.
5254 if (Loop *L = LI->getLoopFor(BB))
5255 return std::make_pair(L->getLoopPredecessor(), L->getHeader());
5257 return std::pair<BasicBlock *, BasicBlock *>();
5260 /// HasSameValue - SCEV structural equivalence is usually sufficient for
5261 /// testing whether two expressions are equal, however for the purposes of
5262 /// looking for a condition guarding a loop, it can be useful to be a little
5263 /// more general, since a front-end may have replicated the controlling
5266 static bool HasSameValue(const SCEV *A, const SCEV *B) {
5267 // Quick check to see if they are the same SCEV.
5268 if (A == B) return true;
5270 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
5271 // two different instructions with the same value. Check for this case.
5272 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
5273 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
5274 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
5275 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
5276 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
5279 // Otherwise assume they may have a different value.
5283 /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
5284 /// predicate Pred. Return true iff any changes were made.
5286 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
5287 const SCEV *&LHS, const SCEV *&RHS) {
5288 bool Changed = false;
5290 // Canonicalize a constant to the right side.
5291 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
5292 // Check for both operands constant.
5293 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
5294 if (ConstantExpr::getICmp(Pred,
5296 RHSC->getValue())->isNullValue())
5297 goto trivially_false;
5299 goto trivially_true;
5301 // Otherwise swap the operands to put the constant on the right.
5302 std::swap(LHS, RHS);
5303 Pred = ICmpInst::getSwappedPredicate(Pred);
5307 // If we're comparing an addrec with a value which is loop-invariant in the
5308 // addrec's loop, put the addrec on the left. Also make a dominance check,
5309 // as both operands could be addrecs loop-invariant in each other's loop.
5310 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
5311 const Loop *L = AR->getLoop();
5312 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
5313 std::swap(LHS, RHS);
5314 Pred = ICmpInst::getSwappedPredicate(Pred);
5319 // If there's a constant operand, canonicalize comparisons with boundary
5320 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
5321 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
5322 const APInt &RA = RC->getValue()->getValue();
5324 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5325 case ICmpInst::ICMP_EQ:
5326 case ICmpInst::ICMP_NE:
5328 case ICmpInst::ICMP_UGE:
5329 if ((RA - 1).isMinValue()) {
5330 Pred = ICmpInst::ICMP_NE;
5331 RHS = getConstant(RA - 1);
5335 if (RA.isMaxValue()) {
5336 Pred = ICmpInst::ICMP_EQ;
5340 if (RA.isMinValue()) goto trivially_true;
5342 Pred = ICmpInst::ICMP_UGT;
5343 RHS = getConstant(RA - 1);
5346 case ICmpInst::ICMP_ULE:
5347 if ((RA + 1).isMaxValue()) {
5348 Pred = ICmpInst::ICMP_NE;
5349 RHS = getConstant(RA + 1);
5353 if (RA.isMinValue()) {
5354 Pred = ICmpInst::ICMP_EQ;
5358 if (RA.isMaxValue()) goto trivially_true;
5360 Pred = ICmpInst::ICMP_ULT;
5361 RHS = getConstant(RA + 1);
5364 case ICmpInst::ICMP_SGE:
5365 if ((RA - 1).isMinSignedValue()) {
5366 Pred = ICmpInst::ICMP_NE;
5367 RHS = getConstant(RA - 1);
5371 if (RA.isMaxSignedValue()) {
5372 Pred = ICmpInst::ICMP_EQ;
5376 if (RA.isMinSignedValue()) goto trivially_true;
5378 Pred = ICmpInst::ICMP_SGT;
5379 RHS = getConstant(RA - 1);
5382 case ICmpInst::ICMP_SLE:
5383 if ((RA + 1).isMaxSignedValue()) {
5384 Pred = ICmpInst::ICMP_NE;
5385 RHS = getConstant(RA + 1);
5389 if (RA.isMinSignedValue()) {
5390 Pred = ICmpInst::ICMP_EQ;
5394 if (RA.isMaxSignedValue()) goto trivially_true;
5396 Pred = ICmpInst::ICMP_SLT;
5397 RHS = getConstant(RA + 1);
5400 case ICmpInst::ICMP_UGT:
5401 if (RA.isMinValue()) {
5402 Pred = ICmpInst::ICMP_NE;
5406 if ((RA + 1).isMaxValue()) {
5407 Pred = ICmpInst::ICMP_EQ;
5408 RHS = getConstant(RA + 1);
5412 if (RA.isMaxValue()) goto trivially_false;
5414 case ICmpInst::ICMP_ULT:
5415 if (RA.isMaxValue()) {
5416 Pred = ICmpInst::ICMP_NE;
5420 if ((RA - 1).isMinValue()) {
5421 Pred = ICmpInst::ICMP_EQ;
5422 RHS = getConstant(RA - 1);
5426 if (RA.isMinValue()) goto trivially_false;
5428 case ICmpInst::ICMP_SGT:
5429 if (RA.isMinSignedValue()) {
5430 Pred = ICmpInst::ICMP_NE;
5434 if ((RA + 1).isMaxSignedValue()) {
5435 Pred = ICmpInst::ICMP_EQ;
5436 RHS = getConstant(RA + 1);
5440 if (RA.isMaxSignedValue()) goto trivially_false;
5442 case ICmpInst::ICMP_SLT:
5443 if (RA.isMaxSignedValue()) {
5444 Pred = ICmpInst::ICMP_NE;
5448 if ((RA - 1).isMinSignedValue()) {
5449 Pred = ICmpInst::ICMP_EQ;
5450 RHS = getConstant(RA - 1);
5454 if (RA.isMinSignedValue()) goto trivially_false;
5459 // Check for obvious equality.
5460 if (HasSameValue(LHS, RHS)) {
5461 if (ICmpInst::isTrueWhenEqual(Pred))
5462 goto trivially_true;
5463 if (ICmpInst::isFalseWhenEqual(Pred))
5464 goto trivially_false;
5467 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
5468 // adding or subtracting 1 from one of the operands.
5470 case ICmpInst::ICMP_SLE:
5471 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
5472 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
5474 Pred = ICmpInst::ICMP_SLT;
5476 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
5477 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
5479 Pred = ICmpInst::ICMP_SLT;
5483 case ICmpInst::ICMP_SGE:
5484 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
5485 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
5487 Pred = ICmpInst::ICMP_SGT;
5489 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
5490 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
5492 Pred = ICmpInst::ICMP_SGT;
5496 case ICmpInst::ICMP_ULE:
5497 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
5498 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
5500 Pred = ICmpInst::ICMP_ULT;
5502 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
5503 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
5505 Pred = ICmpInst::ICMP_ULT;
5509 case ICmpInst::ICMP_UGE:
5510 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
5511 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
5513 Pred = ICmpInst::ICMP_UGT;
5515 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
5516 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
5518 Pred = ICmpInst::ICMP_UGT;
5526 // TODO: More simplifications are possible here.
5532 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
5533 Pred = ICmpInst::ICMP_EQ;
5538 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
5539 Pred = ICmpInst::ICMP_NE;
5543 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
5544 return getSignedRange(S).getSignedMax().isNegative();
5547 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
5548 return getSignedRange(S).getSignedMin().isStrictlyPositive();
5551 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
5552 return !getSignedRange(S).getSignedMin().isNegative();
5555 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
5556 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
5559 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
5560 return isKnownNegative(S) || isKnownPositive(S);
5563 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
5564 const SCEV *LHS, const SCEV *RHS) {
5565 // Canonicalize the inputs first.
5566 (void)SimplifyICmpOperands(Pred, LHS, RHS);
5568 // If LHS or RHS is an addrec, check to see if the condition is true in
5569 // every iteration of the loop.
5570 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
5571 if (isLoopEntryGuardedByCond(
5572 AR->getLoop(), Pred, AR->getStart(), RHS) &&
5573 isLoopBackedgeGuardedByCond(
5574 AR->getLoop(), Pred, AR->getPostIncExpr(*this), RHS))
5576 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS))
5577 if (isLoopEntryGuardedByCond(
5578 AR->getLoop(), Pred, LHS, AR->getStart()) &&
5579 isLoopBackedgeGuardedByCond(
5580 AR->getLoop(), Pred, LHS, AR->getPostIncExpr(*this)))
5583 // Otherwise see what can be done with known constant ranges.
5584 return isKnownPredicateWithRanges(Pred, LHS, RHS);
5588 ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
5589 const SCEV *LHS, const SCEV *RHS) {
5590 if (HasSameValue(LHS, RHS))
5591 return ICmpInst::isTrueWhenEqual(Pred);
5593 // This code is split out from isKnownPredicate because it is called from
5594 // within isLoopEntryGuardedByCond.
5597 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5599 case ICmpInst::ICMP_SGT:
5600 Pred = ICmpInst::ICMP_SLT;
5601 std::swap(LHS, RHS);
5602 case ICmpInst::ICMP_SLT: {
5603 ConstantRange LHSRange = getSignedRange(LHS);
5604 ConstantRange RHSRange = getSignedRange(RHS);
5605 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
5607 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
5611 case ICmpInst::ICMP_SGE:
5612 Pred = ICmpInst::ICMP_SLE;
5613 std::swap(LHS, RHS);
5614 case ICmpInst::ICMP_SLE: {
5615 ConstantRange LHSRange = getSignedRange(LHS);
5616 ConstantRange RHSRange = getSignedRange(RHS);
5617 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
5619 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
5623 case ICmpInst::ICMP_UGT:
5624 Pred = ICmpInst::ICMP_ULT;
5625 std::swap(LHS, RHS);
5626 case ICmpInst::ICMP_ULT: {
5627 ConstantRange LHSRange = getUnsignedRange(LHS);
5628 ConstantRange RHSRange = getUnsignedRange(RHS);
5629 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
5631 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
5635 case ICmpInst::ICMP_UGE:
5636 Pred = ICmpInst::ICMP_ULE;
5637 std::swap(LHS, RHS);
5638 case ICmpInst::ICMP_ULE: {
5639 ConstantRange LHSRange = getUnsignedRange(LHS);
5640 ConstantRange RHSRange = getUnsignedRange(RHS);
5641 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
5643 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
5647 case ICmpInst::ICMP_NE: {
5648 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
5650 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
5653 const SCEV *Diff = getMinusSCEV(LHS, RHS);
5654 if (isKnownNonZero(Diff))
5658 case ICmpInst::ICMP_EQ:
5659 // The check at the top of the function catches the case where
5660 // the values are known to be equal.
5666 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
5667 /// protected by a conditional between LHS and RHS. This is used to
5668 /// to eliminate casts.
5670 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
5671 ICmpInst::Predicate Pred,
5672 const SCEV *LHS, const SCEV *RHS) {
5673 // Interpret a null as meaning no loop, where there is obviously no guard
5674 // (interprocedural conditions notwithstanding).
5675 if (!L) return true;
5677 BasicBlock *Latch = L->getLoopLatch();
5681 BranchInst *LoopContinuePredicate =
5682 dyn_cast<BranchInst>(Latch->getTerminator());
5683 if (!LoopContinuePredicate ||
5684 LoopContinuePredicate->isUnconditional())
5687 return isImpliedCond(Pred, LHS, RHS,
5688 LoopContinuePredicate->getCondition(),
5689 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
5692 /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
5693 /// by a conditional between LHS and RHS. This is used to help avoid max
5694 /// expressions in loop trip counts, and to eliminate casts.
5696 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
5697 ICmpInst::Predicate Pred,
5698 const SCEV *LHS, const SCEV *RHS) {
5699 // Interpret a null as meaning no loop, where there is obviously no guard
5700 // (interprocedural conditions notwithstanding).
5701 if (!L) return false;
5703 // Starting at the loop predecessor, climb up the predecessor chain, as long
5704 // as there are predecessors that can be found that have unique successors
5705 // leading to the original header.
5706 for (std::pair<BasicBlock *, BasicBlock *>
5707 Pair(L->getLoopPredecessor(), L->getHeader());
5709 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
5711 BranchInst *LoopEntryPredicate =
5712 dyn_cast<BranchInst>(Pair.first->getTerminator());
5713 if (!LoopEntryPredicate ||
5714 LoopEntryPredicate->isUnconditional())
5717 if (isImpliedCond(Pred, LHS, RHS,
5718 LoopEntryPredicate->getCondition(),
5719 LoopEntryPredicate->getSuccessor(0) != Pair.second))
5726 /// isImpliedCond - Test whether the condition described by Pred, LHS,
5727 /// and RHS is true whenever the given Cond value evaluates to true.
5728 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
5729 const SCEV *LHS, const SCEV *RHS,
5730 Value *FoundCondValue,
5732 // Recursively handle And and Or conditions.
5733 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
5734 if (BO->getOpcode() == Instruction::And) {
5736 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5737 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
5738 } else if (BO->getOpcode() == Instruction::Or) {
5740 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5741 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
5745 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
5746 if (!ICI) return false;
5748 // Bail if the ICmp's operands' types are wider than the needed type
5749 // before attempting to call getSCEV on them. This avoids infinite
5750 // recursion, since the analysis of widening casts can require loop
5751 // exit condition information for overflow checking, which would
5753 if (getTypeSizeInBits(LHS->getType()) <
5754 getTypeSizeInBits(ICI->getOperand(0)->getType()))
5757 // Now that we found a conditional branch that dominates the loop, check to
5758 // see if it is the comparison we are looking for.
5759 ICmpInst::Predicate FoundPred;
5761 FoundPred = ICI->getInversePredicate();
5763 FoundPred = ICI->getPredicate();
5765 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
5766 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
5768 // Balance the types. The case where FoundLHS' type is wider than
5769 // LHS' type is checked for above.
5770 if (getTypeSizeInBits(LHS->getType()) >
5771 getTypeSizeInBits(FoundLHS->getType())) {
5772 if (CmpInst::isSigned(Pred)) {
5773 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
5774 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
5776 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
5777 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
5781 // Canonicalize the query to match the way instcombine will have
5782 // canonicalized the comparison.
5783 if (SimplifyICmpOperands(Pred, LHS, RHS))
5785 return CmpInst::isTrueWhenEqual(Pred);
5786 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
5787 if (FoundLHS == FoundRHS)
5788 return CmpInst::isFalseWhenEqual(Pred);
5790 // Check to see if we can make the LHS or RHS match.
5791 if (LHS == FoundRHS || RHS == FoundLHS) {
5792 if (isa<SCEVConstant>(RHS)) {
5793 std::swap(FoundLHS, FoundRHS);
5794 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
5796 std::swap(LHS, RHS);
5797 Pred = ICmpInst::getSwappedPredicate(Pred);
5801 // Check whether the found predicate is the same as the desired predicate.
5802 if (FoundPred == Pred)
5803 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
5805 // Check whether swapping the found predicate makes it the same as the
5806 // desired predicate.
5807 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
5808 if (isa<SCEVConstant>(RHS))
5809 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
5811 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
5812 RHS, LHS, FoundLHS, FoundRHS);
5815 // Check whether the actual condition is beyond sufficient.
5816 if (FoundPred == ICmpInst::ICMP_EQ)
5817 if (ICmpInst::isTrueWhenEqual(Pred))
5818 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
5820 if (Pred == ICmpInst::ICMP_NE)
5821 if (!ICmpInst::isTrueWhenEqual(FoundPred))
5822 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
5825 // Otherwise assume the worst.
5829 /// isImpliedCondOperands - Test whether the condition described by Pred,
5830 /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
5831 /// and FoundRHS is true.
5832 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
5833 const SCEV *LHS, const SCEV *RHS,
5834 const SCEV *FoundLHS,
5835 const SCEV *FoundRHS) {
5836 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
5837 FoundLHS, FoundRHS) ||
5838 // ~x < ~y --> x > y
5839 isImpliedCondOperandsHelper(Pred, LHS, RHS,
5840 getNotSCEV(FoundRHS),
5841 getNotSCEV(FoundLHS));
5844 /// isImpliedCondOperandsHelper - Test whether the condition described by
5845 /// Pred, LHS, and RHS is true whenever the condition described by Pred,
5846 /// FoundLHS, and FoundRHS is true.
5848 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
5849 const SCEV *LHS, const SCEV *RHS,
5850 const SCEV *FoundLHS,
5851 const SCEV *FoundRHS) {
5853 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5854 case ICmpInst::ICMP_EQ:
5855 case ICmpInst::ICMP_NE:
5856 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
5859 case ICmpInst::ICMP_SLT:
5860 case ICmpInst::ICMP_SLE:
5861 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
5862 isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS))
5865 case ICmpInst::ICMP_SGT:
5866 case ICmpInst::ICMP_SGE:
5867 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
5868 isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS))
5871 case ICmpInst::ICMP_ULT:
5872 case ICmpInst::ICMP_ULE:
5873 if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
5874 isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS))
5877 case ICmpInst::ICMP_UGT:
5878 case ICmpInst::ICMP_UGE:
5879 if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
5880 isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS))
5888 /// getBECount - Subtract the end and start values and divide by the step,
5889 /// rounding up, to get the number of times the backedge is executed. Return
5890 /// CouldNotCompute if an intermediate computation overflows.
5891 const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
5895 assert(!isKnownNegative(Step) &&
5896 "This code doesn't handle negative strides yet!");
5898 Type *Ty = Start->getType();
5900 // When Start == End, we have an exact BECount == 0. Short-circuit this case
5901 // here because SCEV may not be able to determine that the unsigned division
5902 // after rounding is zero.
5904 return getConstant(Ty, 0);
5906 const SCEV *NegOne = getConstant(Ty, (uint64_t)-1);
5907 const SCEV *Diff = getMinusSCEV(End, Start);
5908 const SCEV *RoundUp = getAddExpr(Step, NegOne);
5910 // Add an adjustment to the difference between End and Start so that
5911 // the division will effectively round up.
5912 const SCEV *Add = getAddExpr(Diff, RoundUp);
5915 // Check Add for unsigned overflow.
5916 // TODO: More sophisticated things could be done here.
5917 Type *WideTy = IntegerType::get(getContext(),
5918 getTypeSizeInBits(Ty) + 1);
5919 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
5920 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
5921 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
5922 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
5923 return getCouldNotCompute();
5926 return getUDivExpr(Add, Step);
5929 /// HowManyLessThans - Return the number of times a backedge containing the
5930 /// specified less-than comparison will execute. If not computable, return
5931 /// CouldNotCompute.
5932 ScalarEvolution::ExitLimit
5933 ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
5934 const Loop *L, bool isSigned) {
5935 // Only handle: "ADDREC < LoopInvariant".
5936 if (!isLoopInvariant(RHS, L)) return getCouldNotCompute();
5938 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
5939 if (!AddRec || AddRec->getLoop() != L)
5940 return getCouldNotCompute();
5942 // Check to see if we have a flag which makes analysis easy.
5943 bool NoWrap = isSigned ? AddRec->getNoWrapFlags(SCEV::FlagNSW) :
5944 AddRec->getNoWrapFlags(SCEV::FlagNUW);
5946 if (AddRec->isAffine()) {
5947 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
5948 const SCEV *Step = AddRec->getStepRecurrence(*this);
5951 return getCouldNotCompute();
5952 if (Step->isOne()) {
5953 // With unit stride, the iteration never steps past the limit value.
5954 } else if (isKnownPositive(Step)) {
5955 // Test whether a positive iteration can step past the limit
5956 // value and past the maximum value for its type in a single step.
5957 // Note that it's not sufficient to check NoWrap here, because even
5958 // though the value after a wrap is undefined, it's not undefined
5959 // behavior, so if wrap does occur, the loop could either terminate or
5960 // loop infinitely, but in either case, the loop is guaranteed to
5961 // iterate at least until the iteration where the wrapping occurs.
5962 const SCEV *One = getConstant(Step->getType(), 1);
5964 APInt Max = APInt::getSignedMaxValue(BitWidth);
5965 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
5966 .slt(getSignedRange(RHS).getSignedMax()))
5967 return getCouldNotCompute();
5969 APInt Max = APInt::getMaxValue(BitWidth);
5970 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
5971 .ult(getUnsignedRange(RHS).getUnsignedMax()))
5972 return getCouldNotCompute();
5975 // TODO: Handle negative strides here and below.
5976 return getCouldNotCompute();
5978 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
5979 // m. So, we count the number of iterations in which {n,+,s} < m is true.
5980 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
5981 // treat m-n as signed nor unsigned due to overflow possibility.
5983 // First, we get the value of the LHS in the first iteration: n
5984 const SCEV *Start = AddRec->getOperand(0);
5986 // Determine the minimum constant start value.
5987 const SCEV *MinStart = getConstant(isSigned ?
5988 getSignedRange(Start).getSignedMin() :
5989 getUnsignedRange(Start).getUnsignedMin());
5991 // If we know that the condition is true in order to enter the loop,
5992 // then we know that it will run exactly (m-n)/s times. Otherwise, we
5993 // only know that it will execute (max(m,n)-n)/s times. In both cases,
5994 // the division must round up.
5995 const SCEV *End = RHS;
5996 if (!isLoopEntryGuardedByCond(L,
5997 isSigned ? ICmpInst::ICMP_SLT :
5999 getMinusSCEV(Start, Step), RHS))
6000 End = isSigned ? getSMaxExpr(RHS, Start)
6001 : getUMaxExpr(RHS, Start);
6003 // Determine the maximum constant end value.
6004 const SCEV *MaxEnd = getConstant(isSigned ?
6005 getSignedRange(End).getSignedMax() :
6006 getUnsignedRange(End).getUnsignedMax());
6008 // If MaxEnd is within a step of the maximum integer value in its type,
6009 // adjust it down to the minimum value which would produce the same effect.
6010 // This allows the subsequent ceiling division of (N+(step-1))/step to
6011 // compute the correct value.
6012 const SCEV *StepMinusOne = getMinusSCEV(Step,
6013 getConstant(Step->getType(), 1));
6016 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
6019 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
6022 // Finally, we subtract these two values and divide, rounding up, to get
6023 // the number of times the backedge is executed.
6024 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
6026 // The maximum backedge count is similar, except using the minimum start
6027 // value and the maximum end value.
6028 // If we already have an exact constant BECount, use it instead.
6029 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) ? BECount
6030 : getBECount(MinStart, MaxEnd, Step, NoWrap);
6032 // If the stride is nonconstant, and NoWrap == true, then
6033 // getBECount(MinStart, MaxEnd) may not compute. This would result in an
6034 // exact BECount and invalid MaxBECount, which should be avoided to catch
6035 // more optimization opportunities.
6036 if (isa<SCEVCouldNotCompute>(MaxBECount))
6037 MaxBECount = BECount;
6039 return ExitLimit(BECount, MaxBECount);
6042 return getCouldNotCompute();
6045 /// getNumIterationsInRange - Return the number of iterations of this loop that
6046 /// produce values in the specified constant range. Another way of looking at
6047 /// this is that it returns the first iteration number where the value is not in
6048 /// the condition, thus computing the exit count. If the iteration count can't
6049 /// be computed, an instance of SCEVCouldNotCompute is returned.
6050 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
6051 ScalarEvolution &SE) const {
6052 if (Range.isFullSet()) // Infinite loop.
6053 return SE.getCouldNotCompute();
6055 // If the start is a non-zero constant, shift the range to simplify things.
6056 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
6057 if (!SC->getValue()->isZero()) {
6058 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
6059 Operands[0] = SE.getConstant(SC->getType(), 0);
6060 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
6061 getNoWrapFlags(FlagNW));
6062 if (const SCEVAddRecExpr *ShiftedAddRec =
6063 dyn_cast<SCEVAddRecExpr>(Shifted))
6064 return ShiftedAddRec->getNumIterationsInRange(
6065 Range.subtract(SC->getValue()->getValue()), SE);
6066 // This is strange and shouldn't happen.
6067 return SE.getCouldNotCompute();
6070 // The only time we can solve this is when we have all constant indices.
6071 // Otherwise, we cannot determine the overflow conditions.
6072 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
6073 if (!isa<SCEVConstant>(getOperand(i)))
6074 return SE.getCouldNotCompute();
6077 // Okay at this point we know that all elements of the chrec are constants and
6078 // that the start element is zero.
6080 // First check to see if the range contains zero. If not, the first
6082 unsigned BitWidth = SE.getTypeSizeInBits(getType());
6083 if (!Range.contains(APInt(BitWidth, 0)))
6084 return SE.getConstant(getType(), 0);
6087 // If this is an affine expression then we have this situation:
6088 // Solve {0,+,A} in Range === Ax in Range
6090 // We know that zero is in the range. If A is positive then we know that
6091 // the upper value of the range must be the first possible exit value.
6092 // If A is negative then the lower of the range is the last possible loop
6093 // value. Also note that we already checked for a full range.
6094 APInt One(BitWidth,1);
6095 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
6096 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
6098 // The exit value should be (End+A)/A.
6099 APInt ExitVal = (End + A).udiv(A);
6100 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
6102 // Evaluate at the exit value. If we really did fall out of the valid
6103 // range, then we computed our trip count, otherwise wrap around or other
6104 // things must have happened.
6105 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
6106 if (Range.contains(Val->getValue()))
6107 return SE.getCouldNotCompute(); // Something strange happened
6109 // Ensure that the previous value is in the range. This is a sanity check.
6110 assert(Range.contains(
6111 EvaluateConstantChrecAtConstant(this,
6112 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
6113 "Linear scev computation is off in a bad way!");
6114 return SE.getConstant(ExitValue);
6115 } else if (isQuadratic()) {
6116 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
6117 // quadratic equation to solve it. To do this, we must frame our problem in
6118 // terms of figuring out when zero is crossed, instead of when
6119 // Range.getUpper() is crossed.
6120 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
6121 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
6122 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(),
6123 // getNoWrapFlags(FlagNW)
6126 // Next, solve the constructed addrec
6127 std::pair<const SCEV *,const SCEV *> Roots =
6128 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
6129 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
6130 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
6132 // Pick the smallest positive root value.
6133 if (ConstantInt *CB =
6134 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
6135 R1->getValue(), R2->getValue()))) {
6136 if (CB->getZExtValue() == false)
6137 std::swap(R1, R2); // R1 is the minimum root now.
6139 // Make sure the root is not off by one. The returned iteration should
6140 // not be in the range, but the previous one should be. When solving
6141 // for "X*X < 5", for example, we should not return a root of 2.
6142 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
6145 if (Range.contains(R1Val->getValue())) {
6146 // The next iteration must be out of the range...
6147 ConstantInt *NextVal =
6148 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
6150 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
6151 if (!Range.contains(R1Val->getValue()))
6152 return SE.getConstant(NextVal);
6153 return SE.getCouldNotCompute(); // Something strange happened
6156 // If R1 was not in the range, then it is a good return value. Make
6157 // sure that R1-1 WAS in the range though, just in case.
6158 ConstantInt *NextVal =
6159 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
6160 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
6161 if (Range.contains(R1Val->getValue()))
6163 return SE.getCouldNotCompute(); // Something strange happened
6168 return SE.getCouldNotCompute();
6173 //===----------------------------------------------------------------------===//
6174 // SCEVCallbackVH Class Implementation
6175 //===----------------------------------------------------------------------===//
6177 void ScalarEvolution::SCEVCallbackVH::deleted() {
6178 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
6179 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
6180 SE->ConstantEvolutionLoopExitValue.erase(PN);
6181 SE->ValueExprMap.erase(getValPtr());
6182 // this now dangles!
6185 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
6186 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
6188 // Forget all the expressions associated with users of the old value,
6189 // so that future queries will recompute the expressions using the new
6191 Value *Old = getValPtr();
6192 SmallVector<User *, 16> Worklist;
6193 SmallPtrSet<User *, 8> Visited;
6194 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
6196 Worklist.push_back(*UI);
6197 while (!Worklist.empty()) {
6198 User *U = Worklist.pop_back_val();
6199 // Deleting the Old value will cause this to dangle. Postpone
6200 // that until everything else is done.
6203 if (!Visited.insert(U))
6205 if (PHINode *PN = dyn_cast<PHINode>(U))
6206 SE->ConstantEvolutionLoopExitValue.erase(PN);
6207 SE->ValueExprMap.erase(U);
6208 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
6210 Worklist.push_back(*UI);
6212 // Delete the Old value.
6213 if (PHINode *PN = dyn_cast<PHINode>(Old))
6214 SE->ConstantEvolutionLoopExitValue.erase(PN);
6215 SE->ValueExprMap.erase(Old);
6216 // this now dangles!
6219 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
6220 : CallbackVH(V), SE(se) {}
6222 //===----------------------------------------------------------------------===//
6223 // ScalarEvolution Class Implementation
6224 //===----------------------------------------------------------------------===//
6226 ScalarEvolution::ScalarEvolution()
6227 : FunctionPass(ID), FirstUnknown(0) {
6228 initializeScalarEvolutionPass(*PassRegistry::getPassRegistry());
6231 bool ScalarEvolution::runOnFunction(Function &F) {
6233 LI = &getAnalysis<LoopInfo>();
6234 TD = getAnalysisIfAvailable<TargetData>();
6235 DT = &getAnalysis<DominatorTree>();
6239 void ScalarEvolution::releaseMemory() {
6240 // Iterate through all the SCEVUnknown instances and call their
6241 // destructors, so that they release their references to their values.
6242 for (SCEVUnknown *U = FirstUnknown; U; U = U->Next)
6246 ValueExprMap.clear();
6248 // Free any extra memory created for ExitNotTakenInfo in the unlikely event
6249 // that a loop had multiple computable exits.
6250 for (DenseMap<const Loop*, BackedgeTakenInfo>::iterator I =
6251 BackedgeTakenCounts.begin(), E = BackedgeTakenCounts.end();
6256 BackedgeTakenCounts.clear();
6257 ConstantEvolutionLoopExitValue.clear();
6258 ValuesAtScopes.clear();
6259 LoopDispositions.clear();
6260 BlockDispositions.clear();
6261 UnsignedRanges.clear();
6262 SignedRanges.clear();
6263 UniqueSCEVs.clear();
6264 SCEVAllocator.Reset();
6267 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
6268 AU.setPreservesAll();
6269 AU.addRequiredTransitive<LoopInfo>();
6270 AU.addRequiredTransitive<DominatorTree>();
6273 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
6274 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
6277 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
6279 // Print all inner loops first
6280 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
6281 PrintLoopInfo(OS, SE, *I);
6284 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
6287 SmallVector<BasicBlock *, 8> ExitBlocks;
6288 L->getExitBlocks(ExitBlocks);
6289 if (ExitBlocks.size() != 1)
6290 OS << "<multiple exits> ";
6292 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
6293 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
6295 OS << "Unpredictable backedge-taken count. ";
6300 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
6303 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
6304 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
6306 OS << "Unpredictable max backedge-taken count. ";
6312 void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
6313 // ScalarEvolution's implementation of the print method is to print
6314 // out SCEV values of all instructions that are interesting. Doing
6315 // this potentially causes it to create new SCEV objects though,
6316 // which technically conflicts with the const qualifier. This isn't
6317 // observable from outside the class though, so casting away the
6318 // const isn't dangerous.
6319 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
6321 OS << "Classifying expressions for: ";
6322 WriteAsOperand(OS, F, /*PrintType=*/false);
6324 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
6325 if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) {
6328 const SCEV *SV = SE.getSCEV(&*I);
6331 const Loop *L = LI->getLoopFor((*I).getParent());
6333 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
6340 OS << "\t\t" "Exits: ";
6341 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
6342 if (!SE.isLoopInvariant(ExitValue, L)) {
6343 OS << "<<Unknown>>";
6352 OS << "Determining loop execution counts for: ";
6353 WriteAsOperand(OS, F, /*PrintType=*/false);
6355 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
6356 PrintLoopInfo(OS, &SE, *I);
6359 ScalarEvolution::LoopDisposition
6360 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
6361 std::map<const Loop *, LoopDisposition> &Values = LoopDispositions[S];
6362 std::pair<std::map<const Loop *, LoopDisposition>::iterator, bool> Pair =
6363 Values.insert(std::make_pair(L, LoopVariant));
6365 return Pair.first->second;
6367 LoopDisposition D = computeLoopDisposition(S, L);
6368 return LoopDispositions[S][L] = D;
6371 ScalarEvolution::LoopDisposition
6372 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
6373 switch (S->getSCEVType()) {
6375 return LoopInvariant;
6379 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
6380 case scAddRecExpr: {
6381 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
6383 // If L is the addrec's loop, it's computable.
6384 if (AR->getLoop() == L)
6385 return LoopComputable;
6387 // Add recurrences are never invariant in the function-body (null loop).
6391 // This recurrence is variant w.r.t. L if L contains AR's loop.
6392 if (L->contains(AR->getLoop()))
6395 // This recurrence is invariant w.r.t. L if AR's loop contains L.
6396 if (AR->getLoop()->contains(L))
6397 return LoopInvariant;
6399 // This recurrence is variant w.r.t. L if any of its operands
6401 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
6403 if (!isLoopInvariant(*I, L))
6406 // Otherwise it's loop-invariant.
6407 return LoopInvariant;
6413 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
6414 bool HasVarying = false;
6415 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
6417 LoopDisposition D = getLoopDisposition(*I, L);
6418 if (D == LoopVariant)
6420 if (D == LoopComputable)
6423 return HasVarying ? LoopComputable : LoopInvariant;
6426 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6427 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
6428 if (LD == LoopVariant)
6430 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
6431 if (RD == LoopVariant)
6433 return (LD == LoopInvariant && RD == LoopInvariant) ?
6434 LoopInvariant : LoopComputable;
6437 // All non-instruction values are loop invariant. All instructions are loop
6438 // invariant if they are not contained in the specified loop.
6439 // Instructions are never considered invariant in the function body
6440 // (null loop) because they are defined within the "loop".
6441 if (Instruction *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
6442 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
6443 return LoopInvariant;
6444 case scCouldNotCompute:
6445 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6449 llvm_unreachable("Unknown SCEV kind!");
6453 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
6454 return getLoopDisposition(S, L) == LoopInvariant;
6457 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
6458 return getLoopDisposition(S, L) == LoopComputable;
6461 ScalarEvolution::BlockDisposition
6462 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
6463 std::map<const BasicBlock *, BlockDisposition> &Values = BlockDispositions[S];
6464 std::pair<std::map<const BasicBlock *, BlockDisposition>::iterator, bool>
6465 Pair = Values.insert(std::make_pair(BB, DoesNotDominateBlock));
6467 return Pair.first->second;
6469 BlockDisposition D = computeBlockDisposition(S, BB);
6470 return BlockDispositions[S][BB] = D;
6473 ScalarEvolution::BlockDisposition
6474 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
6475 switch (S->getSCEVType()) {
6477 return ProperlyDominatesBlock;
6481 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
6482 case scAddRecExpr: {
6483 // This uses a "dominates" query instead of "properly dominates" query
6484 // to test for proper dominance too, because the instruction which
6485 // produces the addrec's value is a PHI, and a PHI effectively properly
6486 // dominates its entire containing block.
6487 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
6488 if (!DT->dominates(AR->getLoop()->getHeader(), BB))
6489 return DoesNotDominateBlock;
6491 // FALL THROUGH into SCEVNAryExpr handling.
6496 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
6498 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
6500 BlockDisposition D = getBlockDisposition(*I, BB);
6501 if (D == DoesNotDominateBlock)
6502 return DoesNotDominateBlock;
6503 if (D == DominatesBlock)
6506 return Proper ? ProperlyDominatesBlock : DominatesBlock;
6509 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6510 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
6511 BlockDisposition LD = getBlockDisposition(LHS, BB);
6512 if (LD == DoesNotDominateBlock)
6513 return DoesNotDominateBlock;
6514 BlockDisposition RD = getBlockDisposition(RHS, BB);
6515 if (RD == DoesNotDominateBlock)
6516 return DoesNotDominateBlock;
6517 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
6518 ProperlyDominatesBlock : DominatesBlock;
6521 if (Instruction *I =
6522 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
6523 if (I->getParent() == BB)
6524 return DominatesBlock;
6525 if (DT->properlyDominates(I->getParent(), BB))
6526 return ProperlyDominatesBlock;
6527 return DoesNotDominateBlock;
6529 return ProperlyDominatesBlock;
6530 case scCouldNotCompute:
6531 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6532 return DoesNotDominateBlock;
6535 llvm_unreachable("Unknown SCEV kind!");
6536 return DoesNotDominateBlock;
6539 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
6540 return getBlockDisposition(S, BB) >= DominatesBlock;
6543 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
6544 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
6547 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
6548 switch (S->getSCEVType()) {
6553 case scSignExtend: {
6554 const SCEVCastExpr *Cast = cast<SCEVCastExpr>(S);
6555 const SCEV *CastOp = Cast->getOperand();
6556 return Op == CastOp || hasOperand(CastOp, Op);
6563 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
6564 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
6566 const SCEV *NAryOp = *I;
6567 if (NAryOp == Op || hasOperand(NAryOp, Op))
6573 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6574 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
6575 return LHS == Op || hasOperand(LHS, Op) ||
6576 RHS == Op || hasOperand(RHS, Op);
6580 case scCouldNotCompute:
6581 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6585 llvm_unreachable("Unknown SCEV kind!");
6589 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
6590 ValuesAtScopes.erase(S);
6591 LoopDispositions.erase(S);
6592 BlockDispositions.erase(S);
6593 UnsignedRanges.erase(S);
6594 SignedRanges.erase(S);