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 WriteAsOperand(OS, AR->getLoop()->getHeader(), /*PrintType=*/false);
168 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
170 switch (NAry->getSCEVType()) {
171 case scAddExpr: OpStr = " + "; break;
172 case scMulExpr: OpStr = " * "; break;
173 case scUMaxExpr: OpStr = " umax "; break;
174 case scSMaxExpr: OpStr = " smax "; break;
177 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
180 if (llvm::next(I) != E)
187 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
188 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
192 const SCEVUnknown *U = cast<SCEVUnknown>(this);
194 if (U->isSizeOf(AllocTy)) {
195 OS << "sizeof(" << *AllocTy << ")";
198 if (U->isAlignOf(AllocTy)) {
199 OS << "alignof(" << *AllocTy << ")";
205 if (U->isOffsetOf(CTy, FieldNo)) {
206 OS << "offsetof(" << *CTy << ", ";
207 WriteAsOperand(OS, FieldNo, false);
212 // Otherwise just print it normally.
213 WriteAsOperand(OS, U->getValue(), false);
216 case scCouldNotCompute:
217 OS << "***COULDNOTCOMPUTE***";
221 llvm_unreachable("Unknown SCEV kind!");
224 const Type *SCEV::getType() const {
225 switch (getSCEVType()) {
227 return cast<SCEVConstant>(this)->getType();
231 return cast<SCEVCastExpr>(this)->getType();
236 return cast<SCEVNAryExpr>(this)->getType();
238 return cast<SCEVAddExpr>(this)->getType();
240 return cast<SCEVUDivExpr>(this)->getType();
242 return cast<SCEVUnknown>(this)->getType();
243 case scCouldNotCompute:
244 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
248 llvm_unreachable("Unknown SCEV kind!");
252 bool SCEV::isZero() const {
253 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
254 return SC->getValue()->isZero();
258 bool SCEV::isOne() const {
259 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
260 return SC->getValue()->isOne();
264 bool SCEV::isAllOnesValue() const {
265 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
266 return SC->getValue()->isAllOnesValue();
270 SCEVCouldNotCompute::SCEVCouldNotCompute() :
271 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
273 bool SCEVCouldNotCompute::classof(const SCEV *S) {
274 return S->getSCEVType() == scCouldNotCompute;
277 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
279 ID.AddInteger(scConstant);
282 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
283 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
284 UniqueSCEVs.InsertNode(S, IP);
288 const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
289 return getConstant(ConstantInt::get(getContext(), Val));
293 ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
294 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
295 return getConstant(ConstantInt::get(ITy, V, isSigned));
298 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
299 unsigned SCEVTy, const SCEV *op, const Type *ty)
300 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
302 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
303 const SCEV *op, const Type *ty)
304 : SCEVCastExpr(ID, scTruncate, op, ty) {
305 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
306 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
307 "Cannot truncate non-integer value!");
310 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
311 const SCEV *op, const Type *ty)
312 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
313 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
314 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
315 "Cannot zero extend non-integer value!");
318 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
319 const SCEV *op, const Type *ty)
320 : SCEVCastExpr(ID, scSignExtend, op, ty) {
321 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
322 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
323 "Cannot sign extend non-integer value!");
326 void SCEVUnknown::deleted() {
327 // Clear this SCEVUnknown from various maps.
328 SE->ValuesAtScopes.erase(this);
329 SE->LoopDispositions.erase(this);
330 SE->UnsignedRanges.erase(this);
331 SE->SignedRanges.erase(this);
333 // Remove this SCEVUnknown from the uniquing map.
334 SE->UniqueSCEVs.RemoveNode(this);
336 // Release the value.
340 void SCEVUnknown::allUsesReplacedWith(Value *New) {
341 // Clear this SCEVUnknown from various maps.
342 SE->ValuesAtScopes.erase(this);
343 SE->LoopDispositions.erase(this);
344 SE->UnsignedRanges.erase(this);
345 SE->SignedRanges.erase(this);
347 // Remove this SCEVUnknown from the uniquing map.
348 SE->UniqueSCEVs.RemoveNode(this);
350 // Update this SCEVUnknown to point to the new value. This is needed
351 // because there may still be outstanding SCEVs which still point to
356 bool SCEVUnknown::isSizeOf(const Type *&AllocTy) const {
357 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
358 if (VCE->getOpcode() == Instruction::PtrToInt)
359 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
360 if (CE->getOpcode() == Instruction::GetElementPtr &&
361 CE->getOperand(0)->isNullValue() &&
362 CE->getNumOperands() == 2)
363 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
365 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
373 bool SCEVUnknown::isAlignOf(const Type *&AllocTy) const {
374 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
375 if (VCE->getOpcode() == Instruction::PtrToInt)
376 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
377 if (CE->getOpcode() == Instruction::GetElementPtr &&
378 CE->getOperand(0)->isNullValue()) {
380 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
381 if (const StructType *STy = dyn_cast<StructType>(Ty))
382 if (!STy->isPacked() &&
383 CE->getNumOperands() == 3 &&
384 CE->getOperand(1)->isNullValue()) {
385 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
387 STy->getNumElements() == 2 &&
388 STy->getElementType(0)->isIntegerTy(1)) {
389 AllocTy = STy->getElementType(1);
398 bool SCEVUnknown::isOffsetOf(const Type *&CTy, Constant *&FieldNo) const {
399 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
400 if (VCE->getOpcode() == Instruction::PtrToInt)
401 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
402 if (CE->getOpcode() == Instruction::GetElementPtr &&
403 CE->getNumOperands() == 3 &&
404 CE->getOperand(0)->isNullValue() &&
405 CE->getOperand(1)->isNullValue()) {
407 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
408 // Ignore vector types here so that ScalarEvolutionExpander doesn't
409 // emit getelementptrs that index into vectors.
410 if (Ty->isStructTy() || Ty->isArrayTy()) {
412 FieldNo = CE->getOperand(2);
420 //===----------------------------------------------------------------------===//
422 //===----------------------------------------------------------------------===//
425 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
426 /// than the complexity of the RHS. This comparator is used to canonicalize
428 class SCEVComplexityCompare {
429 const LoopInfo *const LI;
431 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
433 // Return true or false if LHS is less than, or at least RHS, respectively.
434 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
435 return compare(LHS, RHS) < 0;
438 // Return negative, zero, or positive, if LHS is less than, equal to, or
439 // greater than RHS, respectively. A three-way result allows recursive
440 // comparisons to be more efficient.
441 int compare(const SCEV *LHS, const SCEV *RHS) const {
442 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
446 // Primarily, sort the SCEVs by their getSCEVType().
447 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
449 return (int)LType - (int)RType;
451 // Aside from the getSCEVType() ordering, the particular ordering
452 // isn't very important except that it's beneficial to be consistent,
453 // so that (a + b) and (b + a) don't end up as different expressions.
456 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
457 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
459 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
460 // not as complete as it could be.
461 const Value *LV = LU->getValue(), *RV = RU->getValue();
463 // Order pointer values after integer values. This helps SCEVExpander
465 bool LIsPointer = LV->getType()->isPointerTy(),
466 RIsPointer = RV->getType()->isPointerTy();
467 if (LIsPointer != RIsPointer)
468 return (int)LIsPointer - (int)RIsPointer;
470 // Compare getValueID values.
471 unsigned LID = LV->getValueID(),
472 RID = RV->getValueID();
474 return (int)LID - (int)RID;
476 // Sort arguments by their position.
477 if (const Argument *LA = dyn_cast<Argument>(LV)) {
478 const Argument *RA = cast<Argument>(RV);
479 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
480 return (int)LArgNo - (int)RArgNo;
483 // For instructions, compare their loop depth, and their operand
484 // count. This is pretty loose.
485 if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
486 const Instruction *RInst = cast<Instruction>(RV);
488 // Compare loop depths.
489 const BasicBlock *LParent = LInst->getParent(),
490 *RParent = RInst->getParent();
491 if (LParent != RParent) {
492 unsigned LDepth = LI->getLoopDepth(LParent),
493 RDepth = LI->getLoopDepth(RParent);
494 if (LDepth != RDepth)
495 return (int)LDepth - (int)RDepth;
498 // Compare the number of operands.
499 unsigned LNumOps = LInst->getNumOperands(),
500 RNumOps = RInst->getNumOperands();
501 return (int)LNumOps - (int)RNumOps;
508 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
509 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
511 // Compare constant values.
512 const APInt &LA = LC->getValue()->getValue();
513 const APInt &RA = RC->getValue()->getValue();
514 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
515 if (LBitWidth != RBitWidth)
516 return (int)LBitWidth - (int)RBitWidth;
517 return LA.ult(RA) ? -1 : 1;
521 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
522 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
524 // Compare addrec loop depths.
525 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
526 if (LLoop != RLoop) {
527 unsigned LDepth = LLoop->getLoopDepth(),
528 RDepth = RLoop->getLoopDepth();
529 if (LDepth != RDepth)
530 return (int)LDepth - (int)RDepth;
533 // Addrec complexity grows with operand count.
534 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
535 if (LNumOps != RNumOps)
536 return (int)LNumOps - (int)RNumOps;
538 // Lexicographically compare.
539 for (unsigned i = 0; i != LNumOps; ++i) {
540 long X = compare(LA->getOperand(i), RA->getOperand(i));
552 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
553 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
555 // Lexicographically compare n-ary expressions.
556 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
557 for (unsigned i = 0; i != LNumOps; ++i) {
560 long X = compare(LC->getOperand(i), RC->getOperand(i));
564 return (int)LNumOps - (int)RNumOps;
568 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
569 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
571 // Lexicographically compare udiv expressions.
572 long X = compare(LC->getLHS(), RC->getLHS());
575 return compare(LC->getRHS(), RC->getRHS());
581 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
582 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
584 // Compare cast expressions by operand.
585 return compare(LC->getOperand(), RC->getOperand());
592 llvm_unreachable("Unknown SCEV kind!");
598 /// GroupByComplexity - Given a list of SCEV objects, order them by their
599 /// complexity, and group objects of the same complexity together by value.
600 /// When this routine is finished, we know that any duplicates in the vector are
601 /// consecutive and that complexity is monotonically increasing.
603 /// Note that we go take special precautions to ensure that we get deterministic
604 /// results from this routine. In other words, we don't want the results of
605 /// this to depend on where the addresses of various SCEV objects happened to
608 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
610 if (Ops.size() < 2) return; // Noop
611 if (Ops.size() == 2) {
612 // This is the common case, which also happens to be trivially simple.
614 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
615 if (SCEVComplexityCompare(LI)(RHS, LHS))
620 // Do the rough sort by complexity.
621 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
623 // Now that we are sorted by complexity, group elements of the same
624 // complexity. Note that this is, at worst, N^2, but the vector is likely to
625 // be extremely short in practice. Note that we take this approach because we
626 // do not want to depend on the addresses of the objects we are grouping.
627 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
628 const SCEV *S = Ops[i];
629 unsigned Complexity = S->getSCEVType();
631 // If there are any objects of the same complexity and same value as this
633 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
634 if (Ops[j] == S) { // Found a duplicate.
635 // Move it to immediately after i'th element.
636 std::swap(Ops[i+1], Ops[j]);
637 ++i; // no need to rescan it.
638 if (i == e-2) return; // Done!
646 //===----------------------------------------------------------------------===//
647 // Simple SCEV method implementations
648 //===----------------------------------------------------------------------===//
650 /// BinomialCoefficient - Compute BC(It, K). The result has width W.
652 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
654 const Type* ResultTy) {
655 // Handle the simplest case efficiently.
657 return SE.getTruncateOrZeroExtend(It, ResultTy);
659 // We are using the following formula for BC(It, K):
661 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
663 // Suppose, W is the bitwidth of the return value. We must be prepared for
664 // overflow. Hence, we must assure that the result of our computation is
665 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
666 // safe in modular arithmetic.
668 // However, this code doesn't use exactly that formula; the formula it uses
669 // is something like the following, where T is the number of factors of 2 in
670 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
673 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
675 // This formula is trivially equivalent to the previous formula. However,
676 // this formula can be implemented much more efficiently. The trick is that
677 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
678 // arithmetic. To do exact division in modular arithmetic, all we have
679 // to do is multiply by the inverse. Therefore, this step can be done at
682 // The next issue is how to safely do the division by 2^T. The way this
683 // is done is by doing the multiplication step at a width of at least W + T
684 // bits. This way, the bottom W+T bits of the product are accurate. Then,
685 // when we perform the division by 2^T (which is equivalent to a right shift
686 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
687 // truncated out after the division by 2^T.
689 // In comparison to just directly using the first formula, this technique
690 // is much more efficient; using the first formula requires W * K bits,
691 // but this formula less than W + K bits. Also, the first formula requires
692 // a division step, whereas this formula only requires multiplies and shifts.
694 // It doesn't matter whether the subtraction step is done in the calculation
695 // width or the input iteration count's width; if the subtraction overflows,
696 // the result must be zero anyway. We prefer here to do it in the width of
697 // the induction variable because it helps a lot for certain cases; CodeGen
698 // isn't smart enough to ignore the overflow, which leads to much less
699 // efficient code if the width of the subtraction is wider than the native
702 // (It's possible to not widen at all by pulling out factors of 2 before
703 // the multiplication; for example, K=2 can be calculated as
704 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
705 // extra arithmetic, so it's not an obvious win, and it gets
706 // much more complicated for K > 3.)
708 // Protection from insane SCEVs; this bound is conservative,
709 // but it probably doesn't matter.
711 return SE.getCouldNotCompute();
713 unsigned W = SE.getTypeSizeInBits(ResultTy);
715 // Calculate K! / 2^T and T; we divide out the factors of two before
716 // multiplying for calculating K! / 2^T to avoid overflow.
717 // Other overflow doesn't matter because we only care about the bottom
718 // W bits of the result.
719 APInt OddFactorial(W, 1);
721 for (unsigned i = 3; i <= K; ++i) {
723 unsigned TwoFactors = Mult.countTrailingZeros();
725 Mult = Mult.lshr(TwoFactors);
726 OddFactorial *= Mult;
729 // We need at least W + T bits for the multiplication step
730 unsigned CalculationBits = W + T;
732 // Calculate 2^T, at width T+W.
733 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
735 // Calculate the multiplicative inverse of K! / 2^T;
736 // this multiplication factor will perform the exact division by
738 APInt Mod = APInt::getSignedMinValue(W+1);
739 APInt MultiplyFactor = OddFactorial.zext(W+1);
740 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
741 MultiplyFactor = MultiplyFactor.trunc(W);
743 // Calculate the product, at width T+W
744 const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
746 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
747 for (unsigned i = 1; i != K; ++i) {
748 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
749 Dividend = SE.getMulExpr(Dividend,
750 SE.getTruncateOrZeroExtend(S, CalculationTy));
754 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
756 // Truncate the result, and divide by K! / 2^T.
758 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
759 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
762 /// evaluateAtIteration - Return the value of this chain of recurrences at
763 /// the specified iteration number. We can evaluate this recurrence by
764 /// multiplying each element in the chain by the binomial coefficient
765 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
767 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
769 /// where BC(It, k) stands for binomial coefficient.
771 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
772 ScalarEvolution &SE) const {
773 const SCEV *Result = getStart();
774 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
775 // The computation is correct in the face of overflow provided that the
776 // multiplication is performed _after_ the evaluation of the binomial
778 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
779 if (isa<SCEVCouldNotCompute>(Coeff))
782 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
787 //===----------------------------------------------------------------------===//
788 // SCEV Expression folder implementations
789 //===----------------------------------------------------------------------===//
791 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
793 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
794 "This is not a truncating conversion!");
795 assert(isSCEVable(Ty) &&
796 "This is not a conversion to a SCEVable type!");
797 Ty = getEffectiveSCEVType(Ty);
800 ID.AddInteger(scTruncate);
804 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
806 // Fold if the operand is constant.
807 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
809 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(),
810 getEffectiveSCEVType(Ty))));
812 // trunc(trunc(x)) --> trunc(x)
813 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
814 return getTruncateExpr(ST->getOperand(), Ty);
816 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
817 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
818 return getTruncateOrSignExtend(SS->getOperand(), Ty);
820 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
821 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
822 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
824 // If the input value is a chrec scev, truncate the chrec's operands.
825 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
826 SmallVector<const SCEV *, 4> Operands;
827 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
828 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
829 return getAddRecExpr(Operands, AddRec->getLoop());
832 // As a special case, fold trunc(undef) to undef. We don't want to
833 // know too much about SCEVUnknowns, but this special case is handy
835 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
836 if (isa<UndefValue>(U->getValue()))
837 return getSCEV(UndefValue::get(Ty));
839 // The cast wasn't folded; create an explicit cast node. We can reuse
840 // the existing insert position since if we get here, we won't have
841 // made any changes which would invalidate it.
842 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
844 UniqueSCEVs.InsertNode(S, IP);
848 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
850 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
851 "This is not an extending conversion!");
852 assert(isSCEVable(Ty) &&
853 "This is not a conversion to a SCEVable type!");
854 Ty = getEffectiveSCEVType(Ty);
856 // Fold if the operand is constant.
857 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
859 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(),
860 getEffectiveSCEVType(Ty))));
862 // zext(zext(x)) --> zext(x)
863 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
864 return getZeroExtendExpr(SZ->getOperand(), Ty);
866 // Before doing any expensive analysis, check to see if we've already
867 // computed a SCEV for this Op and Ty.
869 ID.AddInteger(scZeroExtend);
873 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
875 // If the input value is a chrec scev, and we can prove that the value
876 // did not overflow the old, smaller, value, we can zero extend all of the
877 // operands (often constants). This allows analysis of something like
878 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
879 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
880 if (AR->isAffine()) {
881 const SCEV *Start = AR->getStart();
882 const SCEV *Step = AR->getStepRecurrence(*this);
883 unsigned BitWidth = getTypeSizeInBits(AR->getType());
884 const Loop *L = AR->getLoop();
886 // If we have special knowledge that this addrec won't overflow,
887 // we don't need to do any further analysis.
888 if (AR->hasNoUnsignedWrap())
889 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
890 getZeroExtendExpr(Step, Ty),
893 // Check whether the backedge-taken count is SCEVCouldNotCompute.
894 // Note that this serves two purposes: It filters out loops that are
895 // simply not analyzable, and it covers the case where this code is
896 // being called from within backedge-taken count analysis, such that
897 // attempting to ask for the backedge-taken count would likely result
898 // in infinite recursion. In the later case, the analysis code will
899 // cope with a conservative value, and it will take care to purge
900 // that value once it has finished.
901 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
902 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
903 // Manually compute the final value for AR, checking for
906 // Check whether the backedge-taken count can be losslessly casted to
907 // the addrec's type. The count is always unsigned.
908 const SCEV *CastedMaxBECount =
909 getTruncateOrZeroExtend(MaxBECount, Start->getType());
910 const SCEV *RecastedMaxBECount =
911 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
912 if (MaxBECount == RecastedMaxBECount) {
913 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
914 // Check whether Start+Step*MaxBECount has no unsigned overflow.
915 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
916 const SCEV *Add = getAddExpr(Start, ZMul);
917 const SCEV *OperandExtendedAdd =
918 getAddExpr(getZeroExtendExpr(Start, WideTy),
919 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
920 getZeroExtendExpr(Step, WideTy)));
921 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
922 // Return the expression with the addrec on the outside.
923 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
924 getZeroExtendExpr(Step, Ty),
927 // Similar to above, only this time treat the step value as signed.
928 // This covers loops that count down.
929 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
930 Add = getAddExpr(Start, SMul);
932 getAddExpr(getZeroExtendExpr(Start, WideTy),
933 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
934 getSignExtendExpr(Step, WideTy)));
935 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
936 // Return the expression with the addrec on the outside.
937 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
938 getSignExtendExpr(Step, Ty),
942 // If the backedge is guarded by a comparison with the pre-inc value
943 // the addrec is safe. Also, if the entry is guarded by a comparison
944 // with the start value and the backedge is guarded by a comparison
945 // with the post-inc value, the addrec is safe.
946 if (isKnownPositive(Step)) {
947 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
948 getUnsignedRange(Step).getUnsignedMax());
949 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
950 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
951 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
952 AR->getPostIncExpr(*this), N)))
953 // Return the expression with the addrec on the outside.
954 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
955 getZeroExtendExpr(Step, Ty),
957 } else if (isKnownNegative(Step)) {
958 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
959 getSignedRange(Step).getSignedMin());
960 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
961 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
962 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
963 AR->getPostIncExpr(*this), N)))
964 // Return the expression with the addrec on the outside.
965 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
966 getSignExtendExpr(Step, Ty),
972 // The cast wasn't folded; create an explicit cast node.
973 // Recompute the insert position, as it may have been invalidated.
974 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
975 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
977 UniqueSCEVs.InsertNode(S, IP);
981 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
983 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
984 "This is not an extending conversion!");
985 assert(isSCEVable(Ty) &&
986 "This is not a conversion to a SCEVable type!");
987 Ty = getEffectiveSCEVType(Ty);
989 // Fold if the operand is constant.
990 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
992 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(),
993 getEffectiveSCEVType(Ty))));
995 // sext(sext(x)) --> sext(x)
996 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
997 return getSignExtendExpr(SS->getOperand(), Ty);
999 // Before doing any expensive analysis, check to see if we've already
1000 // computed a SCEV for this Op and Ty.
1001 FoldingSetNodeID ID;
1002 ID.AddInteger(scSignExtend);
1006 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1008 // If the input value is a chrec scev, and we can prove that the value
1009 // did not overflow the old, smaller, value, we can sign extend all of the
1010 // operands (often constants). This allows analysis of something like
1011 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1012 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1013 if (AR->isAffine()) {
1014 const SCEV *Start = AR->getStart();
1015 const SCEV *Step = AR->getStepRecurrence(*this);
1016 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1017 const Loop *L = AR->getLoop();
1019 // If we have special knowledge that this addrec won't overflow,
1020 // we don't need to do any further analysis.
1021 if (AR->hasNoSignedWrap())
1022 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1023 getSignExtendExpr(Step, Ty),
1026 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1027 // Note that this serves two purposes: It filters out loops that are
1028 // simply not analyzable, and it covers the case where this code is
1029 // being called from within backedge-taken count analysis, such that
1030 // attempting to ask for the backedge-taken count would likely result
1031 // in infinite recursion. In the later case, the analysis code will
1032 // cope with a conservative value, and it will take care to purge
1033 // that value once it has finished.
1034 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1035 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1036 // Manually compute the final value for AR, checking for
1039 // Check whether the backedge-taken count can be losslessly casted to
1040 // the addrec's type. The count is always unsigned.
1041 const SCEV *CastedMaxBECount =
1042 getTruncateOrZeroExtend(MaxBECount, Start->getType());
1043 const SCEV *RecastedMaxBECount =
1044 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1045 if (MaxBECount == RecastedMaxBECount) {
1046 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1047 // Check whether Start+Step*MaxBECount has no signed overflow.
1048 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
1049 const SCEV *Add = getAddExpr(Start, SMul);
1050 const SCEV *OperandExtendedAdd =
1051 getAddExpr(getSignExtendExpr(Start, WideTy),
1052 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1053 getSignExtendExpr(Step, WideTy)));
1054 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
1055 // Return the expression with the addrec on the outside.
1056 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1057 getSignExtendExpr(Step, Ty),
1060 // Similar to above, only this time treat the step value as unsigned.
1061 // This covers loops that count up with an unsigned step.
1062 const SCEV *UMul = getMulExpr(CastedMaxBECount, Step);
1063 Add = getAddExpr(Start, UMul);
1064 OperandExtendedAdd =
1065 getAddExpr(getSignExtendExpr(Start, WideTy),
1066 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1067 getZeroExtendExpr(Step, WideTy)));
1068 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
1069 // Return the expression with the addrec on the outside.
1070 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1071 getZeroExtendExpr(Step, Ty),
1075 // If the backedge is guarded by a comparison with the pre-inc value
1076 // the addrec is safe. Also, if the entry is guarded by a comparison
1077 // with the start value and the backedge is guarded by a comparison
1078 // with the post-inc value, the addrec is safe.
1079 if (isKnownPositive(Step)) {
1080 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
1081 getSignedRange(Step).getSignedMax());
1082 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
1083 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
1084 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
1085 AR->getPostIncExpr(*this), N)))
1086 // Return the expression with the addrec on the outside.
1087 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1088 getSignExtendExpr(Step, Ty),
1090 } else if (isKnownNegative(Step)) {
1091 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1092 getSignedRange(Step).getSignedMin());
1093 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
1094 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
1095 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1096 AR->getPostIncExpr(*this), N)))
1097 // Return the expression with the addrec on the outside.
1098 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1099 getSignExtendExpr(Step, Ty),
1105 // The cast wasn't folded; create an explicit cast node.
1106 // Recompute the insert position, as it may have been invalidated.
1107 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1108 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1110 UniqueSCEVs.InsertNode(S, IP);
1114 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1115 /// unspecified bits out to the given type.
1117 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1119 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1120 "This is not an extending conversion!");
1121 assert(isSCEVable(Ty) &&
1122 "This is not a conversion to a SCEVable type!");
1123 Ty = getEffectiveSCEVType(Ty);
1125 // Sign-extend negative constants.
1126 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1127 if (SC->getValue()->getValue().isNegative())
1128 return getSignExtendExpr(Op, Ty);
1130 // Peel off a truncate cast.
1131 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
1132 const SCEV *NewOp = T->getOperand();
1133 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1134 return getAnyExtendExpr(NewOp, Ty);
1135 return getTruncateOrNoop(NewOp, Ty);
1138 // Next try a zext cast. If the cast is folded, use it.
1139 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
1140 if (!isa<SCEVZeroExtendExpr>(ZExt))
1143 // Next try a sext cast. If the cast is folded, use it.
1144 const SCEV *SExt = getSignExtendExpr(Op, Ty);
1145 if (!isa<SCEVSignExtendExpr>(SExt))
1148 // Force the cast to be folded into the operands of an addrec.
1149 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1150 SmallVector<const SCEV *, 4> Ops;
1151 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
1153 Ops.push_back(getAnyExtendExpr(*I, Ty));
1154 return getAddRecExpr(Ops, AR->getLoop());
1157 // As a special case, fold anyext(undef) to undef. We don't want to
1158 // know too much about SCEVUnknowns, but this special case is handy
1160 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
1161 if (isa<UndefValue>(U->getValue()))
1162 return getSCEV(UndefValue::get(Ty));
1164 // If the expression is obviously signed, use the sext cast value.
1165 if (isa<SCEVSMaxExpr>(Op))
1168 // Absent any other information, use the zext cast value.
1172 /// CollectAddOperandsWithScales - Process the given Ops list, which is
1173 /// a list of operands to be added under the given scale, update the given
1174 /// map. This is a helper function for getAddRecExpr. As an example of
1175 /// what it does, given a sequence of operands that would form an add
1176 /// expression like this:
1178 /// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1180 /// where A and B are constants, update the map with these values:
1182 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1184 /// and add 13 + A*B*29 to AccumulatedConstant.
1185 /// This will allow getAddRecExpr to produce this:
1187 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1189 /// This form often exposes folding opportunities that are hidden in
1190 /// the original operand list.
1192 /// Return true iff it appears that any interesting folding opportunities
1193 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
1194 /// the common case where no interesting opportunities are present, and
1195 /// is also used as a check to avoid infinite recursion.
1198 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1199 SmallVector<const SCEV *, 8> &NewOps,
1200 APInt &AccumulatedConstant,
1201 const SCEV *const *Ops, size_t NumOperands,
1203 ScalarEvolution &SE) {
1204 bool Interesting = false;
1206 // Iterate over the add operands. They are sorted, with constants first.
1208 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1210 // Pull a buried constant out to the outside.
1211 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1213 AccumulatedConstant += Scale * C->getValue()->getValue();
1216 // Next comes everything else. We're especially interested in multiplies
1217 // here, but they're in the middle, so just visit the rest with one loop.
1218 for (; i != NumOperands; ++i) {
1219 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1220 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1222 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1223 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1224 // A multiplication of a constant with another add; recurse.
1225 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
1227 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1228 Add->op_begin(), Add->getNumOperands(),
1231 // A multiplication of a constant with some other value. Update
1233 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1234 const SCEV *Key = SE.getMulExpr(MulOps);
1235 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1236 M.insert(std::make_pair(Key, NewScale));
1238 NewOps.push_back(Pair.first->first);
1240 Pair.first->second += NewScale;
1241 // The map already had an entry for this value, which may indicate
1242 // a folding opportunity.
1247 // An ordinary operand. Update the map.
1248 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1249 M.insert(std::make_pair(Ops[i], Scale));
1251 NewOps.push_back(Pair.first->first);
1253 Pair.first->second += Scale;
1254 // The map already had an entry for this value, which may indicate
1255 // a folding opportunity.
1265 struct APIntCompare {
1266 bool operator()(const APInt &LHS, const APInt &RHS) const {
1267 return LHS.ult(RHS);
1272 /// getAddExpr - Get a canonical add expression, or something simpler if
1274 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1275 bool HasNUW, bool HasNSW) {
1276 assert(!Ops.empty() && "Cannot get empty add!");
1277 if (Ops.size() == 1) return Ops[0];
1279 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
1280 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1281 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
1282 "SCEVAddExpr operand types don't match!");
1285 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1286 if (!HasNUW && HasNSW) {
1288 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
1289 E = Ops.end(); I != E; ++I)
1290 if (!isKnownNonNegative(*I)) {
1294 if (All) HasNUW = true;
1297 // Sort by complexity, this groups all similar expression types together.
1298 GroupByComplexity(Ops, LI);
1300 // If there are any constants, fold them together.
1302 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1304 assert(Idx < Ops.size());
1305 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1306 // We found two constants, fold them together!
1307 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1308 RHSC->getValue()->getValue());
1309 if (Ops.size() == 2) return Ops[0];
1310 Ops.erase(Ops.begin()+1); // Erase the folded element
1311 LHSC = cast<SCEVConstant>(Ops[0]);
1314 // If we are left with a constant zero being added, strip it off.
1315 if (LHSC->getValue()->isZero()) {
1316 Ops.erase(Ops.begin());
1320 if (Ops.size() == 1) return Ops[0];
1323 // Okay, check to see if the same value occurs in the operand list more than
1324 // once. If so, merge them together into an multiply expression. Since we
1325 // sorted the list, these values are required to be adjacent.
1326 const Type *Ty = Ops[0]->getType();
1327 bool FoundMatch = false;
1328 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
1329 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1330 // Scan ahead to count how many equal operands there are.
1332 while (i+Count != e && Ops[i+Count] == Ops[i])
1334 // Merge the values into a multiply.
1335 const SCEV *Scale = getConstant(Ty, Count);
1336 const SCEV *Mul = getMulExpr(Scale, Ops[i]);
1337 if (Ops.size() == Count)
1340 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
1341 --i; e -= Count - 1;
1345 return getAddExpr(Ops, HasNUW, HasNSW);
1347 // Check for truncates. If all the operands are truncated from the same
1348 // type, see if factoring out the truncate would permit the result to be
1349 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1350 // if the contents of the resulting outer trunc fold to something simple.
1351 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1352 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1353 const Type *DstType = Trunc->getType();
1354 const Type *SrcType = Trunc->getOperand()->getType();
1355 SmallVector<const SCEV *, 8> LargeOps;
1357 // Check all the operands to see if they can be represented in the
1358 // source type of the truncate.
1359 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1360 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1361 if (T->getOperand()->getType() != SrcType) {
1365 LargeOps.push_back(T->getOperand());
1366 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1367 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
1368 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
1369 SmallVector<const SCEV *, 8> LargeMulOps;
1370 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1371 if (const SCEVTruncateExpr *T =
1372 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1373 if (T->getOperand()->getType() != SrcType) {
1377 LargeMulOps.push_back(T->getOperand());
1378 } else if (const SCEVConstant *C =
1379 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1380 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
1387 LargeOps.push_back(getMulExpr(LargeMulOps));
1394 // Evaluate the expression in the larger type.
1395 const SCEV *Fold = getAddExpr(LargeOps, HasNUW, HasNSW);
1396 // If it folds to something simple, use it. Otherwise, don't.
1397 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1398 return getTruncateExpr(Fold, DstType);
1402 // Skip past any other cast SCEVs.
1403 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1406 // If there are add operands they would be next.
1407 if (Idx < Ops.size()) {
1408 bool DeletedAdd = false;
1409 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
1410 // If we have an add, expand the add operands onto the end of the operands
1412 Ops.erase(Ops.begin()+Idx);
1413 Ops.append(Add->op_begin(), Add->op_end());
1417 // If we deleted at least one add, we added operands to the end of the list,
1418 // and they are not necessarily sorted. Recurse to resort and resimplify
1419 // any operands we just acquired.
1421 return getAddExpr(Ops);
1424 // Skip over the add expression until we get to a multiply.
1425 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1428 // Check to see if there are any folding opportunities present with
1429 // operands multiplied by constant values.
1430 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1431 uint64_t BitWidth = getTypeSizeInBits(Ty);
1432 DenseMap<const SCEV *, APInt> M;
1433 SmallVector<const SCEV *, 8> NewOps;
1434 APInt AccumulatedConstant(BitWidth, 0);
1435 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1436 Ops.data(), Ops.size(),
1437 APInt(BitWidth, 1), *this)) {
1438 // Some interesting folding opportunity is present, so its worthwhile to
1439 // re-generate the operands list. Group the operands by constant scale,
1440 // to avoid multiplying by the same constant scale multiple times.
1441 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1442 for (SmallVector<const SCEV *, 8>::const_iterator I = NewOps.begin(),
1443 E = NewOps.end(); I != E; ++I)
1444 MulOpLists[M.find(*I)->second].push_back(*I);
1445 // Re-generate the operands list.
1447 if (AccumulatedConstant != 0)
1448 Ops.push_back(getConstant(AccumulatedConstant));
1449 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1450 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
1452 Ops.push_back(getMulExpr(getConstant(I->first),
1453 getAddExpr(I->second)));
1455 return getConstant(Ty, 0);
1456 if (Ops.size() == 1)
1458 return getAddExpr(Ops);
1462 // If we are adding something to a multiply expression, make sure the
1463 // something is not already an operand of the multiply. If so, merge it into
1465 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
1466 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
1467 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
1468 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
1469 if (isa<SCEVConstant>(MulOpSCEV))
1471 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
1472 if (MulOpSCEV == Ops[AddOp]) {
1473 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1474 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
1475 if (Mul->getNumOperands() != 2) {
1476 // If the multiply has more than two operands, we must get the
1478 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1479 Mul->op_begin()+MulOp);
1480 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
1481 InnerMul = getMulExpr(MulOps);
1483 const SCEV *One = getConstant(Ty, 1);
1484 const SCEV *AddOne = getAddExpr(One, InnerMul);
1485 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
1486 if (Ops.size() == 2) return OuterMul;
1488 Ops.erase(Ops.begin()+AddOp);
1489 Ops.erase(Ops.begin()+Idx-1);
1491 Ops.erase(Ops.begin()+Idx);
1492 Ops.erase(Ops.begin()+AddOp-1);
1494 Ops.push_back(OuterMul);
1495 return getAddExpr(Ops);
1498 // Check this multiply against other multiplies being added together.
1499 for (unsigned OtherMulIdx = Idx+1;
1500 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1502 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
1503 // If MulOp occurs in OtherMul, we can fold the two multiplies
1505 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1506 OMulOp != e; ++OMulOp)
1507 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1508 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1509 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
1510 if (Mul->getNumOperands() != 2) {
1511 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1512 Mul->op_begin()+MulOp);
1513 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
1514 InnerMul1 = getMulExpr(MulOps);
1516 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1517 if (OtherMul->getNumOperands() != 2) {
1518 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1519 OtherMul->op_begin()+OMulOp);
1520 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
1521 InnerMul2 = getMulExpr(MulOps);
1523 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1524 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
1525 if (Ops.size() == 2) return OuterMul;
1526 Ops.erase(Ops.begin()+Idx);
1527 Ops.erase(Ops.begin()+OtherMulIdx-1);
1528 Ops.push_back(OuterMul);
1529 return getAddExpr(Ops);
1535 // If there are any add recurrences in the operands list, see if any other
1536 // added values are loop invariant. If so, we can fold them into the
1538 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1541 // Scan over all recurrences, trying to fold loop invariants into them.
1542 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1543 // Scan all of the other operands to this add and add them to the vector if
1544 // they are loop invariant w.r.t. the recurrence.
1545 SmallVector<const SCEV *, 8> LIOps;
1546 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1547 const Loop *AddRecLoop = AddRec->getLoop();
1548 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1549 if (isLoopInvariant(Ops[i], AddRecLoop)) {
1550 LIOps.push_back(Ops[i]);
1551 Ops.erase(Ops.begin()+i);
1555 // If we found some loop invariants, fold them into the recurrence.
1556 if (!LIOps.empty()) {
1557 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
1558 LIOps.push_back(AddRec->getStart());
1560 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
1562 AddRecOps[0] = getAddExpr(LIOps);
1564 // Build the new addrec. Propagate the NUW and NSW flags if both the
1565 // outer add and the inner addrec are guaranteed to have no overflow.
1566 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop,
1567 HasNUW && AddRec->hasNoUnsignedWrap(),
1568 HasNSW && AddRec->hasNoSignedWrap());
1570 // If all of the other operands were loop invariant, we are done.
1571 if (Ops.size() == 1) return NewRec;
1573 // Otherwise, add the folded AddRec by the non-liv parts.
1574 for (unsigned i = 0;; ++i)
1575 if (Ops[i] == AddRec) {
1579 return getAddExpr(Ops);
1582 // Okay, if there weren't any loop invariants to be folded, check to see if
1583 // there are multiple AddRec's with the same loop induction variable being
1584 // added together. If so, we can fold them.
1585 for (unsigned OtherIdx = Idx+1;
1586 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1588 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
1589 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
1590 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
1592 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1594 if (const SCEVAddRecExpr *OtherAddRec =
1595 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
1596 if (OtherAddRec->getLoop() == AddRecLoop) {
1597 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
1599 if (i >= AddRecOps.size()) {
1600 AddRecOps.append(OtherAddRec->op_begin()+i,
1601 OtherAddRec->op_end());
1604 AddRecOps[i] = getAddExpr(AddRecOps[i],
1605 OtherAddRec->getOperand(i));
1607 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
1609 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop);
1610 return getAddExpr(Ops);
1613 // Otherwise couldn't fold anything into this recurrence. Move onto the
1617 // Okay, it looks like we really DO need an add expr. Check to see if we
1618 // already have one, otherwise create a new one.
1619 FoldingSetNodeID ID;
1620 ID.AddInteger(scAddExpr);
1621 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1622 ID.AddPointer(Ops[i]);
1625 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1627 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1628 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
1629 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
1631 UniqueSCEVs.InsertNode(S, IP);
1633 if (HasNUW) S->setHasNoUnsignedWrap(true);
1634 if (HasNSW) S->setHasNoSignedWrap(true);
1638 /// getMulExpr - Get a canonical multiply expression, or something simpler if
1640 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1641 bool HasNUW, bool HasNSW) {
1642 assert(!Ops.empty() && "Cannot get empty mul!");
1643 if (Ops.size() == 1) return Ops[0];
1645 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
1646 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1647 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
1648 "SCEVMulExpr operand types don't match!");
1651 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1652 if (!HasNUW && HasNSW) {
1654 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
1655 E = Ops.end(); I != E; ++I)
1656 if (!isKnownNonNegative(*I)) {
1660 if (All) HasNUW = true;
1663 // Sort by complexity, this groups all similar expression types together.
1664 GroupByComplexity(Ops, LI);
1666 // If there are any constants, fold them together.
1668 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1670 // C1*(C2+V) -> C1*C2 + C1*V
1671 if (Ops.size() == 2)
1672 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1673 if (Add->getNumOperands() == 2 &&
1674 isa<SCEVConstant>(Add->getOperand(0)))
1675 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1676 getMulExpr(LHSC, Add->getOperand(1)));
1679 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1680 // We found two constants, fold them together!
1681 ConstantInt *Fold = ConstantInt::get(getContext(),
1682 LHSC->getValue()->getValue() *
1683 RHSC->getValue()->getValue());
1684 Ops[0] = getConstant(Fold);
1685 Ops.erase(Ops.begin()+1); // Erase the folded element
1686 if (Ops.size() == 1) return Ops[0];
1687 LHSC = cast<SCEVConstant>(Ops[0]);
1690 // If we are left with a constant one being multiplied, strip it off.
1691 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1692 Ops.erase(Ops.begin());
1694 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1695 // If we have a multiply of zero, it will always be zero.
1697 } else if (Ops[0]->isAllOnesValue()) {
1698 // If we have a mul by -1 of an add, try distributing the -1 among the
1700 if (Ops.size() == 2)
1701 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1702 SmallVector<const SCEV *, 4> NewOps;
1703 bool AnyFolded = false;
1704 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1706 const SCEV *Mul = getMulExpr(Ops[0], *I);
1707 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1708 NewOps.push_back(Mul);
1711 return getAddExpr(NewOps);
1715 if (Ops.size() == 1)
1719 // Skip over the add expression until we get to a multiply.
1720 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1723 // If there are mul operands inline them all into this expression.
1724 if (Idx < Ops.size()) {
1725 bool DeletedMul = false;
1726 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1727 // If we have an mul, expand the mul operands onto the end of the operands
1729 Ops.erase(Ops.begin()+Idx);
1730 Ops.append(Mul->op_begin(), Mul->op_end());
1734 // If we deleted at least one mul, we added operands to the end of the list,
1735 // and they are not necessarily sorted. Recurse to resort and resimplify
1736 // any operands we just acquired.
1738 return getMulExpr(Ops);
1741 // If there are any add recurrences in the operands list, see if any other
1742 // added values are loop invariant. If so, we can fold them into the
1744 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1747 // Scan over all recurrences, trying to fold loop invariants into them.
1748 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1749 // Scan all of the other operands to this mul and add them to the vector if
1750 // they are loop invariant w.r.t. the recurrence.
1751 SmallVector<const SCEV *, 8> LIOps;
1752 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1753 const Loop *AddRecLoop = AddRec->getLoop();
1754 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1755 if (isLoopInvariant(Ops[i], AddRecLoop)) {
1756 LIOps.push_back(Ops[i]);
1757 Ops.erase(Ops.begin()+i);
1761 // If we found some loop invariants, fold them into the recurrence.
1762 if (!LIOps.empty()) {
1763 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
1764 SmallVector<const SCEV *, 4> NewOps;
1765 NewOps.reserve(AddRec->getNumOperands());
1766 const SCEV *Scale = getMulExpr(LIOps);
1767 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1768 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1770 // Build the new addrec. Propagate the NUW and NSW flags if both the
1771 // outer mul and the inner addrec are guaranteed to have no overflow.
1772 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop,
1773 HasNUW && AddRec->hasNoUnsignedWrap(),
1774 HasNSW && AddRec->hasNoSignedWrap());
1776 // If all of the other operands were loop invariant, we are done.
1777 if (Ops.size() == 1) return NewRec;
1779 // Otherwise, multiply the folded AddRec by the non-liv parts.
1780 for (unsigned i = 0;; ++i)
1781 if (Ops[i] == AddRec) {
1785 return getMulExpr(Ops);
1788 // Okay, if there weren't any loop invariants to be folded, check to see if
1789 // there are multiple AddRec's with the same loop induction variable being
1790 // multiplied together. If so, we can fold them.
1791 for (unsigned OtherIdx = Idx+1;
1792 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1794 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
1795 // F * G, where F = {A,+,B}<L> and G = {C,+,D}<L> -->
1796 // {A*C,+,F*D + G*B + B*D}<L>
1797 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1799 if (const SCEVAddRecExpr *OtherAddRec =
1800 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
1801 if (OtherAddRec->getLoop() == AddRecLoop) {
1802 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1803 const SCEV *NewStart = getMulExpr(F->getStart(), G->getStart());
1804 const SCEV *B = F->getStepRecurrence(*this);
1805 const SCEV *D = G->getStepRecurrence(*this);
1806 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
1809 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
1811 if (Ops.size() == 2) return NewAddRec;
1812 Ops[Idx] = AddRec = cast<SCEVAddRecExpr>(NewAddRec);
1813 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
1815 return getMulExpr(Ops);
1818 // Otherwise couldn't fold anything into this recurrence. Move onto the
1822 // Okay, it looks like we really DO need an mul expr. Check to see if we
1823 // already have one, otherwise create a new one.
1824 FoldingSetNodeID ID;
1825 ID.AddInteger(scMulExpr);
1826 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1827 ID.AddPointer(Ops[i]);
1830 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1832 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1833 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
1834 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
1836 UniqueSCEVs.InsertNode(S, IP);
1838 if (HasNUW) S->setHasNoUnsignedWrap(true);
1839 if (HasNSW) S->setHasNoSignedWrap(true);
1843 /// getUDivExpr - Get a canonical unsigned division expression, or something
1844 /// simpler if possible.
1845 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1847 assert(getEffectiveSCEVType(LHS->getType()) ==
1848 getEffectiveSCEVType(RHS->getType()) &&
1849 "SCEVUDivExpr operand types don't match!");
1851 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1852 if (RHSC->getValue()->equalsInt(1))
1853 return LHS; // X udiv 1 --> x
1854 // If the denominator is zero, the result of the udiv is undefined. Don't
1855 // try to analyze it, because the resolution chosen here may differ from
1856 // the resolution chosen in other parts of the compiler.
1857 if (!RHSC->getValue()->isZero()) {
1858 // Determine if the division can be folded into the operands of
1860 // TODO: Generalize this to non-constants by using known-bits information.
1861 const Type *Ty = LHS->getType();
1862 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1863 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
1864 // For non-power-of-two values, effectively round the value up to the
1865 // nearest power of two.
1866 if (!RHSC->getValue()->getValue().isPowerOf2())
1868 const IntegerType *ExtTy =
1869 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
1870 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1871 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1872 if (const SCEVConstant *Step =
1873 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1874 if (!Step->getValue()->getValue()
1875 .urem(RHSC->getValue()->getValue()) &&
1876 getZeroExtendExpr(AR, ExtTy) ==
1877 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1878 getZeroExtendExpr(Step, ExtTy),
1880 SmallVector<const SCEV *, 4> Operands;
1881 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1882 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1883 return getAddRecExpr(Operands, AR->getLoop());
1885 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1886 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1887 SmallVector<const SCEV *, 4> Operands;
1888 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1889 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1890 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
1891 // Find an operand that's safely divisible.
1892 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1893 const SCEV *Op = M->getOperand(i);
1894 const SCEV *Div = getUDivExpr(Op, RHSC);
1895 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1896 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
1899 return getMulExpr(Operands);
1903 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
1904 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1905 SmallVector<const SCEV *, 4> Operands;
1906 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1907 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1908 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1910 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1911 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
1912 if (isa<SCEVUDivExpr>(Op) ||
1913 getMulExpr(Op, RHS) != A->getOperand(i))
1915 Operands.push_back(Op);
1917 if (Operands.size() == A->getNumOperands())
1918 return getAddExpr(Operands);
1922 // Fold if both operands are constant.
1923 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1924 Constant *LHSCV = LHSC->getValue();
1925 Constant *RHSCV = RHSC->getValue();
1926 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1932 FoldingSetNodeID ID;
1933 ID.AddInteger(scUDivExpr);
1937 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1938 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
1940 UniqueSCEVs.InsertNode(S, IP);
1945 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1946 /// Simplify the expression as much as possible.
1947 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
1948 const SCEV *Step, const Loop *L,
1949 bool HasNUW, bool HasNSW) {
1950 SmallVector<const SCEV *, 4> Operands;
1951 Operands.push_back(Start);
1952 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1953 if (StepChrec->getLoop() == L) {
1954 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
1955 return getAddRecExpr(Operands, L);
1958 Operands.push_back(Step);
1959 return getAddRecExpr(Operands, L, HasNUW, HasNSW);
1962 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1963 /// Simplify the expression as much as possible.
1965 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
1967 bool HasNUW, bool HasNSW) {
1968 if (Operands.size() == 1) return Operands[0];
1970 const Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
1971 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1972 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
1973 "SCEVAddRecExpr operand types don't match!");
1974 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1975 assert(isLoopInvariant(Operands[i], L) &&
1976 "SCEVAddRecExpr operand is not loop-invariant!");
1979 if (Operands.back()->isZero()) {
1980 Operands.pop_back();
1981 return getAddRecExpr(Operands, L, HasNUW, HasNSW); // {X,+,0} --> X
1984 // It's tempting to want to call getMaxBackedgeTakenCount count here and
1985 // use that information to infer NUW and NSW flags. However, computing a
1986 // BE count requires calling getAddRecExpr, so we may not yet have a
1987 // meaningful BE count at this point (and if we don't, we'd be stuck
1988 // with a SCEVCouldNotCompute as the cached BE count).
1990 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1991 if (!HasNUW && HasNSW) {
1993 for (SmallVectorImpl<const SCEV *>::const_iterator I = Operands.begin(),
1994 E = Operands.end(); I != E; ++I)
1995 if (!isKnownNonNegative(*I)) {
1999 if (All) HasNUW = true;
2002 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
2003 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
2004 const Loop *NestedLoop = NestedAR->getLoop();
2005 if (L->contains(NestedLoop) ?
2006 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
2007 (!NestedLoop->contains(L) &&
2008 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
2009 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
2010 NestedAR->op_end());
2011 Operands[0] = NestedAR->getStart();
2012 // AddRecs require their operands be loop-invariant with respect to their
2013 // loops. Don't perform this transformation if it would break this
2015 bool AllInvariant = true;
2016 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2017 if (!isLoopInvariant(Operands[i], L)) {
2018 AllInvariant = false;
2022 NestedOperands[0] = getAddRecExpr(Operands, L);
2023 AllInvariant = true;
2024 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
2025 if (!isLoopInvariant(NestedOperands[i], NestedLoop)) {
2026 AllInvariant = false;
2030 // Ok, both add recurrences are valid after the transformation.
2031 return getAddRecExpr(NestedOperands, NestedLoop, HasNUW, HasNSW);
2033 // Reset Operands to its original state.
2034 Operands[0] = NestedAR;
2038 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2039 // already have one, otherwise create a new one.
2040 FoldingSetNodeID ID;
2041 ID.AddInteger(scAddRecExpr);
2042 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2043 ID.AddPointer(Operands[i]);
2047 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2049 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2050 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
2051 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2052 O, Operands.size(), L);
2053 UniqueSCEVs.InsertNode(S, IP);
2055 if (HasNUW) S->setHasNoUnsignedWrap(true);
2056 if (HasNSW) S->setHasNoSignedWrap(true);
2060 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2062 SmallVector<const SCEV *, 2> Ops;
2065 return getSMaxExpr(Ops);
2069 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2070 assert(!Ops.empty() && "Cannot get empty smax!");
2071 if (Ops.size() == 1) return Ops[0];
2073 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2074 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2075 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2076 "SCEVSMaxExpr operand types don't match!");
2079 // Sort by complexity, this groups all similar expression types together.
2080 GroupByComplexity(Ops, LI);
2082 // If there are any constants, fold them together.
2084 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2086 assert(Idx < Ops.size());
2087 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2088 // We found two constants, fold them together!
2089 ConstantInt *Fold = ConstantInt::get(getContext(),
2090 APIntOps::smax(LHSC->getValue()->getValue(),
2091 RHSC->getValue()->getValue()));
2092 Ops[0] = getConstant(Fold);
2093 Ops.erase(Ops.begin()+1); // Erase the folded element
2094 if (Ops.size() == 1) return Ops[0];
2095 LHSC = cast<SCEVConstant>(Ops[0]);
2098 // If we are left with a constant minimum-int, strip it off.
2099 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2100 Ops.erase(Ops.begin());
2102 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2103 // If we have an smax with a constant maximum-int, it will always be
2108 if (Ops.size() == 1) return Ops[0];
2111 // Find the first SMax
2112 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2115 // Check to see if one of the operands is an SMax. If so, expand its operands
2116 // onto our operand list, and recurse to simplify.
2117 if (Idx < Ops.size()) {
2118 bool DeletedSMax = false;
2119 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
2120 Ops.erase(Ops.begin()+Idx);
2121 Ops.append(SMax->op_begin(), SMax->op_end());
2126 return getSMaxExpr(Ops);
2129 // Okay, check to see if the same value occurs in the operand list twice. If
2130 // so, delete one. Since we sorted the list, these values are required to
2132 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2133 // X smax Y smax Y --> X smax Y
2134 // X smax Y --> X, if X is always greater than Y
2135 if (Ops[i] == Ops[i+1] ||
2136 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
2137 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2139 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
2140 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2144 if (Ops.size() == 1) return Ops[0];
2146 assert(!Ops.empty() && "Reduced smax down to nothing!");
2148 // Okay, it looks like we really DO need an smax expr. Check to see if we
2149 // already have one, otherwise create a new one.
2150 FoldingSetNodeID ID;
2151 ID.AddInteger(scSMaxExpr);
2152 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2153 ID.AddPointer(Ops[i]);
2155 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2156 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2157 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2158 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
2160 UniqueSCEVs.InsertNode(S, IP);
2164 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2166 SmallVector<const SCEV *, 2> Ops;
2169 return getUMaxExpr(Ops);
2173 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2174 assert(!Ops.empty() && "Cannot get empty umax!");
2175 if (Ops.size() == 1) return Ops[0];
2177 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2178 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2179 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2180 "SCEVUMaxExpr operand types don't match!");
2183 // Sort by complexity, this groups all similar expression types together.
2184 GroupByComplexity(Ops, LI);
2186 // If there are any constants, fold them together.
2188 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2190 assert(Idx < Ops.size());
2191 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2192 // We found two constants, fold them together!
2193 ConstantInt *Fold = ConstantInt::get(getContext(),
2194 APIntOps::umax(LHSC->getValue()->getValue(),
2195 RHSC->getValue()->getValue()));
2196 Ops[0] = getConstant(Fold);
2197 Ops.erase(Ops.begin()+1); // Erase the folded element
2198 if (Ops.size() == 1) return Ops[0];
2199 LHSC = cast<SCEVConstant>(Ops[0]);
2202 // If we are left with a constant minimum-int, strip it off.
2203 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2204 Ops.erase(Ops.begin());
2206 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2207 // If we have an umax with a constant maximum-int, it will always be
2212 if (Ops.size() == 1) return Ops[0];
2215 // Find the first UMax
2216 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2219 // Check to see if one of the operands is a UMax. If so, expand its operands
2220 // onto our operand list, and recurse to simplify.
2221 if (Idx < Ops.size()) {
2222 bool DeletedUMax = false;
2223 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
2224 Ops.erase(Ops.begin()+Idx);
2225 Ops.append(UMax->op_begin(), UMax->op_end());
2230 return getUMaxExpr(Ops);
2233 // Okay, check to see if the same value occurs in the operand list twice. If
2234 // so, delete one. Since we sorted the list, these values are required to
2236 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2237 // X umax Y umax Y --> X umax Y
2238 // X umax Y --> X, if X is always greater than Y
2239 if (Ops[i] == Ops[i+1] ||
2240 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
2241 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2243 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
2244 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2248 if (Ops.size() == 1) return Ops[0];
2250 assert(!Ops.empty() && "Reduced umax down to nothing!");
2252 // Okay, it looks like we really DO need a umax expr. Check to see if we
2253 // already have one, otherwise create a new one.
2254 FoldingSetNodeID ID;
2255 ID.AddInteger(scUMaxExpr);
2256 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2257 ID.AddPointer(Ops[i]);
2259 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2260 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2261 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2262 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
2264 UniqueSCEVs.InsertNode(S, IP);
2268 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2270 // ~smax(~x, ~y) == smin(x, y).
2271 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2274 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2276 // ~umax(~x, ~y) == umin(x, y)
2277 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2280 const SCEV *ScalarEvolution::getSizeOfExpr(const Type *AllocTy) {
2281 // If we have TargetData, we can bypass creating a target-independent
2282 // constant expression and then folding it back into a ConstantInt.
2283 // This is just a compile-time optimization.
2285 return getConstant(TD->getIntPtrType(getContext()),
2286 TD->getTypeAllocSize(AllocTy));
2288 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2289 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2290 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2292 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2293 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2296 const SCEV *ScalarEvolution::getAlignOfExpr(const Type *AllocTy) {
2297 Constant *C = ConstantExpr::getAlignOf(AllocTy);
2298 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2299 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2301 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2302 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2305 const SCEV *ScalarEvolution::getOffsetOfExpr(const StructType *STy,
2307 // If we have TargetData, we can bypass creating a target-independent
2308 // constant expression and then folding it back into a ConstantInt.
2309 // This is just a compile-time optimization.
2311 return getConstant(TD->getIntPtrType(getContext()),
2312 TD->getStructLayout(STy)->getElementOffset(FieldNo));
2314 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2315 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2316 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2318 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
2319 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2322 const SCEV *ScalarEvolution::getOffsetOfExpr(const Type *CTy,
2323 Constant *FieldNo) {
2324 Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
2325 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2326 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2328 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
2329 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2332 const SCEV *ScalarEvolution::getUnknown(Value *V) {
2333 // Don't attempt to do anything other than create a SCEVUnknown object
2334 // here. createSCEV only calls getUnknown after checking for all other
2335 // interesting possibilities, and any other code that calls getUnknown
2336 // is doing so in order to hide a value from SCEV canonicalization.
2338 FoldingSetNodeID ID;
2339 ID.AddInteger(scUnknown);
2342 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
2343 assert(cast<SCEVUnknown>(S)->getValue() == V &&
2344 "Stale SCEVUnknown in uniquing map!");
2347 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
2349 FirstUnknown = cast<SCEVUnknown>(S);
2350 UniqueSCEVs.InsertNode(S, IP);
2354 //===----------------------------------------------------------------------===//
2355 // Basic SCEV Analysis and PHI Idiom Recognition Code
2358 /// isSCEVable - Test if values of the given type are analyzable within
2359 /// the SCEV framework. This primarily includes integer types, and it
2360 /// can optionally include pointer types if the ScalarEvolution class
2361 /// has access to target-specific information.
2362 bool ScalarEvolution::isSCEVable(const Type *Ty) const {
2363 // Integers and pointers are always SCEVable.
2364 return Ty->isIntegerTy() || Ty->isPointerTy();
2367 /// getTypeSizeInBits - Return the size in bits of the specified type,
2368 /// for which isSCEVable must return true.
2369 uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
2370 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2372 // If we have a TargetData, use it!
2374 return TD->getTypeSizeInBits(Ty);
2376 // Integer types have fixed sizes.
2377 if (Ty->isIntegerTy())
2378 return Ty->getPrimitiveSizeInBits();
2380 // The only other support type is pointer. Without TargetData, conservatively
2381 // assume pointers are 64-bit.
2382 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
2386 /// getEffectiveSCEVType - Return a type with the same bitwidth as
2387 /// the given type and which represents how SCEV will treat the given
2388 /// type, for which isSCEVable must return true. For pointer types,
2389 /// this is the pointer-sized integer type.
2390 const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
2391 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2393 if (Ty->isIntegerTy())
2396 // The only other support type is pointer.
2397 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
2398 if (TD) return TD->getIntPtrType(getContext());
2400 // Without TargetData, conservatively assume pointers are 64-bit.
2401 return Type::getInt64Ty(getContext());
2404 const SCEV *ScalarEvolution::getCouldNotCompute() {
2405 return &CouldNotCompute;
2408 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2409 /// expression and create a new one.
2410 const SCEV *ScalarEvolution::getSCEV(Value *V) {
2411 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
2413 ValueExprMapType::const_iterator I = ValueExprMap.find(V);
2414 if (I != ValueExprMap.end()) return I->second;
2415 const SCEV *S = createSCEV(V);
2417 // The process of creating a SCEV for V may have caused other SCEVs
2418 // to have been created, so it's necessary to insert the new entry
2419 // from scratch, rather than trying to remember the insert position
2421 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(V, this), S));
2425 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2427 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
2428 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2430 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
2432 const Type *Ty = V->getType();
2433 Ty = getEffectiveSCEVType(Ty);
2434 return getMulExpr(V,
2435 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
2438 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
2439 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
2440 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2442 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
2444 const Type *Ty = V->getType();
2445 Ty = getEffectiveSCEVType(Ty);
2446 const SCEV *AllOnes =
2447 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
2448 return getMinusSCEV(AllOnes, V);
2451 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2453 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2455 // Fast path: X - X --> 0.
2457 return getConstant(LHS->getType(), 0);
2460 return getAddExpr(LHS, getNegativeSCEV(RHS));
2463 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2464 /// input value to the specified type. If the type must be extended, it is zero
2467 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
2469 const Type *SrcTy = V->getType();
2470 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2471 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2472 "Cannot truncate or zero extend with non-integer arguments!");
2473 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2474 return V; // No conversion
2475 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2476 return getTruncateExpr(V, Ty);
2477 return getZeroExtendExpr(V, Ty);
2480 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2481 /// input value to the specified type. If the type must be extended, it is sign
2484 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
2486 const Type *SrcTy = V->getType();
2487 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2488 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2489 "Cannot truncate or zero extend with non-integer arguments!");
2490 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2491 return V; // No conversion
2492 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2493 return getTruncateExpr(V, Ty);
2494 return getSignExtendExpr(V, Ty);
2497 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2498 /// input value to the specified type. If the type must be extended, it is zero
2499 /// extended. The conversion must not be narrowing.
2501 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
2502 const Type *SrcTy = V->getType();
2503 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2504 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2505 "Cannot noop or zero extend with non-integer arguments!");
2506 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2507 "getNoopOrZeroExtend cannot truncate!");
2508 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2509 return V; // No conversion
2510 return getZeroExtendExpr(V, Ty);
2513 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2514 /// input value to the specified type. If the type must be extended, it is sign
2515 /// extended. The conversion must not be narrowing.
2517 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
2518 const Type *SrcTy = V->getType();
2519 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2520 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2521 "Cannot noop or sign extend with non-integer arguments!");
2522 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2523 "getNoopOrSignExtend cannot truncate!");
2524 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2525 return V; // No conversion
2526 return getSignExtendExpr(V, Ty);
2529 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2530 /// the input value to the specified type. If the type must be extended,
2531 /// it is extended with unspecified bits. The conversion must not be
2534 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
2535 const Type *SrcTy = V->getType();
2536 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2537 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2538 "Cannot noop or any extend with non-integer arguments!");
2539 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2540 "getNoopOrAnyExtend cannot truncate!");
2541 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2542 return V; // No conversion
2543 return getAnyExtendExpr(V, Ty);
2546 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2547 /// input value to the specified type. The conversion must not be widening.
2549 ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
2550 const Type *SrcTy = V->getType();
2551 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2552 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2553 "Cannot truncate or noop with non-integer arguments!");
2554 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2555 "getTruncateOrNoop cannot extend!");
2556 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2557 return V; // No conversion
2558 return getTruncateExpr(V, Ty);
2561 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2562 /// the types using zero-extension, and then perform a umax operation
2564 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2566 const SCEV *PromotedLHS = LHS;
2567 const SCEV *PromotedRHS = RHS;
2569 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2570 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2572 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2574 return getUMaxExpr(PromotedLHS, PromotedRHS);
2577 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
2578 /// the types using zero-extension, and then perform a umin operation
2580 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2582 const SCEV *PromotedLHS = LHS;
2583 const SCEV *PromotedRHS = RHS;
2585 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2586 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2588 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2590 return getUMinExpr(PromotedLHS, PromotedRHS);
2593 /// PushDefUseChildren - Push users of the given Instruction
2594 /// onto the given Worklist.
2596 PushDefUseChildren(Instruction *I,
2597 SmallVectorImpl<Instruction *> &Worklist) {
2598 // Push the def-use children onto the Worklist stack.
2599 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2601 Worklist.push_back(cast<Instruction>(*UI));
2604 /// ForgetSymbolicValue - This looks up computed SCEV values for all
2605 /// instructions that depend on the given instruction and removes them from
2606 /// the ValueExprMapType map if they reference SymName. This is used during PHI
2609 ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
2610 SmallVector<Instruction *, 16> Worklist;
2611 PushDefUseChildren(PN, Worklist);
2613 SmallPtrSet<Instruction *, 8> Visited;
2615 while (!Worklist.empty()) {
2616 Instruction *I = Worklist.pop_back_val();
2617 if (!Visited.insert(I)) continue;
2619 ValueExprMapType::iterator It =
2620 ValueExprMap.find(static_cast<Value *>(I));
2621 if (It != ValueExprMap.end()) {
2622 const SCEV *Old = It->second;
2624 // Short-circuit the def-use traversal if the symbolic name
2625 // ceases to appear in expressions.
2626 if (Old != SymName && !hasOperand(Old, SymName))
2629 // SCEVUnknown for a PHI either means that it has an unrecognized
2630 // structure, it's a PHI that's in the progress of being computed
2631 // by createNodeForPHI, or it's a single-value PHI. In the first case,
2632 // additional loop trip count information isn't going to change anything.
2633 // In the second case, createNodeForPHI will perform the necessary
2634 // updates on its own when it gets to that point. In the third, we do
2635 // want to forget the SCEVUnknown.
2636 if (!isa<PHINode>(I) ||
2637 !isa<SCEVUnknown>(Old) ||
2638 (I != PN && Old == SymName)) {
2639 ValuesAtScopes.erase(Old);
2640 LoopDispositions.erase(Old);
2641 UnsignedRanges.erase(Old);
2642 SignedRanges.erase(Old);
2643 ValueExprMap.erase(It);
2647 PushDefUseChildren(I, Worklist);
2651 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2652 /// a loop header, making it a potential recurrence, or it doesn't.
2654 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
2655 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2656 if (L->getHeader() == PN->getParent()) {
2657 // The loop may have multiple entrances or multiple exits; we can analyze
2658 // this phi as an addrec if it has a unique entry value and a unique
2660 Value *BEValueV = 0, *StartValueV = 0;
2661 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2662 Value *V = PN->getIncomingValue(i);
2663 if (L->contains(PN->getIncomingBlock(i))) {
2666 } else if (BEValueV != V) {
2670 } else if (!StartValueV) {
2672 } else if (StartValueV != V) {
2677 if (BEValueV && StartValueV) {
2678 // While we are analyzing this PHI node, handle its value symbolically.
2679 const SCEV *SymbolicName = getUnknown(PN);
2680 assert(ValueExprMap.find(PN) == ValueExprMap.end() &&
2681 "PHI node already processed?");
2682 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
2684 // Using this symbolic name for the PHI, analyze the value coming around
2686 const SCEV *BEValue = getSCEV(BEValueV);
2688 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2689 // has a special value for the first iteration of the loop.
2691 // If the value coming around the backedge is an add with the symbolic
2692 // value we just inserted, then we found a simple induction variable!
2693 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
2694 // If there is a single occurrence of the symbolic value, replace it
2695 // with a recurrence.
2696 unsigned FoundIndex = Add->getNumOperands();
2697 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2698 if (Add->getOperand(i) == SymbolicName)
2699 if (FoundIndex == e) {
2704 if (FoundIndex != Add->getNumOperands()) {
2705 // Create an add with everything but the specified operand.
2706 SmallVector<const SCEV *, 8> Ops;
2707 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2708 if (i != FoundIndex)
2709 Ops.push_back(Add->getOperand(i));
2710 const SCEV *Accum = getAddExpr(Ops);
2712 // This is not a valid addrec if the step amount is varying each
2713 // loop iteration, but is not itself an addrec in this loop.
2714 if (isLoopInvariant(Accum, L) ||
2715 (isa<SCEVAddRecExpr>(Accum) &&
2716 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
2717 bool HasNUW = false;
2718 bool HasNSW = false;
2720 // If the increment doesn't overflow, then neither the addrec nor
2721 // the post-increment will overflow.
2722 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
2723 if (OBO->hasNoUnsignedWrap())
2725 if (OBO->hasNoSignedWrap())
2729 const SCEV *StartVal = getSCEV(StartValueV);
2730 const SCEV *PHISCEV =
2731 getAddRecExpr(StartVal, Accum, L, HasNUW, HasNSW);
2733 // Since the no-wrap flags are on the increment, they apply to the
2734 // post-incremented value as well.
2735 if (isLoopInvariant(Accum, L))
2736 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
2737 Accum, L, HasNUW, HasNSW);
2739 // Okay, for the entire analysis of this edge we assumed the PHI
2740 // to be symbolic. We now need to go back and purge all of the
2741 // entries for the scalars that use the symbolic expression.
2742 ForgetSymbolicName(PN, SymbolicName);
2743 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
2747 } else if (const SCEVAddRecExpr *AddRec =
2748 dyn_cast<SCEVAddRecExpr>(BEValue)) {
2749 // Otherwise, this could be a loop like this:
2750 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2751 // In this case, j = {1,+,1} and BEValue is j.
2752 // Because the other in-value of i (0) fits the evolution of BEValue
2753 // i really is an addrec evolution.
2754 if (AddRec->getLoop() == L && AddRec->isAffine()) {
2755 const SCEV *StartVal = getSCEV(StartValueV);
2757 // If StartVal = j.start - j.stride, we can use StartVal as the
2758 // initial step of the addrec evolution.
2759 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
2760 AddRec->getOperand(1))) {
2761 const SCEV *PHISCEV =
2762 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
2764 // Okay, for the entire analysis of this edge we assumed the PHI
2765 // to be symbolic. We now need to go back and purge all of the
2766 // entries for the scalars that use the symbolic expression.
2767 ForgetSymbolicName(PN, SymbolicName);
2768 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
2776 // If the PHI has a single incoming value, follow that value, unless the
2777 // PHI's incoming blocks are in a different loop, in which case doing so
2778 // risks breaking LCSSA form. Instcombine would normally zap these, but
2779 // it doesn't have DominatorTree information, so it may miss cases.
2780 if (Value *V = SimplifyInstruction(PN, TD, DT)) {
2781 Instruction *I = dyn_cast<Instruction>(V);
2782 // Only instructions are problematic for preserving LCSSA form.
2786 // If the instruction is not defined in a loop, then it can be used freely.
2787 Loop *ILoop = LI->getLoopFor(I->getParent());
2791 // If the instruction is defined in the same loop as the phi node, or in a
2792 // loop that contains the phi node loop as an inner loop, then using it as
2793 // a replacement for the phi node will not break LCSSA form.
2794 Loop *PNLoop = LI->getLoopFor(PN->getParent());
2795 if (ILoop->contains(PNLoop))
2799 // If it's not a loop phi, we can't handle it yet.
2800 return getUnknown(PN);
2803 /// createNodeForGEP - Expand GEP instructions into add and multiply
2804 /// operations. This allows them to be analyzed by regular SCEV code.
2806 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
2808 // Don't blindly transfer the inbounds flag from the GEP instruction to the
2809 // Add expression, because the Instruction may be guarded by control flow
2810 // and the no-overflow bits may not be valid for the expression in any
2813 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
2814 Value *Base = GEP->getOperand(0);
2815 // Don't attempt to analyze GEPs over unsized objects.
2816 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2817 return getUnknown(GEP);
2818 const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
2819 gep_type_iterator GTI = gep_type_begin(GEP);
2820 for (GetElementPtrInst::op_iterator I = llvm::next(GEP->op_begin()),
2824 // Compute the (potentially symbolic) offset in bytes for this index.
2825 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2826 // For a struct, add the member offset.
2827 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2828 const SCEV *FieldOffset = getOffsetOfExpr(STy, FieldNo);
2830 // Add the field offset to the running total offset.
2831 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
2833 // For an array, add the element offset, explicitly scaled.
2834 const SCEV *ElementSize = getSizeOfExpr(*GTI);
2835 const SCEV *IndexS = getSCEV(Index);
2836 // Getelementptr indices are signed.
2837 IndexS = getTruncateOrSignExtend(IndexS, IntPtrTy);
2839 // Multiply the index by the element size to compute the element offset.
2840 const SCEV *LocalOffset = getMulExpr(IndexS, ElementSize);
2842 // Add the element offset to the running total offset.
2843 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2847 // Get the SCEV for the GEP base.
2848 const SCEV *BaseS = getSCEV(Base);
2850 // Add the total offset from all the GEP indices to the base.
2851 return getAddExpr(BaseS, TotalOffset);
2854 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2855 /// guaranteed to end in (at every loop iteration). It is, at the same time,
2856 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2857 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
2859 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
2860 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2861 return C->getValue()->getValue().countTrailingZeros();
2863 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
2864 return std::min(GetMinTrailingZeros(T->getOperand()),
2865 (uint32_t)getTypeSizeInBits(T->getType()));
2867 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
2868 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2869 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2870 getTypeSizeInBits(E->getType()) : OpRes;
2873 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
2874 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2875 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2876 getTypeSizeInBits(E->getType()) : OpRes;
2879 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
2880 // The result is the min of all operands results.
2881 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2882 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2883 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2887 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
2888 // The result is the sum of all operands results.
2889 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2890 uint32_t BitWidth = getTypeSizeInBits(M->getType());
2891 for (unsigned i = 1, e = M->getNumOperands();
2892 SumOpRes != BitWidth && i != e; ++i)
2893 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
2898 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
2899 // The result is the min of all operands results.
2900 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2901 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2902 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2906 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
2907 // The result is the min of all operands results.
2908 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2909 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2910 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2914 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
2915 // The result is the min of all operands results.
2916 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2917 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2918 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2922 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2923 // For a SCEVUnknown, ask ValueTracking.
2924 unsigned BitWidth = getTypeSizeInBits(U->getType());
2925 APInt Mask = APInt::getAllOnesValue(BitWidth);
2926 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2927 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2928 return Zeros.countTrailingOnes();
2935 /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2938 ScalarEvolution::getUnsignedRange(const SCEV *S) {
2939 // See if we've computed this range already.
2940 DenseMap<const SCEV *, ConstantRange>::iterator I = UnsignedRanges.find(S);
2941 if (I != UnsignedRanges.end())
2944 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2945 return setUnsignedRange(C, ConstantRange(C->getValue()->getValue()));
2947 unsigned BitWidth = getTypeSizeInBits(S->getType());
2948 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2950 // If the value has known zeros, the maximum unsigned value will have those
2951 // known zeros as well.
2952 uint32_t TZ = GetMinTrailingZeros(S);
2954 ConservativeResult =
2955 ConstantRange(APInt::getMinValue(BitWidth),
2956 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
2958 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2959 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2960 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2961 X = X.add(getUnsignedRange(Add->getOperand(i)));
2962 return setUnsignedRange(Add, ConservativeResult.intersectWith(X));
2965 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2966 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2967 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2968 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
2969 return setUnsignedRange(Mul, ConservativeResult.intersectWith(X));
2972 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2973 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2974 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2975 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
2976 return setUnsignedRange(SMax, ConservativeResult.intersectWith(X));
2979 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2980 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2981 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2982 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
2983 return setUnsignedRange(UMax, ConservativeResult.intersectWith(X));
2986 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2987 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2988 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
2989 return setUnsignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
2992 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2993 ConstantRange X = getUnsignedRange(ZExt->getOperand());
2994 return setUnsignedRange(ZExt,
2995 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
2998 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2999 ConstantRange X = getUnsignedRange(SExt->getOperand());
3000 return setUnsignedRange(SExt,
3001 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
3004 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3005 ConstantRange X = getUnsignedRange(Trunc->getOperand());
3006 return setUnsignedRange(Trunc,
3007 ConservativeResult.intersectWith(X.truncate(BitWidth)));
3010 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
3011 // If there's no unsigned wrap, the value will never be less than its
3013 if (AddRec->hasNoUnsignedWrap())
3014 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
3015 if (!C->getValue()->isZero())
3016 ConservativeResult =
3017 ConservativeResult.intersectWith(
3018 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0)));
3020 // TODO: non-affine addrec
3021 if (AddRec->isAffine()) {
3022 const Type *Ty = AddRec->getType();
3023 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
3024 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3025 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
3026 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3028 const SCEV *Start = AddRec->getStart();
3029 const SCEV *Step = AddRec->getStepRecurrence(*this);
3031 ConstantRange StartRange = getUnsignedRange(Start);
3032 ConstantRange StepRange = getSignedRange(Step);
3033 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3034 ConstantRange EndRange =
3035 StartRange.add(MaxBECountRange.multiply(StepRange));
3037 // Check for overflow. This must be done with ConstantRange arithmetic
3038 // because we could be called from within the ScalarEvolution overflow
3040 ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
3041 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3042 ConstantRange ExtMaxBECountRange =
3043 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3044 ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
3045 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3047 return setUnsignedRange(AddRec, ConservativeResult);
3049 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
3050 EndRange.getUnsignedMin());
3051 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
3052 EndRange.getUnsignedMax());
3053 if (Min.isMinValue() && Max.isMaxValue())
3054 return setUnsignedRange(AddRec, ConservativeResult);
3055 return setUnsignedRange(AddRec,
3056 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
3060 return setUnsignedRange(AddRec, ConservativeResult);
3063 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3064 // For a SCEVUnknown, ask ValueTracking.
3065 APInt Mask = APInt::getAllOnesValue(BitWidth);
3066 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3067 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
3068 if (Ones == ~Zeros + 1)
3069 return setUnsignedRange(U, ConservativeResult);
3070 return setUnsignedRange(U,
3071 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)));
3074 return setUnsignedRange(S, ConservativeResult);
3077 /// getSignedRange - Determine the signed range for a particular SCEV.
3080 ScalarEvolution::getSignedRange(const SCEV *S) {
3081 DenseMap<const SCEV *, ConstantRange>::iterator I = SignedRanges.find(S);
3082 if (I != SignedRanges.end())
3085 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
3086 return setSignedRange(C, ConstantRange(C->getValue()->getValue()));
3088 unsigned BitWidth = getTypeSizeInBits(S->getType());
3089 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3091 // If the value has known zeros, the maximum signed value will have those
3092 // known zeros as well.
3093 uint32_t TZ = GetMinTrailingZeros(S);
3095 ConservativeResult =
3096 ConstantRange(APInt::getSignedMinValue(BitWidth),
3097 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
3099 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3100 ConstantRange X = getSignedRange(Add->getOperand(0));
3101 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3102 X = X.add(getSignedRange(Add->getOperand(i)));
3103 return setSignedRange(Add, ConservativeResult.intersectWith(X));
3106 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3107 ConstantRange X = getSignedRange(Mul->getOperand(0));
3108 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3109 X = X.multiply(getSignedRange(Mul->getOperand(i)));
3110 return setSignedRange(Mul, ConservativeResult.intersectWith(X));
3113 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3114 ConstantRange X = getSignedRange(SMax->getOperand(0));
3115 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3116 X = X.smax(getSignedRange(SMax->getOperand(i)));
3117 return setSignedRange(SMax, ConservativeResult.intersectWith(X));
3120 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3121 ConstantRange X = getSignedRange(UMax->getOperand(0));
3122 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3123 X = X.umax(getSignedRange(UMax->getOperand(i)));
3124 return setSignedRange(UMax, ConservativeResult.intersectWith(X));
3127 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3128 ConstantRange X = getSignedRange(UDiv->getLHS());
3129 ConstantRange Y = getSignedRange(UDiv->getRHS());
3130 return setSignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
3133 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3134 ConstantRange X = getSignedRange(ZExt->getOperand());
3135 return setSignedRange(ZExt,
3136 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
3139 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3140 ConstantRange X = getSignedRange(SExt->getOperand());
3141 return setSignedRange(SExt,
3142 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
3145 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3146 ConstantRange X = getSignedRange(Trunc->getOperand());
3147 return setSignedRange(Trunc,
3148 ConservativeResult.intersectWith(X.truncate(BitWidth)));
3151 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
3152 // If there's no signed wrap, and all the operands have the same sign or
3153 // zero, the value won't ever change sign.
3154 if (AddRec->hasNoSignedWrap()) {
3155 bool AllNonNeg = true;
3156 bool AllNonPos = true;
3157 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3158 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3159 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3162 ConservativeResult = ConservativeResult.intersectWith(
3163 ConstantRange(APInt(BitWidth, 0),
3164 APInt::getSignedMinValue(BitWidth)));
3166 ConservativeResult = ConservativeResult.intersectWith(
3167 ConstantRange(APInt::getSignedMinValue(BitWidth),
3168 APInt(BitWidth, 1)));
3171 // TODO: non-affine addrec
3172 if (AddRec->isAffine()) {
3173 const Type *Ty = AddRec->getType();
3174 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
3175 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3176 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
3177 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3179 const SCEV *Start = AddRec->getStart();
3180 const SCEV *Step = AddRec->getStepRecurrence(*this);
3182 ConstantRange StartRange = getSignedRange(Start);
3183 ConstantRange StepRange = getSignedRange(Step);
3184 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3185 ConstantRange EndRange =
3186 StartRange.add(MaxBECountRange.multiply(StepRange));
3188 // Check for overflow. This must be done with ConstantRange arithmetic
3189 // because we could be called from within the ScalarEvolution overflow
3191 ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
3192 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3193 ConstantRange ExtMaxBECountRange =
3194 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3195 ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
3196 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3198 return setSignedRange(AddRec, ConservativeResult);
3200 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3201 EndRange.getSignedMin());
3202 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3203 EndRange.getSignedMax());
3204 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
3205 return setSignedRange(AddRec, ConservativeResult);
3206 return setSignedRange(AddRec,
3207 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
3211 return setSignedRange(AddRec, ConservativeResult);
3214 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3215 // For a SCEVUnknown, ask ValueTracking.
3216 if (!U->getValue()->getType()->isIntegerTy() && !TD)
3217 return setSignedRange(U, ConservativeResult);
3218 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3220 return setSignedRange(U, ConservativeResult);
3221 return setSignedRange(U, ConservativeResult.intersectWith(
3222 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
3223 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1)));
3226 return setSignedRange(S, ConservativeResult);
3229 /// createSCEV - We know that there is no SCEV for the specified value.
3230 /// Analyze the expression.
3232 const SCEV *ScalarEvolution::createSCEV(Value *V) {
3233 if (!isSCEVable(V->getType()))
3234 return getUnknown(V);
3236 unsigned Opcode = Instruction::UserOp1;
3237 if (Instruction *I = dyn_cast<Instruction>(V)) {
3238 Opcode = I->getOpcode();
3240 // Don't attempt to analyze instructions in blocks that aren't
3241 // reachable. Such instructions don't matter, and they aren't required
3242 // to obey basic rules for definitions dominating uses which this
3243 // analysis depends on.
3244 if (!DT->isReachableFromEntry(I->getParent()))
3245 return getUnknown(V);
3246 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
3247 Opcode = CE->getOpcode();
3248 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3249 return getConstant(CI);
3250 else if (isa<ConstantPointerNull>(V))
3251 return getConstant(V->getType(), 0);
3252 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3253 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
3255 return getUnknown(V);
3257 Operator *U = cast<Operator>(V);
3259 case Instruction::Add: {
3260 // The simple thing to do would be to just call getSCEV on both operands
3261 // and call getAddExpr with the result. However if we're looking at a
3262 // bunch of things all added together, this can be quite inefficient,
3263 // because it leads to N-1 getAddExpr calls for N ultimate operands.
3264 // Instead, gather up all the operands and make a single getAddExpr call.
3265 // LLVM IR canonical form means we need only traverse the left operands.
3266 SmallVector<const SCEV *, 4> AddOps;
3267 AddOps.push_back(getSCEV(U->getOperand(1)));
3268 for (Value *Op = U->getOperand(0); ; Op = U->getOperand(0)) {
3269 unsigned Opcode = Op->getValueID() - Value::InstructionVal;
3270 if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
3272 U = cast<Operator>(Op);
3273 const SCEV *Op1 = getSCEV(U->getOperand(1));
3274 if (Opcode == Instruction::Sub)
3275 AddOps.push_back(getNegativeSCEV(Op1));
3277 AddOps.push_back(Op1);
3279 AddOps.push_back(getSCEV(U->getOperand(0)));
3280 return getAddExpr(AddOps);
3282 case Instruction::Mul: {
3283 // See the Add code above.
3284 SmallVector<const SCEV *, 4> MulOps;
3285 MulOps.push_back(getSCEV(U->getOperand(1)));
3286 for (Value *Op = U->getOperand(0);
3287 Op->getValueID() == Instruction::Mul + Value::InstructionVal;
3288 Op = U->getOperand(0)) {
3289 U = cast<Operator>(Op);
3290 MulOps.push_back(getSCEV(U->getOperand(1)));
3292 MulOps.push_back(getSCEV(U->getOperand(0)));
3293 return getMulExpr(MulOps);
3295 case Instruction::UDiv:
3296 return getUDivExpr(getSCEV(U->getOperand(0)),
3297 getSCEV(U->getOperand(1)));
3298 case Instruction::Sub:
3299 return getMinusSCEV(getSCEV(U->getOperand(0)),
3300 getSCEV(U->getOperand(1)));
3301 case Instruction::And:
3302 // For an expression like x&255 that merely masks off the high bits,
3303 // use zext(trunc(x)) as the SCEV expression.
3304 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3305 if (CI->isNullValue())
3306 return getSCEV(U->getOperand(1));
3307 if (CI->isAllOnesValue())
3308 return getSCEV(U->getOperand(0));
3309 const APInt &A = CI->getValue();
3311 // Instcombine's ShrinkDemandedConstant may strip bits out of
3312 // constants, obscuring what would otherwise be a low-bits mask.
3313 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3314 // knew about to reconstruct a low-bits mask value.
3315 unsigned LZ = A.countLeadingZeros();
3316 unsigned BitWidth = A.getBitWidth();
3317 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3318 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3319 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3321 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3323 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
3325 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
3326 IntegerType::get(getContext(), BitWidth - LZ)),
3331 case Instruction::Or:
3332 // If the RHS of the Or is a constant, we may have something like:
3333 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3334 // optimizations will transparently handle this case.
3336 // In order for this transformation to be safe, the LHS must be of the
3337 // form X*(2^n) and the Or constant must be less than 2^n.
3338 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3339 const SCEV *LHS = getSCEV(U->getOperand(0));
3340 const APInt &CIVal = CI->getValue();
3341 if (GetMinTrailingZeros(LHS) >=
3342 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3343 // Build a plain add SCEV.
3344 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3345 // If the LHS of the add was an addrec and it has no-wrap flags,
3346 // transfer the no-wrap flags, since an or won't introduce a wrap.
3347 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3348 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
3349 if (OldAR->hasNoUnsignedWrap())
3350 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoUnsignedWrap(true);
3351 if (OldAR->hasNoSignedWrap())
3352 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoSignedWrap(true);
3358 case Instruction::Xor:
3359 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3360 // If the RHS of the xor is a signbit, then this is just an add.
3361 // Instcombine turns add of signbit into xor as a strength reduction step.
3362 if (CI->getValue().isSignBit())
3363 return getAddExpr(getSCEV(U->getOperand(0)),
3364 getSCEV(U->getOperand(1)));
3366 // If the RHS of xor is -1, then this is a not operation.
3367 if (CI->isAllOnesValue())
3368 return getNotSCEV(getSCEV(U->getOperand(0)));
3370 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3371 // This is a variant of the check for xor with -1, and it handles
3372 // the case where instcombine has trimmed non-demanded bits out
3373 // of an xor with -1.
3374 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3375 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3376 if (BO->getOpcode() == Instruction::And &&
3377 LCI->getValue() == CI->getValue())
3378 if (const SCEVZeroExtendExpr *Z =
3379 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
3380 const Type *UTy = U->getType();
3381 const SCEV *Z0 = Z->getOperand();
3382 const Type *Z0Ty = Z0->getType();
3383 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3385 // If C is a low-bits mask, the zero extend is serving to
3386 // mask off the high bits. Complement the operand and
3387 // re-apply the zext.
3388 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3389 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3391 // If C is a single bit, it may be in the sign-bit position
3392 // before the zero-extend. In this case, represent the xor
3393 // using an add, which is equivalent, and re-apply the zext.
3394 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
3395 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3397 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3403 case Instruction::Shl:
3404 // Turn shift left of a constant amount into a multiply.
3405 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3406 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
3408 // If the shift count is not less than the bitwidth, the result of
3409 // the shift is undefined. Don't try to analyze it, because the
3410 // resolution chosen here may differ from the resolution chosen in
3411 // other parts of the compiler.
3412 if (SA->getValue().uge(BitWidth))
3415 Constant *X = ConstantInt::get(getContext(),
3416 APInt(BitWidth, 1).shl(SA->getZExtValue()));
3417 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3421 case Instruction::LShr:
3422 // Turn logical shift right of a constant into a unsigned divide.
3423 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3424 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
3426 // If the shift count is not less than the bitwidth, the result of
3427 // the shift is undefined. Don't try to analyze it, because the
3428 // resolution chosen here may differ from the resolution chosen in
3429 // other parts of the compiler.
3430 if (SA->getValue().uge(BitWidth))
3433 Constant *X = ConstantInt::get(getContext(),
3434 APInt(BitWidth, 1).shl(SA->getZExtValue()));
3435 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3439 case Instruction::AShr:
3440 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3441 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
3442 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
3443 if (L->getOpcode() == Instruction::Shl &&
3444 L->getOperand(1) == U->getOperand(1)) {
3445 uint64_t BitWidth = getTypeSizeInBits(U->getType());
3447 // If the shift count is not less than the bitwidth, the result of
3448 // the shift is undefined. Don't try to analyze it, because the
3449 // resolution chosen here may differ from the resolution chosen in
3450 // other parts of the compiler.
3451 if (CI->getValue().uge(BitWidth))
3454 uint64_t Amt = BitWidth - CI->getZExtValue();
3455 if (Amt == BitWidth)
3456 return getSCEV(L->getOperand(0)); // shift by zero --> noop
3458 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
3459 IntegerType::get(getContext(),
3465 case Instruction::Trunc:
3466 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
3468 case Instruction::ZExt:
3469 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3471 case Instruction::SExt:
3472 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3474 case Instruction::BitCast:
3475 // BitCasts are no-op casts so we just eliminate the cast.
3476 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
3477 return getSCEV(U->getOperand(0));
3480 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3481 // lead to pointer expressions which cannot safely be expanded to GEPs,
3482 // because ScalarEvolution doesn't respect the GEP aliasing rules when
3483 // simplifying integer expressions.
3485 case Instruction::GetElementPtr:
3486 return createNodeForGEP(cast<GEPOperator>(U));
3488 case Instruction::PHI:
3489 return createNodeForPHI(cast<PHINode>(U));
3491 case Instruction::Select:
3492 // This could be a smax or umax that was lowered earlier.
3493 // Try to recover it.
3494 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3495 Value *LHS = ICI->getOperand(0);
3496 Value *RHS = ICI->getOperand(1);
3497 switch (ICI->getPredicate()) {
3498 case ICmpInst::ICMP_SLT:
3499 case ICmpInst::ICMP_SLE:
3500 std::swap(LHS, RHS);
3502 case ICmpInst::ICMP_SGT:
3503 case ICmpInst::ICMP_SGE:
3504 // a >s b ? a+x : b+x -> smax(a, b)+x
3505 // a >s b ? b+x : a+x -> smin(a, b)+x
3506 if (LHS->getType() == U->getType()) {
3507 const SCEV *LS = getSCEV(LHS);
3508 const SCEV *RS = getSCEV(RHS);
3509 const SCEV *LA = getSCEV(U->getOperand(1));
3510 const SCEV *RA = getSCEV(U->getOperand(2));
3511 const SCEV *LDiff = getMinusSCEV(LA, LS);
3512 const SCEV *RDiff = getMinusSCEV(RA, RS);
3514 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
3515 LDiff = getMinusSCEV(LA, RS);
3516 RDiff = getMinusSCEV(RA, LS);
3518 return getAddExpr(getSMinExpr(LS, RS), LDiff);
3521 case ICmpInst::ICMP_ULT:
3522 case ICmpInst::ICMP_ULE:
3523 std::swap(LHS, RHS);
3525 case ICmpInst::ICMP_UGT:
3526 case ICmpInst::ICMP_UGE:
3527 // a >u b ? a+x : b+x -> umax(a, b)+x
3528 // a >u b ? b+x : a+x -> umin(a, b)+x
3529 if (LHS->getType() == U->getType()) {
3530 const SCEV *LS = getSCEV(LHS);
3531 const SCEV *RS = getSCEV(RHS);
3532 const SCEV *LA = getSCEV(U->getOperand(1));
3533 const SCEV *RA = getSCEV(U->getOperand(2));
3534 const SCEV *LDiff = getMinusSCEV(LA, LS);
3535 const SCEV *RDiff = getMinusSCEV(RA, RS);
3537 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
3538 LDiff = getMinusSCEV(LA, RS);
3539 RDiff = getMinusSCEV(RA, LS);
3541 return getAddExpr(getUMinExpr(LS, RS), LDiff);
3544 case ICmpInst::ICMP_NE:
3545 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
3546 if (LHS->getType() == U->getType() &&
3547 isa<ConstantInt>(RHS) &&
3548 cast<ConstantInt>(RHS)->isZero()) {
3549 const SCEV *One = getConstant(LHS->getType(), 1);
3550 const SCEV *LS = getSCEV(LHS);
3551 const SCEV *LA = getSCEV(U->getOperand(1));
3552 const SCEV *RA = getSCEV(U->getOperand(2));
3553 const SCEV *LDiff = getMinusSCEV(LA, LS);
3554 const SCEV *RDiff = getMinusSCEV(RA, One);
3556 return getAddExpr(getUMaxExpr(One, LS), LDiff);
3559 case ICmpInst::ICMP_EQ:
3560 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
3561 if (LHS->getType() == U->getType() &&
3562 isa<ConstantInt>(RHS) &&
3563 cast<ConstantInt>(RHS)->isZero()) {
3564 const SCEV *One = getConstant(LHS->getType(), 1);
3565 const SCEV *LS = getSCEV(LHS);
3566 const SCEV *LA = getSCEV(U->getOperand(1));
3567 const SCEV *RA = getSCEV(U->getOperand(2));
3568 const SCEV *LDiff = getMinusSCEV(LA, One);
3569 const SCEV *RDiff = getMinusSCEV(RA, LS);
3571 return getAddExpr(getUMaxExpr(One, LS), LDiff);
3579 default: // We cannot analyze this expression.
3583 return getUnknown(V);
3588 //===----------------------------------------------------------------------===//
3589 // Iteration Count Computation Code
3592 /// getBackedgeTakenCount - If the specified loop has a predictable
3593 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3594 /// object. The backedge-taken count is the number of times the loop header
3595 /// will be branched to from within the loop. This is one less than the
3596 /// trip count of the loop, since it doesn't count the first iteration,
3597 /// when the header is branched to from outside the loop.
3599 /// Note that it is not valid to call this method on a loop without a
3600 /// loop-invariant backedge-taken count (see
3601 /// hasLoopInvariantBackedgeTakenCount).
3603 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
3604 return getBackedgeTakenInfo(L).Exact;
3607 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3608 /// return the least SCEV value that is known never to be less than the
3609 /// actual backedge taken count.
3610 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
3611 return getBackedgeTakenInfo(L).Max;
3614 /// PushLoopPHIs - Push PHI nodes in the header of the given loop
3615 /// onto the given Worklist.
3617 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3618 BasicBlock *Header = L->getHeader();
3620 // Push all Loop-header PHIs onto the Worklist stack.
3621 for (BasicBlock::iterator I = Header->begin();
3622 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3623 Worklist.push_back(PN);
3626 const ScalarEvolution::BackedgeTakenInfo &
3627 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
3628 // Initially insert a CouldNotCompute for this loop. If the insertion
3629 // succeeds, proceed to actually compute a backedge-taken count and
3630 // update the value. The temporary CouldNotCompute value tells SCEV
3631 // code elsewhere that it shouldn't attempt to request a new
3632 // backedge-taken count, which could result in infinite recursion.
3633 std::pair<std::map<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
3634 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3636 BackedgeTakenInfo BECount = ComputeBackedgeTakenCount(L);
3637 if (BECount.Exact != getCouldNotCompute()) {
3638 assert(isLoopInvariant(BECount.Exact, L) &&
3639 isLoopInvariant(BECount.Max, L) &&
3640 "Computed backedge-taken count isn't loop invariant for loop!");
3641 ++NumTripCountsComputed;
3643 // Update the value in the map.
3644 Pair.first->second = BECount;
3646 if (BECount.Max != getCouldNotCompute())
3647 // Update the value in the map.
3648 Pair.first->second = BECount;
3649 if (isa<PHINode>(L->getHeader()->begin()))
3650 // Only count loops that have phi nodes as not being computable.
3651 ++NumTripCountsNotComputed;
3654 // Now that we know more about the trip count for this loop, forget any
3655 // existing SCEV values for PHI nodes in this loop since they are only
3656 // conservative estimates made without the benefit of trip count
3657 // information. This is similar to the code in forgetLoop, except that
3658 // it handles SCEVUnknown PHI nodes specially.
3659 if (BECount.hasAnyInfo()) {
3660 SmallVector<Instruction *, 16> Worklist;
3661 PushLoopPHIs(L, Worklist);
3663 SmallPtrSet<Instruction *, 8> Visited;
3664 while (!Worklist.empty()) {
3665 Instruction *I = Worklist.pop_back_val();
3666 if (!Visited.insert(I)) continue;
3668 ValueExprMapType::iterator It =
3669 ValueExprMap.find(static_cast<Value *>(I));
3670 if (It != ValueExprMap.end()) {
3671 const SCEV *Old = It->second;
3673 // SCEVUnknown for a PHI either means that it has an unrecognized
3674 // structure, or it's a PHI that's in the progress of being computed
3675 // by createNodeForPHI. In the former case, additional loop trip
3676 // count information isn't going to change anything. In the later
3677 // case, createNodeForPHI will perform the necessary updates on its
3678 // own when it gets to that point.
3679 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
3680 ValuesAtScopes.erase(Old);
3681 LoopDispositions.erase(Old);
3682 UnsignedRanges.erase(Old);
3683 SignedRanges.erase(Old);
3684 ValueExprMap.erase(It);
3686 if (PHINode *PN = dyn_cast<PHINode>(I))
3687 ConstantEvolutionLoopExitValue.erase(PN);
3690 PushDefUseChildren(I, Worklist);
3694 return Pair.first->second;
3697 /// forgetLoop - This method should be called by the client when it has
3698 /// changed a loop in a way that may effect ScalarEvolution's ability to
3699 /// compute a trip count, or if the loop is deleted.
3700 void ScalarEvolution::forgetLoop(const Loop *L) {
3701 // Drop any stored trip count value.
3702 BackedgeTakenCounts.erase(L);
3704 // Drop information about expressions based on loop-header PHIs.
3705 SmallVector<Instruction *, 16> Worklist;
3706 PushLoopPHIs(L, Worklist);
3708 SmallPtrSet<Instruction *, 8> Visited;
3709 while (!Worklist.empty()) {
3710 Instruction *I = Worklist.pop_back_val();
3711 if (!Visited.insert(I)) continue;
3713 ValueExprMapType::iterator It = ValueExprMap.find(static_cast<Value *>(I));
3714 if (It != ValueExprMap.end()) {
3715 const SCEV *Old = It->second;
3716 ValuesAtScopes.erase(Old);
3717 LoopDispositions.erase(Old);
3718 UnsignedRanges.erase(Old);
3719 SignedRanges.erase(Old);
3720 ValueExprMap.erase(It);
3721 if (PHINode *PN = dyn_cast<PHINode>(I))
3722 ConstantEvolutionLoopExitValue.erase(PN);
3725 PushDefUseChildren(I, Worklist);
3728 // Forget all contained loops too, to avoid dangling entries in the
3729 // ValuesAtScopes map.
3730 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3734 /// forgetValue - This method should be called by the client when it has
3735 /// changed a value in a way that may effect its value, or which may
3736 /// disconnect it from a def-use chain linking it to a loop.
3737 void ScalarEvolution::forgetValue(Value *V) {
3738 Instruction *I = dyn_cast<Instruction>(V);
3741 // Drop information about expressions based on loop-header PHIs.
3742 SmallVector<Instruction *, 16> Worklist;
3743 Worklist.push_back(I);
3745 SmallPtrSet<Instruction *, 8> Visited;
3746 while (!Worklist.empty()) {
3747 I = Worklist.pop_back_val();
3748 if (!Visited.insert(I)) continue;
3750 ValueExprMapType::iterator It = ValueExprMap.find(static_cast<Value *>(I));
3751 if (It != ValueExprMap.end()) {
3752 const SCEV *Old = It->second;
3753 ValuesAtScopes.erase(Old);
3754 LoopDispositions.erase(Old);
3755 UnsignedRanges.erase(Old);
3756 SignedRanges.erase(Old);
3757 ValueExprMap.erase(It);
3758 if (PHINode *PN = dyn_cast<PHINode>(I))
3759 ConstantEvolutionLoopExitValue.erase(PN);
3762 PushDefUseChildren(I, Worklist);
3766 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
3767 /// of the specified loop will execute.
3768 ScalarEvolution::BackedgeTakenInfo
3769 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
3770 SmallVector<BasicBlock *, 8> ExitingBlocks;
3771 L->getExitingBlocks(ExitingBlocks);
3773 // Examine all exits and pick the most conservative values.
3774 const SCEV *BECount = getCouldNotCompute();
3775 const SCEV *MaxBECount = getCouldNotCompute();
3776 bool CouldNotComputeBECount = false;
3777 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3778 BackedgeTakenInfo NewBTI =
3779 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
3781 if (NewBTI.Exact == getCouldNotCompute()) {
3782 // We couldn't compute an exact value for this exit, so
3783 // we won't be able to compute an exact value for the loop.
3784 CouldNotComputeBECount = true;
3785 BECount = getCouldNotCompute();
3786 } else if (!CouldNotComputeBECount) {
3787 if (BECount == getCouldNotCompute())
3788 BECount = NewBTI.Exact;
3790 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
3792 if (MaxBECount == getCouldNotCompute())
3793 MaxBECount = NewBTI.Max;
3794 else if (NewBTI.Max != getCouldNotCompute())
3795 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
3798 return BackedgeTakenInfo(BECount, MaxBECount);
3801 /// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3802 /// of the specified loop will execute if it exits via the specified block.
3803 ScalarEvolution::BackedgeTakenInfo
3804 ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3805 BasicBlock *ExitingBlock) {
3807 // Okay, we've chosen an exiting block. See what condition causes us to
3808 // exit at this block.
3810 // FIXME: we should be able to handle switch instructions (with a single exit)
3811 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
3812 if (ExitBr == 0) return getCouldNotCompute();
3813 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
3815 // At this point, we know we have a conditional branch that determines whether
3816 // the loop is exited. However, we don't know if the branch is executed each
3817 // time through the loop. If not, then the execution count of the branch will
3818 // not be equal to the trip count of the loop.
3820 // Currently we check for this by checking to see if the Exit branch goes to
3821 // the loop header. If so, we know it will always execute the same number of
3822 // times as the loop. We also handle the case where the exit block *is* the
3823 // loop header. This is common for un-rotated loops.
3825 // If both of those tests fail, walk up the unique predecessor chain to the
3826 // header, stopping if there is an edge that doesn't exit the loop. If the
3827 // header is reached, the execution count of the branch will be equal to the
3828 // trip count of the loop.
3830 // More extensive analysis could be done to handle more cases here.
3832 if (ExitBr->getSuccessor(0) != L->getHeader() &&
3833 ExitBr->getSuccessor(1) != L->getHeader() &&
3834 ExitBr->getParent() != L->getHeader()) {
3835 // The simple checks failed, try climbing the unique predecessor chain
3836 // up to the header.
3838 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3839 BasicBlock *Pred = BB->getUniquePredecessor();
3841 return getCouldNotCompute();
3842 TerminatorInst *PredTerm = Pred->getTerminator();
3843 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3844 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3847 // If the predecessor has a successor that isn't BB and isn't
3848 // outside the loop, assume the worst.
3849 if (L->contains(PredSucc))
3850 return getCouldNotCompute();
3852 if (Pred == L->getHeader()) {
3859 return getCouldNotCompute();
3862 // Proceed to the next level to examine the exit condition expression.
3863 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3864 ExitBr->getSuccessor(0),
3865 ExitBr->getSuccessor(1));
3868 /// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3869 /// backedge of the specified loop will execute if its exit condition
3870 /// were a conditional branch of ExitCond, TBB, and FBB.
3871 ScalarEvolution::BackedgeTakenInfo
3872 ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3876 // Check if the controlling expression for this loop is an And or Or.
3877 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3878 if (BO->getOpcode() == Instruction::And) {
3879 // Recurse on the operands of the and.
3880 BackedgeTakenInfo BTI0 =
3881 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3882 BackedgeTakenInfo BTI1 =
3883 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3884 const SCEV *BECount = getCouldNotCompute();
3885 const SCEV *MaxBECount = getCouldNotCompute();
3886 if (L->contains(TBB)) {
3887 // Both conditions must be true for the loop to continue executing.
3888 // Choose the less conservative count.
3889 if (BTI0.Exact == getCouldNotCompute() ||
3890 BTI1.Exact == getCouldNotCompute())
3891 BECount = getCouldNotCompute();
3893 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3894 if (BTI0.Max == getCouldNotCompute())
3895 MaxBECount = BTI1.Max;
3896 else if (BTI1.Max == getCouldNotCompute())
3897 MaxBECount = BTI0.Max;
3899 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3901 // Both conditions must be true at the same time for the loop to exit.
3902 // For now, be conservative.
3903 assert(L->contains(FBB) && "Loop block has no successor in loop!");
3904 if (BTI0.Max == BTI1.Max)
3905 MaxBECount = BTI0.Max;
3906 if (BTI0.Exact == BTI1.Exact)
3907 BECount = BTI0.Exact;
3910 return BackedgeTakenInfo(BECount, MaxBECount);
3912 if (BO->getOpcode() == Instruction::Or) {
3913 // Recurse on the operands of the or.
3914 BackedgeTakenInfo BTI0 =
3915 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3916 BackedgeTakenInfo BTI1 =
3917 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3918 const SCEV *BECount = getCouldNotCompute();
3919 const SCEV *MaxBECount = getCouldNotCompute();
3920 if (L->contains(FBB)) {
3921 // Both conditions must be false for the loop to continue executing.
3922 // Choose the less conservative count.
3923 if (BTI0.Exact == getCouldNotCompute() ||
3924 BTI1.Exact == getCouldNotCompute())
3925 BECount = getCouldNotCompute();
3927 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3928 if (BTI0.Max == getCouldNotCompute())
3929 MaxBECount = BTI1.Max;
3930 else if (BTI1.Max == getCouldNotCompute())
3931 MaxBECount = BTI0.Max;
3933 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3935 // Both conditions must be false at the same time for the loop to exit.
3936 // For now, be conservative.
3937 assert(L->contains(TBB) && "Loop block has no successor in loop!");
3938 if (BTI0.Max == BTI1.Max)
3939 MaxBECount = BTI0.Max;
3940 if (BTI0.Exact == BTI1.Exact)
3941 BECount = BTI0.Exact;
3944 return BackedgeTakenInfo(BECount, MaxBECount);
3948 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3949 // Proceed to the next level to examine the icmp.
3950 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3951 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
3953 // Check for a constant condition. These are normally stripped out by
3954 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
3955 // preserve the CFG and is temporarily leaving constant conditions
3957 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
3958 if (L->contains(FBB) == !CI->getZExtValue())
3959 // The backedge is always taken.
3960 return getCouldNotCompute();
3962 // The backedge is never taken.
3963 return getConstant(CI->getType(), 0);
3966 // If it's not an integer or pointer comparison then compute it the hard way.
3967 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3970 /// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3971 /// backedge of the specified loop will execute if its exit condition
3972 /// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3973 ScalarEvolution::BackedgeTakenInfo
3974 ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3979 // If the condition was exit on true, convert the condition to exit on false
3980 ICmpInst::Predicate Cond;
3981 if (!L->contains(FBB))
3982 Cond = ExitCond->getPredicate();
3984 Cond = ExitCond->getInversePredicate();
3986 // Handle common loops like: for (X = "string"; *X; ++X)
3987 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3988 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
3989 BackedgeTakenInfo ItCnt =
3990 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
3991 if (ItCnt.hasAnyInfo())
3995 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3996 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
3998 // Try to evaluate any dependencies out of the loop.
3999 LHS = getSCEVAtScope(LHS, L);
4000 RHS = getSCEVAtScope(RHS, L);
4002 // At this point, we would like to compute how many iterations of the
4003 // loop the predicate will return true for these inputs.
4004 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
4005 // If there is a loop-invariant, force it into the RHS.
4006 std::swap(LHS, RHS);
4007 Cond = ICmpInst::getSwappedPredicate(Cond);
4010 // Simplify the operands before analyzing them.
4011 (void)SimplifyICmpOperands(Cond, LHS, RHS);
4013 // If we have a comparison of a chrec against a constant, try to use value
4014 // ranges to answer this query.
4015 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
4016 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
4017 if (AddRec->getLoop() == L) {
4018 // Form the constant range.
4019 ConstantRange CompRange(
4020 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
4022 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
4023 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
4027 case ICmpInst::ICMP_NE: { // while (X != Y)
4028 // Convert to: while (X-Y != 0)
4029 BackedgeTakenInfo BTI = HowFarToZero(getMinusSCEV(LHS, RHS), L);
4030 if (BTI.hasAnyInfo()) return BTI;
4033 case ICmpInst::ICMP_EQ: { // while (X == Y)
4034 // Convert to: while (X-Y == 0)
4035 BackedgeTakenInfo BTI = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
4036 if (BTI.hasAnyInfo()) return BTI;
4039 case ICmpInst::ICMP_SLT: {
4040 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
4041 if (BTI.hasAnyInfo()) return BTI;
4044 case ICmpInst::ICMP_SGT: {
4045 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
4046 getNotSCEV(RHS), L, true);
4047 if (BTI.hasAnyInfo()) return BTI;
4050 case ICmpInst::ICMP_ULT: {
4051 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
4052 if (BTI.hasAnyInfo()) return BTI;
4055 case ICmpInst::ICMP_UGT: {
4056 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
4057 getNotSCEV(RHS), L, false);
4058 if (BTI.hasAnyInfo()) return BTI;
4063 dbgs() << "ComputeBackedgeTakenCount ";
4064 if (ExitCond->getOperand(0)->getType()->isUnsigned())
4065 dbgs() << "[unsigned] ";
4066 dbgs() << *LHS << " "
4067 << Instruction::getOpcodeName(Instruction::ICmp)
4068 << " " << *RHS << "\n";
4073 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
4076 static ConstantInt *
4077 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
4078 ScalarEvolution &SE) {
4079 const SCEV *InVal = SE.getConstant(C);
4080 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
4081 assert(isa<SCEVConstant>(Val) &&
4082 "Evaluation of SCEV at constant didn't fold correctly?");
4083 return cast<SCEVConstant>(Val)->getValue();
4086 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
4087 /// and a GEP expression (missing the pointer index) indexing into it, return
4088 /// the addressed element of the initializer or null if the index expression is
4091 GetAddressedElementFromGlobal(GlobalVariable *GV,
4092 const std::vector<ConstantInt*> &Indices) {
4093 Constant *Init = GV->getInitializer();
4094 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
4095 uint64_t Idx = Indices[i]->getZExtValue();
4096 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
4097 assert(Idx < CS->getNumOperands() && "Bad struct index!");
4098 Init = cast<Constant>(CS->getOperand(Idx));
4099 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
4100 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
4101 Init = cast<Constant>(CA->getOperand(Idx));
4102 } else if (isa<ConstantAggregateZero>(Init)) {
4103 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
4104 assert(Idx < STy->getNumElements() && "Bad struct index!");
4105 Init = Constant::getNullValue(STy->getElementType(Idx));
4106 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
4107 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
4108 Init = Constant::getNullValue(ATy->getElementType());
4110 llvm_unreachable("Unknown constant aggregate type!");
4114 return 0; // Unknown initializer type
4120 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
4121 /// 'icmp op load X, cst', try to see if we can compute the backedge
4122 /// execution count.
4123 ScalarEvolution::BackedgeTakenInfo
4124 ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
4128 ICmpInst::Predicate predicate) {
4129 if (LI->isVolatile()) return getCouldNotCompute();
4131 // Check to see if the loaded pointer is a getelementptr of a global.
4132 // TODO: Use SCEV instead of manually grubbing with GEPs.
4133 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
4134 if (!GEP) return getCouldNotCompute();
4136 // Make sure that it is really a constant global we are gepping, with an
4137 // initializer, and make sure the first IDX is really 0.
4138 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
4139 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
4140 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
4141 !cast<Constant>(GEP->getOperand(1))->isNullValue())
4142 return getCouldNotCompute();
4144 // Okay, we allow one non-constant index into the GEP instruction.
4146 std::vector<ConstantInt*> Indexes;
4147 unsigned VarIdxNum = 0;
4148 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
4149 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4150 Indexes.push_back(CI);
4151 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
4152 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
4153 VarIdx = GEP->getOperand(i);
4155 Indexes.push_back(0);
4158 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
4159 // Check to see if X is a loop variant variable value now.
4160 const SCEV *Idx = getSCEV(VarIdx);
4161 Idx = getSCEVAtScope(Idx, L);
4163 // We can only recognize very limited forms of loop index expressions, in
4164 // particular, only affine AddRec's like {C1,+,C2}.
4165 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
4166 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
4167 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
4168 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
4169 return getCouldNotCompute();
4171 unsigned MaxSteps = MaxBruteForceIterations;
4172 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
4173 ConstantInt *ItCst = ConstantInt::get(
4174 cast<IntegerType>(IdxExpr->getType()), IterationNum);
4175 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
4177 // Form the GEP offset.
4178 Indexes[VarIdxNum] = Val;
4180 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
4181 if (Result == 0) break; // Cannot compute!
4183 // Evaluate the condition for this iteration.
4184 Result = ConstantExpr::getICmp(predicate, Result, RHS);
4185 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
4186 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
4188 dbgs() << "\n***\n*** Computed loop count " << *ItCst
4189 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
4192 ++NumArrayLenItCounts;
4193 return getConstant(ItCst); // Found terminating iteration!
4196 return getCouldNotCompute();
4200 /// CanConstantFold - Return true if we can constant fold an instruction of the
4201 /// specified type, assuming that all operands were constants.
4202 static bool CanConstantFold(const Instruction *I) {
4203 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
4204 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
4207 if (const CallInst *CI = dyn_cast<CallInst>(I))
4208 if (const Function *F = CI->getCalledFunction())
4209 return canConstantFoldCallTo(F);
4213 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
4214 /// in the loop that V is derived from. We allow arbitrary operations along the
4215 /// way, but the operands of an operation must either be constants or a value
4216 /// derived from a constant PHI. If this expression does not fit with these
4217 /// constraints, return null.
4218 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
4219 // If this is not an instruction, or if this is an instruction outside of the
4220 // loop, it can't be derived from a loop PHI.
4221 Instruction *I = dyn_cast<Instruction>(V);
4222 if (I == 0 || !L->contains(I)) return 0;
4224 if (PHINode *PN = dyn_cast<PHINode>(I)) {
4225 if (L->getHeader() == I->getParent())
4228 // We don't currently keep track of the control flow needed to evaluate
4229 // PHIs, so we cannot handle PHIs inside of loops.
4233 // If we won't be able to constant fold this expression even if the operands
4234 // are constants, return early.
4235 if (!CanConstantFold(I)) return 0;
4237 // Otherwise, we can evaluate this instruction if all of its operands are
4238 // constant or derived from a PHI node themselves.
4240 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
4241 if (!isa<Constant>(I->getOperand(Op))) {
4242 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
4243 if (P == 0) return 0; // Not evolving from PHI
4247 return 0; // Evolving from multiple different PHIs.
4250 // This is a expression evolving from a constant PHI!
4254 /// EvaluateExpression - Given an expression that passes the
4255 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
4256 /// in the loop has the value PHIVal. If we can't fold this expression for some
4257 /// reason, return null.
4258 static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
4259 const TargetData *TD) {
4260 if (isa<PHINode>(V)) return PHIVal;
4261 if (Constant *C = dyn_cast<Constant>(V)) return C;
4262 Instruction *I = cast<Instruction>(V);
4264 std::vector<Constant*> Operands(I->getNumOperands());
4266 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4267 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
4268 if (Operands[i] == 0) return 0;
4271 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4272 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
4274 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4275 &Operands[0], Operands.size(), TD);
4278 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
4279 /// in the header of its containing loop, we know the loop executes a
4280 /// constant number of times, and the PHI node is just a recurrence
4281 /// involving constants, fold it.
4283 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
4286 std::map<PHINode*, Constant*>::const_iterator I =
4287 ConstantEvolutionLoopExitValue.find(PN);
4288 if (I != ConstantEvolutionLoopExitValue.end())
4291 if (BEs.ugt(MaxBruteForceIterations))
4292 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
4294 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
4296 // Since the loop is canonicalized, the PHI node must have two entries. One
4297 // entry must be a constant (coming in from outside of the loop), and the
4298 // second must be derived from the same PHI.
4299 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4300 Constant *StartCST =
4301 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4303 return RetVal = 0; // Must be a constant.
4305 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4306 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4307 !isa<Constant>(BEValue))
4308 return RetVal = 0; // Not derived from same PHI.
4310 // Execute the loop symbolically to determine the exit value.
4311 if (BEs.getActiveBits() >= 32)
4312 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
4314 unsigned NumIterations = BEs.getZExtValue(); // must be in range
4315 unsigned IterationNum = 0;
4316 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
4317 if (IterationNum == NumIterations)
4318 return RetVal = PHIVal; // Got exit value!
4320 // Compute the value of the PHI node for the next iteration.
4321 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
4322 if (NextPHI == PHIVal)
4323 return RetVal = NextPHI; // Stopped evolving!
4325 return 0; // Couldn't evaluate!
4330 /// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
4331 /// constant number of times (the condition evolves only from constants),
4332 /// try to evaluate a few iterations of the loop until we get the exit
4333 /// condition gets a value of ExitWhen (true or false). If we cannot
4334 /// evaluate the trip count of the loop, return getCouldNotCompute().
4336 ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
4339 PHINode *PN = getConstantEvolvingPHI(Cond, L);
4340 if (PN == 0) return getCouldNotCompute();
4342 // If the loop is canonicalized, the PHI will have exactly two entries.
4343 // That's the only form we support here.
4344 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
4346 // One entry must be a constant (coming in from outside of the loop), and the
4347 // second must be derived from the same PHI.
4348 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4349 Constant *StartCST =
4350 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4351 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
4353 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4354 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4355 !isa<Constant>(BEValue))
4356 return getCouldNotCompute(); // Not derived from same PHI.
4358 // Okay, we find a PHI node that defines the trip count of this loop. Execute
4359 // the loop symbolically to determine when the condition gets a value of
4361 unsigned IterationNum = 0;
4362 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
4363 for (Constant *PHIVal = StartCST;
4364 IterationNum != MaxIterations; ++IterationNum) {
4365 ConstantInt *CondVal =
4366 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
4368 // Couldn't symbolically evaluate.
4369 if (!CondVal) return getCouldNotCompute();
4371 if (CondVal->getValue() == uint64_t(ExitWhen)) {
4372 ++NumBruteForceTripCountsComputed;
4373 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
4376 // Compute the value of the PHI node for the next iteration.
4377 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
4378 if (NextPHI == 0 || NextPHI == PHIVal)
4379 return getCouldNotCompute();// Couldn't evaluate or not making progress...
4383 // Too many iterations were needed to evaluate.
4384 return getCouldNotCompute();
4387 /// getSCEVAtScope - Return a SCEV expression for the specified value
4388 /// at the specified scope in the program. The L value specifies a loop
4389 /// nest to evaluate the expression at, where null is the top-level or a
4390 /// specified loop is immediately inside of the loop.
4392 /// This method can be used to compute the exit value for a variable defined
4393 /// in a loop by querying what the value will hold in the parent loop.
4395 /// In the case that a relevant loop exit value cannot be computed, the
4396 /// original value V is returned.
4397 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
4398 // Check to see if we've folded this expression at this loop before.
4399 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4400 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4401 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4403 return Pair.first->second ? Pair.first->second : V;
4405 // Otherwise compute it.
4406 const SCEV *C = computeSCEVAtScope(V, L);
4407 ValuesAtScopes[V][L] = C;
4411 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
4412 if (isa<SCEVConstant>(V)) return V;
4414 // If this instruction is evolved from a constant-evolving PHI, compute the
4415 // exit value from the loop without using SCEVs.
4416 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
4417 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
4418 const Loop *LI = (*this->LI)[I->getParent()];
4419 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
4420 if (PHINode *PN = dyn_cast<PHINode>(I))
4421 if (PN->getParent() == LI->getHeader()) {
4422 // Okay, there is no closed form solution for the PHI node. Check
4423 // to see if the loop that contains it has a known backedge-taken
4424 // count. If so, we may be able to force computation of the exit
4426 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
4427 if (const SCEVConstant *BTCC =
4428 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
4429 // Okay, we know how many times the containing loop executes. If
4430 // this is a constant evolving PHI node, get the final value at
4431 // the specified iteration number.
4432 Constant *RV = getConstantEvolutionLoopExitValue(PN,
4433 BTCC->getValue()->getValue(),
4435 if (RV) return getSCEV(RV);
4439 // Okay, this is an expression that we cannot symbolically evaluate
4440 // into a SCEV. Check to see if it's possible to symbolically evaluate
4441 // the arguments into constants, and if so, try to constant propagate the
4442 // result. This is particularly useful for computing loop exit values.
4443 if (CanConstantFold(I)) {
4444 SmallVector<Constant *, 4> Operands;
4445 bool MadeImprovement = false;
4446 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4447 Value *Op = I->getOperand(i);
4448 if (Constant *C = dyn_cast<Constant>(Op)) {
4449 Operands.push_back(C);
4453 // If any of the operands is non-constant and if they are
4454 // non-integer and non-pointer, don't even try to analyze them
4455 // with scev techniques.
4456 if (!isSCEVable(Op->getType()))
4459 const SCEV *OrigV = getSCEV(Op);
4460 const SCEV *OpV = getSCEVAtScope(OrigV, L);
4461 MadeImprovement |= OrigV != OpV;
4464 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
4466 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV))
4467 C = dyn_cast<Constant>(SU->getValue());
4469 if (C->getType() != Op->getType())
4470 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4474 Operands.push_back(C);
4477 // Check to see if getSCEVAtScope actually made an improvement.
4478 if (MadeImprovement) {
4480 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4481 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
4482 Operands[0], Operands[1], TD);
4484 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4485 &Operands[0], Operands.size(), TD);
4492 // This is some other type of SCEVUnknown, just return it.
4496 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
4497 // Avoid performing the look-up in the common case where the specified
4498 // expression has no loop-variant portions.
4499 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
4500 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
4501 if (OpAtScope != Comm->getOperand(i)) {
4502 // Okay, at least one of these operands is loop variant but might be
4503 // foldable. Build a new instance of the folded commutative expression.
4504 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4505 Comm->op_begin()+i);
4506 NewOps.push_back(OpAtScope);
4508 for (++i; i != e; ++i) {
4509 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
4510 NewOps.push_back(OpAtScope);
4512 if (isa<SCEVAddExpr>(Comm))
4513 return getAddExpr(NewOps);
4514 if (isa<SCEVMulExpr>(Comm))
4515 return getMulExpr(NewOps);
4516 if (isa<SCEVSMaxExpr>(Comm))
4517 return getSMaxExpr(NewOps);
4518 if (isa<SCEVUMaxExpr>(Comm))
4519 return getUMaxExpr(NewOps);
4520 llvm_unreachable("Unknown commutative SCEV type!");
4523 // If we got here, all operands are loop invariant.
4527 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
4528 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4529 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
4530 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4531 return Div; // must be loop invariant
4532 return getUDivExpr(LHS, RHS);
4535 // If this is a loop recurrence for a loop that does not contain L, then we
4536 // are dealing with the final value computed by the loop.
4537 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4538 // First, attempt to evaluate each operand.
4539 // Avoid performing the look-up in the common case where the specified
4540 // expression has no loop-variant portions.
4541 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4542 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
4543 if (OpAtScope == AddRec->getOperand(i))
4546 // Okay, at least one of these operands is loop variant but might be
4547 // foldable. Build a new instance of the folded commutative expression.
4548 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
4549 AddRec->op_begin()+i);
4550 NewOps.push_back(OpAtScope);
4551 for (++i; i != e; ++i)
4552 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
4554 AddRec = cast<SCEVAddRecExpr>(getAddRecExpr(NewOps, AddRec->getLoop()));
4558 // If the scope is outside the addrec's loop, evaluate it by using the
4559 // loop exit value of the addrec.
4560 if (!AddRec->getLoop()->contains(L)) {
4561 // To evaluate this recurrence, we need to know how many times the AddRec
4562 // loop iterates. Compute this now.
4563 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
4564 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
4566 // Then, evaluate the AddRec.
4567 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
4573 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
4574 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4575 if (Op == Cast->getOperand())
4576 return Cast; // must be loop invariant
4577 return getZeroExtendExpr(Op, Cast->getType());
4580 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
4581 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4582 if (Op == Cast->getOperand())
4583 return Cast; // must be loop invariant
4584 return getSignExtendExpr(Op, Cast->getType());
4587 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
4588 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4589 if (Op == Cast->getOperand())
4590 return Cast; // must be loop invariant
4591 return getTruncateExpr(Op, Cast->getType());
4594 llvm_unreachable("Unknown SCEV type!");
4598 /// getSCEVAtScope - This is a convenience function which does
4599 /// getSCEVAtScope(getSCEV(V), L).
4600 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
4601 return getSCEVAtScope(getSCEV(V), L);
4604 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4605 /// following equation:
4607 /// A * X = B (mod N)
4609 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4610 /// A and B isn't important.
4612 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
4613 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
4614 ScalarEvolution &SE) {
4615 uint32_t BW = A.getBitWidth();
4616 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4617 assert(A != 0 && "A must be non-zero.");
4621 // The gcd of A and N may have only one prime factor: 2. The number of
4622 // trailing zeros in A is its multiplicity
4623 uint32_t Mult2 = A.countTrailingZeros();
4626 // 2. Check if B is divisible by D.
4628 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4629 // is not less than multiplicity of this prime factor for D.
4630 if (B.countTrailingZeros() < Mult2)
4631 return SE.getCouldNotCompute();
4633 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4636 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4637 // bit width during computations.
4638 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4639 APInt Mod(BW + 1, 0);
4640 Mod.set(BW - Mult2); // Mod = N / D
4641 APInt I = AD.multiplicativeInverse(Mod);
4643 // 4. Compute the minimum unsigned root of the equation:
4644 // I * (B / D) mod (N / D)
4645 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4647 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4649 return SE.getConstant(Result.trunc(BW));
4652 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4653 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4654 /// might be the same) or two SCEVCouldNotCompute objects.
4656 static std::pair<const SCEV *,const SCEV *>
4657 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
4658 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
4659 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4660 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4661 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
4663 // We currently can only solve this if the coefficients are constants.
4664 if (!LC || !MC || !NC) {
4665 const SCEV *CNC = SE.getCouldNotCompute();
4666 return std::make_pair(CNC, CNC);
4669 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
4670 const APInt &L = LC->getValue()->getValue();
4671 const APInt &M = MC->getValue()->getValue();
4672 const APInt &N = NC->getValue()->getValue();
4673 APInt Two(BitWidth, 2);
4674 APInt Four(BitWidth, 4);
4677 using namespace APIntOps;
4679 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4680 // The B coefficient is M-N/2
4684 // The A coefficient is N/2
4685 APInt A(N.sdiv(Two));
4687 // Compute the B^2-4ac term.
4690 SqrtTerm -= Four * (A * C);
4692 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4693 // integer value or else APInt::sqrt() will assert.
4694 APInt SqrtVal(SqrtTerm.sqrt());
4696 // Compute the two solutions for the quadratic formula.
4697 // The divisions must be performed as signed divisions.
4699 APInt TwoA( A << 1 );
4700 if (TwoA.isMinValue()) {
4701 const SCEV *CNC = SE.getCouldNotCompute();
4702 return std::make_pair(CNC, CNC);
4705 LLVMContext &Context = SE.getContext();
4707 ConstantInt *Solution1 =
4708 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
4709 ConstantInt *Solution2 =
4710 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
4712 return std::make_pair(SE.getConstant(Solution1),
4713 SE.getConstant(Solution2));
4714 } // end APIntOps namespace
4717 /// HowFarToZero - Return the number of times a backedge comparing the specified
4718 /// value to zero will execute. If not computable, return CouldNotCompute.
4719 ScalarEvolution::BackedgeTakenInfo
4720 ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
4721 // If the value is a constant
4722 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
4723 // If the value is already zero, the branch will execute zero times.
4724 if (C->getValue()->isZero()) return C;
4725 return getCouldNotCompute(); // Otherwise it will loop infinitely.
4728 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
4729 if (!AddRec || AddRec->getLoop() != L)
4730 return getCouldNotCompute();
4732 if (AddRec->isAffine()) {
4733 // If this is an affine expression, the execution count of this branch is
4734 // the minimum unsigned root of the following equation:
4736 // Start + Step*N = 0 (mod 2^BW)
4740 // Step*N = -Start (mod 2^BW)
4742 // where BW is the common bit width of Start and Step.
4744 // Get the initial value for the loop.
4745 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4746 L->getParentLoop());
4747 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4748 L->getParentLoop());
4750 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
4751 // For now we handle only constant steps.
4753 // First, handle unitary steps.
4754 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
4755 return getNegativeSCEV(Start); // N = -Start (as unsigned)
4756 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4757 return Start; // N = Start (as unsigned)
4759 // Then, try to solve the above equation provided that Start is constant.
4760 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
4761 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
4762 -StartC->getValue()->getValue(),
4765 } else if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
4766 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4767 // the quadratic equation to solve it.
4768 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
4770 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4771 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
4774 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
4775 << " sol#2: " << *R2 << "\n";
4777 // Pick the smallest positive root value.
4778 if (ConstantInt *CB =
4779 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
4780 R1->getValue(), R2->getValue()))) {
4781 if (CB->getZExtValue() == false)
4782 std::swap(R1, R2); // R1 is the minimum root now.
4784 // We can only use this value if the chrec ends up with an exact zero
4785 // value at this index. When solving for "X*X != 5", for example, we
4786 // should not accept a root of 2.
4787 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
4789 return R1; // We found a quadratic root!
4794 return getCouldNotCompute();
4797 /// HowFarToNonZero - Return the number of times a backedge checking the
4798 /// specified value for nonzero will execute. If not computable, return
4800 ScalarEvolution::BackedgeTakenInfo
4801 ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
4802 // Loops that look like: while (X == 0) are very strange indeed. We don't
4803 // handle them yet except for the trivial case. This could be expanded in the
4804 // future as needed.
4806 // If the value is a constant, check to see if it is known to be non-zero
4807 // already. If so, the backedge will execute zero times.
4808 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
4809 if (!C->getValue()->isNullValue())
4810 return getConstant(C->getType(), 0);
4811 return getCouldNotCompute(); // Otherwise it will loop infinitely.
4814 // We could implement others, but I really doubt anyone writes loops like
4815 // this, and if they did, they would already be constant folded.
4816 return getCouldNotCompute();
4819 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4820 /// (which may not be an immediate predecessor) which has exactly one
4821 /// successor from which BB is reachable, or null if no such block is
4824 std::pair<BasicBlock *, BasicBlock *>
4825 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
4826 // If the block has a unique predecessor, then there is no path from the
4827 // predecessor to the block that does not go through the direct edge
4828 // from the predecessor to the block.
4829 if (BasicBlock *Pred = BB->getSinglePredecessor())
4830 return std::make_pair(Pred, BB);
4832 // A loop's header is defined to be a block that dominates the loop.
4833 // If the header has a unique predecessor outside the loop, it must be
4834 // a block that has exactly one successor that can reach the loop.
4835 if (Loop *L = LI->getLoopFor(BB))
4836 return std::make_pair(L->getLoopPredecessor(), L->getHeader());
4838 return std::pair<BasicBlock *, BasicBlock *>();
4841 /// HasSameValue - SCEV structural equivalence is usually sufficient for
4842 /// testing whether two expressions are equal, however for the purposes of
4843 /// looking for a condition guarding a loop, it can be useful to be a little
4844 /// more general, since a front-end may have replicated the controlling
4847 static bool HasSameValue(const SCEV *A, const SCEV *B) {
4848 // Quick check to see if they are the same SCEV.
4849 if (A == B) return true;
4851 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4852 // two different instructions with the same value. Check for this case.
4853 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4854 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4855 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4856 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
4857 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
4860 // Otherwise assume they may have a different value.
4864 /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
4865 /// predicate Pred. Return true iff any changes were made.
4867 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
4868 const SCEV *&LHS, const SCEV *&RHS) {
4869 bool Changed = false;
4871 // Canonicalize a constant to the right side.
4872 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
4873 // Check for both operands constant.
4874 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
4875 if (ConstantExpr::getICmp(Pred,
4877 RHSC->getValue())->isNullValue())
4878 goto trivially_false;
4880 goto trivially_true;
4882 // Otherwise swap the operands to put the constant on the right.
4883 std::swap(LHS, RHS);
4884 Pred = ICmpInst::getSwappedPredicate(Pred);
4888 // If we're comparing an addrec with a value which is loop-invariant in the
4889 // addrec's loop, put the addrec on the left. Also make a dominance check,
4890 // as both operands could be addrecs loop-invariant in each other's loop.
4891 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
4892 const Loop *L = AR->getLoop();
4893 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
4894 std::swap(LHS, RHS);
4895 Pred = ICmpInst::getSwappedPredicate(Pred);
4900 // If there's a constant operand, canonicalize comparisons with boundary
4901 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
4902 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4903 const APInt &RA = RC->getValue()->getValue();
4905 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4906 case ICmpInst::ICMP_EQ:
4907 case ICmpInst::ICMP_NE:
4909 case ICmpInst::ICMP_UGE:
4910 if ((RA - 1).isMinValue()) {
4911 Pred = ICmpInst::ICMP_NE;
4912 RHS = getConstant(RA - 1);
4916 if (RA.isMaxValue()) {
4917 Pred = ICmpInst::ICMP_EQ;
4921 if (RA.isMinValue()) goto trivially_true;
4923 Pred = ICmpInst::ICMP_UGT;
4924 RHS = getConstant(RA - 1);
4927 case ICmpInst::ICMP_ULE:
4928 if ((RA + 1).isMaxValue()) {
4929 Pred = ICmpInst::ICMP_NE;
4930 RHS = getConstant(RA + 1);
4934 if (RA.isMinValue()) {
4935 Pred = ICmpInst::ICMP_EQ;
4939 if (RA.isMaxValue()) goto trivially_true;
4941 Pred = ICmpInst::ICMP_ULT;
4942 RHS = getConstant(RA + 1);
4945 case ICmpInst::ICMP_SGE:
4946 if ((RA - 1).isMinSignedValue()) {
4947 Pred = ICmpInst::ICMP_NE;
4948 RHS = getConstant(RA - 1);
4952 if (RA.isMaxSignedValue()) {
4953 Pred = ICmpInst::ICMP_EQ;
4957 if (RA.isMinSignedValue()) goto trivially_true;
4959 Pred = ICmpInst::ICMP_SGT;
4960 RHS = getConstant(RA - 1);
4963 case ICmpInst::ICMP_SLE:
4964 if ((RA + 1).isMaxSignedValue()) {
4965 Pred = ICmpInst::ICMP_NE;
4966 RHS = getConstant(RA + 1);
4970 if (RA.isMinSignedValue()) {
4971 Pred = ICmpInst::ICMP_EQ;
4975 if (RA.isMaxSignedValue()) goto trivially_true;
4977 Pred = ICmpInst::ICMP_SLT;
4978 RHS = getConstant(RA + 1);
4981 case ICmpInst::ICMP_UGT:
4982 if (RA.isMinValue()) {
4983 Pred = ICmpInst::ICMP_NE;
4987 if ((RA + 1).isMaxValue()) {
4988 Pred = ICmpInst::ICMP_EQ;
4989 RHS = getConstant(RA + 1);
4993 if (RA.isMaxValue()) goto trivially_false;
4995 case ICmpInst::ICMP_ULT:
4996 if (RA.isMaxValue()) {
4997 Pred = ICmpInst::ICMP_NE;
5001 if ((RA - 1).isMinValue()) {
5002 Pred = ICmpInst::ICMP_EQ;
5003 RHS = getConstant(RA - 1);
5007 if (RA.isMinValue()) goto trivially_false;
5009 case ICmpInst::ICMP_SGT:
5010 if (RA.isMinSignedValue()) {
5011 Pred = ICmpInst::ICMP_NE;
5015 if ((RA + 1).isMaxSignedValue()) {
5016 Pred = ICmpInst::ICMP_EQ;
5017 RHS = getConstant(RA + 1);
5021 if (RA.isMaxSignedValue()) goto trivially_false;
5023 case ICmpInst::ICMP_SLT:
5024 if (RA.isMaxSignedValue()) {
5025 Pred = ICmpInst::ICMP_NE;
5029 if ((RA - 1).isMinSignedValue()) {
5030 Pred = ICmpInst::ICMP_EQ;
5031 RHS = getConstant(RA - 1);
5035 if (RA.isMinSignedValue()) goto trivially_false;
5040 // Check for obvious equality.
5041 if (HasSameValue(LHS, RHS)) {
5042 if (ICmpInst::isTrueWhenEqual(Pred))
5043 goto trivially_true;
5044 if (ICmpInst::isFalseWhenEqual(Pred))
5045 goto trivially_false;
5048 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
5049 // adding or subtracting 1 from one of the operands.
5051 case ICmpInst::ICMP_SLE:
5052 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
5053 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
5054 /*HasNUW=*/false, /*HasNSW=*/true);
5055 Pred = ICmpInst::ICMP_SLT;
5057 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
5058 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
5059 /*HasNUW=*/false, /*HasNSW=*/true);
5060 Pred = ICmpInst::ICMP_SLT;
5064 case ICmpInst::ICMP_SGE:
5065 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
5066 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
5067 /*HasNUW=*/false, /*HasNSW=*/true);
5068 Pred = ICmpInst::ICMP_SGT;
5070 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
5071 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
5072 /*HasNUW=*/false, /*HasNSW=*/true);
5073 Pred = ICmpInst::ICMP_SGT;
5077 case ICmpInst::ICMP_ULE:
5078 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
5079 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
5080 /*HasNUW=*/true, /*HasNSW=*/false);
5081 Pred = ICmpInst::ICMP_ULT;
5083 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
5084 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
5085 /*HasNUW=*/true, /*HasNSW=*/false);
5086 Pred = ICmpInst::ICMP_ULT;
5090 case ICmpInst::ICMP_UGE:
5091 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
5092 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
5093 /*HasNUW=*/true, /*HasNSW=*/false);
5094 Pred = ICmpInst::ICMP_UGT;
5096 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
5097 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
5098 /*HasNUW=*/true, /*HasNSW=*/false);
5099 Pred = ICmpInst::ICMP_UGT;
5107 // TODO: More simplifications are possible here.
5113 LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
5114 Pred = ICmpInst::ICMP_EQ;
5119 LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
5120 Pred = ICmpInst::ICMP_NE;
5124 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
5125 return getSignedRange(S).getSignedMax().isNegative();
5128 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
5129 return getSignedRange(S).getSignedMin().isStrictlyPositive();
5132 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
5133 return !getSignedRange(S).getSignedMin().isNegative();
5136 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
5137 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
5140 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
5141 return isKnownNegative(S) || isKnownPositive(S);
5144 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
5145 const SCEV *LHS, const SCEV *RHS) {
5146 // Canonicalize the inputs first.
5147 (void)SimplifyICmpOperands(Pred, LHS, RHS);
5149 // If LHS or RHS is an addrec, check to see if the condition is true in
5150 // every iteration of the loop.
5151 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
5152 if (isLoopEntryGuardedByCond(
5153 AR->getLoop(), Pred, AR->getStart(), RHS) &&
5154 isLoopBackedgeGuardedByCond(
5155 AR->getLoop(), Pred, AR->getPostIncExpr(*this), RHS))
5157 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS))
5158 if (isLoopEntryGuardedByCond(
5159 AR->getLoop(), Pred, LHS, AR->getStart()) &&
5160 isLoopBackedgeGuardedByCond(
5161 AR->getLoop(), Pred, LHS, AR->getPostIncExpr(*this)))
5164 // Otherwise see what can be done with known constant ranges.
5165 return isKnownPredicateWithRanges(Pred, LHS, RHS);
5169 ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
5170 const SCEV *LHS, const SCEV *RHS) {
5171 if (HasSameValue(LHS, RHS))
5172 return ICmpInst::isTrueWhenEqual(Pred);
5174 // This code is split out from isKnownPredicate because it is called from
5175 // within isLoopEntryGuardedByCond.
5178 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5180 case ICmpInst::ICMP_SGT:
5181 Pred = ICmpInst::ICMP_SLT;
5182 std::swap(LHS, RHS);
5183 case ICmpInst::ICMP_SLT: {
5184 ConstantRange LHSRange = getSignedRange(LHS);
5185 ConstantRange RHSRange = getSignedRange(RHS);
5186 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
5188 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
5192 case ICmpInst::ICMP_SGE:
5193 Pred = ICmpInst::ICMP_SLE;
5194 std::swap(LHS, RHS);
5195 case ICmpInst::ICMP_SLE: {
5196 ConstantRange LHSRange = getSignedRange(LHS);
5197 ConstantRange RHSRange = getSignedRange(RHS);
5198 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
5200 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
5204 case ICmpInst::ICMP_UGT:
5205 Pred = ICmpInst::ICMP_ULT;
5206 std::swap(LHS, RHS);
5207 case ICmpInst::ICMP_ULT: {
5208 ConstantRange LHSRange = getUnsignedRange(LHS);
5209 ConstantRange RHSRange = getUnsignedRange(RHS);
5210 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
5212 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
5216 case ICmpInst::ICMP_UGE:
5217 Pred = ICmpInst::ICMP_ULE;
5218 std::swap(LHS, RHS);
5219 case ICmpInst::ICMP_ULE: {
5220 ConstantRange LHSRange = getUnsignedRange(LHS);
5221 ConstantRange RHSRange = getUnsignedRange(RHS);
5222 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
5224 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
5228 case ICmpInst::ICMP_NE: {
5229 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
5231 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
5234 const SCEV *Diff = getMinusSCEV(LHS, RHS);
5235 if (isKnownNonZero(Diff))
5239 case ICmpInst::ICMP_EQ:
5240 // The check at the top of the function catches the case where
5241 // the values are known to be equal.
5247 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
5248 /// protected by a conditional between LHS and RHS. This is used to
5249 /// to eliminate casts.
5251 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
5252 ICmpInst::Predicate Pred,
5253 const SCEV *LHS, const SCEV *RHS) {
5254 // Interpret a null as meaning no loop, where there is obviously no guard
5255 // (interprocedural conditions notwithstanding).
5256 if (!L) return true;
5258 BasicBlock *Latch = L->getLoopLatch();
5262 BranchInst *LoopContinuePredicate =
5263 dyn_cast<BranchInst>(Latch->getTerminator());
5264 if (!LoopContinuePredicate ||
5265 LoopContinuePredicate->isUnconditional())
5268 return isImpliedCond(Pred, LHS, RHS,
5269 LoopContinuePredicate->getCondition(),
5270 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
5273 /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
5274 /// by a conditional between LHS and RHS. This is used to help avoid max
5275 /// expressions in loop trip counts, and to eliminate casts.
5277 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
5278 ICmpInst::Predicate Pred,
5279 const SCEV *LHS, const SCEV *RHS) {
5280 // Interpret a null as meaning no loop, where there is obviously no guard
5281 // (interprocedural conditions notwithstanding).
5282 if (!L) return false;
5284 // Starting at the loop predecessor, climb up the predecessor chain, as long
5285 // as there are predecessors that can be found that have unique successors
5286 // leading to the original header.
5287 for (std::pair<BasicBlock *, BasicBlock *>
5288 Pair(L->getLoopPredecessor(), L->getHeader());
5290 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
5292 BranchInst *LoopEntryPredicate =
5293 dyn_cast<BranchInst>(Pair.first->getTerminator());
5294 if (!LoopEntryPredicate ||
5295 LoopEntryPredicate->isUnconditional())
5298 if (isImpliedCond(Pred, LHS, RHS,
5299 LoopEntryPredicate->getCondition(),
5300 LoopEntryPredicate->getSuccessor(0) != Pair.second))
5307 /// isImpliedCond - Test whether the condition described by Pred, LHS,
5308 /// and RHS is true whenever the given Cond value evaluates to true.
5309 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
5310 const SCEV *LHS, const SCEV *RHS,
5311 Value *FoundCondValue,
5313 // Recursively handle And and Or conditions.
5314 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
5315 if (BO->getOpcode() == Instruction::And) {
5317 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5318 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
5319 } else if (BO->getOpcode() == Instruction::Or) {
5321 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5322 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
5326 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
5327 if (!ICI) return false;
5329 // Bail if the ICmp's operands' types are wider than the needed type
5330 // before attempting to call getSCEV on them. This avoids infinite
5331 // recursion, since the analysis of widening casts can require loop
5332 // exit condition information for overflow checking, which would
5334 if (getTypeSizeInBits(LHS->getType()) <
5335 getTypeSizeInBits(ICI->getOperand(0)->getType()))
5338 // Now that we found a conditional branch that dominates the loop, check to
5339 // see if it is the comparison we are looking for.
5340 ICmpInst::Predicate FoundPred;
5342 FoundPred = ICI->getInversePredicate();
5344 FoundPred = ICI->getPredicate();
5346 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
5347 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
5349 // Balance the types. The case where FoundLHS' type is wider than
5350 // LHS' type is checked for above.
5351 if (getTypeSizeInBits(LHS->getType()) >
5352 getTypeSizeInBits(FoundLHS->getType())) {
5353 if (CmpInst::isSigned(Pred)) {
5354 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
5355 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
5357 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
5358 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
5362 // Canonicalize the query to match the way instcombine will have
5363 // canonicalized the comparison.
5364 if (SimplifyICmpOperands(Pred, LHS, RHS))
5366 return CmpInst::isTrueWhenEqual(Pred);
5367 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
5368 if (FoundLHS == FoundRHS)
5369 return CmpInst::isFalseWhenEqual(Pred);
5371 // Check to see if we can make the LHS or RHS match.
5372 if (LHS == FoundRHS || RHS == FoundLHS) {
5373 if (isa<SCEVConstant>(RHS)) {
5374 std::swap(FoundLHS, FoundRHS);
5375 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
5377 std::swap(LHS, RHS);
5378 Pred = ICmpInst::getSwappedPredicate(Pred);
5382 // Check whether the found predicate is the same as the desired predicate.
5383 if (FoundPred == Pred)
5384 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
5386 // Check whether swapping the found predicate makes it the same as the
5387 // desired predicate.
5388 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
5389 if (isa<SCEVConstant>(RHS))
5390 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
5392 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
5393 RHS, LHS, FoundLHS, FoundRHS);
5396 // Check whether the actual condition is beyond sufficient.
5397 if (FoundPred == ICmpInst::ICMP_EQ)
5398 if (ICmpInst::isTrueWhenEqual(Pred))
5399 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
5401 if (Pred == ICmpInst::ICMP_NE)
5402 if (!ICmpInst::isTrueWhenEqual(FoundPred))
5403 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
5406 // Otherwise assume the worst.
5410 /// isImpliedCondOperands - Test whether the condition described by Pred,
5411 /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
5412 /// and FoundRHS is true.
5413 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
5414 const SCEV *LHS, const SCEV *RHS,
5415 const SCEV *FoundLHS,
5416 const SCEV *FoundRHS) {
5417 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
5418 FoundLHS, FoundRHS) ||
5419 // ~x < ~y --> x > y
5420 isImpliedCondOperandsHelper(Pred, LHS, RHS,
5421 getNotSCEV(FoundRHS),
5422 getNotSCEV(FoundLHS));
5425 /// isImpliedCondOperandsHelper - Test whether the condition described by
5426 /// Pred, LHS, and RHS is true whenever the condition described by Pred,
5427 /// FoundLHS, and FoundRHS is true.
5429 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
5430 const SCEV *LHS, const SCEV *RHS,
5431 const SCEV *FoundLHS,
5432 const SCEV *FoundRHS) {
5434 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5435 case ICmpInst::ICMP_EQ:
5436 case ICmpInst::ICMP_NE:
5437 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
5440 case ICmpInst::ICMP_SLT:
5441 case ICmpInst::ICMP_SLE:
5442 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
5443 isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS))
5446 case ICmpInst::ICMP_SGT:
5447 case ICmpInst::ICMP_SGE:
5448 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
5449 isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS))
5452 case ICmpInst::ICMP_ULT:
5453 case ICmpInst::ICMP_ULE:
5454 if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
5455 isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS))
5458 case ICmpInst::ICMP_UGT:
5459 case ICmpInst::ICMP_UGE:
5460 if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
5461 isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS))
5469 /// getBECount - Subtract the end and start values and divide by the step,
5470 /// rounding up, to get the number of times the backedge is executed. Return
5471 /// CouldNotCompute if an intermediate computation overflows.
5472 const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
5476 assert(!isKnownNegative(Step) &&
5477 "This code doesn't handle negative strides yet!");
5479 const Type *Ty = Start->getType();
5480 const SCEV *NegOne = getConstant(Ty, (uint64_t)-1);
5481 const SCEV *Diff = getMinusSCEV(End, Start);
5482 const SCEV *RoundUp = getAddExpr(Step, NegOne);
5484 // Add an adjustment to the difference between End and Start so that
5485 // the division will effectively round up.
5486 const SCEV *Add = getAddExpr(Diff, RoundUp);
5489 // Check Add for unsigned overflow.
5490 // TODO: More sophisticated things could be done here.
5491 const Type *WideTy = IntegerType::get(getContext(),
5492 getTypeSizeInBits(Ty) + 1);
5493 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
5494 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
5495 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
5496 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
5497 return getCouldNotCompute();
5500 return getUDivExpr(Add, Step);
5503 /// HowManyLessThans - Return the number of times a backedge containing the
5504 /// specified less-than comparison will execute. If not computable, return
5505 /// CouldNotCompute.
5506 ScalarEvolution::BackedgeTakenInfo
5507 ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
5508 const Loop *L, bool isSigned) {
5509 // Only handle: "ADDREC < LoopInvariant".
5510 if (!isLoopInvariant(RHS, L)) return getCouldNotCompute();
5512 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
5513 if (!AddRec || AddRec->getLoop() != L)
5514 return getCouldNotCompute();
5516 // Check to see if we have a flag which makes analysis easy.
5517 bool NoWrap = isSigned ? AddRec->hasNoSignedWrap() :
5518 AddRec->hasNoUnsignedWrap();
5520 if (AddRec->isAffine()) {
5521 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
5522 const SCEV *Step = AddRec->getStepRecurrence(*this);
5525 return getCouldNotCompute();
5526 if (Step->isOne()) {
5527 // With unit stride, the iteration never steps past the limit value.
5528 } else if (isKnownPositive(Step)) {
5529 // Test whether a positive iteration can step past the limit
5530 // value and past the maximum value for its type in a single step.
5531 // Note that it's not sufficient to check NoWrap here, because even
5532 // though the value after a wrap is undefined, it's not undefined
5533 // behavior, so if wrap does occur, the loop could either terminate or
5534 // loop infinitely, but in either case, the loop is guaranteed to
5535 // iterate at least until the iteration where the wrapping occurs.
5536 const SCEV *One = getConstant(Step->getType(), 1);
5538 APInt Max = APInt::getSignedMaxValue(BitWidth);
5539 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
5540 .slt(getSignedRange(RHS).getSignedMax()))
5541 return getCouldNotCompute();
5543 APInt Max = APInt::getMaxValue(BitWidth);
5544 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
5545 .ult(getUnsignedRange(RHS).getUnsignedMax()))
5546 return getCouldNotCompute();
5549 // TODO: Handle negative strides here and below.
5550 return getCouldNotCompute();
5552 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
5553 // m. So, we count the number of iterations in which {n,+,s} < m is true.
5554 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
5555 // treat m-n as signed nor unsigned due to overflow possibility.
5557 // First, we get the value of the LHS in the first iteration: n
5558 const SCEV *Start = AddRec->getOperand(0);
5560 // Determine the minimum constant start value.
5561 const SCEV *MinStart = getConstant(isSigned ?
5562 getSignedRange(Start).getSignedMin() :
5563 getUnsignedRange(Start).getUnsignedMin());
5565 // If we know that the condition is true in order to enter the loop,
5566 // then we know that it will run exactly (m-n)/s times. Otherwise, we
5567 // only know that it will execute (max(m,n)-n)/s times. In both cases,
5568 // the division must round up.
5569 const SCEV *End = RHS;
5570 if (!isLoopEntryGuardedByCond(L,
5571 isSigned ? ICmpInst::ICMP_SLT :
5573 getMinusSCEV(Start, Step), RHS))
5574 End = isSigned ? getSMaxExpr(RHS, Start)
5575 : getUMaxExpr(RHS, Start);
5577 // Determine the maximum constant end value.
5578 const SCEV *MaxEnd = getConstant(isSigned ?
5579 getSignedRange(End).getSignedMax() :
5580 getUnsignedRange(End).getUnsignedMax());
5582 // If MaxEnd is within a step of the maximum integer value in its type,
5583 // adjust it down to the minimum value which would produce the same effect.
5584 // This allows the subsequent ceiling division of (N+(step-1))/step to
5585 // compute the correct value.
5586 const SCEV *StepMinusOne = getMinusSCEV(Step,
5587 getConstant(Step->getType(), 1));
5590 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
5593 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
5596 // Finally, we subtract these two values and divide, rounding up, to get
5597 // the number of times the backedge is executed.
5598 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
5600 // The maximum backedge count is similar, except using the minimum start
5601 // value and the maximum end value.
5602 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step, NoWrap);
5604 return BackedgeTakenInfo(BECount, MaxBECount);
5607 return getCouldNotCompute();
5610 /// getNumIterationsInRange - Return the number of iterations of this loop that
5611 /// produce values in the specified constant range. Another way of looking at
5612 /// this is that it returns the first iteration number where the value is not in
5613 /// the condition, thus computing the exit count. If the iteration count can't
5614 /// be computed, an instance of SCEVCouldNotCompute is returned.
5615 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
5616 ScalarEvolution &SE) const {
5617 if (Range.isFullSet()) // Infinite loop.
5618 return SE.getCouldNotCompute();
5620 // If the start is a non-zero constant, shift the range to simplify things.
5621 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
5622 if (!SC->getValue()->isZero()) {
5623 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
5624 Operands[0] = SE.getConstant(SC->getType(), 0);
5625 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
5626 if (const SCEVAddRecExpr *ShiftedAddRec =
5627 dyn_cast<SCEVAddRecExpr>(Shifted))
5628 return ShiftedAddRec->getNumIterationsInRange(
5629 Range.subtract(SC->getValue()->getValue()), SE);
5630 // This is strange and shouldn't happen.
5631 return SE.getCouldNotCompute();
5634 // The only time we can solve this is when we have all constant indices.
5635 // Otherwise, we cannot determine the overflow conditions.
5636 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5637 if (!isa<SCEVConstant>(getOperand(i)))
5638 return SE.getCouldNotCompute();
5641 // Okay at this point we know that all elements of the chrec are constants and
5642 // that the start element is zero.
5644 // First check to see if the range contains zero. If not, the first
5646 unsigned BitWidth = SE.getTypeSizeInBits(getType());
5647 if (!Range.contains(APInt(BitWidth, 0)))
5648 return SE.getConstant(getType(), 0);
5651 // If this is an affine expression then we have this situation:
5652 // Solve {0,+,A} in Range === Ax in Range
5654 // We know that zero is in the range. If A is positive then we know that
5655 // the upper value of the range must be the first possible exit value.
5656 // If A is negative then the lower of the range is the last possible loop
5657 // value. Also note that we already checked for a full range.
5658 APInt One(BitWidth,1);
5659 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
5660 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
5662 // The exit value should be (End+A)/A.
5663 APInt ExitVal = (End + A).udiv(A);
5664 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
5666 // Evaluate at the exit value. If we really did fall out of the valid
5667 // range, then we computed our trip count, otherwise wrap around or other
5668 // things must have happened.
5669 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
5670 if (Range.contains(Val->getValue()))
5671 return SE.getCouldNotCompute(); // Something strange happened
5673 // Ensure that the previous value is in the range. This is a sanity check.
5674 assert(Range.contains(
5675 EvaluateConstantChrecAtConstant(this,
5676 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
5677 "Linear scev computation is off in a bad way!");
5678 return SE.getConstant(ExitValue);
5679 } else if (isQuadratic()) {
5680 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5681 // quadratic equation to solve it. To do this, we must frame our problem in
5682 // terms of figuring out when zero is crossed, instead of when
5683 // Range.getUpper() is crossed.
5684 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
5685 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
5686 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
5688 // Next, solve the constructed addrec
5689 std::pair<const SCEV *,const SCEV *> Roots =
5690 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
5691 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5692 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
5694 // Pick the smallest positive root value.
5695 if (ConstantInt *CB =
5696 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
5697 R1->getValue(), R2->getValue()))) {
5698 if (CB->getZExtValue() == false)
5699 std::swap(R1, R2); // R1 is the minimum root now.
5701 // Make sure the root is not off by one. The returned iteration should
5702 // not be in the range, but the previous one should be. When solving
5703 // for "X*X < 5", for example, we should not return a root of 2.
5704 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
5707 if (Range.contains(R1Val->getValue())) {
5708 // The next iteration must be out of the range...
5709 ConstantInt *NextVal =
5710 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
5712 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
5713 if (!Range.contains(R1Val->getValue()))
5714 return SE.getConstant(NextVal);
5715 return SE.getCouldNotCompute(); // Something strange happened
5718 // If R1 was not in the range, then it is a good return value. Make
5719 // sure that R1-1 WAS in the range though, just in case.
5720 ConstantInt *NextVal =
5721 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
5722 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
5723 if (Range.contains(R1Val->getValue()))
5725 return SE.getCouldNotCompute(); // Something strange happened
5730 return SE.getCouldNotCompute();
5735 //===----------------------------------------------------------------------===//
5736 // SCEVCallbackVH Class Implementation
5737 //===----------------------------------------------------------------------===//
5739 void ScalarEvolution::SCEVCallbackVH::deleted() {
5740 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
5741 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5742 SE->ConstantEvolutionLoopExitValue.erase(PN);
5743 SE->ValueExprMap.erase(getValPtr());
5744 // this now dangles!
5747 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
5748 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
5750 // Forget all the expressions associated with users of the old value,
5751 // so that future queries will recompute the expressions using the new
5753 Value *Old = getValPtr();
5754 SmallVector<User *, 16> Worklist;
5755 SmallPtrSet<User *, 8> Visited;
5756 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5758 Worklist.push_back(*UI);
5759 while (!Worklist.empty()) {
5760 User *U = Worklist.pop_back_val();
5761 // Deleting the Old value will cause this to dangle. Postpone
5762 // that until everything else is done.
5765 if (!Visited.insert(U))
5767 if (PHINode *PN = dyn_cast<PHINode>(U))
5768 SE->ConstantEvolutionLoopExitValue.erase(PN);
5769 SE->ValueExprMap.erase(U);
5770 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5772 Worklist.push_back(*UI);
5774 // Delete the Old value.
5775 if (PHINode *PN = dyn_cast<PHINode>(Old))
5776 SE->ConstantEvolutionLoopExitValue.erase(PN);
5777 SE->ValueExprMap.erase(Old);
5778 // this now dangles!
5781 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
5782 : CallbackVH(V), SE(se) {}
5784 //===----------------------------------------------------------------------===//
5785 // ScalarEvolution Class Implementation
5786 //===----------------------------------------------------------------------===//
5788 ScalarEvolution::ScalarEvolution()
5789 : FunctionPass(ID), FirstUnknown(0) {
5790 initializeScalarEvolutionPass(*PassRegistry::getPassRegistry());
5793 bool ScalarEvolution::runOnFunction(Function &F) {
5795 LI = &getAnalysis<LoopInfo>();
5796 TD = getAnalysisIfAvailable<TargetData>();
5797 DT = &getAnalysis<DominatorTree>();
5801 void ScalarEvolution::releaseMemory() {
5802 // Iterate through all the SCEVUnknown instances and call their
5803 // destructors, so that they release their references to their values.
5804 for (SCEVUnknown *U = FirstUnknown; U; U = U->Next)
5808 ValueExprMap.clear();
5809 BackedgeTakenCounts.clear();
5810 ConstantEvolutionLoopExitValue.clear();
5811 ValuesAtScopes.clear();
5812 LoopDispositions.clear();
5813 UnsignedRanges.clear();
5814 SignedRanges.clear();
5815 UniqueSCEVs.clear();
5816 SCEVAllocator.Reset();
5819 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5820 AU.setPreservesAll();
5821 AU.addRequiredTransitive<LoopInfo>();
5822 AU.addRequiredTransitive<DominatorTree>();
5825 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
5826 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
5829 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
5831 // Print all inner loops first
5832 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5833 PrintLoopInfo(OS, SE, *I);
5836 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5839 SmallVector<BasicBlock *, 8> ExitBlocks;
5840 L->getExitBlocks(ExitBlocks);
5841 if (ExitBlocks.size() != 1)
5842 OS << "<multiple exits> ";
5844 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5845 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
5847 OS << "Unpredictable backedge-taken count. ";
5852 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5855 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5856 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5858 OS << "Unpredictable max backedge-taken count. ";
5864 void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
5865 // ScalarEvolution's implementation of the print method is to print
5866 // out SCEV values of all instructions that are interesting. Doing
5867 // this potentially causes it to create new SCEV objects though,
5868 // which technically conflicts with the const qualifier. This isn't
5869 // observable from outside the class though, so casting away the
5870 // const isn't dangerous.
5871 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
5873 OS << "Classifying expressions for: ";
5874 WriteAsOperand(OS, F, /*PrintType=*/false);
5876 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
5877 if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) {
5880 const SCEV *SV = SE.getSCEV(&*I);
5883 const Loop *L = LI->getLoopFor((*I).getParent());
5885 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
5892 OS << "\t\t" "Exits: ";
5893 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
5894 if (!SE.isLoopInvariant(ExitValue, L)) {
5895 OS << "<<Unknown>>";
5904 OS << "Determining loop execution counts for: ";
5905 WriteAsOperand(OS, F, /*PrintType=*/false);
5907 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5908 PrintLoopInfo(OS, &SE, *I);
5911 ScalarEvolution::LoopDisposition
5912 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
5913 std::map<const Loop *, LoopDisposition> &Values = LoopDispositions[S];
5914 std::pair<std::map<const Loop *, LoopDisposition>::iterator, bool> Pair =
5915 Values.insert(std::make_pair(L, LoopVariant));
5917 return Pair.first->second;
5919 LoopDisposition D = computeLoopDisposition(S, L);
5920 return LoopDispositions[S][L] = D;
5923 ScalarEvolution::LoopDisposition
5924 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
5925 switch (S->getSCEVType()) {
5927 return LoopInvariant;
5931 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
5932 case scAddRecExpr: {
5933 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
5935 // If L is the addrec's loop, it's computable.
5936 if (AR->getLoop() == L)
5937 return LoopComputable;
5939 // Add recurrences are never invariant in the function-body (null loop).
5943 // This recurrence is variant w.r.t. L if L contains AR's loop.
5944 if (L->contains(AR->getLoop()))
5947 // This recurrence is invariant w.r.t. L if AR's loop contains L.
5948 if (AR->getLoop()->contains(L))
5949 return LoopInvariant;
5951 // This recurrence is variant w.r.t. L if any of its operands
5953 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
5955 if (!isLoopInvariant(*I, L))
5958 // Otherwise it's loop-invariant.
5959 return LoopInvariant;
5965 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
5966 bool HasVarying = false;
5967 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
5969 LoopDisposition D = getLoopDisposition(*I, L);
5970 if (D == LoopVariant)
5972 if (D == LoopComputable)
5975 return HasVarying ? LoopComputable : LoopInvariant;
5978 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
5979 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
5980 if (LD == LoopVariant)
5982 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
5983 if (RD == LoopVariant)
5985 return (LD == LoopInvariant && RD == LoopInvariant) ?
5986 LoopInvariant : LoopComputable;
5989 // All non-instruction values are loop invariant. All instructions are loop
5990 // invariant if they are not contained in the specified loop.
5991 // Instructions are never considered invariant in the function body
5992 // (null loop) because they are defined within the "loop".
5993 if (Instruction *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
5994 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
5995 return LoopInvariant;
5996 case scCouldNotCompute:
5997 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6001 llvm_unreachable("Unknown SCEV kind!");
6005 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
6006 return getLoopDisposition(S, L) == LoopInvariant;
6009 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
6010 return getLoopDisposition(S, L) == LoopComputable;
6013 bool ScalarEvolution::dominates(const SCEV *S, BasicBlock *BB) const {
6014 switch (S->getSCEVType()) {
6020 return dominates(cast<SCEVCastExpr>(S)->getOperand(), BB);
6021 case scAddRecExpr: {
6022 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
6023 if (!DT->dominates(AR->getLoop()->getHeader(), BB))
6026 // FALL THROUGH into SCEVNAryExpr handling.
6031 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
6032 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
6034 if (!dominates(*I, BB))
6039 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6040 return dominates(UDiv->getLHS(), BB) && dominates(UDiv->getRHS(), BB);
6043 if (Instruction *I =
6044 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
6045 return DT->dominates(I->getParent(), BB);
6047 case scCouldNotCompute:
6048 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6052 llvm_unreachable("Unknown SCEV kind!");
6056 bool ScalarEvolution::properlyDominates(const SCEV *S, BasicBlock *BB) const {
6057 switch (S->getSCEVType()) {
6063 return properlyDominates(cast<SCEVCastExpr>(S)->getOperand(), BB);
6064 case scAddRecExpr: {
6065 // This uses a "dominates" query instead of "properly dominates" query
6066 // because the instruction which produces the addrec's value is a PHI, and
6067 // a PHI effectively properly dominates its entire containing block.
6068 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
6069 if (!DT->dominates(AR->getLoop()->getHeader(), BB))
6072 // FALL THROUGH into SCEVNAryExpr handling.
6077 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
6078 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
6080 if (!properlyDominates(*I, BB))
6085 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6086 return properlyDominates(UDiv->getLHS(), BB) &&
6087 properlyDominates(UDiv->getRHS(), BB);
6090 if (Instruction *I =
6091 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
6092 return DT->properlyDominates(I->getParent(), BB);
6094 case scCouldNotCompute:
6095 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6099 llvm_unreachable("Unknown SCEV kind!");
6103 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
6104 switch (S->getSCEVType()) {
6109 case scSignExtend: {
6110 const SCEVCastExpr *Cast = cast<SCEVCastExpr>(S);
6111 const SCEV *CastOp = Cast->getOperand();
6112 return Op == CastOp || hasOperand(CastOp, Op);
6119 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
6120 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
6122 const SCEV *NAryOp = *I;
6123 if (NAryOp == Op || hasOperand(NAryOp, Op))
6129 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6130 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
6131 return LHS == Op || hasOperand(LHS, Op) ||
6132 RHS == Op || hasOperand(RHS, Op);
6136 case scCouldNotCompute:
6137 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6141 llvm_unreachable("Unknown SCEV kind!");