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 const 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(const Type *Ty, uint64_t V, bool isSigned) {
301 const 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, const Type *ty)
307 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
309 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
310 const SCEV *op, const 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, const 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, const 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(const 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(const 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 (const 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(const 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,
655 const Type* ResultTy) {
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 const 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 // FIXME: Can use SCEV::FlagNUW
936 L, SCEV::FlagAnyWrap);
938 // Check whether the backedge-taken count is SCEVCouldNotCompute.
939 // Note that this serves two purposes: It filters out loops that are
940 // simply not analyzable, and it covers the case where this code is
941 // being called from within backedge-taken count analysis, such that
942 // attempting to ask for the backedge-taken count would likely result
943 // in infinite recursion. In the later case, the analysis code will
944 // cope with a conservative value, and it will take care to purge
945 // that value once it has finished.
946 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
947 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
948 // Manually compute the final value for AR, checking for
951 // Check whether the backedge-taken count can be losslessly casted to
952 // the addrec's type. The count is always unsigned.
953 const SCEV *CastedMaxBECount =
954 getTruncateOrZeroExtend(MaxBECount, Start->getType());
955 const SCEV *RecastedMaxBECount =
956 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
957 if (MaxBECount == RecastedMaxBECount) {
958 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
959 // Check whether Start+Step*MaxBECount has no unsigned overflow.
960 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
961 const SCEV *Add = getAddExpr(Start, ZMul);
962 const SCEV *OperandExtendedAdd =
963 getAddExpr(getZeroExtendExpr(Start, WideTy),
964 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
965 getZeroExtendExpr(Step, WideTy)));
966 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
967 // Return the expression with the addrec on the outside.
968 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
969 getZeroExtendExpr(Step, Ty),
970 // FIXME: can use FlagNUW
971 L, SCEV::FlagAnyWrap);
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 // Return the expression with the addrec on the outside.
983 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
984 getSignExtendExpr(Step, Ty),
985 // FIXME: can use FlagNW
986 L, SCEV::FlagAnyWrap);
989 // If the backedge is guarded by a comparison with the pre-inc value
990 // the addrec is safe. Also, if the entry is guarded by a comparison
991 // with the start value and the backedge is guarded by a comparison
992 // with the post-inc value, the addrec is safe.
993 if (isKnownPositive(Step)) {
994 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
995 getUnsignedRange(Step).getUnsignedMax());
996 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
997 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
998 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
999 AR->getPostIncExpr(*this), N)))
1000 // Return the expression with the addrec on the outside.
1001 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1002 getZeroExtendExpr(Step, Ty),
1003 // FIXME: can use FlagNUW
1004 L, SCEV::FlagAnyWrap);
1005 } else if (isKnownNegative(Step)) {
1006 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1007 getSignedRange(Step).getSignedMin());
1008 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1009 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
1010 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1011 AR->getPostIncExpr(*this), N)))
1012 // Return the expression with the addrec on the outside. The
1013 // negative step causes unsigned wrap, but it still can't self-wrap.
1014 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1015 getSignExtendExpr(Step, Ty),
1016 // FIXME: can use FlagNW
1017 L, SCEV::FlagAnyWrap);
1022 // The cast wasn't folded; create an explicit cast node.
1023 // Recompute the insert position, as it may have been invalidated.
1024 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1025 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1027 UniqueSCEVs.InsertNode(S, IP);
1031 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
1033 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1034 "This is not an extending conversion!");
1035 assert(isSCEVable(Ty) &&
1036 "This is not a conversion to a SCEVable type!");
1037 Ty = getEffectiveSCEVType(Ty);
1039 // Fold if the operand is constant.
1040 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1042 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(),
1043 getEffectiveSCEVType(Ty))));
1045 // sext(sext(x)) --> sext(x)
1046 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1047 return getSignExtendExpr(SS->getOperand(), Ty);
1049 // sext(zext(x)) --> zext(x)
1050 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1051 return getZeroExtendExpr(SZ->getOperand(), Ty);
1053 // Before doing any expensive analysis, check to see if we've already
1054 // computed a SCEV for this Op and Ty.
1055 FoldingSetNodeID ID;
1056 ID.AddInteger(scSignExtend);
1060 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1062 // If the input value is provably positive, build a zext instead.
1063 if (isKnownNonNegative(Op))
1064 return getZeroExtendExpr(Op, Ty);
1066 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1067 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1068 // It's possible the bits taken off by the truncate were all sign bits. If
1069 // so, we should be able to simplify this further.
1070 const SCEV *X = ST->getOperand();
1071 ConstantRange CR = getSignedRange(X);
1072 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1073 unsigned NewBits = getTypeSizeInBits(Ty);
1074 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1075 CR.sextOrTrunc(NewBits)))
1076 return getTruncateOrSignExtend(X, Ty);
1079 // If the input value is a chrec scev, and we can prove that the value
1080 // did not overflow the old, smaller, value, we can sign extend all of the
1081 // operands (often constants). This allows analysis of something like
1082 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1083 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1084 if (AR->isAffine()) {
1085 const SCEV *Start = AR->getStart();
1086 const SCEV *Step = AR->getStepRecurrence(*this);
1087 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1088 const Loop *L = AR->getLoop();
1090 // If we have special knowledge that this addrec won't overflow,
1091 // we don't need to do any further analysis.
1092 if (AR->getNoWrapFlags(SCEV::FlagNSW))
1093 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1094 getSignExtendExpr(Step, Ty),
1095 // FIXME: can use SCEV::FlagNSW
1096 L, SCEV::FlagAnyWrap);
1098 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1099 // Note that this serves two purposes: It filters out loops that are
1100 // simply not analyzable, and it covers the case where this code is
1101 // being called from within backedge-taken count analysis, such that
1102 // attempting to ask for the backedge-taken count would likely result
1103 // in infinite recursion. In the later case, the analysis code will
1104 // cope with a conservative value, and it will take care to purge
1105 // that value once it has finished.
1106 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1107 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1108 // Manually compute the final value for AR, checking for
1111 // Check whether the backedge-taken count can be losslessly casted to
1112 // the addrec's type. The count is always unsigned.
1113 const SCEV *CastedMaxBECount =
1114 getTruncateOrZeroExtend(MaxBECount, Start->getType());
1115 const SCEV *RecastedMaxBECount =
1116 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1117 if (MaxBECount == RecastedMaxBECount) {
1118 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1119 // Check whether Start+Step*MaxBECount has no signed overflow.
1120 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
1121 const SCEV *Add = getAddExpr(Start, SMul);
1122 const SCEV *OperandExtendedAdd =
1123 getAddExpr(getSignExtendExpr(Start, WideTy),
1124 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1125 getSignExtendExpr(Step, WideTy)));
1126 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
1127 // Return the expression with the addrec on the outside.
1128 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1129 getSignExtendExpr(Step, Ty),
1130 // FIXME: can use SCEV::FlagNSW
1131 L, SCEV::FlagAnyWrap);
1133 // Similar to above, only this time treat the step value as unsigned.
1134 // This covers loops that count up with an unsigned step.
1135 const SCEV *UMul = getMulExpr(CastedMaxBECount, Step);
1136 Add = getAddExpr(Start, UMul);
1137 OperandExtendedAdd =
1138 getAddExpr(getSignExtendExpr(Start, WideTy),
1139 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1140 getZeroExtendExpr(Step, WideTy)));
1141 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
1142 // Return the expression with the addrec on the outside.
1143 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1144 getZeroExtendExpr(Step, Ty),
1145 // FIXME: can use SCEV::FlagNSW
1146 L, SCEV::FlagAnyWrap);
1149 // If the backedge is guarded by a comparison with the pre-inc value
1150 // the addrec is safe. Also, if the entry is guarded by a comparison
1151 // with the start value and the backedge is guarded by a comparison
1152 // with the post-inc value, the addrec is safe.
1153 if (isKnownPositive(Step)) {
1154 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
1155 getSignedRange(Step).getSignedMax());
1156 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
1157 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
1158 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
1159 AR->getPostIncExpr(*this), N)))
1160 // Return the expression with the addrec on the outside.
1161 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1162 getSignExtendExpr(Step, Ty),
1163 // FIXME: can use SCEV::FlagNSW
1164 L, SCEV::FlagAnyWrap);
1165 } else if (isKnownNegative(Step)) {
1166 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1167 getSignedRange(Step).getSignedMin());
1168 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
1169 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
1170 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1171 AR->getPostIncExpr(*this), N)))
1172 // Return the expression with the addrec on the outside.
1173 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1174 getSignExtendExpr(Step, Ty),
1175 // FIXME: can use SCEV::FlagNSW
1176 L, SCEV::FlagAnyWrap);
1181 // The cast wasn't folded; create an explicit cast node.
1182 // Recompute the insert position, as it may have been invalidated.
1183 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1184 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1186 UniqueSCEVs.InsertNode(S, IP);
1190 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1191 /// unspecified bits out to the given type.
1193 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1195 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1196 "This is not an extending conversion!");
1197 assert(isSCEVable(Ty) &&
1198 "This is not a conversion to a SCEVable type!");
1199 Ty = getEffectiveSCEVType(Ty);
1201 // Sign-extend negative constants.
1202 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1203 if (SC->getValue()->getValue().isNegative())
1204 return getSignExtendExpr(Op, Ty);
1206 // Peel off a truncate cast.
1207 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
1208 const SCEV *NewOp = T->getOperand();
1209 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1210 return getAnyExtendExpr(NewOp, Ty);
1211 return getTruncateOrNoop(NewOp, Ty);
1214 // Next try a zext cast. If the cast is folded, use it.
1215 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
1216 if (!isa<SCEVZeroExtendExpr>(ZExt))
1219 // Next try a sext cast. If the cast is folded, use it.
1220 const SCEV *SExt = getSignExtendExpr(Op, Ty);
1221 if (!isa<SCEVSignExtendExpr>(SExt))
1224 // Force the cast to be folded into the operands of an addrec.
1225 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1226 SmallVector<const SCEV *, 4> Ops;
1227 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
1229 Ops.push_back(getAnyExtendExpr(*I, Ty));
1230 // FIXME: can use AR->getNoWrapFlags(SCEV::FlagNW)
1231 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagAnyWrap);
1234 // As a special case, fold anyext(undef) to undef. We don't want to
1235 // know too much about SCEVUnknowns, but this special case is handy
1237 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
1238 if (isa<UndefValue>(U->getValue()))
1239 return getSCEV(UndefValue::get(Ty));
1241 // If the expression is obviously signed, use the sext cast value.
1242 if (isa<SCEVSMaxExpr>(Op))
1245 // Absent any other information, use the zext cast value.
1249 /// CollectAddOperandsWithScales - Process the given Ops list, which is
1250 /// a list of operands to be added under the given scale, update the given
1251 /// map. This is a helper function for getAddRecExpr. As an example of
1252 /// what it does, given a sequence of operands that would form an add
1253 /// expression like this:
1255 /// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1257 /// where A and B are constants, update the map with these values:
1259 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1261 /// and add 13 + A*B*29 to AccumulatedConstant.
1262 /// This will allow getAddRecExpr to produce this:
1264 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1266 /// This form often exposes folding opportunities that are hidden in
1267 /// the original operand list.
1269 /// Return true iff it appears that any interesting folding opportunities
1270 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
1271 /// the common case where no interesting opportunities are present, and
1272 /// is also used as a check to avoid infinite recursion.
1275 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1276 SmallVector<const SCEV *, 8> &NewOps,
1277 APInt &AccumulatedConstant,
1278 const SCEV *const *Ops, size_t NumOperands,
1280 ScalarEvolution &SE) {
1281 bool Interesting = false;
1283 // Iterate over the add operands. They are sorted, with constants first.
1285 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1287 // Pull a buried constant out to the outside.
1288 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1290 AccumulatedConstant += Scale * C->getValue()->getValue();
1293 // Next comes everything else. We're especially interested in multiplies
1294 // here, but they're in the middle, so just visit the rest with one loop.
1295 for (; i != NumOperands; ++i) {
1296 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1297 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1299 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1300 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1301 // A multiplication of a constant with another add; recurse.
1302 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
1304 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1305 Add->op_begin(), Add->getNumOperands(),
1308 // A multiplication of a constant with some other value. Update
1310 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1311 const SCEV *Key = SE.getMulExpr(MulOps);
1312 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1313 M.insert(std::make_pair(Key, NewScale));
1315 NewOps.push_back(Pair.first->first);
1317 Pair.first->second += NewScale;
1318 // The map already had an entry for this value, which may indicate
1319 // a folding opportunity.
1324 // An ordinary operand. Update the map.
1325 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1326 M.insert(std::make_pair(Ops[i], Scale));
1328 NewOps.push_back(Pair.first->first);
1330 Pair.first->second += Scale;
1331 // The map already had an entry for this value, which may indicate
1332 // a folding opportunity.
1342 struct APIntCompare {
1343 bool operator()(const APInt &LHS, const APInt &RHS) const {
1344 return LHS.ult(RHS);
1349 /// getAddExpr - Get a canonical add expression, or something simpler if
1351 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1352 SCEV::NoWrapFlags Flags) {
1353 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
1354 "only nuw or nsw allowed");
1355 assert(!Ops.empty() && "Cannot get empty add!");
1356 if (Ops.size() == 1) return Ops[0];
1358 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
1359 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1360 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
1361 "SCEVAddExpr operand types don't match!");
1364 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
1365 if (!(Flags & SCEV::FlagNUW) && (Flags & SCEV::FlagNSW)) {
1367 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
1368 E = Ops.end(); I != E; ++I)
1369 if (!isKnownNonNegative(*I)) {
1373 if (All) Flags = setFlags(Flags, SCEV::FlagNUW);
1376 // Sort by complexity, this groups all similar expression types together.
1377 GroupByComplexity(Ops, LI);
1379 // If there are any constants, fold them together.
1381 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1383 assert(Idx < Ops.size());
1384 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1385 // We found two constants, fold them together!
1386 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1387 RHSC->getValue()->getValue());
1388 if (Ops.size() == 2) return Ops[0];
1389 Ops.erase(Ops.begin()+1); // Erase the folded element
1390 LHSC = cast<SCEVConstant>(Ops[0]);
1393 // If we are left with a constant zero being added, strip it off.
1394 if (LHSC->getValue()->isZero()) {
1395 Ops.erase(Ops.begin());
1399 if (Ops.size() == 1) return Ops[0];
1402 // Okay, check to see if the same value occurs in the operand list more than
1403 // once. If so, merge them together into an multiply expression. Since we
1404 // sorted the list, these values are required to be adjacent.
1405 const Type *Ty = Ops[0]->getType();
1406 bool FoundMatch = false;
1407 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
1408 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1409 // Scan ahead to count how many equal operands there are.
1411 while (i+Count != e && Ops[i+Count] == Ops[i])
1413 // Merge the values into a multiply.
1414 const SCEV *Scale = getConstant(Ty, Count);
1415 const SCEV *Mul = getMulExpr(Scale, Ops[i]);
1416 if (Ops.size() == Count)
1419 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
1420 --i; e -= Count - 1;
1424 return getAddExpr(Ops, Flags);
1426 // Check for truncates. If all the operands are truncated from the same
1427 // type, see if factoring out the truncate would permit the result to be
1428 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1429 // if the contents of the resulting outer trunc fold to something simple.
1430 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1431 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1432 const Type *DstType = Trunc->getType();
1433 const Type *SrcType = Trunc->getOperand()->getType();
1434 SmallVector<const SCEV *, 8> LargeOps;
1436 // Check all the operands to see if they can be represented in the
1437 // source type of the truncate.
1438 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1439 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1440 if (T->getOperand()->getType() != SrcType) {
1444 LargeOps.push_back(T->getOperand());
1445 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1446 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
1447 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
1448 SmallVector<const SCEV *, 8> LargeMulOps;
1449 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1450 if (const SCEVTruncateExpr *T =
1451 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1452 if (T->getOperand()->getType() != SrcType) {
1456 LargeMulOps.push_back(T->getOperand());
1457 } else if (const SCEVConstant *C =
1458 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1459 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
1466 LargeOps.push_back(getMulExpr(LargeMulOps));
1473 // Evaluate the expression in the larger type.
1474 const SCEV *Fold = getAddExpr(LargeOps, Flags);
1475 // If it folds to something simple, use it. Otherwise, don't.
1476 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1477 return getTruncateExpr(Fold, DstType);
1481 // Skip past any other cast SCEVs.
1482 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1485 // If there are add operands they would be next.
1486 if (Idx < Ops.size()) {
1487 bool DeletedAdd = false;
1488 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
1489 // If we have an add, expand the add operands onto the end of the operands
1491 Ops.erase(Ops.begin()+Idx);
1492 Ops.append(Add->op_begin(), Add->op_end());
1496 // If we deleted at least one add, we added operands to the end of the list,
1497 // and they are not necessarily sorted. Recurse to resort and resimplify
1498 // any operands we just acquired.
1500 return getAddExpr(Ops);
1503 // Skip over the add expression until we get to a multiply.
1504 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1507 // Check to see if there are any folding opportunities present with
1508 // operands multiplied by constant values.
1509 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1510 uint64_t BitWidth = getTypeSizeInBits(Ty);
1511 DenseMap<const SCEV *, APInt> M;
1512 SmallVector<const SCEV *, 8> NewOps;
1513 APInt AccumulatedConstant(BitWidth, 0);
1514 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1515 Ops.data(), Ops.size(),
1516 APInt(BitWidth, 1), *this)) {
1517 // Some interesting folding opportunity is present, so its worthwhile to
1518 // re-generate the operands list. Group the operands by constant scale,
1519 // to avoid multiplying by the same constant scale multiple times.
1520 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1521 for (SmallVector<const SCEV *, 8>::const_iterator I = NewOps.begin(),
1522 E = NewOps.end(); I != E; ++I)
1523 MulOpLists[M.find(*I)->second].push_back(*I);
1524 // Re-generate the operands list.
1526 if (AccumulatedConstant != 0)
1527 Ops.push_back(getConstant(AccumulatedConstant));
1528 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1529 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
1531 Ops.push_back(getMulExpr(getConstant(I->first),
1532 getAddExpr(I->second)));
1534 return getConstant(Ty, 0);
1535 if (Ops.size() == 1)
1537 return getAddExpr(Ops);
1541 // If we are adding something to a multiply expression, make sure the
1542 // something is not already an operand of the multiply. If so, merge it into
1544 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
1545 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
1546 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
1547 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
1548 if (isa<SCEVConstant>(MulOpSCEV))
1550 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
1551 if (MulOpSCEV == Ops[AddOp]) {
1552 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1553 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
1554 if (Mul->getNumOperands() != 2) {
1555 // If the multiply has more than two operands, we must get the
1557 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1558 Mul->op_begin()+MulOp);
1559 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
1560 InnerMul = getMulExpr(MulOps);
1562 const SCEV *One = getConstant(Ty, 1);
1563 const SCEV *AddOne = getAddExpr(One, InnerMul);
1564 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
1565 if (Ops.size() == 2) return OuterMul;
1567 Ops.erase(Ops.begin()+AddOp);
1568 Ops.erase(Ops.begin()+Idx-1);
1570 Ops.erase(Ops.begin()+Idx);
1571 Ops.erase(Ops.begin()+AddOp-1);
1573 Ops.push_back(OuterMul);
1574 return getAddExpr(Ops);
1577 // Check this multiply against other multiplies being added together.
1578 for (unsigned OtherMulIdx = Idx+1;
1579 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1581 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
1582 // If MulOp occurs in OtherMul, we can fold the two multiplies
1584 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1585 OMulOp != e; ++OMulOp)
1586 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1587 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1588 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
1589 if (Mul->getNumOperands() != 2) {
1590 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1591 Mul->op_begin()+MulOp);
1592 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
1593 InnerMul1 = getMulExpr(MulOps);
1595 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1596 if (OtherMul->getNumOperands() != 2) {
1597 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1598 OtherMul->op_begin()+OMulOp);
1599 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
1600 InnerMul2 = getMulExpr(MulOps);
1602 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1603 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
1604 if (Ops.size() == 2) return OuterMul;
1605 Ops.erase(Ops.begin()+Idx);
1606 Ops.erase(Ops.begin()+OtherMulIdx-1);
1607 Ops.push_back(OuterMul);
1608 return getAddExpr(Ops);
1614 // If there are any add recurrences in the operands list, see if any other
1615 // added values are loop invariant. If so, we can fold them into the
1617 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1620 // Scan over all recurrences, trying to fold loop invariants into them.
1621 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1622 // Scan all of the other operands to this add and add them to the vector if
1623 // they are loop invariant w.r.t. the recurrence.
1624 SmallVector<const SCEV *, 8> LIOps;
1625 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1626 const Loop *AddRecLoop = AddRec->getLoop();
1627 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1628 if (isLoopInvariant(Ops[i], AddRecLoop)) {
1629 LIOps.push_back(Ops[i]);
1630 Ops.erase(Ops.begin()+i);
1634 // If we found some loop invariants, fold them into the recurrence.
1635 if (!LIOps.empty()) {
1636 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
1637 LIOps.push_back(AddRec->getStart());
1639 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
1641 AddRecOps[0] = getAddExpr(LIOps);
1643 // Build the new addrec. Propagate the NUW and NSW flags if both the
1644 // outer add and the inner addrec are guaranteed to have no overflow.
1645 // FIXME: Always propagate NW
1646 // AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW))
1647 Flags = AddRec->getNoWrapFlags(Flags);
1648 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
1650 // If all of the other operands were loop invariant, we are done.
1651 if (Ops.size() == 1) return NewRec;
1653 // Otherwise, add the folded AddRec by the non-liv parts.
1654 for (unsigned i = 0;; ++i)
1655 if (Ops[i] == AddRec) {
1659 return getAddExpr(Ops);
1662 // Okay, if there weren't any loop invariants to be folded, check to see if
1663 // there are multiple AddRec's with the same loop induction variable being
1664 // added together. If so, we can fold them.
1665 for (unsigned OtherIdx = Idx+1;
1666 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1668 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
1669 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
1670 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
1672 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1674 if (const SCEVAddRecExpr *OtherAddRec =
1675 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
1676 if (OtherAddRec->getLoop() == AddRecLoop) {
1677 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
1679 if (i >= AddRecOps.size()) {
1680 AddRecOps.append(OtherAddRec->op_begin()+i,
1681 OtherAddRec->op_end());
1684 AddRecOps[i] = getAddExpr(AddRecOps[i],
1685 OtherAddRec->getOperand(i));
1687 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
1689 // Step size has changed, so we cannot guarantee no self-wraparound.
1690 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
1691 return getAddExpr(Ops);
1694 // Otherwise couldn't fold anything into this recurrence. Move onto the
1698 // Okay, it looks like we really DO need an add expr. Check to see if we
1699 // already have one, otherwise create a new one.
1700 FoldingSetNodeID ID;
1701 ID.AddInteger(scAddExpr);
1702 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1703 ID.AddPointer(Ops[i]);
1706 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1708 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1709 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
1710 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
1712 UniqueSCEVs.InsertNode(S, IP);
1714 S->setNoWrapFlags(Flags);
1718 /// getMulExpr - Get a canonical multiply expression, or something simpler if
1720 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1721 SCEV::NoWrapFlags Flags) {
1722 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
1723 "only nuw or nsw allowed");
1724 assert(!Ops.empty() && "Cannot get empty mul!");
1725 if (Ops.size() == 1) return Ops[0];
1727 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
1728 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1729 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
1730 "SCEVMulExpr operand types don't match!");
1733 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
1734 if (!(Flags & SCEV::FlagNUW) && (Flags & SCEV::FlagNSW)) {
1736 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
1737 E = Ops.end(); I != E; ++I)
1738 if (!isKnownNonNegative(*I)) {
1742 if (All) Flags = setFlags(Flags, SCEV::FlagNUW);
1745 // Sort by complexity, this groups all similar expression types together.
1746 GroupByComplexity(Ops, LI);
1748 // If there are any constants, fold them together.
1750 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1752 // C1*(C2+V) -> C1*C2 + C1*V
1753 if (Ops.size() == 2)
1754 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1755 if (Add->getNumOperands() == 2 &&
1756 isa<SCEVConstant>(Add->getOperand(0)))
1757 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1758 getMulExpr(LHSC, Add->getOperand(1)));
1761 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1762 // We found two constants, fold them together!
1763 ConstantInt *Fold = ConstantInt::get(getContext(),
1764 LHSC->getValue()->getValue() *
1765 RHSC->getValue()->getValue());
1766 Ops[0] = getConstant(Fold);
1767 Ops.erase(Ops.begin()+1); // Erase the folded element
1768 if (Ops.size() == 1) return Ops[0];
1769 LHSC = cast<SCEVConstant>(Ops[0]);
1772 // If we are left with a constant one being multiplied, strip it off.
1773 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1774 Ops.erase(Ops.begin());
1776 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1777 // If we have a multiply of zero, it will always be zero.
1779 } else if (Ops[0]->isAllOnesValue()) {
1780 // If we have a mul by -1 of an add, try distributing the -1 among the
1782 if (Ops.size() == 2) {
1783 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1784 SmallVector<const SCEV *, 4> NewOps;
1785 bool AnyFolded = false;
1786 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(),
1787 E = Add->op_end(); I != E; ++I) {
1788 const SCEV *Mul = getMulExpr(Ops[0], *I);
1789 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1790 NewOps.push_back(Mul);
1793 return getAddExpr(NewOps);
1795 else if (const SCEVAddRecExpr *
1796 AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
1797 // Negation preserves a recurrence's no self-wrap property.
1798 SmallVector<const SCEV *, 4> Operands;
1799 for (SCEVAddRecExpr::op_iterator I = AddRec->op_begin(),
1800 E = AddRec->op_end(); I != E; ++I) {
1801 Operands.push_back(getMulExpr(Ops[0], *I));
1803 return getAddRecExpr(Operands, AddRec->getLoop(),
1804 AddRec->getNoWrapFlags(SCEV::FlagNW));
1809 if (Ops.size() == 1)
1813 // Skip over the add expression until we get to a multiply.
1814 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1817 // If there are mul operands inline them all into this expression.
1818 if (Idx < Ops.size()) {
1819 bool DeletedMul = false;
1820 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1821 // If we have an mul, expand the mul operands onto the end of the operands
1823 Ops.erase(Ops.begin()+Idx);
1824 Ops.append(Mul->op_begin(), Mul->op_end());
1828 // If we deleted at least one mul, we added operands to the end of the list,
1829 // and they are not necessarily sorted. Recurse to resort and resimplify
1830 // any operands we just acquired.
1832 return getMulExpr(Ops);
1835 // If there are any add recurrences in the operands list, see if any other
1836 // added values are loop invariant. If so, we can fold them into the
1838 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1841 // Scan over all recurrences, trying to fold loop invariants into them.
1842 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1843 // Scan all of the other operands to this mul and add them to the vector if
1844 // they are loop invariant w.r.t. the recurrence.
1845 SmallVector<const SCEV *, 8> LIOps;
1846 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1847 const Loop *AddRecLoop = AddRec->getLoop();
1848 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1849 if (isLoopInvariant(Ops[i], AddRecLoop)) {
1850 LIOps.push_back(Ops[i]);
1851 Ops.erase(Ops.begin()+i);
1855 // If we found some loop invariants, fold them into the recurrence.
1856 if (!LIOps.empty()) {
1857 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
1858 SmallVector<const SCEV *, 4> NewOps;
1859 NewOps.reserve(AddRec->getNumOperands());
1860 const SCEV *Scale = getMulExpr(LIOps);
1861 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1862 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1864 // Build the new addrec. Propagate the NUW and NSW flags if both the
1865 // outer mul and the inner addrec are guaranteed to have no overflow.
1867 // No self-wrap cannot be guaranteed after changing the step size, but
1868 // will be infered if either NUW or NSW is true.
1869 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
1870 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
1872 // If all of the other operands were loop invariant, we are done.
1873 if (Ops.size() == 1) return NewRec;
1875 // Otherwise, multiply the folded AddRec by the non-liv parts.
1876 for (unsigned i = 0;; ++i)
1877 if (Ops[i] == AddRec) {
1881 return getMulExpr(Ops);
1884 // Okay, if there weren't any loop invariants to be folded, check to see if
1885 // there are multiple AddRec's with the same loop induction variable being
1886 // multiplied together. If so, we can fold them.
1887 for (unsigned OtherIdx = Idx+1;
1888 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1890 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
1891 // F * G, where F = {A,+,B}<L> and G = {C,+,D}<L> -->
1892 // {A*C,+,F*D + G*B + B*D}<L>
1893 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1895 if (const SCEVAddRecExpr *OtherAddRec =
1896 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
1897 if (OtherAddRec->getLoop() == AddRecLoop) {
1898 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1899 const SCEV *NewStart = getMulExpr(F->getStart(), G->getStart());
1900 const SCEV *B = F->getStepRecurrence(*this);
1901 const SCEV *D = G->getStepRecurrence(*this);
1902 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
1905 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
1908 if (Ops.size() == 2) return NewAddRec;
1909 Ops[Idx] = AddRec = cast<SCEVAddRecExpr>(NewAddRec);
1910 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
1912 return getMulExpr(Ops);
1915 // Otherwise couldn't fold anything into this recurrence. Move onto the
1919 // Okay, it looks like we really DO need an mul expr. Check to see if we
1920 // already have one, otherwise create a new one.
1921 FoldingSetNodeID ID;
1922 ID.AddInteger(scMulExpr);
1923 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1924 ID.AddPointer(Ops[i]);
1927 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1929 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1930 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
1931 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
1933 UniqueSCEVs.InsertNode(S, IP);
1935 S->setNoWrapFlags(Flags);
1939 /// getUDivExpr - Get a canonical unsigned division expression, or something
1940 /// simpler if possible.
1941 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1943 assert(getEffectiveSCEVType(LHS->getType()) ==
1944 getEffectiveSCEVType(RHS->getType()) &&
1945 "SCEVUDivExpr operand types don't match!");
1947 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1948 if (RHSC->getValue()->equalsInt(1))
1949 return LHS; // X udiv 1 --> x
1950 // If the denominator is zero, the result of the udiv is undefined. Don't
1951 // try to analyze it, because the resolution chosen here may differ from
1952 // the resolution chosen in other parts of the compiler.
1953 if (!RHSC->getValue()->isZero()) {
1954 // Determine if the division can be folded into the operands of
1956 // TODO: Generalize this to non-constants by using known-bits information.
1957 const Type *Ty = LHS->getType();
1958 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1959 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
1960 // For non-power-of-two values, effectively round the value up to the
1961 // nearest power of two.
1962 if (!RHSC->getValue()->getValue().isPowerOf2())
1964 const IntegerType *ExtTy =
1965 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
1966 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1967 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1968 if (const SCEVConstant *Step =
1969 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1970 if (!Step->getValue()->getValue()
1971 .urem(RHSC->getValue()->getValue()) &&
1972 getZeroExtendExpr(AR, ExtTy) ==
1973 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1974 getZeroExtendExpr(Step, ExtTy),
1975 AR->getLoop(), SCEV::FlagAnyWrap)) {
1976 SmallVector<const SCEV *, 4> Operands;
1977 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1978 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1979 return getAddRecExpr(Operands, AR->getLoop(),
1980 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
1983 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1984 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1985 SmallVector<const SCEV *, 4> Operands;
1986 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1987 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1988 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
1989 // Find an operand that's safely divisible.
1990 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1991 const SCEV *Op = M->getOperand(i);
1992 const SCEV *Div = getUDivExpr(Op, RHSC);
1993 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1994 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
1997 return getMulExpr(Operands);
2001 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
2002 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
2003 SmallVector<const SCEV *, 4> Operands;
2004 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
2005 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
2006 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2008 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2009 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2010 if (isa<SCEVUDivExpr>(Op) ||
2011 getMulExpr(Op, RHS) != A->getOperand(i))
2013 Operands.push_back(Op);
2015 if (Operands.size() == A->getNumOperands())
2016 return getAddExpr(Operands);
2020 // Fold if both operands are constant.
2021 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2022 Constant *LHSCV = LHSC->getValue();
2023 Constant *RHSCV = RHSC->getValue();
2024 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2030 FoldingSetNodeID ID;
2031 ID.AddInteger(scUDivExpr);
2035 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2036 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2038 UniqueSCEVs.InsertNode(S, IP);
2043 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
2044 /// Simplify the expression as much as possible.
2045 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
2047 SCEV::NoWrapFlags Flags) {
2048 SmallVector<const SCEV *, 4> Operands;
2049 Operands.push_back(Start);
2050 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
2051 if (StepChrec->getLoop() == L) {
2052 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
2053 // FIXME: can use maskFlags(Flags, SCEV::FlagNW)
2054 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap);
2057 Operands.push_back(Step);
2058 return getAddRecExpr(Operands, L, Flags);
2061 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
2062 /// Simplify the expression as much as possible.
2064 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
2065 const Loop *L, SCEV::NoWrapFlags Flags) {
2066 if (Operands.size() == 1) return Operands[0];
2068 const Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
2069 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
2070 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
2071 "SCEVAddRecExpr operand types don't match!");
2072 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2073 assert(isLoopInvariant(Operands[i], L) &&
2074 "SCEVAddRecExpr operand is not loop-invariant!");
2077 if (Operands.back()->isZero()) {
2078 Operands.pop_back();
2079 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
2082 // It's tempting to want to call getMaxBackedgeTakenCount count here and
2083 // use that information to infer NUW and NSW flags. However, computing a
2084 // BE count requires calling getAddRecExpr, so we may not yet have a
2085 // meaningful BE count at this point (and if we don't, we'd be stuck
2086 // with a SCEVCouldNotCompute as the cached BE count).
2088 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2089 if (!(Flags & SCEV::FlagNUW) && (Flags & SCEV::FlagNSW)) {
2091 for (SmallVectorImpl<const SCEV *>::const_iterator I = Operands.begin(),
2092 E = Operands.end(); I != E; ++I)
2093 if (!isKnownNonNegative(*I)) {
2097 if (All) Flags = setFlags(Flags, SCEV::FlagNUW);
2100 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
2101 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
2102 const Loop *NestedLoop = NestedAR->getLoop();
2103 if (L->contains(NestedLoop) ?
2104 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
2105 (!NestedLoop->contains(L) &&
2106 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
2107 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
2108 NestedAR->op_end());
2109 Operands[0] = NestedAR->getStart();
2110 // AddRecs require their operands be loop-invariant with respect to their
2111 // loops. Don't perform this transformation if it would break this
2113 bool AllInvariant = true;
2114 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2115 if (!isLoopInvariant(Operands[i], L)) {
2116 AllInvariant = false;
2120 // Create a recurrence for the outer loop with the same step size.
2123 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
2124 // inner recurrence has the same property.
2125 // maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
2126 SCEV::NoWrapFlags OuterFlags = SCEV::FlagAnyWrap;
2128 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
2129 AllInvariant = true;
2130 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
2131 if (!isLoopInvariant(NestedOperands[i], NestedLoop)) {
2132 AllInvariant = false;
2136 // Ok, both add recurrences are valid after the transformation.
2139 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
2140 // the outer recurrence has the same property.
2141 // maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
2142 SCEV::NoWrapFlags InnerFlags = SCEV::FlagAnyWrap;
2143 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
2146 // Reset Operands to its original state.
2147 Operands[0] = NestedAR;
2151 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2152 // already have one, otherwise create a new one.
2153 FoldingSetNodeID ID;
2154 ID.AddInteger(scAddRecExpr);
2155 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2156 ID.AddPointer(Operands[i]);
2160 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2162 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2163 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
2164 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2165 O, Operands.size(), L);
2166 UniqueSCEVs.InsertNode(S, IP);
2168 S->setNoWrapFlags(Flags);
2172 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2174 SmallVector<const SCEV *, 2> Ops;
2177 return getSMaxExpr(Ops);
2181 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2182 assert(!Ops.empty() && "Cannot get empty smax!");
2183 if (Ops.size() == 1) return Ops[0];
2185 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2186 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2187 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2188 "SCEVSMaxExpr operand types don't match!");
2191 // Sort by complexity, this groups all similar expression types together.
2192 GroupByComplexity(Ops, LI);
2194 // If there are any constants, fold them together.
2196 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2198 assert(Idx < Ops.size());
2199 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2200 // We found two constants, fold them together!
2201 ConstantInt *Fold = ConstantInt::get(getContext(),
2202 APIntOps::smax(LHSC->getValue()->getValue(),
2203 RHSC->getValue()->getValue()));
2204 Ops[0] = getConstant(Fold);
2205 Ops.erase(Ops.begin()+1); // Erase the folded element
2206 if (Ops.size() == 1) return Ops[0];
2207 LHSC = cast<SCEVConstant>(Ops[0]);
2210 // If we are left with a constant minimum-int, strip it off.
2211 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2212 Ops.erase(Ops.begin());
2214 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2215 // If we have an smax with a constant maximum-int, it will always be
2220 if (Ops.size() == 1) return Ops[0];
2223 // Find the first SMax
2224 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2227 // Check to see if one of the operands is an SMax. If so, expand its operands
2228 // onto our operand list, and recurse to simplify.
2229 if (Idx < Ops.size()) {
2230 bool DeletedSMax = false;
2231 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
2232 Ops.erase(Ops.begin()+Idx);
2233 Ops.append(SMax->op_begin(), SMax->op_end());
2238 return getSMaxExpr(Ops);
2241 // Okay, check to see if the same value occurs in the operand list twice. If
2242 // so, delete one. Since we sorted the list, these values are required to
2244 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2245 // X smax Y smax Y --> X smax Y
2246 // X smax Y --> X, if X is always greater than Y
2247 if (Ops[i] == Ops[i+1] ||
2248 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
2249 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2251 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
2252 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2256 if (Ops.size() == 1) return Ops[0];
2258 assert(!Ops.empty() && "Reduced smax down to nothing!");
2260 // Okay, it looks like we really DO need an smax expr. Check to see if we
2261 // already have one, otherwise create a new one.
2262 FoldingSetNodeID ID;
2263 ID.AddInteger(scSMaxExpr);
2264 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2265 ID.AddPointer(Ops[i]);
2267 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2268 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2269 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2270 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
2272 UniqueSCEVs.InsertNode(S, IP);
2276 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2278 SmallVector<const SCEV *, 2> Ops;
2281 return getUMaxExpr(Ops);
2285 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2286 assert(!Ops.empty() && "Cannot get empty umax!");
2287 if (Ops.size() == 1) return Ops[0];
2289 const 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 "SCEVUMaxExpr 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::umax(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(false)) {
2316 Ops.erase(Ops.begin());
2318 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2319 // If we have an umax with a constant maximum-int, it will always be
2324 if (Ops.size() == 1) return Ops[0];
2327 // Find the first UMax
2328 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2331 // Check to see if one of the operands is a UMax. If so, expand its operands
2332 // onto our operand list, and recurse to simplify.
2333 if (Idx < Ops.size()) {
2334 bool DeletedUMax = false;
2335 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
2336 Ops.erase(Ops.begin()+Idx);
2337 Ops.append(UMax->op_begin(), UMax->op_end());
2342 return getUMaxExpr(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 umax Y umax Y --> X umax Y
2350 // X umax Y --> X, if X is always greater than Y
2351 if (Ops[i] == Ops[i+1] ||
2352 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
2353 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2355 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, 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 umax down to nothing!");
2364 // Okay, it looks like we really DO need a umax expr. Check to see if we
2365 // already have one, otherwise create a new one.
2366 FoldingSetNodeID ID;
2367 ID.AddInteger(scUMaxExpr);
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) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
2376 UniqueSCEVs.InsertNode(S, IP);
2380 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2382 // ~smax(~x, ~y) == smin(x, y).
2383 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2386 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2388 // ~umax(~x, ~y) == umin(x, y)
2389 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2392 const SCEV *ScalarEvolution::getSizeOfExpr(const Type *AllocTy) {
2393 // If we have TargetData, we can bypass creating a target-independent
2394 // constant expression and then folding it back into a ConstantInt.
2395 // This is just a compile-time optimization.
2397 return getConstant(TD->getIntPtrType(getContext()),
2398 TD->getTypeAllocSize(AllocTy));
2400 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2401 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2402 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2404 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2405 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2408 const SCEV *ScalarEvolution::getAlignOfExpr(const Type *AllocTy) {
2409 Constant *C = ConstantExpr::getAlignOf(AllocTy);
2410 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2411 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2413 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2414 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2417 const SCEV *ScalarEvolution::getOffsetOfExpr(const StructType *STy,
2419 // If we have TargetData, we can bypass creating a target-independent
2420 // constant expression and then folding it back into a ConstantInt.
2421 // This is just a compile-time optimization.
2423 return getConstant(TD->getIntPtrType(getContext()),
2424 TD->getStructLayout(STy)->getElementOffset(FieldNo));
2426 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2427 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2428 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2430 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
2431 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2434 const SCEV *ScalarEvolution::getOffsetOfExpr(const Type *CTy,
2435 Constant *FieldNo) {
2436 Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
2437 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2438 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2440 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
2441 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2444 const SCEV *ScalarEvolution::getUnknown(Value *V) {
2445 // Don't attempt to do anything other than create a SCEVUnknown object
2446 // here. createSCEV only calls getUnknown after checking for all other
2447 // interesting possibilities, and any other code that calls getUnknown
2448 // is doing so in order to hide a value from SCEV canonicalization.
2450 FoldingSetNodeID ID;
2451 ID.AddInteger(scUnknown);
2454 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
2455 assert(cast<SCEVUnknown>(S)->getValue() == V &&
2456 "Stale SCEVUnknown in uniquing map!");
2459 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
2461 FirstUnknown = cast<SCEVUnknown>(S);
2462 UniqueSCEVs.InsertNode(S, IP);
2466 //===----------------------------------------------------------------------===//
2467 // Basic SCEV Analysis and PHI Idiom Recognition Code
2470 /// isSCEVable - Test if values of the given type are analyzable within
2471 /// the SCEV framework. This primarily includes integer types, and it
2472 /// can optionally include pointer types if the ScalarEvolution class
2473 /// has access to target-specific information.
2474 bool ScalarEvolution::isSCEVable(const Type *Ty) const {
2475 // Integers and pointers are always SCEVable.
2476 return Ty->isIntegerTy() || Ty->isPointerTy();
2479 /// getTypeSizeInBits - Return the size in bits of the specified type,
2480 /// for which isSCEVable must return true.
2481 uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
2482 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2484 // If we have a TargetData, use it!
2486 return TD->getTypeSizeInBits(Ty);
2488 // Integer types have fixed sizes.
2489 if (Ty->isIntegerTy())
2490 return Ty->getPrimitiveSizeInBits();
2492 // The only other support type is pointer. Without TargetData, conservatively
2493 // assume pointers are 64-bit.
2494 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
2498 /// getEffectiveSCEVType - Return a type with the same bitwidth as
2499 /// the given type and which represents how SCEV will treat the given
2500 /// type, for which isSCEVable must return true. For pointer types,
2501 /// this is the pointer-sized integer type.
2502 const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
2503 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2505 if (Ty->isIntegerTy())
2508 // The only other support type is pointer.
2509 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
2510 if (TD) return TD->getIntPtrType(getContext());
2512 // Without TargetData, conservatively assume pointers are 64-bit.
2513 return Type::getInt64Ty(getContext());
2516 const SCEV *ScalarEvolution::getCouldNotCompute() {
2517 return &CouldNotCompute;
2520 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2521 /// expression and create a new one.
2522 const SCEV *ScalarEvolution::getSCEV(Value *V) {
2523 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
2525 ValueExprMapType::const_iterator I = ValueExprMap.find(V);
2526 if (I != ValueExprMap.end()) return I->second;
2527 const SCEV *S = createSCEV(V);
2529 // The process of creating a SCEV for V may have caused other SCEVs
2530 // to have been created, so it's necessary to insert the new entry
2531 // from scratch, rather than trying to remember the insert position
2533 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(V, this), S));
2537 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2539 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
2540 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2542 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
2544 const Type *Ty = V->getType();
2545 Ty = getEffectiveSCEVType(Ty);
2546 return getMulExpr(V,
2547 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
2550 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
2551 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
2552 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2554 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
2556 const Type *Ty = V->getType();
2557 Ty = getEffectiveSCEVType(Ty);
2558 const SCEV *AllOnes =
2559 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
2560 return getMinusSCEV(AllOnes, V);
2563 /// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
2565 /// FIXME: prohibit FlagNUW here, as soon as getMinusSCEVForExitTest goes.
2566 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
2567 SCEV::NoWrapFlags Flags) {
2568 // Fast path: X - X --> 0.
2570 return getConstant(LHS->getType(), 0);
2573 return getAddExpr(LHS, getNegativeSCEV(RHS), Flags);
2576 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2577 /// input value to the specified type. If the type must be extended, it is zero
2580 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, const Type *Ty) {
2581 const Type *SrcTy = V->getType();
2582 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2583 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2584 "Cannot truncate or zero extend with non-integer arguments!");
2585 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2586 return V; // No conversion
2587 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2588 return getTruncateExpr(V, Ty);
2589 return getZeroExtendExpr(V, Ty);
2592 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2593 /// input value to the specified type. If the type must be extended, it is sign
2596 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
2598 const Type *SrcTy = V->getType();
2599 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2600 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2601 "Cannot truncate or zero extend with non-integer arguments!");
2602 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2603 return V; // No conversion
2604 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2605 return getTruncateExpr(V, Ty);
2606 return getSignExtendExpr(V, Ty);
2609 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2610 /// input value to the specified type. If the type must be extended, it is zero
2611 /// extended. The conversion must not be narrowing.
2613 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
2614 const Type *SrcTy = V->getType();
2615 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2616 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2617 "Cannot noop or zero extend with non-integer arguments!");
2618 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2619 "getNoopOrZeroExtend cannot truncate!");
2620 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2621 return V; // No conversion
2622 return getZeroExtendExpr(V, Ty);
2625 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2626 /// input value to the specified type. If the type must be extended, it is sign
2627 /// extended. The conversion must not be narrowing.
2629 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
2630 const Type *SrcTy = V->getType();
2631 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2632 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2633 "Cannot noop or sign extend with non-integer arguments!");
2634 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2635 "getNoopOrSignExtend cannot truncate!");
2636 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2637 return V; // No conversion
2638 return getSignExtendExpr(V, Ty);
2641 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2642 /// the input value to the specified type. If the type must be extended,
2643 /// it is extended with unspecified bits. The conversion must not be
2646 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
2647 const Type *SrcTy = V->getType();
2648 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2649 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2650 "Cannot noop or any extend with non-integer arguments!");
2651 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2652 "getNoopOrAnyExtend cannot truncate!");
2653 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2654 return V; // No conversion
2655 return getAnyExtendExpr(V, Ty);
2658 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2659 /// input value to the specified type. The conversion must not be widening.
2661 ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
2662 const Type *SrcTy = V->getType();
2663 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2664 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2665 "Cannot truncate or noop with non-integer arguments!");
2666 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2667 "getTruncateOrNoop cannot extend!");
2668 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2669 return V; // No conversion
2670 return getTruncateExpr(V, Ty);
2673 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2674 /// the types using zero-extension, and then perform a umax operation
2676 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2678 const SCEV *PromotedLHS = LHS;
2679 const SCEV *PromotedRHS = RHS;
2681 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2682 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2684 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2686 return getUMaxExpr(PromotedLHS, PromotedRHS);
2689 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
2690 /// the types using zero-extension, and then perform a umin operation
2692 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2694 const SCEV *PromotedLHS = LHS;
2695 const SCEV *PromotedRHS = RHS;
2697 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2698 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2700 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2702 return getUMinExpr(PromotedLHS, PromotedRHS);
2705 /// PushDefUseChildren - Push users of the given Instruction
2706 /// onto the given Worklist.
2708 PushDefUseChildren(Instruction *I,
2709 SmallVectorImpl<Instruction *> &Worklist) {
2710 // Push the def-use children onto the Worklist stack.
2711 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2713 Worklist.push_back(cast<Instruction>(*UI));
2716 /// ForgetSymbolicValue - This looks up computed SCEV values for all
2717 /// instructions that depend on the given instruction and removes them from
2718 /// the ValueExprMapType map if they reference SymName. This is used during PHI
2721 ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
2722 SmallVector<Instruction *, 16> Worklist;
2723 PushDefUseChildren(PN, Worklist);
2725 SmallPtrSet<Instruction *, 8> Visited;
2727 while (!Worklist.empty()) {
2728 Instruction *I = Worklist.pop_back_val();
2729 if (!Visited.insert(I)) continue;
2731 ValueExprMapType::iterator It =
2732 ValueExprMap.find(static_cast<Value *>(I));
2733 if (It != ValueExprMap.end()) {
2734 const SCEV *Old = It->second;
2736 // Short-circuit the def-use traversal if the symbolic name
2737 // ceases to appear in expressions.
2738 if (Old != SymName && !hasOperand(Old, SymName))
2741 // SCEVUnknown for a PHI either means that it has an unrecognized
2742 // structure, it's a PHI that's in the progress of being computed
2743 // by createNodeForPHI, or it's a single-value PHI. In the first case,
2744 // additional loop trip count information isn't going to change anything.
2745 // In the second case, createNodeForPHI will perform the necessary
2746 // updates on its own when it gets to that point. In the third, we do
2747 // want to forget the SCEVUnknown.
2748 if (!isa<PHINode>(I) ||
2749 !isa<SCEVUnknown>(Old) ||
2750 (I != PN && Old == SymName)) {
2751 forgetMemoizedResults(Old);
2752 ValueExprMap.erase(It);
2756 PushDefUseChildren(I, Worklist);
2760 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2761 /// a loop header, making it a potential recurrence, or it doesn't.
2763 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
2764 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2765 if (L->getHeader() == PN->getParent()) {
2766 // The loop may have multiple entrances or multiple exits; we can analyze
2767 // this phi as an addrec if it has a unique entry value and a unique
2769 Value *BEValueV = 0, *StartValueV = 0;
2770 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2771 Value *V = PN->getIncomingValue(i);
2772 if (L->contains(PN->getIncomingBlock(i))) {
2775 } else if (BEValueV != V) {
2779 } else if (!StartValueV) {
2781 } else if (StartValueV != V) {
2786 if (BEValueV && StartValueV) {
2787 // While we are analyzing this PHI node, handle its value symbolically.
2788 const SCEV *SymbolicName = getUnknown(PN);
2789 assert(ValueExprMap.find(PN) == ValueExprMap.end() &&
2790 "PHI node already processed?");
2791 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
2793 // Using this symbolic name for the PHI, analyze the value coming around
2795 const SCEV *BEValue = getSCEV(BEValueV);
2797 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2798 // has a special value for the first iteration of the loop.
2800 // If the value coming around the backedge is an add with the symbolic
2801 // value we just inserted, then we found a simple induction variable!
2802 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
2803 // If there is a single occurrence of the symbolic value, replace it
2804 // with a recurrence.
2805 unsigned FoundIndex = Add->getNumOperands();
2806 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2807 if (Add->getOperand(i) == SymbolicName)
2808 if (FoundIndex == e) {
2813 if (FoundIndex != Add->getNumOperands()) {
2814 // Create an add with everything but the specified operand.
2815 SmallVector<const SCEV *, 8> Ops;
2816 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2817 if (i != FoundIndex)
2818 Ops.push_back(Add->getOperand(i));
2819 const SCEV *Accum = getAddExpr(Ops);
2821 // This is not a valid addrec if the step amount is varying each
2822 // loop iteration, but is not itself an addrec in this loop.
2823 if (isLoopInvariant(Accum, L) ||
2824 (isa<SCEVAddRecExpr>(Accum) &&
2825 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
2826 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
2828 // If the increment doesn't overflow, then neither the addrec nor
2829 // the post-increment will overflow.
2830 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
2831 if (OBO->hasNoUnsignedWrap())
2832 Flags = setFlags(Flags, SCEV::FlagNUW);
2833 if (OBO->hasNoSignedWrap())
2834 Flags = setFlags(Flags, SCEV::FlagNSW);
2835 } else if (const GEPOperator *GEP =
2836 dyn_cast<GEPOperator>(BEValueV)) {
2837 // If the increment is an inbounds GEP, then we know the address
2838 // space cannot be wrapped around. We cannot make any guarantee
2839 // about signed or unsigned overflow because pointers are
2840 // unsigned but we may have a negative index from the base
2842 if (GEP->isInBounds())
2843 // FIXME: should be SCEV::FlagNW
2844 Flags = setFlags(Flags, SCEV::FlagNSW);
2847 const SCEV *StartVal = getSCEV(StartValueV);
2848 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
2850 // Since the no-wrap flags are on the increment, they apply to the
2851 // post-incremented value as well.
2852 if (isLoopInvariant(Accum, L))
2853 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
2856 // Okay, for the entire analysis of this edge we assumed the PHI
2857 // to be symbolic. We now need to go back and purge all of the
2858 // entries for the scalars that use the symbolic expression.
2859 ForgetSymbolicName(PN, SymbolicName);
2860 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
2864 } else if (const SCEVAddRecExpr *AddRec =
2865 dyn_cast<SCEVAddRecExpr>(BEValue)) {
2866 // Otherwise, this could be a loop like this:
2867 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2868 // In this case, j = {1,+,1} and BEValue is j.
2869 // Because the other in-value of i (0) fits the evolution of BEValue
2870 // i really is an addrec evolution.
2871 if (AddRec->getLoop() == L && AddRec->isAffine()) {
2872 const SCEV *StartVal = getSCEV(StartValueV);
2874 // If StartVal = j.start - j.stride, we can use StartVal as the
2875 // initial step of the addrec evolution.
2876 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
2877 AddRec->getOperand(1))) {
2878 // FIXME: For constant StartVal, we should be able to infer
2880 const SCEV *PHISCEV =
2881 getAddRecExpr(StartVal, AddRec->getOperand(1), L,
2884 // Okay, for the entire analysis of this edge we assumed the PHI
2885 // to be symbolic. We now need to go back and purge all of the
2886 // entries for the scalars that use the symbolic expression.
2887 ForgetSymbolicName(PN, SymbolicName);
2888 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
2896 // If the PHI has a single incoming value, follow that value, unless the
2897 // PHI's incoming blocks are in a different loop, in which case doing so
2898 // risks breaking LCSSA form. Instcombine would normally zap these, but
2899 // it doesn't have DominatorTree information, so it may miss cases.
2900 if (Value *V = SimplifyInstruction(PN, TD, DT))
2901 if (LI->replacementPreservesLCSSAForm(PN, V))
2904 // If it's not a loop phi, we can't handle it yet.
2905 return getUnknown(PN);
2908 /// createNodeForGEP - Expand GEP instructions into add and multiply
2909 /// operations. This allows them to be analyzed by regular SCEV code.
2911 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
2913 // Don't blindly transfer the inbounds flag from the GEP instruction to the
2914 // Add expression, because the Instruction may be guarded by control flow
2915 // and the no-overflow bits may not be valid for the expression in any
2917 bool isInBounds = GEP->isInBounds();
2919 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
2920 Value *Base = GEP->getOperand(0);
2921 // Don't attempt to analyze GEPs over unsized objects.
2922 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2923 return getUnknown(GEP);
2924 const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
2925 gep_type_iterator GTI = gep_type_begin(GEP);
2926 for (GetElementPtrInst::op_iterator I = llvm::next(GEP->op_begin()),
2930 // Compute the (potentially symbolic) offset in bytes for this index.
2931 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2932 // For a struct, add the member offset.
2933 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2934 const SCEV *FieldOffset = getOffsetOfExpr(STy, FieldNo);
2936 // Add the field offset to the running total offset.
2937 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
2939 // For an array, add the element offset, explicitly scaled.
2940 const SCEV *ElementSize = getSizeOfExpr(*GTI);
2941 const SCEV *IndexS = getSCEV(Index);
2942 // Getelementptr indices are signed.
2943 IndexS = getTruncateOrSignExtend(IndexS, IntPtrTy);
2945 // Multiply the index by the element size to compute the element offset.
2946 const SCEV *LocalOffset = getMulExpr(IndexS, ElementSize,
2947 isInBounds ? SCEV::FlagNSW :
2950 // Add the element offset to the running total offset.
2951 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2955 // Get the SCEV for the GEP base.
2956 const SCEV *BaseS = getSCEV(Base);
2958 // Add the total offset from all the GEP indices to the base.
2959 return getAddExpr(BaseS, TotalOffset,
2960 isInBounds ? SCEV::FlagNSW : SCEV::FlagAnyWrap);
2963 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2964 /// guaranteed to end in (at every loop iteration). It is, at the same time,
2965 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2966 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
2968 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
2969 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2970 return C->getValue()->getValue().countTrailingZeros();
2972 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
2973 return std::min(GetMinTrailingZeros(T->getOperand()),
2974 (uint32_t)getTypeSizeInBits(T->getType()));
2976 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
2977 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2978 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2979 getTypeSizeInBits(E->getType()) : OpRes;
2982 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
2983 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2984 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2985 getTypeSizeInBits(E->getType()) : OpRes;
2988 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
2989 // The result is the min of all operands results.
2990 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2991 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2992 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2996 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
2997 // The result is the sum of all operands results.
2998 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2999 uint32_t BitWidth = getTypeSizeInBits(M->getType());
3000 for (unsigned i = 1, e = M->getNumOperands();
3001 SumOpRes != BitWidth && i != e; ++i)
3002 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
3007 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
3008 // The result is the min of all operands results.
3009 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
3010 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
3011 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
3015 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
3016 // The result is the min of all operands results.
3017 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
3018 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
3019 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
3023 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
3024 // The result is the min of all operands results.
3025 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
3026 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
3027 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
3031 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3032 // For a SCEVUnknown, ask ValueTracking.
3033 unsigned BitWidth = getTypeSizeInBits(U->getType());
3034 APInt Mask = APInt::getAllOnesValue(BitWidth);
3035 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3036 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
3037 return Zeros.countTrailingOnes();
3044 /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
3047 ScalarEvolution::getUnsignedRange(const SCEV *S) {
3048 // See if we've computed this range already.
3049 DenseMap<const SCEV *, ConstantRange>::iterator I = UnsignedRanges.find(S);
3050 if (I != UnsignedRanges.end())
3053 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
3054 return setUnsignedRange(C, ConstantRange(C->getValue()->getValue()));
3056 unsigned BitWidth = getTypeSizeInBits(S->getType());
3057 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3059 // If the value has known zeros, the maximum unsigned value will have those
3060 // known zeros as well.
3061 uint32_t TZ = GetMinTrailingZeros(S);
3063 ConservativeResult =
3064 ConstantRange(APInt::getMinValue(BitWidth),
3065 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
3067 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3068 ConstantRange X = getUnsignedRange(Add->getOperand(0));
3069 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3070 X = X.add(getUnsignedRange(Add->getOperand(i)));
3071 return setUnsignedRange(Add, ConservativeResult.intersectWith(X));
3074 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3075 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
3076 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3077 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
3078 return setUnsignedRange(Mul, ConservativeResult.intersectWith(X));
3081 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3082 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
3083 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3084 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
3085 return setUnsignedRange(SMax, ConservativeResult.intersectWith(X));
3088 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3089 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
3090 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3091 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
3092 return setUnsignedRange(UMax, ConservativeResult.intersectWith(X));
3095 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3096 ConstantRange X = getUnsignedRange(UDiv->getLHS());
3097 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
3098 return setUnsignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
3101 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3102 ConstantRange X = getUnsignedRange(ZExt->getOperand());
3103 return setUnsignedRange(ZExt,
3104 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
3107 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3108 ConstantRange X = getUnsignedRange(SExt->getOperand());
3109 return setUnsignedRange(SExt,
3110 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
3113 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3114 ConstantRange X = getUnsignedRange(Trunc->getOperand());
3115 return setUnsignedRange(Trunc,
3116 ConservativeResult.intersectWith(X.truncate(BitWidth)));
3119 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
3120 // If there's no unsigned wrap, the value will never be less than its
3122 // FIXME: can broaden to FlagNW?
3123 if (AddRec->getNoWrapFlags(SCEV::FlagNUW))
3124 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
3125 if (!C->getValue()->isZero())
3126 ConservativeResult =
3127 ConservativeResult.intersectWith(
3128 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0)));
3130 // TODO: non-affine addrec
3131 if (AddRec->isAffine()) {
3132 const Type *Ty = AddRec->getType();
3133 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
3134 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3135 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
3136 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3138 const SCEV *Start = AddRec->getStart();
3139 const SCEV *Step = AddRec->getStepRecurrence(*this);
3141 ConstantRange StartRange = getUnsignedRange(Start);
3142 ConstantRange StepRange = getSignedRange(Step);
3143 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3144 ConstantRange EndRange =
3145 StartRange.add(MaxBECountRange.multiply(StepRange));
3147 // Check for overflow. This must be done with ConstantRange arithmetic
3148 // because we could be called from within the ScalarEvolution overflow
3150 ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
3151 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3152 ConstantRange ExtMaxBECountRange =
3153 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3154 ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
3155 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3157 return setUnsignedRange(AddRec, ConservativeResult);
3159 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
3160 EndRange.getUnsignedMin());
3161 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
3162 EndRange.getUnsignedMax());
3163 if (Min.isMinValue() && Max.isMaxValue())
3164 return setUnsignedRange(AddRec, ConservativeResult);
3165 return setUnsignedRange(AddRec,
3166 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
3170 return setUnsignedRange(AddRec, ConservativeResult);
3173 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3174 // For a SCEVUnknown, ask ValueTracking.
3175 APInt Mask = APInt::getAllOnesValue(BitWidth);
3176 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3177 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
3178 if (Ones == ~Zeros + 1)
3179 return setUnsignedRange(U, ConservativeResult);
3180 return setUnsignedRange(U,
3181 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)));
3184 return setUnsignedRange(S, ConservativeResult);
3187 /// getSignedRange - Determine the signed range for a particular SCEV.
3190 ScalarEvolution::getSignedRange(const SCEV *S) {
3191 // See if we've computed this range already.
3192 DenseMap<const SCEV *, ConstantRange>::iterator I = SignedRanges.find(S);
3193 if (I != SignedRanges.end())
3196 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
3197 return setSignedRange(C, ConstantRange(C->getValue()->getValue()));
3199 unsigned BitWidth = getTypeSizeInBits(S->getType());
3200 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3202 // If the value has known zeros, the maximum signed value will have those
3203 // known zeros as well.
3204 uint32_t TZ = GetMinTrailingZeros(S);
3206 ConservativeResult =
3207 ConstantRange(APInt::getSignedMinValue(BitWidth),
3208 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
3210 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3211 ConstantRange X = getSignedRange(Add->getOperand(0));
3212 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3213 X = X.add(getSignedRange(Add->getOperand(i)));
3214 return setSignedRange(Add, ConservativeResult.intersectWith(X));
3217 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3218 ConstantRange X = getSignedRange(Mul->getOperand(0));
3219 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3220 X = X.multiply(getSignedRange(Mul->getOperand(i)));
3221 return setSignedRange(Mul, ConservativeResult.intersectWith(X));
3224 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3225 ConstantRange X = getSignedRange(SMax->getOperand(0));
3226 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3227 X = X.smax(getSignedRange(SMax->getOperand(i)));
3228 return setSignedRange(SMax, ConservativeResult.intersectWith(X));
3231 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3232 ConstantRange X = getSignedRange(UMax->getOperand(0));
3233 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3234 X = X.umax(getSignedRange(UMax->getOperand(i)));
3235 return setSignedRange(UMax, ConservativeResult.intersectWith(X));
3238 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3239 ConstantRange X = getSignedRange(UDiv->getLHS());
3240 ConstantRange Y = getSignedRange(UDiv->getRHS());
3241 return setSignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
3244 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3245 ConstantRange X = getSignedRange(ZExt->getOperand());
3246 return setSignedRange(ZExt,
3247 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
3250 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3251 ConstantRange X = getSignedRange(SExt->getOperand());
3252 return setSignedRange(SExt,
3253 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
3256 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3257 ConstantRange X = getSignedRange(Trunc->getOperand());
3258 return setSignedRange(Trunc,
3259 ConservativeResult.intersectWith(X.truncate(BitWidth)));
3262 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
3263 // If there's no signed wrap, and all the operands have the same sign or
3264 // zero, the value won't ever change sign.
3265 if (AddRec->getNoWrapFlags(SCEV::FlagNSW)) {
3266 bool AllNonNeg = true;
3267 bool AllNonPos = true;
3268 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3269 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3270 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3273 ConservativeResult = ConservativeResult.intersectWith(
3274 ConstantRange(APInt(BitWidth, 0),
3275 APInt::getSignedMinValue(BitWidth)));
3277 ConservativeResult = ConservativeResult.intersectWith(
3278 ConstantRange(APInt::getSignedMinValue(BitWidth),
3279 APInt(BitWidth, 1)));
3282 // TODO: non-affine addrec
3283 if (AddRec->isAffine()) {
3284 const Type *Ty = AddRec->getType();
3285 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
3286 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3287 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
3288 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3290 const SCEV *Start = AddRec->getStart();
3291 const SCEV *Step = AddRec->getStepRecurrence(*this);
3293 ConstantRange StartRange = getSignedRange(Start);
3294 ConstantRange StepRange = getSignedRange(Step);
3295 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3296 ConstantRange EndRange =
3297 StartRange.add(MaxBECountRange.multiply(StepRange));
3299 // Check for overflow. This must be done with ConstantRange arithmetic
3300 // because we could be called from within the ScalarEvolution overflow
3302 ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
3303 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3304 ConstantRange ExtMaxBECountRange =
3305 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3306 ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
3307 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3309 return setSignedRange(AddRec, ConservativeResult);
3311 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3312 EndRange.getSignedMin());
3313 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3314 EndRange.getSignedMax());
3315 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
3316 return setSignedRange(AddRec, ConservativeResult);
3317 return setSignedRange(AddRec,
3318 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
3322 return setSignedRange(AddRec, ConservativeResult);
3325 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3326 // For a SCEVUnknown, ask ValueTracking.
3327 if (!U->getValue()->getType()->isIntegerTy() && !TD)
3328 return setSignedRange(U, ConservativeResult);
3329 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3331 return setSignedRange(U, ConservativeResult);
3332 return setSignedRange(U, ConservativeResult.intersectWith(
3333 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
3334 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1)));
3337 return setSignedRange(S, ConservativeResult);
3340 /// createSCEV - We know that there is no SCEV for the specified value.
3341 /// Analyze the expression.
3343 const SCEV *ScalarEvolution::createSCEV(Value *V) {
3344 if (!isSCEVable(V->getType()))
3345 return getUnknown(V);
3347 unsigned Opcode = Instruction::UserOp1;
3348 if (Instruction *I = dyn_cast<Instruction>(V)) {
3349 Opcode = I->getOpcode();
3351 // Don't attempt to analyze instructions in blocks that aren't
3352 // reachable. Such instructions don't matter, and they aren't required
3353 // to obey basic rules for definitions dominating uses which this
3354 // analysis depends on.
3355 if (!DT->isReachableFromEntry(I->getParent()))
3356 return getUnknown(V);
3357 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
3358 Opcode = CE->getOpcode();
3359 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3360 return getConstant(CI);
3361 else if (isa<ConstantPointerNull>(V))
3362 return getConstant(V->getType(), 0);
3363 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3364 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
3366 return getUnknown(V);
3368 Operator *U = cast<Operator>(V);
3370 case Instruction::Add: {
3371 // The simple thing to do would be to just call getSCEV on both operands
3372 // and call getAddExpr with the result. However if we're looking at a
3373 // bunch of things all added together, this can be quite inefficient,
3374 // because it leads to N-1 getAddExpr calls for N ultimate operands.
3375 // Instead, gather up all the operands and make a single getAddExpr call.
3376 // LLVM IR canonical form means we need only traverse the left operands.
3377 SmallVector<const SCEV *, 4> AddOps;
3378 AddOps.push_back(getSCEV(U->getOperand(1)));
3379 for (Value *Op = U->getOperand(0); ; Op = U->getOperand(0)) {
3380 unsigned Opcode = Op->getValueID() - Value::InstructionVal;
3381 if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
3383 U = cast<Operator>(Op);
3384 const SCEV *Op1 = getSCEV(U->getOperand(1));
3385 if (Opcode == Instruction::Sub)
3386 AddOps.push_back(getNegativeSCEV(Op1));
3388 AddOps.push_back(Op1);
3390 AddOps.push_back(getSCEV(U->getOperand(0)));
3391 return getAddExpr(AddOps);
3393 case Instruction::Mul: {
3394 // See the Add code above.
3395 SmallVector<const SCEV *, 4> MulOps;
3396 MulOps.push_back(getSCEV(U->getOperand(1)));
3397 for (Value *Op = U->getOperand(0);
3398 Op->getValueID() == Instruction::Mul + Value::InstructionVal;
3399 Op = U->getOperand(0)) {
3400 U = cast<Operator>(Op);
3401 MulOps.push_back(getSCEV(U->getOperand(1)));
3403 MulOps.push_back(getSCEV(U->getOperand(0)));
3404 return getMulExpr(MulOps);
3406 case Instruction::UDiv:
3407 return getUDivExpr(getSCEV(U->getOperand(0)),
3408 getSCEV(U->getOperand(1)));
3409 case Instruction::Sub:
3410 return getMinusSCEV(getSCEV(U->getOperand(0)),
3411 getSCEV(U->getOperand(1)));
3412 case Instruction::And:
3413 // For an expression like x&255 that merely masks off the high bits,
3414 // use zext(trunc(x)) as the SCEV expression.
3415 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3416 if (CI->isNullValue())
3417 return getSCEV(U->getOperand(1));
3418 if (CI->isAllOnesValue())
3419 return getSCEV(U->getOperand(0));
3420 const APInt &A = CI->getValue();
3422 // Instcombine's ShrinkDemandedConstant may strip bits out of
3423 // constants, obscuring what would otherwise be a low-bits mask.
3424 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3425 // knew about to reconstruct a low-bits mask value.
3426 unsigned LZ = A.countLeadingZeros();
3427 unsigned BitWidth = A.getBitWidth();
3428 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3429 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3430 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3432 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3434 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
3436 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
3437 IntegerType::get(getContext(), BitWidth - LZ)),
3442 case Instruction::Or:
3443 // If the RHS of the Or is a constant, we may have something like:
3444 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3445 // optimizations will transparently handle this case.
3447 // In order for this transformation to be safe, the LHS must be of the
3448 // form X*(2^n) and the Or constant must be less than 2^n.
3449 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3450 const SCEV *LHS = getSCEV(U->getOperand(0));
3451 const APInt &CIVal = CI->getValue();
3452 if (GetMinTrailingZeros(LHS) >=
3453 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3454 // Build a plain add SCEV.
3455 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3456 // If the LHS of the add was an addrec and it has no-wrap flags,
3457 // transfer the no-wrap flags, since an or won't introduce a wrap.
3458 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3459 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
3460 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
3461 OldAR->getNoWrapFlags());
3467 case Instruction::Xor:
3468 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3469 // If the RHS of the xor is a signbit, then this is just an add.
3470 // Instcombine turns add of signbit into xor as a strength reduction step.
3471 if (CI->getValue().isSignBit())
3472 return getAddExpr(getSCEV(U->getOperand(0)),
3473 getSCEV(U->getOperand(1)));
3475 // If the RHS of xor is -1, then this is a not operation.
3476 if (CI->isAllOnesValue())
3477 return getNotSCEV(getSCEV(U->getOperand(0)));
3479 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3480 // This is a variant of the check for xor with -1, and it handles
3481 // the case where instcombine has trimmed non-demanded bits out
3482 // of an xor with -1.
3483 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3484 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3485 if (BO->getOpcode() == Instruction::And &&
3486 LCI->getValue() == CI->getValue())
3487 if (const SCEVZeroExtendExpr *Z =
3488 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
3489 const Type *UTy = U->getType();
3490 const SCEV *Z0 = Z->getOperand();
3491 const Type *Z0Ty = Z0->getType();
3492 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3494 // If C is a low-bits mask, the zero extend is serving to
3495 // mask off the high bits. Complement the operand and
3496 // re-apply the zext.
3497 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3498 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3500 // If C is a single bit, it may be in the sign-bit position
3501 // before the zero-extend. In this case, represent the xor
3502 // using an add, which is equivalent, and re-apply the zext.
3503 APInt Trunc = CI->getValue().trunc(Z0TySize);
3504 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3506 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3512 case Instruction::Shl:
3513 // Turn shift left of a constant amount into a multiply.
3514 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3515 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
3517 // If the shift count is not less than the bitwidth, the result of
3518 // the shift is undefined. Don't try to analyze it, because the
3519 // resolution chosen here may differ from the resolution chosen in
3520 // other parts of the compiler.
3521 if (SA->getValue().uge(BitWidth))
3524 Constant *X = ConstantInt::get(getContext(),
3525 APInt(BitWidth, 1).shl(SA->getZExtValue()));
3526 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3530 case Instruction::LShr:
3531 // Turn logical shift right of a constant into a unsigned divide.
3532 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3533 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
3535 // If the shift count is not less than the bitwidth, the result of
3536 // the shift is undefined. Don't try to analyze it, because the
3537 // resolution chosen here may differ from the resolution chosen in
3538 // other parts of the compiler.
3539 if (SA->getValue().uge(BitWidth))
3542 Constant *X = ConstantInt::get(getContext(),
3543 APInt(BitWidth, 1).shl(SA->getZExtValue()));
3544 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3548 case Instruction::AShr:
3549 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3550 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
3551 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
3552 if (L->getOpcode() == Instruction::Shl &&
3553 L->getOperand(1) == U->getOperand(1)) {
3554 uint64_t BitWidth = getTypeSizeInBits(U->getType());
3556 // If the shift count is not less than the bitwidth, the result of
3557 // the shift is undefined. Don't try to analyze it, because the
3558 // resolution chosen here may differ from the resolution chosen in
3559 // other parts of the compiler.
3560 if (CI->getValue().uge(BitWidth))
3563 uint64_t Amt = BitWidth - CI->getZExtValue();
3564 if (Amt == BitWidth)
3565 return getSCEV(L->getOperand(0)); // shift by zero --> noop
3567 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
3568 IntegerType::get(getContext(),
3574 case Instruction::Trunc:
3575 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
3577 case Instruction::ZExt:
3578 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3580 case Instruction::SExt:
3581 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3583 case Instruction::BitCast:
3584 // BitCasts are no-op casts so we just eliminate the cast.
3585 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
3586 return getSCEV(U->getOperand(0));
3589 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3590 // lead to pointer expressions which cannot safely be expanded to GEPs,
3591 // because ScalarEvolution doesn't respect the GEP aliasing rules when
3592 // simplifying integer expressions.
3594 case Instruction::GetElementPtr:
3595 return createNodeForGEP(cast<GEPOperator>(U));
3597 case Instruction::PHI:
3598 return createNodeForPHI(cast<PHINode>(U));
3600 case Instruction::Select:
3601 // This could be a smax or umax that was lowered earlier.
3602 // Try to recover it.
3603 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3604 Value *LHS = ICI->getOperand(0);
3605 Value *RHS = ICI->getOperand(1);
3606 switch (ICI->getPredicate()) {
3607 case ICmpInst::ICMP_SLT:
3608 case ICmpInst::ICMP_SLE:
3609 std::swap(LHS, RHS);
3611 case ICmpInst::ICMP_SGT:
3612 case ICmpInst::ICMP_SGE:
3613 // a >s b ? a+x : b+x -> smax(a, b)+x
3614 // a >s b ? b+x : a+x -> smin(a, b)+x
3615 if (LHS->getType() == U->getType()) {
3616 const SCEV *LS = getSCEV(LHS);
3617 const SCEV *RS = getSCEV(RHS);
3618 const SCEV *LA = getSCEV(U->getOperand(1));
3619 const SCEV *RA = getSCEV(U->getOperand(2));
3620 const SCEV *LDiff = getMinusSCEV(LA, LS);
3621 const SCEV *RDiff = getMinusSCEV(RA, RS);
3623 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
3624 LDiff = getMinusSCEV(LA, RS);
3625 RDiff = getMinusSCEV(RA, LS);
3627 return getAddExpr(getSMinExpr(LS, RS), LDiff);
3630 case ICmpInst::ICMP_ULT:
3631 case ICmpInst::ICMP_ULE:
3632 std::swap(LHS, RHS);
3634 case ICmpInst::ICMP_UGT:
3635 case ICmpInst::ICMP_UGE:
3636 // a >u b ? a+x : b+x -> umax(a, b)+x
3637 // a >u b ? b+x : a+x -> umin(a, b)+x
3638 if (LHS->getType() == U->getType()) {
3639 const SCEV *LS = getSCEV(LHS);
3640 const SCEV *RS = getSCEV(RHS);
3641 const SCEV *LA = getSCEV(U->getOperand(1));
3642 const SCEV *RA = getSCEV(U->getOperand(2));
3643 const SCEV *LDiff = getMinusSCEV(LA, LS);
3644 const SCEV *RDiff = getMinusSCEV(RA, RS);
3646 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
3647 LDiff = getMinusSCEV(LA, RS);
3648 RDiff = getMinusSCEV(RA, LS);
3650 return getAddExpr(getUMinExpr(LS, RS), LDiff);
3653 case ICmpInst::ICMP_NE:
3654 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
3655 if (LHS->getType() == U->getType() &&
3656 isa<ConstantInt>(RHS) &&
3657 cast<ConstantInt>(RHS)->isZero()) {
3658 const SCEV *One = getConstant(LHS->getType(), 1);
3659 const SCEV *LS = getSCEV(LHS);
3660 const SCEV *LA = getSCEV(U->getOperand(1));
3661 const SCEV *RA = getSCEV(U->getOperand(2));
3662 const SCEV *LDiff = getMinusSCEV(LA, LS);
3663 const SCEV *RDiff = getMinusSCEV(RA, One);
3665 return getAddExpr(getUMaxExpr(One, LS), LDiff);
3668 case ICmpInst::ICMP_EQ:
3669 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
3670 if (LHS->getType() == U->getType() &&
3671 isa<ConstantInt>(RHS) &&
3672 cast<ConstantInt>(RHS)->isZero()) {
3673 const SCEV *One = getConstant(LHS->getType(), 1);
3674 const SCEV *LS = getSCEV(LHS);
3675 const SCEV *LA = getSCEV(U->getOperand(1));
3676 const SCEV *RA = getSCEV(U->getOperand(2));
3677 const SCEV *LDiff = getMinusSCEV(LA, One);
3678 const SCEV *RDiff = getMinusSCEV(RA, LS);
3680 return getAddExpr(getUMaxExpr(One, LS), LDiff);
3688 default: // We cannot analyze this expression.
3692 return getUnknown(V);
3697 //===----------------------------------------------------------------------===//
3698 // Iteration Count Computation Code
3701 /// getBackedgeTakenCount - If the specified loop has a predictable
3702 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3703 /// object. The backedge-taken count is the number of times the loop header
3704 /// will be branched to from within the loop. This is one less than the
3705 /// trip count of the loop, since it doesn't count the first iteration,
3706 /// when the header is branched to from outside the loop.
3708 /// Note that it is not valid to call this method on a loop without a
3709 /// loop-invariant backedge-taken count (see
3710 /// hasLoopInvariantBackedgeTakenCount).
3712 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
3713 return getBackedgeTakenInfo(L).Exact;
3716 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3717 /// return the least SCEV value that is known never to be less than the
3718 /// actual backedge taken count.
3719 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
3720 return getBackedgeTakenInfo(L).Max;
3723 /// PushLoopPHIs - Push PHI nodes in the header of the given loop
3724 /// onto the given Worklist.
3726 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3727 BasicBlock *Header = L->getHeader();
3729 // Push all Loop-header PHIs onto the Worklist stack.
3730 for (BasicBlock::iterator I = Header->begin();
3731 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3732 Worklist.push_back(PN);
3735 const ScalarEvolution::BackedgeTakenInfo &
3736 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
3737 // Initially insert a CouldNotCompute for this loop. If the insertion
3738 // succeeds, proceed to actually compute a backedge-taken count and
3739 // update the value. The temporary CouldNotCompute value tells SCEV
3740 // code elsewhere that it shouldn't attempt to request a new
3741 // backedge-taken count, which could result in infinite recursion.
3742 std::pair<std::map<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
3743 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3745 return Pair.first->second;
3747 BackedgeTakenInfo BECount = ComputeBackedgeTakenCount(L);
3748 if (BECount.Exact != getCouldNotCompute()) {
3749 assert(isLoopInvariant(BECount.Exact, L) &&
3750 isLoopInvariant(BECount.Max, L) &&
3751 "Computed backedge-taken count isn't loop invariant for loop!");
3752 ++NumTripCountsComputed;
3754 // Update the value in the map.
3755 Pair.first->second = BECount;
3757 if (BECount.Max != getCouldNotCompute())
3758 // Update the value in the map.
3759 Pair.first->second = BECount;
3760 if (isa<PHINode>(L->getHeader()->begin()))
3761 // Only count loops that have phi nodes as not being computable.
3762 ++NumTripCountsNotComputed;
3765 // Now that we know more about the trip count for this loop, forget any
3766 // existing SCEV values for PHI nodes in this loop since they are only
3767 // conservative estimates made without the benefit of trip count
3768 // information. This is similar to the code in forgetLoop, except that
3769 // it handles SCEVUnknown PHI nodes specially.
3770 if (BECount.hasAnyInfo()) {
3771 SmallVector<Instruction *, 16> Worklist;
3772 PushLoopPHIs(L, Worklist);
3774 SmallPtrSet<Instruction *, 8> Visited;
3775 while (!Worklist.empty()) {
3776 Instruction *I = Worklist.pop_back_val();
3777 if (!Visited.insert(I)) continue;
3779 ValueExprMapType::iterator It =
3780 ValueExprMap.find(static_cast<Value *>(I));
3781 if (It != ValueExprMap.end()) {
3782 const SCEV *Old = It->second;
3784 // SCEVUnknown for a PHI either means that it has an unrecognized
3785 // structure, or it's a PHI that's in the progress of being computed
3786 // by createNodeForPHI. In the former case, additional loop trip
3787 // count information isn't going to change anything. In the later
3788 // case, createNodeForPHI will perform the necessary updates on its
3789 // own when it gets to that point.
3790 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
3791 forgetMemoizedResults(Old);
3792 ValueExprMap.erase(It);
3794 if (PHINode *PN = dyn_cast<PHINode>(I))
3795 ConstantEvolutionLoopExitValue.erase(PN);
3798 PushDefUseChildren(I, Worklist);
3801 return Pair.first->second;
3804 /// forgetLoop - This method should be called by the client when it has
3805 /// changed a loop in a way that may effect ScalarEvolution's ability to
3806 /// compute a trip count, or if the loop is deleted.
3807 void ScalarEvolution::forgetLoop(const Loop *L) {
3808 // Drop any stored trip count value.
3809 BackedgeTakenCounts.erase(L);
3811 // Drop information about expressions based on loop-header PHIs.
3812 SmallVector<Instruction *, 16> Worklist;
3813 PushLoopPHIs(L, Worklist);
3815 SmallPtrSet<Instruction *, 8> Visited;
3816 while (!Worklist.empty()) {
3817 Instruction *I = Worklist.pop_back_val();
3818 if (!Visited.insert(I)) continue;
3820 ValueExprMapType::iterator It = ValueExprMap.find(static_cast<Value *>(I));
3821 if (It != ValueExprMap.end()) {
3822 forgetMemoizedResults(It->second);
3823 ValueExprMap.erase(It);
3824 if (PHINode *PN = dyn_cast<PHINode>(I))
3825 ConstantEvolutionLoopExitValue.erase(PN);
3828 PushDefUseChildren(I, Worklist);
3831 // Forget all contained loops too, to avoid dangling entries in the
3832 // ValuesAtScopes map.
3833 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3837 /// forgetValue - This method should be called by the client when it has
3838 /// changed a value in a way that may effect its value, or which may
3839 /// disconnect it from a def-use chain linking it to a loop.
3840 void ScalarEvolution::forgetValue(Value *V) {
3841 Instruction *I = dyn_cast<Instruction>(V);
3844 // Drop information about expressions based on loop-header PHIs.
3845 SmallVector<Instruction *, 16> Worklist;
3846 Worklist.push_back(I);
3848 SmallPtrSet<Instruction *, 8> Visited;
3849 while (!Worklist.empty()) {
3850 I = Worklist.pop_back_val();
3851 if (!Visited.insert(I)) continue;
3853 ValueExprMapType::iterator It = ValueExprMap.find(static_cast<Value *>(I));
3854 if (It != ValueExprMap.end()) {
3855 forgetMemoizedResults(It->second);
3856 ValueExprMap.erase(It);
3857 if (PHINode *PN = dyn_cast<PHINode>(I))
3858 ConstantEvolutionLoopExitValue.erase(PN);
3861 PushDefUseChildren(I, Worklist);
3865 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
3866 /// of the specified loop will execute.
3867 ScalarEvolution::BackedgeTakenInfo
3868 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
3869 SmallVector<BasicBlock *, 8> ExitingBlocks;
3870 L->getExitingBlocks(ExitingBlocks);
3872 // Examine all exits and pick the most conservative values.
3873 const SCEV *BECount = getCouldNotCompute();
3874 const SCEV *MaxBECount = getCouldNotCompute();
3875 bool CouldNotComputeBECount = false;
3876 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3877 BackedgeTakenInfo NewBTI =
3878 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
3880 if (NewBTI.Exact == getCouldNotCompute()) {
3881 // We couldn't compute an exact value for this exit, so
3882 // we won't be able to compute an exact value for the loop.
3883 CouldNotComputeBECount = true;
3884 BECount = getCouldNotCompute();
3885 } else if (!CouldNotComputeBECount) {
3886 if (BECount == getCouldNotCompute())
3887 BECount = NewBTI.Exact;
3889 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
3891 if (MaxBECount == getCouldNotCompute())
3892 MaxBECount = NewBTI.Max;
3893 else if (NewBTI.Max != getCouldNotCompute())
3894 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
3897 return BackedgeTakenInfo(BECount, MaxBECount);
3900 /// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3901 /// of the specified loop will execute if it exits via the specified block.
3902 ScalarEvolution::BackedgeTakenInfo
3903 ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3904 BasicBlock *ExitingBlock) {
3906 // Okay, we've chosen an exiting block. See what condition causes us to
3907 // exit at this block.
3909 // FIXME: we should be able to handle switch instructions (with a single exit)
3910 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
3911 if (ExitBr == 0) return getCouldNotCompute();
3912 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
3914 // At this point, we know we have a conditional branch that determines whether
3915 // the loop is exited. However, we don't know if the branch is executed each
3916 // time through the loop. If not, then the execution count of the branch will
3917 // not be equal to the trip count of the loop.
3919 // Currently we check for this by checking to see if the Exit branch goes to
3920 // the loop header. If so, we know it will always execute the same number of
3921 // times as the loop. We also handle the case where the exit block *is* the
3922 // loop header. This is common for un-rotated loops.
3924 // If both of those tests fail, walk up the unique predecessor chain to the
3925 // header, stopping if there is an edge that doesn't exit the loop. If the
3926 // header is reached, the execution count of the branch will be equal to the
3927 // trip count of the loop.
3929 // More extensive analysis could be done to handle more cases here.
3931 if (ExitBr->getSuccessor(0) != L->getHeader() &&
3932 ExitBr->getSuccessor(1) != L->getHeader() &&
3933 ExitBr->getParent() != L->getHeader()) {
3934 // The simple checks failed, try climbing the unique predecessor chain
3935 // up to the header.
3937 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3938 BasicBlock *Pred = BB->getUniquePredecessor();
3940 return getCouldNotCompute();
3941 TerminatorInst *PredTerm = Pred->getTerminator();
3942 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3943 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3946 // If the predecessor has a successor that isn't BB and isn't
3947 // outside the loop, assume the worst.
3948 if (L->contains(PredSucc))
3949 return getCouldNotCompute();
3951 if (Pred == L->getHeader()) {
3958 return getCouldNotCompute();
3961 // Proceed to the next level to examine the exit condition expression.
3962 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3963 ExitBr->getSuccessor(0),
3964 ExitBr->getSuccessor(1));
3967 /// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3968 /// backedge of the specified loop will execute if its exit condition
3969 /// were a conditional branch of ExitCond, TBB, and FBB.
3970 ScalarEvolution::BackedgeTakenInfo
3971 ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3975 // Check if the controlling expression for this loop is an And or Or.
3976 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3977 if (BO->getOpcode() == Instruction::And) {
3978 // Recurse on the operands of the and.
3979 BackedgeTakenInfo BTI0 =
3980 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3981 BackedgeTakenInfo BTI1 =
3982 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3983 const SCEV *BECount = getCouldNotCompute();
3984 const SCEV *MaxBECount = getCouldNotCompute();
3985 if (L->contains(TBB)) {
3986 // Both conditions must be true for the loop to continue executing.
3987 // Choose the less conservative count.
3988 if (BTI0.Exact == getCouldNotCompute() ||
3989 BTI1.Exact == getCouldNotCompute())
3990 BECount = getCouldNotCompute();
3992 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3993 if (BTI0.Max == getCouldNotCompute())
3994 MaxBECount = BTI1.Max;
3995 else if (BTI1.Max == getCouldNotCompute())
3996 MaxBECount = BTI0.Max;
3998 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
4000 // Both conditions must be true at the same time for the loop to exit.
4001 // For now, be conservative.
4002 assert(L->contains(FBB) && "Loop block has no successor in loop!");
4003 if (BTI0.Max == BTI1.Max)
4004 MaxBECount = BTI0.Max;
4005 if (BTI0.Exact == BTI1.Exact)
4006 BECount = BTI0.Exact;
4009 return BackedgeTakenInfo(BECount, MaxBECount);
4011 if (BO->getOpcode() == Instruction::Or) {
4012 // Recurse on the operands of the or.
4013 BackedgeTakenInfo BTI0 =
4014 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
4015 BackedgeTakenInfo BTI1 =
4016 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
4017 const SCEV *BECount = getCouldNotCompute();
4018 const SCEV *MaxBECount = getCouldNotCompute();
4019 if (L->contains(FBB)) {
4020 // Both conditions must be false for the loop to continue executing.
4021 // Choose the less conservative count.
4022 if (BTI0.Exact == getCouldNotCompute() ||
4023 BTI1.Exact == getCouldNotCompute())
4024 BECount = getCouldNotCompute();
4026 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
4027 if (BTI0.Max == getCouldNotCompute())
4028 MaxBECount = BTI1.Max;
4029 else if (BTI1.Max == getCouldNotCompute())
4030 MaxBECount = BTI0.Max;
4032 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
4034 // Both conditions must be false at the same time for the loop to exit.
4035 // For now, be conservative.
4036 assert(L->contains(TBB) && "Loop block has no successor in loop!");
4037 if (BTI0.Max == BTI1.Max)
4038 MaxBECount = BTI0.Max;
4039 if (BTI0.Exact == BTI1.Exact)
4040 BECount = BTI0.Exact;
4043 return BackedgeTakenInfo(BECount, MaxBECount);
4047 // With an icmp, it may be feasible to compute an exact backedge-taken count.
4048 // Proceed to the next level to examine the icmp.
4049 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
4050 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
4052 // Check for a constant condition. These are normally stripped out by
4053 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
4054 // preserve the CFG and is temporarily leaving constant conditions
4056 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
4057 if (L->contains(FBB) == !CI->getZExtValue())
4058 // The backedge is always taken.
4059 return getCouldNotCompute();
4061 // The backedge is never taken.
4062 return getConstant(CI->getType(), 0);
4065 // If it's not an integer or pointer comparison then compute it the hard way.
4066 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
4069 static const SCEVAddRecExpr *
4070 isSimpleUnwrappingAddRec(const SCEV *S, const Loop *L) {
4071 const SCEVAddRecExpr *SA = dyn_cast<SCEVAddRecExpr>(S);
4073 // The SCEV must be an addrec of this loop.
4074 if (!SA || SA->getLoop() != L || !SA->isAffine())
4077 // The SCEV must be known to not wrap in some way to be interesting.
4078 if (!SA->getNoWrapFlags(SCEV::FlagNW))
4081 // The stride must be a constant so that we know if it is striding up or down.
4082 if (!isa<SCEVConstant>(SA->getOperand(1)))
4087 /// getMinusSCEVForExitTest - When considering an exit test for a loop with a
4088 /// "x != y" exit test, we turn this into a computation that evaluates x-y != 0,
4089 /// and this function returns the expression to use for x-y. We know and take
4090 /// advantage of the fact that this subtraction is only being used in a
4091 /// comparison by zero context.
4093 /// FIXME: this can be completely removed once AddRec FlagNWs are propagated.
4094 static const SCEV *getMinusSCEVForExitTest(const SCEV *LHS, const SCEV *RHS,
4095 const Loop *L, ScalarEvolution &SE) {
4096 // If either LHS or RHS is an AddRec SCEV (of this loop) that is known to not
4097 // self-wrap, then we know that the value will either become the other one
4098 // (and thus the loop terminates), that the loop will terminate through some
4099 // other exit condition first, or that the loop has undefined behavior. This
4100 // information is useful when the addrec has a stride that is != 1 or -1,
4101 // because it means we can't "miss" the exit value.
4103 // In any of these three cases, it is safe to turn the exit condition into a
4104 // "counting down" AddRec (to zero) by subtracting the two inputs as normal,
4105 // but since we know that the "end cannot be missed" we can force the
4106 // resulting AddRec to be a NUW addrec. Since it is counting down, this means
4107 // that the AddRec *cannot* pass zero.
4109 // See if LHS and RHS are addrec's we can handle.
4110 const SCEVAddRecExpr *LHSA = isSimpleUnwrappingAddRec(LHS, L);
4111 const SCEVAddRecExpr *RHSA = isSimpleUnwrappingAddRec(RHS, L);
4113 // If neither addrec is interesting, just return a minus.
4114 if (RHSA == 0 && LHSA == 0)
4115 return SE.getMinusSCEV(LHS, RHS);
4117 // If only one of LHS and RHS are an AddRec of this loop, make sure it is LHS.
4118 if (RHSA && LHSA == 0) {
4119 // Safe because a-b === b-a for comparisons against zero.
4120 std::swap(LHS, RHS);
4121 std::swap(LHSA, RHSA);
4124 // Handle the case when only one is advancing in a non-overflowing way.
4126 // If RHS is loop varying, then we can't predict when LHS will cross it.
4127 if (!SE.isLoopInvariant(RHS, L))
4128 return SE.getMinusSCEV(LHS, RHS);
4130 // If LHS has a positive stride, then we compute RHS-LHS, because the loop
4131 // is counting up until it crosses RHS (which must be larger than LHS). If
4132 // it is negative, we compute LHS-RHS because we're counting down to RHS.
4133 const ConstantInt *Stride =
4134 cast<SCEVConstant>(LHSA->getOperand(1))->getValue();
4135 if (Stride->getValue().isNegative())
4136 std::swap(LHS, RHS);
4138 return SE.getMinusSCEV(RHS, LHS, SCEV::FlagNUW);
4141 // If both LHS and RHS are interesting, we have something like:
4143 const ConstantInt *LHSStride =
4144 cast<SCEVConstant>(LHSA->getOperand(1))->getValue();
4145 const ConstantInt *RHSStride =
4146 cast<SCEVConstant>(RHSA->getOperand(1))->getValue();
4148 // If the strides are equal, then this is just a (complex) loop invariant
4149 // comparison of a and b.
4150 if (LHSStride == RHSStride)
4151 return SE.getMinusSCEV(LHSA->getStart(), RHSA->getStart());
4153 // If the signs of the strides differ, then the negative stride is counting
4154 // down to the positive stride.
4155 if (LHSStride->getValue().isNegative() != RHSStride->getValue().isNegative()){
4156 if (RHSStride->getValue().isNegative())
4157 std::swap(LHS, RHS);
4159 // If LHS's stride is smaller than RHS's stride, then "b" must be less than
4160 // "a" and "b" is RHS is counting up (catching up) to LHS. This is true
4161 // whether the strides are positive or negative.
4162 if (RHSStride->getValue().slt(LHSStride->getValue()))
4163 std::swap(LHS, RHS);
4166 return SE.getMinusSCEV(LHS, RHS, SCEV::FlagNUW);
4169 /// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
4170 /// backedge of the specified loop will execute if its exit condition
4171 /// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
4172 ScalarEvolution::BackedgeTakenInfo
4173 ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
4178 // If the condition was exit on true, convert the condition to exit on false
4179 ICmpInst::Predicate Cond;
4180 if (!L->contains(FBB))
4181 Cond = ExitCond->getPredicate();
4183 Cond = ExitCond->getInversePredicate();
4185 // Handle common loops like: for (X = "string"; *X; ++X)
4186 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
4187 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
4188 BackedgeTakenInfo ItCnt =
4189 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
4190 if (ItCnt.hasAnyInfo())
4194 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
4195 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
4197 // Try to evaluate any dependencies out of the loop.
4198 LHS = getSCEVAtScope(LHS, L);
4199 RHS = getSCEVAtScope(RHS, L);
4201 // At this point, we would like to compute how many iterations of the
4202 // loop the predicate will return true for these inputs.
4203 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
4204 // If there is a loop-invariant, force it into the RHS.
4205 std::swap(LHS, RHS);
4206 Cond = ICmpInst::getSwappedPredicate(Cond);
4209 // Simplify the operands before analyzing them.
4210 (void)SimplifyICmpOperands(Cond, LHS, RHS);
4212 // If we have a comparison of a chrec against a constant, try to use value
4213 // ranges to answer this query.
4214 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
4215 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
4216 if (AddRec->getLoop() == L) {
4217 // Form the constant range.
4218 ConstantRange CompRange(
4219 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
4221 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
4222 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
4226 case ICmpInst::ICMP_NE: { // while (X != Y)
4227 // Convert to: while (X-Y != 0)
4228 // FIXME: Once AddRec FlagNW are propagated, should be:
4229 // BackedgeTakenInfo BTI = HowFarToZero(getMinusSCEV(LHS, RHS), L);
4230 BackedgeTakenInfo BTI = HowFarToZero(getMinusSCEVForExitTest(LHS, RHS, L,
4232 if (BTI.hasAnyInfo()) return BTI;
4235 case ICmpInst::ICMP_EQ: { // while (X == Y)
4236 // Convert to: while (X-Y == 0)
4237 BackedgeTakenInfo BTI = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
4238 if (BTI.hasAnyInfo()) return BTI;
4241 case ICmpInst::ICMP_SLT: {
4242 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
4243 if (BTI.hasAnyInfo()) return BTI;
4246 case ICmpInst::ICMP_SGT: {
4247 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
4248 getNotSCEV(RHS), L, true);
4249 if (BTI.hasAnyInfo()) return BTI;
4252 case ICmpInst::ICMP_ULT: {
4253 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
4254 if (BTI.hasAnyInfo()) return BTI;
4257 case ICmpInst::ICMP_UGT: {
4258 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
4259 getNotSCEV(RHS), L, false);
4260 if (BTI.hasAnyInfo()) return BTI;
4265 dbgs() << "ComputeBackedgeTakenCount ";
4266 if (ExitCond->getOperand(0)->getType()->isUnsigned())
4267 dbgs() << "[unsigned] ";
4268 dbgs() << *LHS << " "
4269 << Instruction::getOpcodeName(Instruction::ICmp)
4270 << " " << *RHS << "\n";
4275 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
4278 static ConstantInt *
4279 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
4280 ScalarEvolution &SE) {
4281 const SCEV *InVal = SE.getConstant(C);
4282 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
4283 assert(isa<SCEVConstant>(Val) &&
4284 "Evaluation of SCEV at constant didn't fold correctly?");
4285 return cast<SCEVConstant>(Val)->getValue();
4288 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
4289 /// and a GEP expression (missing the pointer index) indexing into it, return
4290 /// the addressed element of the initializer or null if the index expression is
4293 GetAddressedElementFromGlobal(GlobalVariable *GV,
4294 const std::vector<ConstantInt*> &Indices) {
4295 Constant *Init = GV->getInitializer();
4296 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
4297 uint64_t Idx = Indices[i]->getZExtValue();
4298 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
4299 assert(Idx < CS->getNumOperands() && "Bad struct index!");
4300 Init = cast<Constant>(CS->getOperand(Idx));
4301 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
4302 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
4303 Init = cast<Constant>(CA->getOperand(Idx));
4304 } else if (isa<ConstantAggregateZero>(Init)) {
4305 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
4306 assert(Idx < STy->getNumElements() && "Bad struct index!");
4307 Init = Constant::getNullValue(STy->getElementType(Idx));
4308 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
4309 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
4310 Init = Constant::getNullValue(ATy->getElementType());
4312 llvm_unreachable("Unknown constant aggregate type!");
4316 return 0; // Unknown initializer type
4322 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
4323 /// 'icmp op load X, cst', try to see if we can compute the backedge
4324 /// execution count.
4325 ScalarEvolution::BackedgeTakenInfo
4326 ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
4330 ICmpInst::Predicate predicate) {
4331 if (LI->isVolatile()) return getCouldNotCompute();
4333 // Check to see if the loaded pointer is a getelementptr of a global.
4334 // TODO: Use SCEV instead of manually grubbing with GEPs.
4335 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
4336 if (!GEP) return getCouldNotCompute();
4338 // Make sure that it is really a constant global we are gepping, with an
4339 // initializer, and make sure the first IDX is really 0.
4340 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
4341 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
4342 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
4343 !cast<Constant>(GEP->getOperand(1))->isNullValue())
4344 return getCouldNotCompute();
4346 // Okay, we allow one non-constant index into the GEP instruction.
4348 std::vector<ConstantInt*> Indexes;
4349 unsigned VarIdxNum = 0;
4350 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
4351 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4352 Indexes.push_back(CI);
4353 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
4354 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
4355 VarIdx = GEP->getOperand(i);
4357 Indexes.push_back(0);
4360 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
4361 // Check to see if X is a loop variant variable value now.
4362 const SCEV *Idx = getSCEV(VarIdx);
4363 Idx = getSCEVAtScope(Idx, L);
4365 // We can only recognize very limited forms of loop index expressions, in
4366 // particular, only affine AddRec's like {C1,+,C2}.
4367 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
4368 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
4369 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
4370 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
4371 return getCouldNotCompute();
4373 unsigned MaxSteps = MaxBruteForceIterations;
4374 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
4375 ConstantInt *ItCst = ConstantInt::get(
4376 cast<IntegerType>(IdxExpr->getType()), IterationNum);
4377 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
4379 // Form the GEP offset.
4380 Indexes[VarIdxNum] = Val;
4382 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
4383 if (Result == 0) break; // Cannot compute!
4385 // Evaluate the condition for this iteration.
4386 Result = ConstantExpr::getICmp(predicate, Result, RHS);
4387 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
4388 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
4390 dbgs() << "\n***\n*** Computed loop count " << *ItCst
4391 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
4394 ++NumArrayLenItCounts;
4395 return getConstant(ItCst); // Found terminating iteration!
4398 return getCouldNotCompute();
4402 /// CanConstantFold - Return true if we can constant fold an instruction of the
4403 /// specified type, assuming that all operands were constants.
4404 static bool CanConstantFold(const Instruction *I) {
4405 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
4406 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
4409 if (const CallInst *CI = dyn_cast<CallInst>(I))
4410 if (const Function *F = CI->getCalledFunction())
4411 return canConstantFoldCallTo(F);
4415 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
4416 /// in the loop that V is derived from. We allow arbitrary operations along the
4417 /// way, but the operands of an operation must either be constants or a value
4418 /// derived from a constant PHI. If this expression does not fit with these
4419 /// constraints, return null.
4420 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
4421 // If this is not an instruction, or if this is an instruction outside of the
4422 // loop, it can't be derived from a loop PHI.
4423 Instruction *I = dyn_cast<Instruction>(V);
4424 if (I == 0 || !L->contains(I)) return 0;
4426 if (PHINode *PN = dyn_cast<PHINode>(I)) {
4427 if (L->getHeader() == I->getParent())
4430 // We don't currently keep track of the control flow needed to evaluate
4431 // PHIs, so we cannot handle PHIs inside of loops.
4435 // If we won't be able to constant fold this expression even if the operands
4436 // are constants, return early.
4437 if (!CanConstantFold(I)) return 0;
4439 // Otherwise, we can evaluate this instruction if all of its operands are
4440 // constant or derived from a PHI node themselves.
4442 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
4443 if (!isa<Constant>(I->getOperand(Op))) {
4444 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
4445 if (P == 0) return 0; // Not evolving from PHI
4449 return 0; // Evolving from multiple different PHIs.
4452 // This is a expression evolving from a constant PHI!
4456 /// EvaluateExpression - Given an expression that passes the
4457 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
4458 /// in the loop has the value PHIVal. If we can't fold this expression for some
4459 /// reason, return null.
4460 static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
4461 const TargetData *TD) {
4462 if (isa<PHINode>(V)) return PHIVal;
4463 if (Constant *C = dyn_cast<Constant>(V)) return C;
4464 Instruction *I = cast<Instruction>(V);
4466 std::vector<Constant*> Operands(I->getNumOperands());
4468 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4469 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
4470 if (Operands[i] == 0) return 0;
4473 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4474 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
4476 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4477 &Operands[0], Operands.size(), TD);
4480 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
4481 /// in the header of its containing loop, we know the loop executes a
4482 /// constant number of times, and the PHI node is just a recurrence
4483 /// involving constants, fold it.
4485 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
4488 std::map<PHINode*, Constant*>::const_iterator I =
4489 ConstantEvolutionLoopExitValue.find(PN);
4490 if (I != ConstantEvolutionLoopExitValue.end())
4493 if (BEs.ugt(MaxBruteForceIterations))
4494 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
4496 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
4498 // Since the loop is canonicalized, the PHI node must have two entries. One
4499 // entry must be a constant (coming in from outside of the loop), and the
4500 // second must be derived from the same PHI.
4501 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4502 Constant *StartCST =
4503 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4505 return RetVal = 0; // Must be a constant.
4507 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4508 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4509 !isa<Constant>(BEValue))
4510 return RetVal = 0; // Not derived from same PHI.
4512 // Execute the loop symbolically to determine the exit value.
4513 if (BEs.getActiveBits() >= 32)
4514 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
4516 unsigned NumIterations = BEs.getZExtValue(); // must be in range
4517 unsigned IterationNum = 0;
4518 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
4519 if (IterationNum == NumIterations)
4520 return RetVal = PHIVal; // Got exit value!
4522 // Compute the value of the PHI node for the next iteration.
4523 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
4524 if (NextPHI == PHIVal)
4525 return RetVal = NextPHI; // Stopped evolving!
4527 return 0; // Couldn't evaluate!
4532 /// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
4533 /// constant number of times (the condition evolves only from constants),
4534 /// try to evaluate a few iterations of the loop until we get the exit
4535 /// condition gets a value of ExitWhen (true or false). If we cannot
4536 /// evaluate the trip count of the loop, return getCouldNotCompute().
4538 ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
4541 PHINode *PN = getConstantEvolvingPHI(Cond, L);
4542 if (PN == 0) return getCouldNotCompute();
4544 // If the loop is canonicalized, the PHI will have exactly two entries.
4545 // That's the only form we support here.
4546 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
4548 // One entry must be a constant (coming in from outside of the loop), and the
4549 // second must be derived from the same PHI.
4550 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4551 Constant *StartCST =
4552 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4553 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
4555 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4556 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4557 !isa<Constant>(BEValue))
4558 return getCouldNotCompute(); // Not derived from same PHI.
4560 // Okay, we find a PHI node that defines the trip count of this loop. Execute
4561 // the loop symbolically to determine when the condition gets a value of
4563 unsigned IterationNum = 0;
4564 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
4565 for (Constant *PHIVal = StartCST;
4566 IterationNum != MaxIterations; ++IterationNum) {
4567 ConstantInt *CondVal =
4568 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
4570 // Couldn't symbolically evaluate.
4571 if (!CondVal) return getCouldNotCompute();
4573 if (CondVal->getValue() == uint64_t(ExitWhen)) {
4574 ++NumBruteForceTripCountsComputed;
4575 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
4578 // Compute the value of the PHI node for the next iteration.
4579 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
4580 if (NextPHI == 0 || NextPHI == PHIVal)
4581 return getCouldNotCompute();// Couldn't evaluate or not making progress...
4585 // Too many iterations were needed to evaluate.
4586 return getCouldNotCompute();
4589 /// getSCEVAtScope - Return a SCEV expression for the specified value
4590 /// at the specified scope in the program. The L value specifies a loop
4591 /// nest to evaluate the expression at, where null is the top-level or a
4592 /// specified loop is immediately inside of the loop.
4594 /// This method can be used to compute the exit value for a variable defined
4595 /// in a loop by querying what the value will hold in the parent loop.
4597 /// In the case that a relevant loop exit value cannot be computed, the
4598 /// original value V is returned.
4599 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
4600 // Check to see if we've folded this expression at this loop before.
4601 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4602 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4603 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4605 return Pair.first->second ? Pair.first->second : V;
4607 // Otherwise compute it.
4608 const SCEV *C = computeSCEVAtScope(V, L);
4609 ValuesAtScopes[V][L] = C;
4613 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
4614 if (isa<SCEVConstant>(V)) return V;
4616 // If this instruction is evolved from a constant-evolving PHI, compute the
4617 // exit value from the loop without using SCEVs.
4618 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
4619 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
4620 const Loop *LI = (*this->LI)[I->getParent()];
4621 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
4622 if (PHINode *PN = dyn_cast<PHINode>(I))
4623 if (PN->getParent() == LI->getHeader()) {
4624 // Okay, there is no closed form solution for the PHI node. Check
4625 // to see if the loop that contains it has a known backedge-taken
4626 // count. If so, we may be able to force computation of the exit
4628 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
4629 if (const SCEVConstant *BTCC =
4630 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
4631 // Okay, we know how many times the containing loop executes. If
4632 // this is a constant evolving PHI node, get the final value at
4633 // the specified iteration number.
4634 Constant *RV = getConstantEvolutionLoopExitValue(PN,
4635 BTCC->getValue()->getValue(),
4637 if (RV) return getSCEV(RV);
4641 // Okay, this is an expression that we cannot symbolically evaluate
4642 // into a SCEV. Check to see if it's possible to symbolically evaluate
4643 // the arguments into constants, and if so, try to constant propagate the
4644 // result. This is particularly useful for computing loop exit values.
4645 if (CanConstantFold(I)) {
4646 SmallVector<Constant *, 4> Operands;
4647 bool MadeImprovement = false;
4648 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4649 Value *Op = I->getOperand(i);
4650 if (Constant *C = dyn_cast<Constant>(Op)) {
4651 Operands.push_back(C);
4655 // If any of the operands is non-constant and if they are
4656 // non-integer and non-pointer, don't even try to analyze them
4657 // with scev techniques.
4658 if (!isSCEVable(Op->getType()))
4661 const SCEV *OrigV = getSCEV(Op);
4662 const SCEV *OpV = getSCEVAtScope(OrigV, L);
4663 MadeImprovement |= OrigV != OpV;
4666 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
4668 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV))
4669 C = dyn_cast<Constant>(SU->getValue());
4671 if (C->getType() != Op->getType())
4672 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4676 Operands.push_back(C);
4679 // Check to see if getSCEVAtScope actually made an improvement.
4680 if (MadeImprovement) {
4682 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4683 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
4684 Operands[0], Operands[1], TD);
4686 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4687 &Operands[0], Operands.size(), TD);
4694 // This is some other type of SCEVUnknown, just return it.
4698 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
4699 // Avoid performing the look-up in the common case where the specified
4700 // expression has no loop-variant portions.
4701 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
4702 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
4703 if (OpAtScope != Comm->getOperand(i)) {
4704 // Okay, at least one of these operands is loop variant but might be
4705 // foldable. Build a new instance of the folded commutative expression.
4706 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4707 Comm->op_begin()+i);
4708 NewOps.push_back(OpAtScope);
4710 for (++i; i != e; ++i) {
4711 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
4712 NewOps.push_back(OpAtScope);
4714 if (isa<SCEVAddExpr>(Comm))
4715 return getAddExpr(NewOps);
4716 if (isa<SCEVMulExpr>(Comm))
4717 return getMulExpr(NewOps);
4718 if (isa<SCEVSMaxExpr>(Comm))
4719 return getSMaxExpr(NewOps);
4720 if (isa<SCEVUMaxExpr>(Comm))
4721 return getUMaxExpr(NewOps);
4722 llvm_unreachable("Unknown commutative SCEV type!");
4725 // If we got here, all operands are loop invariant.
4729 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
4730 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4731 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
4732 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4733 return Div; // must be loop invariant
4734 return getUDivExpr(LHS, RHS);
4737 // If this is a loop recurrence for a loop that does not contain L, then we
4738 // are dealing with the final value computed by the loop.
4739 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4740 // First, attempt to evaluate each operand.
4741 // Avoid performing the look-up in the common case where the specified
4742 // expression has no loop-variant portions.
4743 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4744 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
4745 if (OpAtScope == AddRec->getOperand(i))
4748 // Okay, at least one of these operands is loop variant but might be
4749 // foldable. Build a new instance of the folded commutative expression.
4750 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
4751 AddRec->op_begin()+i);
4752 NewOps.push_back(OpAtScope);
4753 for (++i; i != e; ++i)
4754 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
4756 AddRec = cast<SCEVAddRecExpr>(
4757 getAddRecExpr(NewOps, AddRec->getLoop(),
4758 // FIXME: AddRec->getNoWrapFlags(SCEV::FlagNW)
4759 SCEV::FlagAnyWrap));
4763 // If the scope is outside the addrec's loop, evaluate it by using the
4764 // loop exit value of the addrec.
4765 if (!AddRec->getLoop()->contains(L)) {
4766 // To evaluate this recurrence, we need to know how many times the AddRec
4767 // loop iterates. Compute this now.
4768 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
4769 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
4771 // Then, evaluate the AddRec.
4772 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
4778 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
4779 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4780 if (Op == Cast->getOperand())
4781 return Cast; // must be loop invariant
4782 return getZeroExtendExpr(Op, Cast->getType());
4785 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
4786 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4787 if (Op == Cast->getOperand())
4788 return Cast; // must be loop invariant
4789 return getSignExtendExpr(Op, Cast->getType());
4792 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
4793 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4794 if (Op == Cast->getOperand())
4795 return Cast; // must be loop invariant
4796 return getTruncateExpr(Op, Cast->getType());
4799 llvm_unreachable("Unknown SCEV type!");
4803 /// getSCEVAtScope - This is a convenience function which does
4804 /// getSCEVAtScope(getSCEV(V), L).
4805 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
4806 return getSCEVAtScope(getSCEV(V), L);
4809 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4810 /// following equation:
4812 /// A * X = B (mod N)
4814 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4815 /// A and B isn't important.
4817 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
4818 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
4819 ScalarEvolution &SE) {
4820 uint32_t BW = A.getBitWidth();
4821 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4822 assert(A != 0 && "A must be non-zero.");
4826 // The gcd of A and N may have only one prime factor: 2. The number of
4827 // trailing zeros in A is its multiplicity
4828 uint32_t Mult2 = A.countTrailingZeros();
4831 // 2. Check if B is divisible by D.
4833 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4834 // is not less than multiplicity of this prime factor for D.
4835 if (B.countTrailingZeros() < Mult2)
4836 return SE.getCouldNotCompute();
4838 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4841 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4842 // bit width during computations.
4843 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4844 APInt Mod(BW + 1, 0);
4845 Mod.setBit(BW - Mult2); // Mod = N / D
4846 APInt I = AD.multiplicativeInverse(Mod);
4848 // 4. Compute the minimum unsigned root of the equation:
4849 // I * (B / D) mod (N / D)
4850 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4852 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4854 return SE.getConstant(Result.trunc(BW));
4857 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4858 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4859 /// might be the same) or two SCEVCouldNotCompute objects.
4861 static std::pair<const SCEV *,const SCEV *>
4862 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
4863 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
4864 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4865 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4866 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
4868 // We currently can only solve this if the coefficients are constants.
4869 if (!LC || !MC || !NC) {
4870 const SCEV *CNC = SE.getCouldNotCompute();
4871 return std::make_pair(CNC, CNC);
4874 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
4875 const APInt &L = LC->getValue()->getValue();
4876 const APInt &M = MC->getValue()->getValue();
4877 const APInt &N = NC->getValue()->getValue();
4878 APInt Two(BitWidth, 2);
4879 APInt Four(BitWidth, 4);
4882 using namespace APIntOps;
4884 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4885 // The B coefficient is M-N/2
4889 // The A coefficient is N/2
4890 APInt A(N.sdiv(Two));
4892 // Compute the B^2-4ac term.
4895 SqrtTerm -= Four * (A * C);
4897 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4898 // integer value or else APInt::sqrt() will assert.
4899 APInt SqrtVal(SqrtTerm.sqrt());
4901 // Compute the two solutions for the quadratic formula.
4902 // The divisions must be performed as signed divisions.
4904 APInt TwoA( A << 1 );
4905 if (TwoA.isMinValue()) {
4906 const SCEV *CNC = SE.getCouldNotCompute();
4907 return std::make_pair(CNC, CNC);
4910 LLVMContext &Context = SE.getContext();
4912 ConstantInt *Solution1 =
4913 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
4914 ConstantInt *Solution2 =
4915 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
4917 return std::make_pair(SE.getConstant(Solution1),
4918 SE.getConstant(Solution2));
4919 } // end APIntOps namespace
4922 /// HowFarToZero - Return the number of times a backedge comparing the specified
4923 /// value to zero will execute. If not computable, return CouldNotCompute.
4925 /// This is only used for loops with a "x != y" exit test. The exit condition is
4926 /// now expressed as a single expression, V = x-y. So the exit test is
4927 /// effectively V != 0. We know and take advantage of the fact that this
4928 /// expression only being used in a comparison by zero context.
4929 ScalarEvolution::BackedgeTakenInfo
4930 ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
4931 // If the value is a constant
4932 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
4933 // If the value is already zero, the branch will execute zero times.
4934 if (C->getValue()->isZero()) return C;
4935 return getCouldNotCompute(); // Otherwise it will loop infinitely.
4938 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
4939 if (!AddRec || AddRec->getLoop() != L)
4940 return getCouldNotCompute();
4942 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4943 // the quadratic equation to solve it.
4944 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
4945 std::pair<const SCEV *,const SCEV *> Roots =
4946 SolveQuadraticEquation(AddRec, *this);
4947 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4948 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
4951 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
4952 << " sol#2: " << *R2 << "\n";
4954 // Pick the smallest positive root value.
4955 if (ConstantInt *CB =
4956 dyn_cast<ConstantInt>(ConstantExpr::getICmp(CmpInst::ICMP_ULT,
4959 if (CB->getZExtValue() == false)
4960 std::swap(R1, R2); // R1 is the minimum root now.
4962 // We can only use this value if the chrec ends up with an exact zero
4963 // value at this index. When solving for "X*X != 5", for example, we
4964 // should not accept a root of 2.
4965 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
4967 return R1; // We found a quadratic root!
4970 return getCouldNotCompute();
4973 // Otherwise we can only handle this if it is affine.
4974 if (!AddRec->isAffine())
4975 return getCouldNotCompute();
4977 // If this is an affine expression, the execution count of this branch is
4978 // the minimum unsigned root of the following equation:
4980 // Start + Step*N = 0 (mod 2^BW)
4984 // Step*N = -Start (mod 2^BW)
4986 // where BW is the common bit width of Start and Step.
4988 // Get the initial value for the loop.
4989 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
4990 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
4992 // For now we handle only constant steps.
4994 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
4995 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
4996 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
4997 // We have not yet seen any such cases.
4998 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
5000 return getCouldNotCompute();
5002 // For positive steps (counting up until unsigned overflow):
5003 // N = -Start/Step (as unsigned)
5004 // For negative steps (counting down to zero):
5006 // First compute the unsigned distance from zero in the direction of Step.
5007 bool CountDown = StepC->getValue()->getValue().isNegative();
5008 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
5010 // Handle unitary steps, which cannot wraparound.
5011 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
5012 // N = Distance (as unsigned)
5013 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue())
5016 // If the recurrence is known not to wraparound, unsigned divide computes the
5017 // back edge count. We know that the value will either become zero (and thus
5018 // the loop terminates), that the loop will terminate through some other exit
5019 // condition first, or that the loop has undefined behavior. This means
5020 // we can't "miss" the exit value, even with nonunit stride.
5022 // FIXME: Prove that loops always exhibits *acceptable* undefined
5023 // behavior. Loops must exhibit defined behavior until a wrapped value is
5024 // actually used. So the trip count computed by udiv could be smaller than the
5025 // number of well-defined iterations.
5026 if (AddRec->getNoWrapFlags(SCEV::FlagNW))
5027 // FIXME: We really want an "isexact" bit for udiv.
5028 return getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
5030 // Then, try to solve the above equation provided that Start is constant.
5031 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
5032 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
5033 -StartC->getValue()->getValue(),
5035 return getCouldNotCompute();
5038 /// HowFarToNonZero - Return the number of times a backedge checking the
5039 /// specified value for nonzero will execute. If not computable, return
5041 ScalarEvolution::BackedgeTakenInfo
5042 ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
5043 // Loops that look like: while (X == 0) are very strange indeed. We don't
5044 // handle them yet except for the trivial case. This could be expanded in the
5045 // future as needed.
5047 // If the value is a constant, check to see if it is known to be non-zero
5048 // already. If so, the backedge will execute zero times.
5049 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
5050 if (!C->getValue()->isNullValue())
5051 return getConstant(C->getType(), 0);
5052 return getCouldNotCompute(); // Otherwise it will loop infinitely.
5055 // We could implement others, but I really doubt anyone writes loops like
5056 // this, and if they did, they would already be constant folded.
5057 return getCouldNotCompute();
5060 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
5061 /// (which may not be an immediate predecessor) which has exactly one
5062 /// successor from which BB is reachable, or null if no such block is
5065 std::pair<BasicBlock *, BasicBlock *>
5066 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
5067 // If the block has a unique predecessor, then there is no path from the
5068 // predecessor to the block that does not go through the direct edge
5069 // from the predecessor to the block.
5070 if (BasicBlock *Pred = BB->getSinglePredecessor())
5071 return std::make_pair(Pred, BB);
5073 // A loop's header is defined to be a block that dominates the loop.
5074 // If the header has a unique predecessor outside the loop, it must be
5075 // a block that has exactly one successor that can reach the loop.
5076 if (Loop *L = LI->getLoopFor(BB))
5077 return std::make_pair(L->getLoopPredecessor(), L->getHeader());
5079 return std::pair<BasicBlock *, BasicBlock *>();
5082 /// HasSameValue - SCEV structural equivalence is usually sufficient for
5083 /// testing whether two expressions are equal, however for the purposes of
5084 /// looking for a condition guarding a loop, it can be useful to be a little
5085 /// more general, since a front-end may have replicated the controlling
5088 static bool HasSameValue(const SCEV *A, const SCEV *B) {
5089 // Quick check to see if they are the same SCEV.
5090 if (A == B) return true;
5092 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
5093 // two different instructions with the same value. Check for this case.
5094 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
5095 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
5096 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
5097 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
5098 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
5101 // Otherwise assume they may have a different value.
5105 /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
5106 /// predicate Pred. Return true iff any changes were made.
5108 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
5109 const SCEV *&LHS, const SCEV *&RHS) {
5110 bool Changed = false;
5112 // Canonicalize a constant to the right side.
5113 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
5114 // Check for both operands constant.
5115 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
5116 if (ConstantExpr::getICmp(Pred,
5118 RHSC->getValue())->isNullValue())
5119 goto trivially_false;
5121 goto trivially_true;
5123 // Otherwise swap the operands to put the constant on the right.
5124 std::swap(LHS, RHS);
5125 Pred = ICmpInst::getSwappedPredicate(Pred);
5129 // If we're comparing an addrec with a value which is loop-invariant in the
5130 // addrec's loop, put the addrec on the left. Also make a dominance check,
5131 // as both operands could be addrecs loop-invariant in each other's loop.
5132 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
5133 const Loop *L = AR->getLoop();
5134 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
5135 std::swap(LHS, RHS);
5136 Pred = ICmpInst::getSwappedPredicate(Pred);
5141 // If there's a constant operand, canonicalize comparisons with boundary
5142 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
5143 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
5144 const APInt &RA = RC->getValue()->getValue();
5146 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5147 case ICmpInst::ICMP_EQ:
5148 case ICmpInst::ICMP_NE:
5150 case ICmpInst::ICMP_UGE:
5151 if ((RA - 1).isMinValue()) {
5152 Pred = ICmpInst::ICMP_NE;
5153 RHS = getConstant(RA - 1);
5157 if (RA.isMaxValue()) {
5158 Pred = ICmpInst::ICMP_EQ;
5162 if (RA.isMinValue()) goto trivially_true;
5164 Pred = ICmpInst::ICMP_UGT;
5165 RHS = getConstant(RA - 1);
5168 case ICmpInst::ICMP_ULE:
5169 if ((RA + 1).isMaxValue()) {
5170 Pred = ICmpInst::ICMP_NE;
5171 RHS = getConstant(RA + 1);
5175 if (RA.isMinValue()) {
5176 Pred = ICmpInst::ICMP_EQ;
5180 if (RA.isMaxValue()) goto trivially_true;
5182 Pred = ICmpInst::ICMP_ULT;
5183 RHS = getConstant(RA + 1);
5186 case ICmpInst::ICMP_SGE:
5187 if ((RA - 1).isMinSignedValue()) {
5188 Pred = ICmpInst::ICMP_NE;
5189 RHS = getConstant(RA - 1);
5193 if (RA.isMaxSignedValue()) {
5194 Pred = ICmpInst::ICMP_EQ;
5198 if (RA.isMinSignedValue()) goto trivially_true;
5200 Pred = ICmpInst::ICMP_SGT;
5201 RHS = getConstant(RA - 1);
5204 case ICmpInst::ICMP_SLE:
5205 if ((RA + 1).isMaxSignedValue()) {
5206 Pred = ICmpInst::ICMP_NE;
5207 RHS = getConstant(RA + 1);
5211 if (RA.isMinSignedValue()) {
5212 Pred = ICmpInst::ICMP_EQ;
5216 if (RA.isMaxSignedValue()) goto trivially_true;
5218 Pred = ICmpInst::ICMP_SLT;
5219 RHS = getConstant(RA + 1);
5222 case ICmpInst::ICMP_UGT:
5223 if (RA.isMinValue()) {
5224 Pred = ICmpInst::ICMP_NE;
5228 if ((RA + 1).isMaxValue()) {
5229 Pred = ICmpInst::ICMP_EQ;
5230 RHS = getConstant(RA + 1);
5234 if (RA.isMaxValue()) goto trivially_false;
5236 case ICmpInst::ICMP_ULT:
5237 if (RA.isMaxValue()) {
5238 Pred = ICmpInst::ICMP_NE;
5242 if ((RA - 1).isMinValue()) {
5243 Pred = ICmpInst::ICMP_EQ;
5244 RHS = getConstant(RA - 1);
5248 if (RA.isMinValue()) goto trivially_false;
5250 case ICmpInst::ICMP_SGT:
5251 if (RA.isMinSignedValue()) {
5252 Pred = ICmpInst::ICMP_NE;
5256 if ((RA + 1).isMaxSignedValue()) {
5257 Pred = ICmpInst::ICMP_EQ;
5258 RHS = getConstant(RA + 1);
5262 if (RA.isMaxSignedValue()) goto trivially_false;
5264 case ICmpInst::ICMP_SLT:
5265 if (RA.isMaxSignedValue()) {
5266 Pred = ICmpInst::ICMP_NE;
5270 if ((RA - 1).isMinSignedValue()) {
5271 Pred = ICmpInst::ICMP_EQ;
5272 RHS = getConstant(RA - 1);
5276 if (RA.isMinSignedValue()) goto trivially_false;
5281 // Check for obvious equality.
5282 if (HasSameValue(LHS, RHS)) {
5283 if (ICmpInst::isTrueWhenEqual(Pred))
5284 goto trivially_true;
5285 if (ICmpInst::isFalseWhenEqual(Pred))
5286 goto trivially_false;
5289 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
5290 // adding or subtracting 1 from one of the operands.
5292 case ICmpInst::ICMP_SLE:
5293 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
5294 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
5296 Pred = ICmpInst::ICMP_SLT;
5298 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
5299 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
5301 Pred = ICmpInst::ICMP_SLT;
5305 case ICmpInst::ICMP_SGE:
5306 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
5307 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
5309 Pred = ICmpInst::ICMP_SGT;
5311 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
5312 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
5314 Pred = ICmpInst::ICMP_SGT;
5318 case ICmpInst::ICMP_ULE:
5319 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
5320 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
5322 Pred = ICmpInst::ICMP_ULT;
5324 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
5325 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
5327 Pred = ICmpInst::ICMP_ULT;
5331 case ICmpInst::ICMP_UGE:
5332 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
5333 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
5335 Pred = ICmpInst::ICMP_UGT;
5337 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
5338 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
5340 Pred = ICmpInst::ICMP_UGT;
5348 // TODO: More simplifications are possible here.
5354 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
5355 Pred = ICmpInst::ICMP_EQ;
5360 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
5361 Pred = ICmpInst::ICMP_NE;
5365 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
5366 return getSignedRange(S).getSignedMax().isNegative();
5369 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
5370 return getSignedRange(S).getSignedMin().isStrictlyPositive();
5373 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
5374 return !getSignedRange(S).getSignedMin().isNegative();
5377 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
5378 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
5381 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
5382 return isKnownNegative(S) || isKnownPositive(S);
5385 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
5386 const SCEV *LHS, const SCEV *RHS) {
5387 // Canonicalize the inputs first.
5388 (void)SimplifyICmpOperands(Pred, LHS, RHS);
5390 // If LHS or RHS is an addrec, check to see if the condition is true in
5391 // every iteration of the loop.
5392 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
5393 if (isLoopEntryGuardedByCond(
5394 AR->getLoop(), Pred, AR->getStart(), RHS) &&
5395 isLoopBackedgeGuardedByCond(
5396 AR->getLoop(), Pred, AR->getPostIncExpr(*this), RHS))
5398 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS))
5399 if (isLoopEntryGuardedByCond(
5400 AR->getLoop(), Pred, LHS, AR->getStart()) &&
5401 isLoopBackedgeGuardedByCond(
5402 AR->getLoop(), Pred, LHS, AR->getPostIncExpr(*this)))
5405 // Otherwise see what can be done with known constant ranges.
5406 return isKnownPredicateWithRanges(Pred, LHS, RHS);
5410 ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
5411 const SCEV *LHS, const SCEV *RHS) {
5412 if (HasSameValue(LHS, RHS))
5413 return ICmpInst::isTrueWhenEqual(Pred);
5415 // This code is split out from isKnownPredicate because it is called from
5416 // within isLoopEntryGuardedByCond.
5419 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5421 case ICmpInst::ICMP_SGT:
5422 Pred = ICmpInst::ICMP_SLT;
5423 std::swap(LHS, RHS);
5424 case ICmpInst::ICMP_SLT: {
5425 ConstantRange LHSRange = getSignedRange(LHS);
5426 ConstantRange RHSRange = getSignedRange(RHS);
5427 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
5429 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
5433 case ICmpInst::ICMP_SGE:
5434 Pred = ICmpInst::ICMP_SLE;
5435 std::swap(LHS, RHS);
5436 case ICmpInst::ICMP_SLE: {
5437 ConstantRange LHSRange = getSignedRange(LHS);
5438 ConstantRange RHSRange = getSignedRange(RHS);
5439 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
5441 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
5445 case ICmpInst::ICMP_UGT:
5446 Pred = ICmpInst::ICMP_ULT;
5447 std::swap(LHS, RHS);
5448 case ICmpInst::ICMP_ULT: {
5449 ConstantRange LHSRange = getUnsignedRange(LHS);
5450 ConstantRange RHSRange = getUnsignedRange(RHS);
5451 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
5453 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
5457 case ICmpInst::ICMP_UGE:
5458 Pred = ICmpInst::ICMP_ULE;
5459 std::swap(LHS, RHS);
5460 case ICmpInst::ICMP_ULE: {
5461 ConstantRange LHSRange = getUnsignedRange(LHS);
5462 ConstantRange RHSRange = getUnsignedRange(RHS);
5463 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
5465 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
5469 case ICmpInst::ICMP_NE: {
5470 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
5472 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
5475 const SCEV *Diff = getMinusSCEV(LHS, RHS);
5476 if (isKnownNonZero(Diff))
5480 case ICmpInst::ICMP_EQ:
5481 // The check at the top of the function catches the case where
5482 // the values are known to be equal.
5488 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
5489 /// protected by a conditional between LHS and RHS. This is used to
5490 /// to eliminate casts.
5492 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
5493 ICmpInst::Predicate Pred,
5494 const SCEV *LHS, const SCEV *RHS) {
5495 // Interpret a null as meaning no loop, where there is obviously no guard
5496 // (interprocedural conditions notwithstanding).
5497 if (!L) return true;
5499 BasicBlock *Latch = L->getLoopLatch();
5503 BranchInst *LoopContinuePredicate =
5504 dyn_cast<BranchInst>(Latch->getTerminator());
5505 if (!LoopContinuePredicate ||
5506 LoopContinuePredicate->isUnconditional())
5509 return isImpliedCond(Pred, LHS, RHS,
5510 LoopContinuePredicate->getCondition(),
5511 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
5514 /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
5515 /// by a conditional between LHS and RHS. This is used to help avoid max
5516 /// expressions in loop trip counts, and to eliminate casts.
5518 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
5519 ICmpInst::Predicate Pred,
5520 const SCEV *LHS, const SCEV *RHS) {
5521 // Interpret a null as meaning no loop, where there is obviously no guard
5522 // (interprocedural conditions notwithstanding).
5523 if (!L) return false;
5525 // Starting at the loop predecessor, climb up the predecessor chain, as long
5526 // as there are predecessors that can be found that have unique successors
5527 // leading to the original header.
5528 for (std::pair<BasicBlock *, BasicBlock *>
5529 Pair(L->getLoopPredecessor(), L->getHeader());
5531 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
5533 BranchInst *LoopEntryPredicate =
5534 dyn_cast<BranchInst>(Pair.first->getTerminator());
5535 if (!LoopEntryPredicate ||
5536 LoopEntryPredicate->isUnconditional())
5539 if (isImpliedCond(Pred, LHS, RHS,
5540 LoopEntryPredicate->getCondition(),
5541 LoopEntryPredicate->getSuccessor(0) != Pair.second))
5548 /// isImpliedCond - Test whether the condition described by Pred, LHS,
5549 /// and RHS is true whenever the given Cond value evaluates to true.
5550 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
5551 const SCEV *LHS, const SCEV *RHS,
5552 Value *FoundCondValue,
5554 // Recursively handle And and Or conditions.
5555 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
5556 if (BO->getOpcode() == Instruction::And) {
5558 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5559 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
5560 } else if (BO->getOpcode() == Instruction::Or) {
5562 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5563 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
5567 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
5568 if (!ICI) return false;
5570 // Bail if the ICmp's operands' types are wider than the needed type
5571 // before attempting to call getSCEV on them. This avoids infinite
5572 // recursion, since the analysis of widening casts can require loop
5573 // exit condition information for overflow checking, which would
5575 if (getTypeSizeInBits(LHS->getType()) <
5576 getTypeSizeInBits(ICI->getOperand(0)->getType()))
5579 // Now that we found a conditional branch that dominates the loop, check to
5580 // see if it is the comparison we are looking for.
5581 ICmpInst::Predicate FoundPred;
5583 FoundPred = ICI->getInversePredicate();
5585 FoundPred = ICI->getPredicate();
5587 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
5588 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
5590 // Balance the types. The case where FoundLHS' type is wider than
5591 // LHS' type is checked for above.
5592 if (getTypeSizeInBits(LHS->getType()) >
5593 getTypeSizeInBits(FoundLHS->getType())) {
5594 if (CmpInst::isSigned(Pred)) {
5595 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
5596 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
5598 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
5599 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
5603 // Canonicalize the query to match the way instcombine will have
5604 // canonicalized the comparison.
5605 if (SimplifyICmpOperands(Pred, LHS, RHS))
5607 return CmpInst::isTrueWhenEqual(Pred);
5608 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
5609 if (FoundLHS == FoundRHS)
5610 return CmpInst::isFalseWhenEqual(Pred);
5612 // Check to see if we can make the LHS or RHS match.
5613 if (LHS == FoundRHS || RHS == FoundLHS) {
5614 if (isa<SCEVConstant>(RHS)) {
5615 std::swap(FoundLHS, FoundRHS);
5616 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
5618 std::swap(LHS, RHS);
5619 Pred = ICmpInst::getSwappedPredicate(Pred);
5623 // Check whether the found predicate is the same as the desired predicate.
5624 if (FoundPred == Pred)
5625 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
5627 // Check whether swapping the found predicate makes it the same as the
5628 // desired predicate.
5629 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
5630 if (isa<SCEVConstant>(RHS))
5631 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
5633 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
5634 RHS, LHS, FoundLHS, FoundRHS);
5637 // Check whether the actual condition is beyond sufficient.
5638 if (FoundPred == ICmpInst::ICMP_EQ)
5639 if (ICmpInst::isTrueWhenEqual(Pred))
5640 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
5642 if (Pred == ICmpInst::ICMP_NE)
5643 if (!ICmpInst::isTrueWhenEqual(FoundPred))
5644 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
5647 // Otherwise assume the worst.
5651 /// isImpliedCondOperands - Test whether the condition described by Pred,
5652 /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
5653 /// and FoundRHS is true.
5654 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
5655 const SCEV *LHS, const SCEV *RHS,
5656 const SCEV *FoundLHS,
5657 const SCEV *FoundRHS) {
5658 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
5659 FoundLHS, FoundRHS) ||
5660 // ~x < ~y --> x > y
5661 isImpliedCondOperandsHelper(Pred, LHS, RHS,
5662 getNotSCEV(FoundRHS),
5663 getNotSCEV(FoundLHS));
5666 /// isImpliedCondOperandsHelper - Test whether the condition described by
5667 /// Pred, LHS, and RHS is true whenever the condition described by Pred,
5668 /// FoundLHS, and FoundRHS is true.
5670 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
5671 const SCEV *LHS, const SCEV *RHS,
5672 const SCEV *FoundLHS,
5673 const SCEV *FoundRHS) {
5675 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5676 case ICmpInst::ICMP_EQ:
5677 case ICmpInst::ICMP_NE:
5678 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
5681 case ICmpInst::ICMP_SLT:
5682 case ICmpInst::ICMP_SLE:
5683 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
5684 isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS))
5687 case ICmpInst::ICMP_SGT:
5688 case ICmpInst::ICMP_SGE:
5689 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
5690 isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS))
5693 case ICmpInst::ICMP_ULT:
5694 case ICmpInst::ICMP_ULE:
5695 if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
5696 isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS))
5699 case ICmpInst::ICMP_UGT:
5700 case ICmpInst::ICMP_UGE:
5701 if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
5702 isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS))
5710 /// getBECount - Subtract the end and start values and divide by the step,
5711 /// rounding up, to get the number of times the backedge is executed. Return
5712 /// CouldNotCompute if an intermediate computation overflows.
5713 const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
5717 assert(!isKnownNegative(Step) &&
5718 "This code doesn't handle negative strides yet!");
5720 const Type *Ty = Start->getType();
5722 // When Start == End, we have an exact BECount == 0. Short-circuit this case
5723 // here because SCEV may not be able to determine that the unsigned division
5724 // after rounding is zero.
5726 return getConstant(Ty, 0);
5728 const SCEV *NegOne = getConstant(Ty, (uint64_t)-1);
5729 const SCEV *Diff = getMinusSCEV(End, Start);
5730 const SCEV *RoundUp = getAddExpr(Step, NegOne);
5732 // Add an adjustment to the difference between End and Start so that
5733 // the division will effectively round up.
5734 const SCEV *Add = getAddExpr(Diff, RoundUp);
5737 // Check Add for unsigned overflow.
5738 // TODO: More sophisticated things could be done here.
5739 const Type *WideTy = IntegerType::get(getContext(),
5740 getTypeSizeInBits(Ty) + 1);
5741 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
5742 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
5743 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
5744 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
5745 return getCouldNotCompute();
5748 return getUDivExpr(Add, Step);
5751 /// HowManyLessThans - Return the number of times a backedge containing the
5752 /// specified less-than comparison will execute. If not computable, return
5753 /// CouldNotCompute.
5754 ScalarEvolution::BackedgeTakenInfo
5755 ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
5756 const Loop *L, bool isSigned) {
5757 // Only handle: "ADDREC < LoopInvariant".
5758 if (!isLoopInvariant(RHS, L)) return getCouldNotCompute();
5760 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
5761 if (!AddRec || AddRec->getLoop() != L)
5762 return getCouldNotCompute();
5764 // Check to see if we have a flag which makes analysis easy.
5765 bool NoWrap = isSigned ? AddRec->getNoWrapFlags(SCEV::FlagNSW) :
5766 AddRec->getNoWrapFlags(SCEV::FlagNUW);
5768 if (AddRec->isAffine()) {
5769 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
5770 const SCEV *Step = AddRec->getStepRecurrence(*this);
5773 return getCouldNotCompute();
5774 if (Step->isOne()) {
5775 // With unit stride, the iteration never steps past the limit value.
5776 } else if (isKnownPositive(Step)) {
5777 // Test whether a positive iteration can step past the limit
5778 // value and past the maximum value for its type in a single step.
5779 // Note that it's not sufficient to check NoWrap here, because even
5780 // though the value after a wrap is undefined, it's not undefined
5781 // behavior, so if wrap does occur, the loop could either terminate or
5782 // loop infinitely, but in either case, the loop is guaranteed to
5783 // iterate at least until the iteration where the wrapping occurs.
5784 const SCEV *One = getConstant(Step->getType(), 1);
5786 APInt Max = APInt::getSignedMaxValue(BitWidth);
5787 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
5788 .slt(getSignedRange(RHS).getSignedMax()))
5789 return getCouldNotCompute();
5791 APInt Max = APInt::getMaxValue(BitWidth);
5792 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
5793 .ult(getUnsignedRange(RHS).getUnsignedMax()))
5794 return getCouldNotCompute();
5797 // TODO: Handle negative strides here and below.
5798 return getCouldNotCompute();
5800 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
5801 // m. So, we count the number of iterations in which {n,+,s} < m is true.
5802 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
5803 // treat m-n as signed nor unsigned due to overflow possibility.
5805 // First, we get the value of the LHS in the first iteration: n
5806 const SCEV *Start = AddRec->getOperand(0);
5808 // Determine the minimum constant start value.
5809 const SCEV *MinStart = getConstant(isSigned ?
5810 getSignedRange(Start).getSignedMin() :
5811 getUnsignedRange(Start).getUnsignedMin());
5813 // If we know that the condition is true in order to enter the loop,
5814 // then we know that it will run exactly (m-n)/s times. Otherwise, we
5815 // only know that it will execute (max(m,n)-n)/s times. In both cases,
5816 // the division must round up.
5817 const SCEV *End = RHS;
5818 if (!isLoopEntryGuardedByCond(L,
5819 isSigned ? ICmpInst::ICMP_SLT :
5821 getMinusSCEV(Start, Step), RHS))
5822 End = isSigned ? getSMaxExpr(RHS, Start)
5823 : getUMaxExpr(RHS, Start);
5825 // Determine the maximum constant end value.
5826 const SCEV *MaxEnd = getConstant(isSigned ?
5827 getSignedRange(End).getSignedMax() :
5828 getUnsignedRange(End).getUnsignedMax());
5830 // If MaxEnd is within a step of the maximum integer value in its type,
5831 // adjust it down to the minimum value which would produce the same effect.
5832 // This allows the subsequent ceiling division of (N+(step-1))/step to
5833 // compute the correct value.
5834 const SCEV *StepMinusOne = getMinusSCEV(Step,
5835 getConstant(Step->getType(), 1));
5838 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
5841 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
5844 // Finally, we subtract these two values and divide, rounding up, to get
5845 // the number of times the backedge is executed.
5846 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
5848 // The maximum backedge count is similar, except using the minimum start
5849 // value and the maximum end value.
5850 // If we already have an exact constant BECount, use it instead.
5851 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) ? BECount
5852 : getBECount(MinStart, MaxEnd, Step, NoWrap);
5854 // If the stride is nonconstant, and NoWrap == true, then
5855 // getBECount(MinStart, MaxEnd) may not compute. This would result in an
5856 // exact BECount and invalid MaxBECount, which should be avoided to catch
5857 // more optimization opportunities.
5858 if (isa<SCEVCouldNotCompute>(MaxBECount))
5859 MaxBECount = BECount;
5861 return BackedgeTakenInfo(BECount, MaxBECount);
5864 return getCouldNotCompute();
5867 /// getNumIterationsInRange - Return the number of iterations of this loop that
5868 /// produce values in the specified constant range. Another way of looking at
5869 /// this is that it returns the first iteration number where the value is not in
5870 /// the condition, thus computing the exit count. If the iteration count can't
5871 /// be computed, an instance of SCEVCouldNotCompute is returned.
5872 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
5873 ScalarEvolution &SE) const {
5874 if (Range.isFullSet()) // Infinite loop.
5875 return SE.getCouldNotCompute();
5877 // If the start is a non-zero constant, shift the range to simplify things.
5878 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
5879 if (!SC->getValue()->isZero()) {
5880 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
5881 Operands[0] = SE.getConstant(SC->getType(), 0);
5882 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
5883 // FIXME: getNoWrapFlags(FlagNW)
5885 if (const SCEVAddRecExpr *ShiftedAddRec =
5886 dyn_cast<SCEVAddRecExpr>(Shifted))
5887 return ShiftedAddRec->getNumIterationsInRange(
5888 Range.subtract(SC->getValue()->getValue()), SE);
5889 // This is strange and shouldn't happen.
5890 return SE.getCouldNotCompute();
5893 // The only time we can solve this is when we have all constant indices.
5894 // Otherwise, we cannot determine the overflow conditions.
5895 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5896 if (!isa<SCEVConstant>(getOperand(i)))
5897 return SE.getCouldNotCompute();
5900 // Okay at this point we know that all elements of the chrec are constants and
5901 // that the start element is zero.
5903 // First check to see if the range contains zero. If not, the first
5905 unsigned BitWidth = SE.getTypeSizeInBits(getType());
5906 if (!Range.contains(APInt(BitWidth, 0)))
5907 return SE.getConstant(getType(), 0);
5910 // If this is an affine expression then we have this situation:
5911 // Solve {0,+,A} in Range === Ax in Range
5913 // We know that zero is in the range. If A is positive then we know that
5914 // the upper value of the range must be the first possible exit value.
5915 // If A is negative then the lower of the range is the last possible loop
5916 // value. Also note that we already checked for a full range.
5917 APInt One(BitWidth,1);
5918 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
5919 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
5921 // The exit value should be (End+A)/A.
5922 APInt ExitVal = (End + A).udiv(A);
5923 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
5925 // Evaluate at the exit value. If we really did fall out of the valid
5926 // range, then we computed our trip count, otherwise wrap around or other
5927 // things must have happened.
5928 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
5929 if (Range.contains(Val->getValue()))
5930 return SE.getCouldNotCompute(); // Something strange happened
5932 // Ensure that the previous value is in the range. This is a sanity check.
5933 assert(Range.contains(
5934 EvaluateConstantChrecAtConstant(this,
5935 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
5936 "Linear scev computation is off in a bad way!");
5937 return SE.getConstant(ExitValue);
5938 } else if (isQuadratic()) {
5939 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5940 // quadratic equation to solve it. To do this, we must frame our problem in
5941 // terms of figuring out when zero is crossed, instead of when
5942 // Range.getUpper() is crossed.
5943 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
5944 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
5945 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(),
5946 // getNoWrapFlags(FlagNW)
5949 // Next, solve the constructed addrec
5950 std::pair<const SCEV *,const SCEV *> Roots =
5951 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
5952 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5953 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
5955 // Pick the smallest positive root value.
5956 if (ConstantInt *CB =
5957 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
5958 R1->getValue(), R2->getValue()))) {
5959 if (CB->getZExtValue() == false)
5960 std::swap(R1, R2); // R1 is the minimum root now.
5962 // Make sure the root is not off by one. The returned iteration should
5963 // not be in the range, but the previous one should be. When solving
5964 // for "X*X < 5", for example, we should not return a root of 2.
5965 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
5968 if (Range.contains(R1Val->getValue())) {
5969 // The next iteration must be out of the range...
5970 ConstantInt *NextVal =
5971 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
5973 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
5974 if (!Range.contains(R1Val->getValue()))
5975 return SE.getConstant(NextVal);
5976 return SE.getCouldNotCompute(); // Something strange happened
5979 // If R1 was not in the range, then it is a good return value. Make
5980 // sure that R1-1 WAS in the range though, just in case.
5981 ConstantInt *NextVal =
5982 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
5983 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
5984 if (Range.contains(R1Val->getValue()))
5986 return SE.getCouldNotCompute(); // Something strange happened
5991 return SE.getCouldNotCompute();
5996 //===----------------------------------------------------------------------===//
5997 // SCEVCallbackVH Class Implementation
5998 //===----------------------------------------------------------------------===//
6000 void ScalarEvolution::SCEVCallbackVH::deleted() {
6001 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
6002 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
6003 SE->ConstantEvolutionLoopExitValue.erase(PN);
6004 SE->ValueExprMap.erase(getValPtr());
6005 // this now dangles!
6008 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
6009 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
6011 // Forget all the expressions associated with users of the old value,
6012 // so that future queries will recompute the expressions using the new
6014 Value *Old = getValPtr();
6015 SmallVector<User *, 16> Worklist;
6016 SmallPtrSet<User *, 8> Visited;
6017 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
6019 Worklist.push_back(*UI);
6020 while (!Worklist.empty()) {
6021 User *U = Worklist.pop_back_val();
6022 // Deleting the Old value will cause this to dangle. Postpone
6023 // that until everything else is done.
6026 if (!Visited.insert(U))
6028 if (PHINode *PN = dyn_cast<PHINode>(U))
6029 SE->ConstantEvolutionLoopExitValue.erase(PN);
6030 SE->ValueExprMap.erase(U);
6031 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
6033 Worklist.push_back(*UI);
6035 // Delete the Old value.
6036 if (PHINode *PN = dyn_cast<PHINode>(Old))
6037 SE->ConstantEvolutionLoopExitValue.erase(PN);
6038 SE->ValueExprMap.erase(Old);
6039 // this now dangles!
6042 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
6043 : CallbackVH(V), SE(se) {}
6045 //===----------------------------------------------------------------------===//
6046 // ScalarEvolution Class Implementation
6047 //===----------------------------------------------------------------------===//
6049 ScalarEvolution::ScalarEvolution()
6050 : FunctionPass(ID), FirstUnknown(0) {
6051 initializeScalarEvolutionPass(*PassRegistry::getPassRegistry());
6054 bool ScalarEvolution::runOnFunction(Function &F) {
6056 LI = &getAnalysis<LoopInfo>();
6057 TD = getAnalysisIfAvailable<TargetData>();
6058 DT = &getAnalysis<DominatorTree>();
6062 void ScalarEvolution::releaseMemory() {
6063 // Iterate through all the SCEVUnknown instances and call their
6064 // destructors, so that they release their references to their values.
6065 for (SCEVUnknown *U = FirstUnknown; U; U = U->Next)
6069 ValueExprMap.clear();
6070 BackedgeTakenCounts.clear();
6071 ConstantEvolutionLoopExitValue.clear();
6072 ValuesAtScopes.clear();
6073 LoopDispositions.clear();
6074 BlockDispositions.clear();
6075 UnsignedRanges.clear();
6076 SignedRanges.clear();
6077 UniqueSCEVs.clear();
6078 SCEVAllocator.Reset();
6081 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
6082 AU.setPreservesAll();
6083 AU.addRequiredTransitive<LoopInfo>();
6084 AU.addRequiredTransitive<DominatorTree>();
6087 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
6088 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
6091 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
6093 // Print all inner loops first
6094 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
6095 PrintLoopInfo(OS, SE, *I);
6098 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
6101 SmallVector<BasicBlock *, 8> ExitBlocks;
6102 L->getExitBlocks(ExitBlocks);
6103 if (ExitBlocks.size() != 1)
6104 OS << "<multiple exits> ";
6106 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
6107 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
6109 OS << "Unpredictable backedge-taken count. ";
6114 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
6117 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
6118 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
6120 OS << "Unpredictable max backedge-taken count. ";
6126 void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
6127 // ScalarEvolution's implementation of the print method is to print
6128 // out SCEV values of all instructions that are interesting. Doing
6129 // this potentially causes it to create new SCEV objects though,
6130 // which technically conflicts with the const qualifier. This isn't
6131 // observable from outside the class though, so casting away the
6132 // const isn't dangerous.
6133 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
6135 OS << "Classifying expressions for: ";
6136 WriteAsOperand(OS, F, /*PrintType=*/false);
6138 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
6139 if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) {
6142 const SCEV *SV = SE.getSCEV(&*I);
6145 const Loop *L = LI->getLoopFor((*I).getParent());
6147 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
6154 OS << "\t\t" "Exits: ";
6155 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
6156 if (!SE.isLoopInvariant(ExitValue, L)) {
6157 OS << "<<Unknown>>";
6166 OS << "Determining loop execution counts for: ";
6167 WriteAsOperand(OS, F, /*PrintType=*/false);
6169 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
6170 PrintLoopInfo(OS, &SE, *I);
6173 ScalarEvolution::LoopDisposition
6174 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
6175 std::map<const Loop *, LoopDisposition> &Values = LoopDispositions[S];
6176 std::pair<std::map<const Loop *, LoopDisposition>::iterator, bool> Pair =
6177 Values.insert(std::make_pair(L, LoopVariant));
6179 return Pair.first->second;
6181 LoopDisposition D = computeLoopDisposition(S, L);
6182 return LoopDispositions[S][L] = D;
6185 ScalarEvolution::LoopDisposition
6186 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
6187 switch (S->getSCEVType()) {
6189 return LoopInvariant;
6193 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
6194 case scAddRecExpr: {
6195 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
6197 // If L is the addrec's loop, it's computable.
6198 if (AR->getLoop() == L)
6199 return LoopComputable;
6201 // Add recurrences are never invariant in the function-body (null loop).
6205 // This recurrence is variant w.r.t. L if L contains AR's loop.
6206 if (L->contains(AR->getLoop()))
6209 // This recurrence is invariant w.r.t. L if AR's loop contains L.
6210 if (AR->getLoop()->contains(L))
6211 return LoopInvariant;
6213 // This recurrence is variant w.r.t. L if any of its operands
6215 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
6217 if (!isLoopInvariant(*I, L))
6220 // Otherwise it's loop-invariant.
6221 return LoopInvariant;
6227 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
6228 bool HasVarying = false;
6229 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
6231 LoopDisposition D = getLoopDisposition(*I, L);
6232 if (D == LoopVariant)
6234 if (D == LoopComputable)
6237 return HasVarying ? LoopComputable : LoopInvariant;
6240 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6241 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
6242 if (LD == LoopVariant)
6244 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
6245 if (RD == LoopVariant)
6247 return (LD == LoopInvariant && RD == LoopInvariant) ?
6248 LoopInvariant : LoopComputable;
6251 // All non-instruction values are loop invariant. All instructions are loop
6252 // invariant if they are not contained in the specified loop.
6253 // Instructions are never considered invariant in the function body
6254 // (null loop) because they are defined within the "loop".
6255 if (Instruction *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
6256 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
6257 return LoopInvariant;
6258 case scCouldNotCompute:
6259 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6263 llvm_unreachable("Unknown SCEV kind!");
6267 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
6268 return getLoopDisposition(S, L) == LoopInvariant;
6271 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
6272 return getLoopDisposition(S, L) == LoopComputable;
6275 ScalarEvolution::BlockDisposition
6276 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
6277 std::map<const BasicBlock *, BlockDisposition> &Values = BlockDispositions[S];
6278 std::pair<std::map<const BasicBlock *, BlockDisposition>::iterator, bool>
6279 Pair = Values.insert(std::make_pair(BB, DoesNotDominateBlock));
6281 return Pair.first->second;
6283 BlockDisposition D = computeBlockDisposition(S, BB);
6284 return BlockDispositions[S][BB] = D;
6287 ScalarEvolution::BlockDisposition
6288 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
6289 switch (S->getSCEVType()) {
6291 return ProperlyDominatesBlock;
6295 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
6296 case scAddRecExpr: {
6297 // This uses a "dominates" query instead of "properly dominates" query
6298 // to test for proper dominance too, because the instruction which
6299 // produces the addrec's value is a PHI, and a PHI effectively properly
6300 // dominates its entire containing block.
6301 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
6302 if (!DT->dominates(AR->getLoop()->getHeader(), BB))
6303 return DoesNotDominateBlock;
6305 // FALL THROUGH into SCEVNAryExpr handling.
6310 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
6312 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
6314 BlockDisposition D = getBlockDisposition(*I, BB);
6315 if (D == DoesNotDominateBlock)
6316 return DoesNotDominateBlock;
6317 if (D == DominatesBlock)
6320 return Proper ? ProperlyDominatesBlock : DominatesBlock;
6323 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6324 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
6325 BlockDisposition LD = getBlockDisposition(LHS, BB);
6326 if (LD == DoesNotDominateBlock)
6327 return DoesNotDominateBlock;
6328 BlockDisposition RD = getBlockDisposition(RHS, BB);
6329 if (RD == DoesNotDominateBlock)
6330 return DoesNotDominateBlock;
6331 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
6332 ProperlyDominatesBlock : DominatesBlock;
6335 if (Instruction *I =
6336 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
6337 if (I->getParent() == BB)
6338 return DominatesBlock;
6339 if (DT->properlyDominates(I->getParent(), BB))
6340 return ProperlyDominatesBlock;
6341 return DoesNotDominateBlock;
6343 return ProperlyDominatesBlock;
6344 case scCouldNotCompute:
6345 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6346 return DoesNotDominateBlock;
6349 llvm_unreachable("Unknown SCEV kind!");
6350 return DoesNotDominateBlock;
6353 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
6354 return getBlockDisposition(S, BB) >= DominatesBlock;
6357 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
6358 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
6361 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
6362 switch (S->getSCEVType()) {
6367 case scSignExtend: {
6368 const SCEVCastExpr *Cast = cast<SCEVCastExpr>(S);
6369 const SCEV *CastOp = Cast->getOperand();
6370 return Op == CastOp || hasOperand(CastOp, Op);
6377 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
6378 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
6380 const SCEV *NAryOp = *I;
6381 if (NAryOp == Op || hasOperand(NAryOp, Op))
6387 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6388 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
6389 return LHS == Op || hasOperand(LHS, Op) ||
6390 RHS == Op || hasOperand(RHS, Op);
6394 case scCouldNotCompute:
6395 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6399 llvm_unreachable("Unknown SCEV kind!");
6403 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
6404 ValuesAtScopes.erase(S);
6405 LoopDispositions.erase(S);
6406 BlockDispositions.erase(S);
6407 UnsignedRanges.erase(S);
6408 SignedRanges.erase(S);