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/LoopInfo.h"
73 #include "llvm/Analysis/ValueTracking.h"
74 #include "llvm/Assembly/Writer.h"
75 #include "llvm/Target/TargetData.h"
76 #include "llvm/Support/CommandLine.h"
77 #include "llvm/Support/ConstantRange.h"
78 #include "llvm/Support/Debug.h"
79 #include "llvm/Support/ErrorHandling.h"
80 #include "llvm/Support/GetElementPtrTypeIterator.h"
81 #include "llvm/Support/InstIterator.h"
82 #include "llvm/Support/MathExtras.h"
83 #include "llvm/Support/raw_ostream.h"
84 #include "llvm/ADT/Statistic.h"
85 #include "llvm/ADT/STLExtras.h"
86 #include "llvm/ADT/SmallPtrSet.h"
90 STATISTIC(NumArrayLenItCounts,
91 "Number of trip counts computed with array length");
92 STATISTIC(NumTripCountsComputed,
93 "Number of loops with predictable loop counts");
94 STATISTIC(NumTripCountsNotComputed,
95 "Number of loops without predictable loop counts");
96 STATISTIC(NumBruteForceTripCountsComputed,
97 "Number of loops with trip counts computed by force");
99 static cl::opt<unsigned>
100 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
101 cl::desc("Maximum number of iterations SCEV will "
102 "symbolically execute a constant "
106 static RegisterPass<ScalarEvolution>
107 R("scalar-evolution", "Scalar Evolution Analysis", false, true);
108 char ScalarEvolution::ID = 0;
110 //===----------------------------------------------------------------------===//
111 // SCEV class definitions
112 //===----------------------------------------------------------------------===//
114 //===----------------------------------------------------------------------===//
115 // Implementation of the SCEV class.
120 void SCEV::dump() const {
125 bool SCEV::isZero() const {
126 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
127 return SC->getValue()->isZero();
131 bool SCEV::isOne() const {
132 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
133 return SC->getValue()->isOne();
137 bool SCEV::isAllOnesValue() const {
138 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
139 return SC->getValue()->isAllOnesValue();
143 SCEVCouldNotCompute::SCEVCouldNotCompute() :
144 SCEV(FoldingSetNodeID(), scCouldNotCompute) {}
146 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
147 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
151 const Type *SCEVCouldNotCompute::getType() const {
152 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
156 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
157 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
161 bool SCEVCouldNotCompute::hasOperand(const SCEV *) const {
162 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
166 void SCEVCouldNotCompute::print(raw_ostream &OS) const {
167 OS << "***COULDNOTCOMPUTE***";
170 bool SCEVCouldNotCompute::classof(const SCEV *S) {
171 return S->getSCEVType() == scCouldNotCompute;
174 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
176 ID.AddInteger(scConstant);
179 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
180 SCEV *S = SCEVAllocator.Allocate<SCEVConstant>();
181 new (S) SCEVConstant(ID, V);
182 UniqueSCEVs.InsertNode(S, IP);
186 const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
187 return getConstant(ConstantInt::get(getContext(), Val));
191 ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
193 ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
196 const Type *SCEVConstant::getType() const { return V->getType(); }
198 void SCEVConstant::print(raw_ostream &OS) const {
199 WriteAsOperand(OS, V, false);
202 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeID &ID,
203 unsigned SCEVTy, const SCEV *op, const Type *ty)
204 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
206 bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
207 return Op->dominates(BB, DT);
210 bool SCEVCastExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
211 return Op->properlyDominates(BB, DT);
214 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeID &ID,
215 const SCEV *op, const Type *ty)
216 : SCEVCastExpr(ID, scTruncate, op, ty) {
217 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
218 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
219 "Cannot truncate non-integer value!");
222 void SCEVTruncateExpr::print(raw_ostream &OS) const {
223 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
226 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeID &ID,
227 const SCEV *op, const Type *ty)
228 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
229 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
230 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
231 "Cannot zero extend non-integer value!");
234 void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
235 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
238 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeID &ID,
239 const SCEV *op, const Type *ty)
240 : SCEVCastExpr(ID, scSignExtend, op, ty) {
241 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
242 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
243 "Cannot sign extend non-integer value!");
246 void SCEVSignExtendExpr::print(raw_ostream &OS) const {
247 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
250 void SCEVCommutativeExpr::print(raw_ostream &OS) const {
251 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
252 const char *OpStr = getOperationStr();
253 OS << "(" << *Operands[0];
254 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
255 OS << OpStr << *Operands[i];
259 bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
260 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
261 if (!getOperand(i)->dominates(BB, DT))
267 bool SCEVNAryExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
268 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
269 if (!getOperand(i)->properlyDominates(BB, DT))
275 bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
276 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
279 bool SCEVUDivExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
280 return LHS->properlyDominates(BB, DT) && RHS->properlyDominates(BB, DT);
283 void SCEVUDivExpr::print(raw_ostream &OS) const {
284 OS << "(" << *LHS << " /u " << *RHS << ")";
287 const Type *SCEVUDivExpr::getType() const {
288 // In most cases the types of LHS and RHS will be the same, but in some
289 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
290 // depend on the type for correctness, but handling types carefully can
291 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
292 // a pointer type than the RHS, so use the RHS' type here.
293 return RHS->getType();
296 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
297 // Add recurrences are never invariant in the function-body (null loop).
301 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
302 if (QueryLoop->contains(L))
305 // This recurrence is variant w.r.t. QueryLoop if any of its operands
307 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
308 if (!getOperand(i)->isLoopInvariant(QueryLoop))
311 // Otherwise it's loop-invariant.
316 SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
317 return DT->dominates(L->getHeader(), BB) &&
318 SCEVNAryExpr::dominates(BB, DT);
322 SCEVAddRecExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
323 // This uses a "dominates" query instead of "properly dominates" query because
324 // the instruction which produces the addrec's value is a PHI, and a PHI
325 // effectively properly dominates its entire containing block.
326 return DT->dominates(L->getHeader(), BB) &&
327 SCEVNAryExpr::properlyDominates(BB, DT);
330 void SCEVAddRecExpr::print(raw_ostream &OS) const {
331 OS << "{" << *Operands[0];
332 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
333 OS << ",+," << *Operands[i];
335 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
339 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
340 // All non-instruction values are loop invariant. All instructions are loop
341 // invariant if they are not contained in the specified loop.
342 // Instructions are never considered invariant in the function body
343 // (null loop) because they are defined within the "loop".
344 if (Instruction *I = dyn_cast<Instruction>(V))
345 return L && !L->contains(I);
349 bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
350 if (Instruction *I = dyn_cast<Instruction>(getValue()))
351 return DT->dominates(I->getParent(), BB);
355 bool SCEVUnknown::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
356 if (Instruction *I = dyn_cast<Instruction>(getValue()))
357 return DT->properlyDominates(I->getParent(), BB);
361 const Type *SCEVUnknown::getType() const {
365 bool SCEVUnknown::isSizeOf(const Type *&AllocTy) const {
366 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
367 if (VCE->getOpcode() == Instruction::PtrToInt)
368 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
369 if (CE->getOpcode() == Instruction::GetElementPtr &&
370 CE->getOperand(0)->isNullValue() &&
371 CE->getNumOperands() == 2)
372 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
374 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
382 bool SCEVUnknown::isAlignOf(const Type *&AllocTy) const {
383 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
384 if (VCE->getOpcode() == Instruction::PtrToInt)
385 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
386 if (CE->getOpcode() == Instruction::GetElementPtr &&
387 CE->getOperand(0)->isNullValue()) {
389 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
390 if (const StructType *STy = dyn_cast<StructType>(Ty))
391 if (!STy->isPacked() &&
392 CE->getNumOperands() == 3 &&
393 CE->getOperand(1)->isNullValue()) {
394 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
396 STy->getNumElements() == 2 &&
397 STy->getElementType(0)->isIntegerTy(1)) {
398 AllocTy = STy->getElementType(1);
407 bool SCEVUnknown::isOffsetOf(const Type *&CTy, Constant *&FieldNo) const {
408 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
409 if (VCE->getOpcode() == Instruction::PtrToInt)
410 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
411 if (CE->getOpcode() == Instruction::GetElementPtr &&
412 CE->getNumOperands() == 3 &&
413 CE->getOperand(0)->isNullValue() &&
414 CE->getOperand(1)->isNullValue()) {
416 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
417 // Ignore vector types here so that ScalarEvolutionExpander doesn't
418 // emit getelementptrs that index into vectors.
419 if (Ty->isStructTy() || Ty->isArrayTy()) {
421 FieldNo = CE->getOperand(2);
429 void SCEVUnknown::print(raw_ostream &OS) const {
431 if (isSizeOf(AllocTy)) {
432 OS << "sizeof(" << *AllocTy << ")";
435 if (isAlignOf(AllocTy)) {
436 OS << "alignof(" << *AllocTy << ")";
442 if (isOffsetOf(CTy, FieldNo)) {
443 OS << "offsetof(" << *CTy << ", ";
444 WriteAsOperand(OS, FieldNo, false);
449 // Otherwise just print it normally.
450 WriteAsOperand(OS, V, false);
453 //===----------------------------------------------------------------------===//
455 //===----------------------------------------------------------------------===//
457 static bool CompareTypes(const Type *A, const Type *B) {
458 if (A->getTypeID() != B->getTypeID())
459 return A->getTypeID() < B->getTypeID();
460 if (const IntegerType *AI = dyn_cast<IntegerType>(A)) {
461 const IntegerType *BI = cast<IntegerType>(B);
462 return AI->getBitWidth() < BI->getBitWidth();
464 if (const PointerType *AI = dyn_cast<PointerType>(A)) {
465 const PointerType *BI = cast<PointerType>(B);
466 return CompareTypes(AI->getElementType(), BI->getElementType());
468 if (const ArrayType *AI = dyn_cast<ArrayType>(A)) {
469 const ArrayType *BI = cast<ArrayType>(B);
470 if (AI->getNumElements() != BI->getNumElements())
471 return AI->getNumElements() < BI->getNumElements();
472 return CompareTypes(AI->getElementType(), BI->getElementType());
474 if (const VectorType *AI = dyn_cast<VectorType>(A)) {
475 const VectorType *BI = cast<VectorType>(B);
476 if (AI->getNumElements() != BI->getNumElements())
477 return AI->getNumElements() < BI->getNumElements();
478 return CompareTypes(AI->getElementType(), BI->getElementType());
480 if (const StructType *AI = dyn_cast<StructType>(A)) {
481 const StructType *BI = cast<StructType>(B);
482 if (AI->getNumElements() != BI->getNumElements())
483 return AI->getNumElements() < BI->getNumElements();
484 for (unsigned i = 0, e = AI->getNumElements(); i != e; ++i)
485 if (CompareTypes(AI->getElementType(i), BI->getElementType(i)) ||
486 CompareTypes(BI->getElementType(i), AI->getElementType(i)))
487 return CompareTypes(AI->getElementType(i), BI->getElementType(i));
493 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
494 /// than the complexity of the RHS. This comparator is used to canonicalize
496 class SCEVComplexityCompare {
499 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
501 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
502 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
506 // Primarily, sort the SCEVs by their getSCEVType().
507 if (LHS->getSCEVType() != RHS->getSCEVType())
508 return LHS->getSCEVType() < RHS->getSCEVType();
510 // Aside from the getSCEVType() ordering, the particular ordering
511 // isn't very important except that it's beneficial to be consistent,
512 // so that (a + b) and (b + a) don't end up as different expressions.
514 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
515 // not as complete as it could be.
516 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
517 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
519 // Order pointer values after integer values. This helps SCEVExpander
521 if (LU->getType()->isPointerTy() && !RU->getType()->isPointerTy())
523 if (RU->getType()->isPointerTy() && !LU->getType()->isPointerTy())
526 // Compare getValueID values.
527 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
528 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
530 // Sort arguments by their position.
531 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
532 const Argument *RA = cast<Argument>(RU->getValue());
533 return LA->getArgNo() < RA->getArgNo();
536 // For instructions, compare their loop depth, and their opcode.
537 // This is pretty loose.
538 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
539 Instruction *RV = cast<Instruction>(RU->getValue());
541 // Compare loop depths.
542 if (LI->getLoopDepth(LV->getParent()) !=
543 LI->getLoopDepth(RV->getParent()))
544 return LI->getLoopDepth(LV->getParent()) <
545 LI->getLoopDepth(RV->getParent());
548 if (LV->getOpcode() != RV->getOpcode())
549 return LV->getOpcode() < RV->getOpcode();
551 // Compare the number of operands.
552 if (LV->getNumOperands() != RV->getNumOperands())
553 return LV->getNumOperands() < RV->getNumOperands();
559 // Compare constant values.
560 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
561 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
562 if (LC->getValue()->getBitWidth() != RC->getValue()->getBitWidth())
563 return LC->getValue()->getBitWidth() < RC->getValue()->getBitWidth();
564 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
567 // Compare addrec loop depths.
568 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
569 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
570 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
571 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
574 // Lexicographically compare n-ary expressions.
575 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
576 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
577 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
578 if (i >= RC->getNumOperands())
580 if (operator()(LC->getOperand(i), RC->getOperand(i)))
582 if (operator()(RC->getOperand(i), LC->getOperand(i)))
585 return LC->getNumOperands() < RC->getNumOperands();
588 // Lexicographically compare udiv expressions.
589 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
590 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
591 if (operator()(LC->getLHS(), RC->getLHS()))
593 if (operator()(RC->getLHS(), LC->getLHS()))
595 if (operator()(LC->getRHS(), RC->getRHS()))
597 if (operator()(RC->getRHS(), LC->getRHS()))
602 // Compare cast expressions by operand.
603 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
604 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
605 return operator()(LC->getOperand(), RC->getOperand());
608 llvm_unreachable("Unknown SCEV kind!");
614 /// GroupByComplexity - Given a list of SCEV objects, order them by their
615 /// complexity, and group objects of the same complexity together by value.
616 /// When this routine is finished, we know that any duplicates in the vector are
617 /// consecutive and that complexity is monotonically increasing.
619 /// Note that we go take special precautions to ensure that we get determinstic
620 /// results from this routine. In other words, we don't want the results of
621 /// this to depend on where the addresses of various SCEV objects happened to
624 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
626 if (Ops.size() < 2) return; // Noop
627 if (Ops.size() == 2) {
628 // This is the common case, which also happens to be trivially simple.
630 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
631 std::swap(Ops[0], Ops[1]);
635 // Do the rough sort by complexity.
636 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
638 // Now that we are sorted by complexity, group elements of the same
639 // complexity. Note that this is, at worst, N^2, but the vector is likely to
640 // be extremely short in practice. Note that we take this approach because we
641 // do not want to depend on the addresses of the objects we are grouping.
642 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
643 const SCEV *S = Ops[i];
644 unsigned Complexity = S->getSCEVType();
646 // If there are any objects of the same complexity and same value as this
648 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
649 if (Ops[j] == S) { // Found a duplicate.
650 // Move it to immediately after i'th element.
651 std::swap(Ops[i+1], Ops[j]);
652 ++i; // no need to rescan it.
653 if (i == e-2) return; // Done!
661 //===----------------------------------------------------------------------===//
662 // Simple SCEV method implementations
663 //===----------------------------------------------------------------------===//
665 /// BinomialCoefficient - Compute BC(It, K). The result has width W.
667 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
669 const Type* ResultTy) {
670 // Handle the simplest case efficiently.
672 return SE.getTruncateOrZeroExtend(It, ResultTy);
674 // We are using the following formula for BC(It, K):
676 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
678 // Suppose, W is the bitwidth of the return value. We must be prepared for
679 // overflow. Hence, we must assure that the result of our computation is
680 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
681 // safe in modular arithmetic.
683 // However, this code doesn't use exactly that formula; the formula it uses
684 // is something like the following, where T is the number of factors of 2 in
685 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
688 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
690 // This formula is trivially equivalent to the previous formula. However,
691 // this formula can be implemented much more efficiently. The trick is that
692 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
693 // arithmetic. To do exact division in modular arithmetic, all we have
694 // to do is multiply by the inverse. Therefore, this step can be done at
697 // The next issue is how to safely do the division by 2^T. The way this
698 // is done is by doing the multiplication step at a width of at least W + T
699 // bits. This way, the bottom W+T bits of the product are accurate. Then,
700 // when we perform the division by 2^T (which is equivalent to a right shift
701 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
702 // truncated out after the division by 2^T.
704 // In comparison to just directly using the first formula, this technique
705 // is much more efficient; using the first formula requires W * K bits,
706 // but this formula less than W + K bits. Also, the first formula requires
707 // a division step, whereas this formula only requires multiplies and shifts.
709 // It doesn't matter whether the subtraction step is done in the calculation
710 // width or the input iteration count's width; if the subtraction overflows,
711 // the result must be zero anyway. We prefer here to do it in the width of
712 // the induction variable because it helps a lot for certain cases; CodeGen
713 // isn't smart enough to ignore the overflow, which leads to much less
714 // efficient code if the width of the subtraction is wider than the native
717 // (It's possible to not widen at all by pulling out factors of 2 before
718 // the multiplication; for example, K=2 can be calculated as
719 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
720 // extra arithmetic, so it's not an obvious win, and it gets
721 // much more complicated for K > 3.)
723 // Protection from insane SCEVs; this bound is conservative,
724 // but it probably doesn't matter.
726 return SE.getCouldNotCompute();
728 unsigned W = SE.getTypeSizeInBits(ResultTy);
730 // Calculate K! / 2^T and T; we divide out the factors of two before
731 // multiplying for calculating K! / 2^T to avoid overflow.
732 // Other overflow doesn't matter because we only care about the bottom
733 // W bits of the result.
734 APInt OddFactorial(W, 1);
736 for (unsigned i = 3; i <= K; ++i) {
738 unsigned TwoFactors = Mult.countTrailingZeros();
740 Mult = Mult.lshr(TwoFactors);
741 OddFactorial *= Mult;
744 // We need at least W + T bits for the multiplication step
745 unsigned CalculationBits = W + T;
747 // Calcuate 2^T, at width T+W.
748 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
750 // Calculate the multiplicative inverse of K! / 2^T;
751 // this multiplication factor will perform the exact division by
753 APInt Mod = APInt::getSignedMinValue(W+1);
754 APInt MultiplyFactor = OddFactorial.zext(W+1);
755 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
756 MultiplyFactor = MultiplyFactor.trunc(W);
758 // Calculate the product, at width T+W
759 const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
761 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
762 for (unsigned i = 1; i != K; ++i) {
763 const SCEV *S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
764 Dividend = SE.getMulExpr(Dividend,
765 SE.getTruncateOrZeroExtend(S, CalculationTy));
769 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
771 // Truncate the result, and divide by K! / 2^T.
773 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
774 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
777 /// evaluateAtIteration - Return the value of this chain of recurrences at
778 /// the specified iteration number. We can evaluate this recurrence by
779 /// multiplying each element in the chain by the binomial coefficient
780 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
782 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
784 /// where BC(It, k) stands for binomial coefficient.
786 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
787 ScalarEvolution &SE) const {
788 const SCEV *Result = getStart();
789 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
790 // The computation is correct in the face of overflow provided that the
791 // multiplication is performed _after_ the evaluation of the binomial
793 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
794 if (isa<SCEVCouldNotCompute>(Coeff))
797 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
802 //===----------------------------------------------------------------------===//
803 // SCEV Expression folder implementations
804 //===----------------------------------------------------------------------===//
806 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
808 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
809 "This is not a truncating conversion!");
810 assert(isSCEVable(Ty) &&
811 "This is not a conversion to a SCEVable type!");
812 Ty = getEffectiveSCEVType(Ty);
815 ID.AddInteger(scTruncate);
819 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
821 // Fold if the operand is constant.
822 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
824 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
826 // trunc(trunc(x)) --> trunc(x)
827 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
828 return getTruncateExpr(ST->getOperand(), Ty);
830 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
831 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
832 return getTruncateOrSignExtend(SS->getOperand(), Ty);
834 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
835 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
836 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
838 // If the input value is a chrec scev, truncate the chrec's operands.
839 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
840 SmallVector<const SCEV *, 4> Operands;
841 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
842 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
843 return getAddRecExpr(Operands, AddRec->getLoop());
846 // The cast wasn't folded; create an explicit cast node.
847 // Recompute the insert position, as it may have been invalidated.
848 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
849 SCEV *S = SCEVAllocator.Allocate<SCEVTruncateExpr>();
850 new (S) SCEVTruncateExpr(ID, Op, Ty);
851 UniqueSCEVs.InsertNode(S, IP);
855 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
857 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
858 "This is not an extending conversion!");
859 assert(isSCEVable(Ty) &&
860 "This is not a conversion to a SCEVable type!");
861 Ty = getEffectiveSCEVType(Ty);
863 // Fold if the operand is constant.
864 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
865 const Type *IntTy = getEffectiveSCEVType(Ty);
866 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
867 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
868 return getConstant(cast<ConstantInt>(C));
871 // zext(zext(x)) --> zext(x)
872 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
873 return getZeroExtendExpr(SZ->getOperand(), Ty);
875 // Before doing any expensive analysis, check to see if we've already
876 // computed a SCEV for this Op and Ty.
878 ID.AddInteger(scZeroExtend);
882 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
884 // If the input value is a chrec scev, and we can prove that the value
885 // did not overflow the old, smaller, value, we can zero extend all of the
886 // operands (often constants). This allows analysis of something like
887 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
888 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
889 if (AR->isAffine()) {
890 const SCEV *Start = AR->getStart();
891 const SCEV *Step = AR->getStepRecurrence(*this);
892 unsigned BitWidth = getTypeSizeInBits(AR->getType());
893 const Loop *L = AR->getLoop();
895 // If we have special knowledge that this addrec won't overflow,
896 // we don't need to do any further analysis.
897 if (AR->hasNoUnsignedWrap())
898 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
899 getZeroExtendExpr(Step, Ty),
902 // Check whether the backedge-taken count is SCEVCouldNotCompute.
903 // Note that this serves two purposes: It filters out loops that are
904 // simply not analyzable, and it covers the case where this code is
905 // being called from within backedge-taken count analysis, such that
906 // attempting to ask for the backedge-taken count would likely result
907 // in infinite recursion. In the later case, the analysis code will
908 // cope with a conservative value, and it will take care to purge
909 // that value once it has finished.
910 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
911 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
912 // Manually compute the final value for AR, checking for
915 // Check whether the backedge-taken count can be losslessly casted to
916 // the addrec's type. The count is always unsigned.
917 const SCEV *CastedMaxBECount =
918 getTruncateOrZeroExtend(MaxBECount, Start->getType());
919 const SCEV *RecastedMaxBECount =
920 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
921 if (MaxBECount == RecastedMaxBECount) {
922 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
923 // Check whether Start+Step*MaxBECount has no unsigned overflow.
924 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
925 const SCEV *Add = getAddExpr(Start, ZMul);
926 const SCEV *OperandExtendedAdd =
927 getAddExpr(getZeroExtendExpr(Start, WideTy),
928 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
929 getZeroExtendExpr(Step, WideTy)));
930 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
931 // Return the expression with the addrec on the outside.
932 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
933 getZeroExtendExpr(Step, Ty),
936 // Similar to above, only this time treat the step value as signed.
937 // This covers loops that count down.
938 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
939 Add = getAddExpr(Start, SMul);
941 getAddExpr(getZeroExtendExpr(Start, WideTy),
942 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
943 getSignExtendExpr(Step, WideTy)));
944 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
945 // Return the expression with the addrec on the outside.
946 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
947 getSignExtendExpr(Step, Ty),
951 // If the backedge is guarded by a comparison with the pre-inc value
952 // the addrec is safe. Also, if the entry is guarded by a comparison
953 // with the start value and the backedge is guarded by a comparison
954 // with the post-inc value, the addrec is safe.
955 if (isKnownPositive(Step)) {
956 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
957 getUnsignedRange(Step).getUnsignedMax());
958 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
959 (isLoopGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
960 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
961 AR->getPostIncExpr(*this), N)))
962 // Return the expression with the addrec on the outside.
963 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
964 getZeroExtendExpr(Step, Ty),
966 } else if (isKnownNegative(Step)) {
967 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
968 getSignedRange(Step).getSignedMin());
969 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) &&
970 (isLoopGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) ||
971 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
972 AR->getPostIncExpr(*this), N)))
973 // Return the expression with the addrec on the outside.
974 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
975 getSignExtendExpr(Step, Ty),
981 // The cast wasn't folded; create an explicit cast node.
982 // Recompute the insert position, as it may have been invalidated.
983 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
984 SCEV *S = SCEVAllocator.Allocate<SCEVZeroExtendExpr>();
985 new (S) SCEVZeroExtendExpr(ID, Op, Ty);
986 UniqueSCEVs.InsertNode(S, IP);
990 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
992 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
993 "This is not an extending conversion!");
994 assert(isSCEVable(Ty) &&
995 "This is not a conversion to a SCEVable type!");
996 Ty = getEffectiveSCEVType(Ty);
998 // Fold if the operand is constant.
999 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
1000 const Type *IntTy = getEffectiveSCEVType(Ty);
1001 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
1002 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
1003 return getConstant(cast<ConstantInt>(C));
1006 // sext(sext(x)) --> sext(x)
1007 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1008 return getSignExtendExpr(SS->getOperand(), Ty);
1010 // Before doing any expensive analysis, check to see if we've already
1011 // computed a SCEV for this Op and Ty.
1012 FoldingSetNodeID ID;
1013 ID.AddInteger(scSignExtend);
1017 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1019 // If the input value is a chrec scev, and we can prove that the value
1020 // did not overflow the old, smaller, value, we can sign extend all of the
1021 // operands (often constants). This allows analysis of something like
1022 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1023 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1024 if (AR->isAffine()) {
1025 const SCEV *Start = AR->getStart();
1026 const SCEV *Step = AR->getStepRecurrence(*this);
1027 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1028 const Loop *L = AR->getLoop();
1030 // If we have special knowledge that this addrec won't overflow,
1031 // we don't need to do any further analysis.
1032 if (AR->hasNoSignedWrap())
1033 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1034 getSignExtendExpr(Step, Ty),
1037 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1038 // Note that this serves two purposes: It filters out loops that are
1039 // simply not analyzable, and it covers the case where this code is
1040 // being called from within backedge-taken count analysis, such that
1041 // attempting to ask for the backedge-taken count would likely result
1042 // in infinite recursion. In the later case, the analysis code will
1043 // cope with a conservative value, and it will take care to purge
1044 // that value once it has finished.
1045 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1046 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1047 // Manually compute the final value for AR, checking for
1050 // Check whether the backedge-taken count can be losslessly casted to
1051 // the addrec's type. The count is always unsigned.
1052 const SCEV *CastedMaxBECount =
1053 getTruncateOrZeroExtend(MaxBECount, Start->getType());
1054 const SCEV *RecastedMaxBECount =
1055 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1056 if (MaxBECount == RecastedMaxBECount) {
1057 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1058 // Check whether Start+Step*MaxBECount has no signed overflow.
1059 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
1060 const SCEV *Add = getAddExpr(Start, SMul);
1061 const SCEV *OperandExtendedAdd =
1062 getAddExpr(getSignExtendExpr(Start, WideTy),
1063 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1064 getSignExtendExpr(Step, WideTy)));
1065 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
1066 // Return the expression with the addrec on the outside.
1067 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1068 getSignExtendExpr(Step, Ty),
1071 // Similar to above, only this time treat the step value as unsigned.
1072 // This covers loops that count up with an unsigned step.
1073 const SCEV *UMul = getMulExpr(CastedMaxBECount, Step);
1074 Add = getAddExpr(Start, UMul);
1075 OperandExtendedAdd =
1076 getAddExpr(getSignExtendExpr(Start, WideTy),
1077 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1078 getZeroExtendExpr(Step, WideTy)));
1079 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
1080 // Return the expression with the addrec on the outside.
1081 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1082 getZeroExtendExpr(Step, Ty),
1086 // If the backedge is guarded by a comparison with the pre-inc value
1087 // the addrec is safe. Also, if the entry is guarded by a comparison
1088 // with the start value and the backedge is guarded by a comparison
1089 // with the post-inc value, the addrec is safe.
1090 if (isKnownPositive(Step)) {
1091 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
1092 getSignedRange(Step).getSignedMax());
1093 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
1094 (isLoopGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
1095 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
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),
1101 } else if (isKnownNegative(Step)) {
1102 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1103 getSignedRange(Step).getSignedMin());
1104 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
1105 (isLoopGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
1106 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1107 AR->getPostIncExpr(*this), N)))
1108 // Return the expression with the addrec on the outside.
1109 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1110 getSignExtendExpr(Step, Ty),
1116 // The cast wasn't folded; create an explicit cast node.
1117 // Recompute the insert position, as it may have been invalidated.
1118 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1119 SCEV *S = SCEVAllocator.Allocate<SCEVSignExtendExpr>();
1120 new (S) SCEVSignExtendExpr(ID, Op, Ty);
1121 UniqueSCEVs.InsertNode(S, IP);
1125 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1126 /// unspecified bits out to the given type.
1128 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1130 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1131 "This is not an extending conversion!");
1132 assert(isSCEVable(Ty) &&
1133 "This is not a conversion to a SCEVable type!");
1134 Ty = getEffectiveSCEVType(Ty);
1136 // Sign-extend negative constants.
1137 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1138 if (SC->getValue()->getValue().isNegative())
1139 return getSignExtendExpr(Op, Ty);
1141 // Peel off a truncate cast.
1142 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
1143 const SCEV *NewOp = T->getOperand();
1144 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1145 return getAnyExtendExpr(NewOp, Ty);
1146 return getTruncateOrNoop(NewOp, Ty);
1149 // Next try a zext cast. If the cast is folded, use it.
1150 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
1151 if (!isa<SCEVZeroExtendExpr>(ZExt))
1154 // Next try a sext cast. If the cast is folded, use it.
1155 const SCEV *SExt = getSignExtendExpr(Op, Ty);
1156 if (!isa<SCEVSignExtendExpr>(SExt))
1159 // Force the cast to be folded into the operands of an addrec.
1160 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1161 SmallVector<const SCEV *, 4> Ops;
1162 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
1164 Ops.push_back(getAnyExtendExpr(*I, Ty));
1165 return getAddRecExpr(Ops, AR->getLoop());
1168 // If the expression is obviously signed, use the sext cast value.
1169 if (isa<SCEVSMaxExpr>(Op))
1172 // Absent any other information, use the zext cast value.
1176 /// CollectAddOperandsWithScales - Process the given Ops list, which is
1177 /// a list of operands to be added under the given scale, update the given
1178 /// map. This is a helper function for getAddRecExpr. As an example of
1179 /// what it does, given a sequence of operands that would form an add
1180 /// expression like this:
1182 /// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1184 /// where A and B are constants, update the map with these values:
1186 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1188 /// and add 13 + A*B*29 to AccumulatedConstant.
1189 /// This will allow getAddRecExpr to produce this:
1191 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1193 /// This form often exposes folding opportunities that are hidden in
1194 /// the original operand list.
1196 /// Return true iff it appears that any interesting folding opportunities
1197 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
1198 /// the common case where no interesting opportunities are present, and
1199 /// is also used as a check to avoid infinite recursion.
1202 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1203 SmallVector<const SCEV *, 8> &NewOps,
1204 APInt &AccumulatedConstant,
1205 const SmallVectorImpl<const SCEV *> &Ops,
1207 ScalarEvolution &SE) {
1208 bool Interesting = false;
1210 // Iterate over the add operands.
1211 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1212 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1213 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1215 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1216 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1217 // A multiplication of a constant with another add; recurse.
1219 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1220 cast<SCEVAddExpr>(Mul->getOperand(1))
1224 // A multiplication of a constant with some other value. Update
1226 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1227 const SCEV *Key = SE.getMulExpr(MulOps);
1228 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1229 M.insert(std::make_pair(Key, NewScale));
1231 NewOps.push_back(Pair.first->first);
1233 Pair.first->second += NewScale;
1234 // The map already had an entry for this value, which may indicate
1235 // a folding opportunity.
1239 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1240 // Pull a buried constant out to the outside.
1241 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1243 AccumulatedConstant += Scale * C->getValue()->getValue();
1245 // An ordinary operand. Update the map.
1246 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1247 M.insert(std::make_pair(Ops[i], Scale));
1249 NewOps.push_back(Pair.first->first);
1251 Pair.first->second += Scale;
1252 // The map already had an entry for this value, which may indicate
1253 // a folding opportunity.
1263 struct APIntCompare {
1264 bool operator()(const APInt &LHS, const APInt &RHS) const {
1265 return LHS.ult(RHS);
1270 /// getAddExpr - Get a canonical add expression, or something simpler if
1272 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1273 bool HasNUW, bool HasNSW) {
1274 assert(!Ops.empty() && "Cannot get empty add!");
1275 if (Ops.size() == 1) return Ops[0];
1277 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1278 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1279 getEffectiveSCEVType(Ops[0]->getType()) &&
1280 "SCEVAddExpr operand types don't match!");
1283 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1284 if (!HasNUW && HasNSW) {
1286 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1287 if (!isKnownNonNegative(Ops[i])) {
1291 if (All) HasNUW = true;
1294 // Sort by complexity, this groups all similar expression types together.
1295 GroupByComplexity(Ops, LI);
1297 // If there are any constants, fold them together.
1299 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1301 assert(Idx < Ops.size());
1302 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1303 // We found two constants, fold them together!
1304 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1305 RHSC->getValue()->getValue());
1306 if (Ops.size() == 2) return Ops[0];
1307 Ops.erase(Ops.begin()+1); // Erase the folded element
1308 LHSC = cast<SCEVConstant>(Ops[0]);
1311 // If we are left with a constant zero being added, strip it off.
1312 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1313 Ops.erase(Ops.begin());
1318 if (Ops.size() == 1) return Ops[0];
1320 // Okay, check to see if the same value occurs in the operand list twice. If
1321 // so, merge them together into an multiply expression. Since we sorted the
1322 // list, these values are required to be adjacent.
1323 const Type *Ty = Ops[0]->getType();
1324 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1325 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1326 // Found a match, merge the two values into a multiply, and add any
1327 // remaining values to the result.
1328 const SCEV *Two = getIntegerSCEV(2, Ty);
1329 const SCEV *Mul = getMulExpr(Ops[i], Two);
1330 if (Ops.size() == 2)
1332 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1334 return getAddExpr(Ops, HasNUW, HasNSW);
1337 // Check for truncates. If all the operands are truncated from the same
1338 // type, see if factoring out the truncate would permit the result to be
1339 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1340 // if the contents of the resulting outer trunc fold to something simple.
1341 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1342 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1343 const Type *DstType = Trunc->getType();
1344 const Type *SrcType = Trunc->getOperand()->getType();
1345 SmallVector<const SCEV *, 8> LargeOps;
1347 // Check all the operands to see if they can be represented in the
1348 // source type of the truncate.
1349 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1350 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1351 if (T->getOperand()->getType() != SrcType) {
1355 LargeOps.push_back(T->getOperand());
1356 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1357 // This could be either sign or zero extension, but sign extension
1358 // is much more likely to be foldable here.
1359 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1360 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
1361 SmallVector<const SCEV *, 8> LargeMulOps;
1362 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1363 if (const SCEVTruncateExpr *T =
1364 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1365 if (T->getOperand()->getType() != SrcType) {
1369 LargeMulOps.push_back(T->getOperand());
1370 } else if (const SCEVConstant *C =
1371 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1372 // This could be either sign or zero extension, but sign extension
1373 // is much more likely to be foldable here.
1374 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1381 LargeOps.push_back(getMulExpr(LargeMulOps));
1388 // Evaluate the expression in the larger type.
1389 const SCEV *Fold = getAddExpr(LargeOps, HasNUW, HasNSW);
1390 // If it folds to something simple, use it. Otherwise, don't.
1391 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1392 return getTruncateExpr(Fold, DstType);
1396 // Skip past any other cast SCEVs.
1397 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1400 // If there are add operands they would be next.
1401 if (Idx < Ops.size()) {
1402 bool DeletedAdd = false;
1403 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
1404 // If we have an add, expand the add operands onto the end of the operands
1406 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1407 Ops.erase(Ops.begin()+Idx);
1411 // If we deleted at least one add, we added operands to the end of the list,
1412 // and they are not necessarily sorted. Recurse to resort and resimplify
1413 // any operands we just aquired.
1415 return getAddExpr(Ops);
1418 // Skip over the add expression until we get to a multiply.
1419 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1422 // Check to see if there are any folding opportunities present with
1423 // operands multiplied by constant values.
1424 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1425 uint64_t BitWidth = getTypeSizeInBits(Ty);
1426 DenseMap<const SCEV *, APInt> M;
1427 SmallVector<const SCEV *, 8> NewOps;
1428 APInt AccumulatedConstant(BitWidth, 0);
1429 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1430 Ops, APInt(BitWidth, 1), *this)) {
1431 // Some interesting folding opportunity is present, so its worthwhile to
1432 // re-generate the operands list. Group the operands by constant scale,
1433 // to avoid multiplying by the same constant scale multiple times.
1434 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1435 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
1436 E = NewOps.end(); I != E; ++I)
1437 MulOpLists[M.find(*I)->second].push_back(*I);
1438 // Re-generate the operands list.
1440 if (AccumulatedConstant != 0)
1441 Ops.push_back(getConstant(AccumulatedConstant));
1442 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1443 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
1445 Ops.push_back(getMulExpr(getConstant(I->first),
1446 getAddExpr(I->second)));
1448 return getIntegerSCEV(0, Ty);
1449 if (Ops.size() == 1)
1451 return getAddExpr(Ops);
1455 // If we are adding something to a multiply expression, make sure the
1456 // something is not already an operand of the multiply. If so, merge it into
1458 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
1459 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
1460 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
1461 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
1462 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
1463 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
1464 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1465 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
1466 if (Mul->getNumOperands() != 2) {
1467 // If the multiply has more than two operands, we must get the
1469 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
1470 MulOps.erase(MulOps.begin()+MulOp);
1471 InnerMul = getMulExpr(MulOps);
1473 const SCEV *One = getIntegerSCEV(1, Ty);
1474 const SCEV *AddOne = getAddExpr(InnerMul, One);
1475 const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
1476 if (Ops.size() == 2) return OuterMul;
1478 Ops.erase(Ops.begin()+AddOp);
1479 Ops.erase(Ops.begin()+Idx-1);
1481 Ops.erase(Ops.begin()+Idx);
1482 Ops.erase(Ops.begin()+AddOp-1);
1484 Ops.push_back(OuterMul);
1485 return getAddExpr(Ops);
1488 // Check this multiply against other multiplies being added together.
1489 for (unsigned OtherMulIdx = Idx+1;
1490 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1492 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
1493 // If MulOp occurs in OtherMul, we can fold the two multiplies
1495 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1496 OMulOp != e; ++OMulOp)
1497 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1498 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1499 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
1500 if (Mul->getNumOperands() != 2) {
1501 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1503 MulOps.erase(MulOps.begin()+MulOp);
1504 InnerMul1 = getMulExpr(MulOps);
1506 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1507 if (OtherMul->getNumOperands() != 2) {
1508 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1509 OtherMul->op_end());
1510 MulOps.erase(MulOps.begin()+OMulOp);
1511 InnerMul2 = getMulExpr(MulOps);
1513 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1514 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
1515 if (Ops.size() == 2) return OuterMul;
1516 Ops.erase(Ops.begin()+Idx);
1517 Ops.erase(Ops.begin()+OtherMulIdx-1);
1518 Ops.push_back(OuterMul);
1519 return getAddExpr(Ops);
1525 // If there are any add recurrences in the operands list, see if any other
1526 // added values are loop invariant. If so, we can fold them into the
1528 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1531 // Scan over all recurrences, trying to fold loop invariants into them.
1532 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1533 // Scan all of the other operands to this add and add them to the vector if
1534 // they are loop invariant w.r.t. the recurrence.
1535 SmallVector<const SCEV *, 8> LIOps;
1536 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1537 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1538 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1539 LIOps.push_back(Ops[i]);
1540 Ops.erase(Ops.begin()+i);
1544 // If we found some loop invariants, fold them into the recurrence.
1545 if (!LIOps.empty()) {
1546 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
1547 LIOps.push_back(AddRec->getStart());
1549 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
1551 AddRecOps[0] = getAddExpr(LIOps);
1553 // It's tempting to propagate NUW/NSW flags here, but nuw/nsw addition
1554 // is not associative so this isn't necessarily safe.
1555 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
1557 // If all of the other operands were loop invariant, we are done.
1558 if (Ops.size() == 1) return NewRec;
1560 // Otherwise, add the folded AddRec by the non-liv parts.
1561 for (unsigned i = 0;; ++i)
1562 if (Ops[i] == AddRec) {
1566 return getAddExpr(Ops);
1569 // Okay, if there weren't any loop invariants to be folded, check to see if
1570 // there are multiple AddRec's with the same loop induction variable being
1571 // added together. If so, we can fold them.
1572 for (unsigned OtherIdx = Idx+1;
1573 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1574 if (OtherIdx != Idx) {
1575 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1576 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1577 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1578 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1580 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1581 if (i >= NewOps.size()) {
1582 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1583 OtherAddRec->op_end());
1586 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
1588 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
1590 if (Ops.size() == 2) return NewAddRec;
1592 Ops.erase(Ops.begin()+Idx);
1593 Ops.erase(Ops.begin()+OtherIdx-1);
1594 Ops.push_back(NewAddRec);
1595 return getAddExpr(Ops);
1599 // Otherwise couldn't fold anything into this recurrence. Move onto the
1603 // Okay, it looks like we really DO need an add expr. Check to see if we
1604 // already have one, otherwise create a new one.
1605 FoldingSetNodeID ID;
1606 ID.AddInteger(scAddExpr);
1607 ID.AddInteger(Ops.size());
1608 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1609 ID.AddPointer(Ops[i]);
1612 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1614 S = SCEVAllocator.Allocate<SCEVAddExpr>();
1615 new (S) SCEVAddExpr(ID, Ops);
1616 UniqueSCEVs.InsertNode(S, IP);
1618 if (HasNUW) S->setHasNoUnsignedWrap(true);
1619 if (HasNSW) S->setHasNoSignedWrap(true);
1623 /// getMulExpr - Get a canonical multiply expression, or something simpler if
1625 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1626 bool HasNUW, bool HasNSW) {
1627 assert(!Ops.empty() && "Cannot get empty mul!");
1628 if (Ops.size() == 1) return Ops[0];
1630 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1631 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1632 getEffectiveSCEVType(Ops[0]->getType()) &&
1633 "SCEVMulExpr operand types don't match!");
1636 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1637 if (!HasNUW && HasNSW) {
1639 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1640 if (!isKnownNonNegative(Ops[i])) {
1644 if (All) HasNUW = true;
1647 // Sort by complexity, this groups all similar expression types together.
1648 GroupByComplexity(Ops, LI);
1650 // If there are any constants, fold them together.
1652 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1654 // C1*(C2+V) -> C1*C2 + C1*V
1655 if (Ops.size() == 2)
1656 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1657 if (Add->getNumOperands() == 2 &&
1658 isa<SCEVConstant>(Add->getOperand(0)))
1659 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1660 getMulExpr(LHSC, Add->getOperand(1)));
1663 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1664 // We found two constants, fold them together!
1665 ConstantInt *Fold = ConstantInt::get(getContext(),
1666 LHSC->getValue()->getValue() *
1667 RHSC->getValue()->getValue());
1668 Ops[0] = getConstant(Fold);
1669 Ops.erase(Ops.begin()+1); // Erase the folded element
1670 if (Ops.size() == 1) return Ops[0];
1671 LHSC = cast<SCEVConstant>(Ops[0]);
1674 // If we are left with a constant one being multiplied, strip it off.
1675 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1676 Ops.erase(Ops.begin());
1678 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1679 // If we have a multiply of zero, it will always be zero.
1681 } else if (Ops[0]->isAllOnesValue()) {
1682 // If we have a mul by -1 of an add, try distributing the -1 among the
1684 if (Ops.size() == 2)
1685 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1686 SmallVector<const SCEV *, 4> NewOps;
1687 bool AnyFolded = false;
1688 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1690 const SCEV *Mul = getMulExpr(Ops[0], *I);
1691 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1692 NewOps.push_back(Mul);
1695 return getAddExpr(NewOps);
1700 // Skip over the add expression until we get to a multiply.
1701 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1704 if (Ops.size() == 1)
1707 // If there are mul operands inline them all into this expression.
1708 if (Idx < Ops.size()) {
1709 bool DeletedMul = false;
1710 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1711 // If we have an mul, expand the mul operands onto the end of the operands
1713 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1714 Ops.erase(Ops.begin()+Idx);
1718 // If we deleted at least one mul, we added operands to the end of the list,
1719 // and they are not necessarily sorted. Recurse to resort and resimplify
1720 // any operands we just aquired.
1722 return getMulExpr(Ops);
1725 // If there are any add recurrences in the operands list, see if any other
1726 // added values are loop invariant. If so, we can fold them into the
1728 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1731 // Scan over all recurrences, trying to fold loop invariants into them.
1732 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1733 // Scan all of the other operands to this mul and add them to the vector if
1734 // they are loop invariant w.r.t. the recurrence.
1735 SmallVector<const SCEV *, 8> LIOps;
1736 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1737 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1738 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1739 LIOps.push_back(Ops[i]);
1740 Ops.erase(Ops.begin()+i);
1744 // If we found some loop invariants, fold them into the recurrence.
1745 if (!LIOps.empty()) {
1746 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
1747 SmallVector<const SCEV *, 4> NewOps;
1748 NewOps.reserve(AddRec->getNumOperands());
1749 if (LIOps.size() == 1) {
1750 const SCEV *Scale = LIOps[0];
1751 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1752 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1754 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1755 SmallVector<const SCEV *, 4> MulOps(LIOps.begin(), LIOps.end());
1756 MulOps.push_back(AddRec->getOperand(i));
1757 NewOps.push_back(getMulExpr(MulOps));
1761 // It's tempting to propagate the NSW flag here, but nsw multiplication
1762 // is not associative so this isn't necessarily safe.
1763 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(),
1764 HasNUW && AddRec->hasNoUnsignedWrap(),
1767 // If all of the other operands were loop invariant, we are done.
1768 if (Ops.size() == 1) return NewRec;
1770 // Otherwise, multiply the folded AddRec by the non-liv parts.
1771 for (unsigned i = 0;; ++i)
1772 if (Ops[i] == AddRec) {
1776 return getMulExpr(Ops);
1779 // Okay, if there weren't any loop invariants to be folded, check to see if
1780 // there are multiple AddRec's with the same loop induction variable being
1781 // multiplied together. If so, we can fold them.
1782 for (unsigned OtherIdx = Idx+1;
1783 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1784 if (OtherIdx != Idx) {
1785 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1786 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1787 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1788 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1789 const SCEV *NewStart = getMulExpr(F->getStart(),
1791 const SCEV *B = F->getStepRecurrence(*this);
1792 const SCEV *D = G->getStepRecurrence(*this);
1793 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
1796 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
1798 if (Ops.size() == 2) return NewAddRec;
1800 Ops.erase(Ops.begin()+Idx);
1801 Ops.erase(Ops.begin()+OtherIdx-1);
1802 Ops.push_back(NewAddRec);
1803 return getMulExpr(Ops);
1807 // Otherwise couldn't fold anything into this recurrence. Move onto the
1811 // Okay, it looks like we really DO need an mul expr. Check to see if we
1812 // already have one, otherwise create a new one.
1813 FoldingSetNodeID ID;
1814 ID.AddInteger(scMulExpr);
1815 ID.AddInteger(Ops.size());
1816 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1817 ID.AddPointer(Ops[i]);
1820 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1822 S = SCEVAllocator.Allocate<SCEVMulExpr>();
1823 new (S) SCEVMulExpr(ID, Ops);
1824 UniqueSCEVs.InsertNode(S, IP);
1826 if (HasNUW) S->setHasNoUnsignedWrap(true);
1827 if (HasNSW) S->setHasNoSignedWrap(true);
1831 /// getUDivExpr - Get a canonical unsigned division expression, or something
1832 /// simpler if possible.
1833 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1835 assert(getEffectiveSCEVType(LHS->getType()) ==
1836 getEffectiveSCEVType(RHS->getType()) &&
1837 "SCEVUDivExpr operand types don't match!");
1839 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1840 if (RHSC->getValue()->equalsInt(1))
1841 return LHS; // X udiv 1 --> x
1843 return getIntegerSCEV(0, LHS->getType()); // value is undefined
1845 // Determine if the division can be folded into the operands of
1847 // TODO: Generalize this to non-constants by using known-bits information.
1848 const Type *Ty = LHS->getType();
1849 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1850 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1851 // For non-power-of-two values, effectively round the value up to the
1852 // nearest power of two.
1853 if (!RHSC->getValue()->getValue().isPowerOf2())
1855 const IntegerType *ExtTy =
1856 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
1857 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1858 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1859 if (const SCEVConstant *Step =
1860 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1861 if (!Step->getValue()->getValue()
1862 .urem(RHSC->getValue()->getValue()) &&
1863 getZeroExtendExpr(AR, ExtTy) ==
1864 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1865 getZeroExtendExpr(Step, ExtTy),
1867 SmallVector<const SCEV *, 4> Operands;
1868 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1869 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1870 return getAddRecExpr(Operands, AR->getLoop());
1872 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1873 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1874 SmallVector<const SCEV *, 4> Operands;
1875 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1876 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1877 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
1878 // Find an operand that's safely divisible.
1879 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1880 const SCEV *Op = M->getOperand(i);
1881 const SCEV *Div = getUDivExpr(Op, RHSC);
1882 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1883 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
1884 Operands = SmallVector<const SCEV *, 4>(MOperands.begin(),
1887 return getMulExpr(Operands);
1891 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
1892 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1893 SmallVector<const SCEV *, 4> Operands;
1894 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1895 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1896 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1898 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1899 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
1900 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1902 Operands.push_back(Op);
1904 if (Operands.size() == A->getNumOperands())
1905 return getAddExpr(Operands);
1909 // Fold if both operands are constant.
1910 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1911 Constant *LHSCV = LHSC->getValue();
1912 Constant *RHSCV = RHSC->getValue();
1913 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1918 FoldingSetNodeID ID;
1919 ID.AddInteger(scUDivExpr);
1923 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1924 SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>();
1925 new (S) SCEVUDivExpr(ID, LHS, RHS);
1926 UniqueSCEVs.InsertNode(S, IP);
1931 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1932 /// Simplify the expression as much as possible.
1933 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
1934 const SCEV *Step, const Loop *L,
1935 bool HasNUW, bool HasNSW) {
1936 SmallVector<const SCEV *, 4> Operands;
1937 Operands.push_back(Start);
1938 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1939 if (StepChrec->getLoop() == L) {
1940 Operands.insert(Operands.end(), StepChrec->op_begin(),
1941 StepChrec->op_end());
1942 return getAddRecExpr(Operands, L);
1945 Operands.push_back(Step);
1946 return getAddRecExpr(Operands, L, HasNUW, HasNSW);
1949 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1950 /// Simplify the expression as much as possible.
1952 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
1954 bool HasNUW, bool HasNSW) {
1955 if (Operands.size() == 1) return Operands[0];
1957 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1958 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1959 getEffectiveSCEVType(Operands[0]->getType()) &&
1960 "SCEVAddRecExpr operand types don't match!");
1963 if (Operands.back()->isZero()) {
1964 Operands.pop_back();
1965 return getAddRecExpr(Operands, L, HasNUW, HasNSW); // {X,+,0} --> X
1968 // It's tempting to want to call getMaxBackedgeTakenCount count here and
1969 // use that information to infer NUW and NSW flags. However, computing a
1970 // BE count requires calling getAddRecExpr, so we may not yet have a
1971 // meaningful BE count at this point (and if we don't, we'd be stuck
1972 // with a SCEVCouldNotCompute as the cached BE count).
1974 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1975 if (!HasNUW && HasNSW) {
1977 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1978 if (!isKnownNonNegative(Operands[i])) {
1982 if (All) HasNUW = true;
1985 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1986 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1987 const Loop *NestedLoop = NestedAR->getLoop();
1988 if (L->contains(NestedLoop->getHeader()) ?
1989 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
1990 (!NestedLoop->contains(L->getHeader()) &&
1991 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
1992 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
1993 NestedAR->op_end());
1994 Operands[0] = NestedAR->getStart();
1995 // AddRecs require their operands be loop-invariant with respect to their
1996 // loops. Don't perform this transformation if it would break this
1998 bool AllInvariant = true;
1999 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2000 if (!Operands[i]->isLoopInvariant(L)) {
2001 AllInvariant = false;
2005 NestedOperands[0] = getAddRecExpr(Operands, L);
2006 AllInvariant = true;
2007 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
2008 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
2009 AllInvariant = false;
2013 // Ok, both add recurrences are valid after the transformation.
2014 return getAddRecExpr(NestedOperands, NestedLoop, HasNUW, HasNSW);
2016 // Reset Operands to its original state.
2017 Operands[0] = NestedAR;
2021 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2022 // already have one, otherwise create a new one.
2023 FoldingSetNodeID ID;
2024 ID.AddInteger(scAddRecExpr);
2025 ID.AddInteger(Operands.size());
2026 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2027 ID.AddPointer(Operands[i]);
2031 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2033 S = SCEVAllocator.Allocate<SCEVAddRecExpr>();
2034 new (S) SCEVAddRecExpr(ID, Operands, L);
2035 UniqueSCEVs.InsertNode(S, IP);
2037 if (HasNUW) S->setHasNoUnsignedWrap(true);
2038 if (HasNSW) S->setHasNoSignedWrap(true);
2042 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2044 SmallVector<const SCEV *, 2> Ops;
2047 return getSMaxExpr(Ops);
2051 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2052 assert(!Ops.empty() && "Cannot get empty smax!");
2053 if (Ops.size() == 1) return Ops[0];
2055 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2056 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2057 getEffectiveSCEVType(Ops[0]->getType()) &&
2058 "SCEVSMaxExpr operand types don't match!");
2061 // Sort by complexity, this groups all similar expression types together.
2062 GroupByComplexity(Ops, LI);
2064 // If there are any constants, fold them together.
2066 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2068 assert(Idx < Ops.size());
2069 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2070 // We found two constants, fold them together!
2071 ConstantInt *Fold = ConstantInt::get(getContext(),
2072 APIntOps::smax(LHSC->getValue()->getValue(),
2073 RHSC->getValue()->getValue()));
2074 Ops[0] = getConstant(Fold);
2075 Ops.erase(Ops.begin()+1); // Erase the folded element
2076 if (Ops.size() == 1) return Ops[0];
2077 LHSC = cast<SCEVConstant>(Ops[0]);
2080 // If we are left with a constant minimum-int, strip it off.
2081 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2082 Ops.erase(Ops.begin());
2084 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2085 // If we have an smax with a constant maximum-int, it will always be
2091 if (Ops.size() == 1) return Ops[0];
2093 // Find the first SMax
2094 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2097 // Check to see if one of the operands is an SMax. If so, expand its operands
2098 // onto our operand list, and recurse to simplify.
2099 if (Idx < Ops.size()) {
2100 bool DeletedSMax = false;
2101 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
2102 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
2103 Ops.erase(Ops.begin()+Idx);
2108 return getSMaxExpr(Ops);
2111 // Okay, check to see if the same value occurs in the operand list twice. If
2112 // so, delete one. Since we sorted the list, these values are required to
2114 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2115 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
2116 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2120 if (Ops.size() == 1) return Ops[0];
2122 assert(!Ops.empty() && "Reduced smax down to nothing!");
2124 // Okay, it looks like we really DO need an smax expr. Check to see if we
2125 // already have one, otherwise create a new one.
2126 FoldingSetNodeID ID;
2127 ID.AddInteger(scSMaxExpr);
2128 ID.AddInteger(Ops.size());
2129 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2130 ID.AddPointer(Ops[i]);
2132 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2133 SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>();
2134 new (S) SCEVSMaxExpr(ID, Ops);
2135 UniqueSCEVs.InsertNode(S, IP);
2139 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2141 SmallVector<const SCEV *, 2> Ops;
2144 return getUMaxExpr(Ops);
2148 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2149 assert(!Ops.empty() && "Cannot get empty umax!");
2150 if (Ops.size() == 1) return Ops[0];
2152 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2153 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2154 getEffectiveSCEVType(Ops[0]->getType()) &&
2155 "SCEVUMaxExpr operand types don't match!");
2158 // Sort by complexity, this groups all similar expression types together.
2159 GroupByComplexity(Ops, LI);
2161 // If there are any constants, fold them together.
2163 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2165 assert(Idx < Ops.size());
2166 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2167 // We found two constants, fold them together!
2168 ConstantInt *Fold = ConstantInt::get(getContext(),
2169 APIntOps::umax(LHSC->getValue()->getValue(),
2170 RHSC->getValue()->getValue()));
2171 Ops[0] = getConstant(Fold);
2172 Ops.erase(Ops.begin()+1); // Erase the folded element
2173 if (Ops.size() == 1) return Ops[0];
2174 LHSC = cast<SCEVConstant>(Ops[0]);
2177 // If we are left with a constant minimum-int, strip it off.
2178 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2179 Ops.erase(Ops.begin());
2181 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2182 // If we have an umax with a constant maximum-int, it will always be
2188 if (Ops.size() == 1) return Ops[0];
2190 // Find the first UMax
2191 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2194 // Check to see if one of the operands is a UMax. If so, expand its operands
2195 // onto our operand list, and recurse to simplify.
2196 if (Idx < Ops.size()) {
2197 bool DeletedUMax = false;
2198 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
2199 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
2200 Ops.erase(Ops.begin()+Idx);
2205 return getUMaxExpr(Ops);
2208 // Okay, check to see if the same value occurs in the operand list twice. If
2209 // so, delete one. Since we sorted the list, these values are required to
2211 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2212 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
2213 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2217 if (Ops.size() == 1) return Ops[0];
2219 assert(!Ops.empty() && "Reduced umax down to nothing!");
2221 // Okay, it looks like we really DO need a umax expr. Check to see if we
2222 // already have one, otherwise create a new one.
2223 FoldingSetNodeID ID;
2224 ID.AddInteger(scUMaxExpr);
2225 ID.AddInteger(Ops.size());
2226 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2227 ID.AddPointer(Ops[i]);
2229 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2230 SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>();
2231 new (S) SCEVUMaxExpr(ID, Ops);
2232 UniqueSCEVs.InsertNode(S, IP);
2236 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2238 // ~smax(~x, ~y) == smin(x, y).
2239 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2242 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2244 // ~umax(~x, ~y) == umin(x, y)
2245 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2248 const SCEV *ScalarEvolution::getSizeOfExpr(const Type *AllocTy) {
2249 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2250 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2251 C = ConstantFoldConstantExpression(CE, TD);
2252 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2253 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2256 const SCEV *ScalarEvolution::getAlignOfExpr(const Type *AllocTy) {
2257 Constant *C = ConstantExpr::getAlignOf(AllocTy);
2258 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2259 C = ConstantFoldConstantExpression(CE, TD);
2260 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2261 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2264 const SCEV *ScalarEvolution::getOffsetOfExpr(const StructType *STy,
2266 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2267 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2268 C = ConstantFoldConstantExpression(CE, TD);
2269 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
2270 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2273 const SCEV *ScalarEvolution::getOffsetOfExpr(const Type *CTy,
2274 Constant *FieldNo) {
2275 Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
2276 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2277 C = ConstantFoldConstantExpression(CE, TD);
2278 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
2279 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2282 const SCEV *ScalarEvolution::getUnknown(Value *V) {
2283 // Don't attempt to do anything other than create a SCEVUnknown object
2284 // here. createSCEV only calls getUnknown after checking for all other
2285 // interesting possibilities, and any other code that calls getUnknown
2286 // is doing so in order to hide a value from SCEV canonicalization.
2288 FoldingSetNodeID ID;
2289 ID.AddInteger(scUnknown);
2292 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2293 SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>();
2294 new (S) SCEVUnknown(ID, V);
2295 UniqueSCEVs.InsertNode(S, IP);
2299 //===----------------------------------------------------------------------===//
2300 // Basic SCEV Analysis and PHI Idiom Recognition Code
2303 /// isSCEVable - Test if values of the given type are analyzable within
2304 /// the SCEV framework. This primarily includes integer types, and it
2305 /// can optionally include pointer types if the ScalarEvolution class
2306 /// has access to target-specific information.
2307 bool ScalarEvolution::isSCEVable(const Type *Ty) const {
2308 // Integers and pointers are always SCEVable.
2309 return Ty->isIntegerTy() || Ty->isPointerTy();
2312 /// getTypeSizeInBits - Return the size in bits of the specified type,
2313 /// for which isSCEVable must return true.
2314 uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
2315 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2317 // If we have a TargetData, use it!
2319 return TD->getTypeSizeInBits(Ty);
2321 // Integer types have fixed sizes.
2322 if (Ty->isIntegerTy())
2323 return Ty->getPrimitiveSizeInBits();
2325 // The only other support type is pointer. Without TargetData, conservatively
2326 // assume pointers are 64-bit.
2327 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
2331 /// getEffectiveSCEVType - Return a type with the same bitwidth as
2332 /// the given type and which represents how SCEV will treat the given
2333 /// type, for which isSCEVable must return true. For pointer types,
2334 /// this is the pointer-sized integer type.
2335 const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
2336 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2338 if (Ty->isIntegerTy())
2341 // The only other support type is pointer.
2342 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
2343 if (TD) return TD->getIntPtrType(getContext());
2345 // Without TargetData, conservatively assume pointers are 64-bit.
2346 return Type::getInt64Ty(getContext());
2349 const SCEV *ScalarEvolution::getCouldNotCompute() {
2350 return &CouldNotCompute;
2353 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2354 /// expression and create a new one.
2355 const SCEV *ScalarEvolution::getSCEV(Value *V) {
2356 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
2358 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
2359 if (I != Scalars.end()) return I->second;
2360 const SCEV *S = createSCEV(V);
2361 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
2365 /// getIntegerSCEV - Given a SCEVable type, create a constant for the
2366 /// specified signed integer value and return a SCEV for the constant.
2367 const SCEV *ScalarEvolution::getIntegerSCEV(int64_t Val, const Type *Ty) {
2368 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
2369 return getConstant(ConstantInt::get(ITy, Val));
2372 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2374 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
2375 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2377 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
2379 const Type *Ty = V->getType();
2380 Ty = getEffectiveSCEVType(Ty);
2381 return getMulExpr(V,
2382 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
2385 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
2386 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
2387 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2389 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
2391 const Type *Ty = V->getType();
2392 Ty = getEffectiveSCEVType(Ty);
2393 const SCEV *AllOnes =
2394 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
2395 return getMinusSCEV(AllOnes, V);
2398 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2400 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2403 return getAddExpr(LHS, getNegativeSCEV(RHS));
2406 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2407 /// input value to the specified type. If the type must be extended, it is zero
2410 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
2412 const Type *SrcTy = V->getType();
2413 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2414 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2415 "Cannot truncate or zero extend with non-integer arguments!");
2416 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2417 return V; // No conversion
2418 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2419 return getTruncateExpr(V, Ty);
2420 return getZeroExtendExpr(V, Ty);
2423 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2424 /// input value to the specified type. If the type must be extended, it is sign
2427 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
2429 const Type *SrcTy = V->getType();
2430 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2431 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2432 "Cannot truncate or zero extend with non-integer arguments!");
2433 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2434 return V; // No conversion
2435 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2436 return getTruncateExpr(V, Ty);
2437 return getSignExtendExpr(V, Ty);
2440 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2441 /// input value to the specified type. If the type must be extended, it is zero
2442 /// extended. The conversion must not be narrowing.
2444 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
2445 const Type *SrcTy = V->getType();
2446 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2447 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2448 "Cannot noop or zero extend with non-integer arguments!");
2449 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2450 "getNoopOrZeroExtend cannot truncate!");
2451 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2452 return V; // No conversion
2453 return getZeroExtendExpr(V, Ty);
2456 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2457 /// input value to the specified type. If the type must be extended, it is sign
2458 /// extended. The conversion must not be narrowing.
2460 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
2461 const Type *SrcTy = V->getType();
2462 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2463 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2464 "Cannot noop or sign extend with non-integer arguments!");
2465 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2466 "getNoopOrSignExtend cannot truncate!");
2467 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2468 return V; // No conversion
2469 return getSignExtendExpr(V, Ty);
2472 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2473 /// the input value to the specified type. If the type must be extended,
2474 /// it is extended with unspecified bits. The conversion must not be
2477 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
2478 const Type *SrcTy = V->getType();
2479 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2480 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2481 "Cannot noop or any extend with non-integer arguments!");
2482 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2483 "getNoopOrAnyExtend cannot truncate!");
2484 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2485 return V; // No conversion
2486 return getAnyExtendExpr(V, Ty);
2489 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2490 /// input value to the specified type. The conversion must not be widening.
2492 ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
2493 const Type *SrcTy = V->getType();
2494 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2495 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2496 "Cannot truncate or noop with non-integer arguments!");
2497 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2498 "getTruncateOrNoop cannot extend!");
2499 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2500 return V; // No conversion
2501 return getTruncateExpr(V, Ty);
2504 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2505 /// the types using zero-extension, and then perform a umax operation
2507 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2509 const SCEV *PromotedLHS = LHS;
2510 const SCEV *PromotedRHS = RHS;
2512 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2513 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2515 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2517 return getUMaxExpr(PromotedLHS, PromotedRHS);
2520 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
2521 /// the types using zero-extension, and then perform a umin operation
2523 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2525 const SCEV *PromotedLHS = LHS;
2526 const SCEV *PromotedRHS = RHS;
2528 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2529 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2531 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2533 return getUMinExpr(PromotedLHS, PromotedRHS);
2536 /// PushDefUseChildren - Push users of the given Instruction
2537 /// onto the given Worklist.
2539 PushDefUseChildren(Instruction *I,
2540 SmallVectorImpl<Instruction *> &Worklist) {
2541 // Push the def-use children onto the Worklist stack.
2542 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2544 Worklist.push_back(cast<Instruction>(UI));
2547 /// ForgetSymbolicValue - This looks up computed SCEV values for all
2548 /// instructions that depend on the given instruction and removes them from
2549 /// the Scalars map if they reference SymName. This is used during PHI
2552 ScalarEvolution::ForgetSymbolicName(Instruction *I, const SCEV *SymName) {
2553 SmallVector<Instruction *, 16> Worklist;
2554 PushDefUseChildren(I, Worklist);
2556 SmallPtrSet<Instruction *, 8> Visited;
2558 while (!Worklist.empty()) {
2559 I = Worklist.pop_back_val();
2560 if (!Visited.insert(I)) continue;
2562 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
2563 Scalars.find(static_cast<Value *>(I));
2564 if (It != Scalars.end()) {
2565 // Short-circuit the def-use traversal if the symbolic name
2566 // ceases to appear in expressions.
2567 if (It->second != SymName && !It->second->hasOperand(SymName))
2570 // SCEVUnknown for a PHI either means that it has an unrecognized
2571 // structure, or it's a PHI that's in the progress of being computed
2572 // by createNodeForPHI. In the former case, additional loop trip
2573 // count information isn't going to change anything. In the later
2574 // case, createNodeForPHI will perform the necessary updates on its
2575 // own when it gets to that point.
2576 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
2577 ValuesAtScopes.erase(It->second);
2582 PushDefUseChildren(I, Worklist);
2586 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2587 /// a loop header, making it a potential recurrence, or it doesn't.
2589 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
2590 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
2591 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2592 if (L->getHeader() == PN->getParent()) {
2593 // If it lives in the loop header, it has two incoming values, one
2594 // from outside the loop, and one from inside.
2595 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2596 unsigned BackEdge = IncomingEdge^1;
2598 // While we are analyzing this PHI node, handle its value symbolically.
2599 const SCEV *SymbolicName = getUnknown(PN);
2600 assert(Scalars.find(PN) == Scalars.end() &&
2601 "PHI node already processed?");
2602 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
2604 // Using this symbolic name for the PHI, analyze the value coming around
2606 Value *BEValueV = PN->getIncomingValue(BackEdge);
2607 const SCEV *BEValue = getSCEV(BEValueV);
2609 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2610 // has a special value for the first iteration of the loop.
2612 // If the value coming around the backedge is an add with the symbolic
2613 // value we just inserted, then we found a simple induction variable!
2614 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
2615 // If there is a single occurrence of the symbolic value, replace it
2616 // with a recurrence.
2617 unsigned FoundIndex = Add->getNumOperands();
2618 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2619 if (Add->getOperand(i) == SymbolicName)
2620 if (FoundIndex == e) {
2625 if (FoundIndex != Add->getNumOperands()) {
2626 // Create an add with everything but the specified operand.
2627 SmallVector<const SCEV *, 8> Ops;
2628 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2629 if (i != FoundIndex)
2630 Ops.push_back(Add->getOperand(i));
2631 const SCEV *Accum = getAddExpr(Ops);
2633 // This is not a valid addrec if the step amount is varying each
2634 // loop iteration, but is not itself an addrec in this loop.
2635 if (Accum->isLoopInvariant(L) ||
2636 (isa<SCEVAddRecExpr>(Accum) &&
2637 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
2638 bool HasNUW = false;
2639 bool HasNSW = false;
2641 // If the increment doesn't overflow, then neither the addrec nor
2642 // the post-increment will overflow.
2643 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
2644 if (OBO->hasNoUnsignedWrap())
2646 if (OBO->hasNoSignedWrap())
2650 const SCEV *StartVal =
2651 getSCEV(PN->getIncomingValue(IncomingEdge));
2652 const SCEV *PHISCEV =
2653 getAddRecExpr(StartVal, Accum, L, HasNUW, HasNSW);
2655 // Since the no-wrap flags are on the increment, they apply to the
2656 // post-incremented value as well.
2657 if (Accum->isLoopInvariant(L))
2658 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
2659 Accum, L, HasNUW, HasNSW);
2661 // Okay, for the entire analysis of this edge we assumed the PHI
2662 // to be symbolic. We now need to go back and purge all of the
2663 // entries for the scalars that use the symbolic expression.
2664 ForgetSymbolicName(PN, SymbolicName);
2665 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
2669 } else if (const SCEVAddRecExpr *AddRec =
2670 dyn_cast<SCEVAddRecExpr>(BEValue)) {
2671 // Otherwise, this could be a loop like this:
2672 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2673 // In this case, j = {1,+,1} and BEValue is j.
2674 // Because the other in-value of i (0) fits the evolution of BEValue
2675 // i really is an addrec evolution.
2676 if (AddRec->getLoop() == L && AddRec->isAffine()) {
2677 const SCEV *StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
2679 // If StartVal = j.start - j.stride, we can use StartVal as the
2680 // initial step of the addrec evolution.
2681 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
2682 AddRec->getOperand(1))) {
2683 const SCEV *PHISCEV =
2684 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
2686 // Okay, for the entire analysis of this edge we assumed the PHI
2687 // to be symbolic. We now need to go back and purge all of the
2688 // entries for the scalars that use the symbolic expression.
2689 ForgetSymbolicName(PN, SymbolicName);
2690 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
2696 return SymbolicName;
2699 // It's tempting to recognize PHIs with a unique incoming value, however
2700 // this leads passes like indvars to break LCSSA form. Fortunately, such
2701 // PHIs are rare, as instcombine zaps them.
2703 // If it's not a loop phi, we can't handle it yet.
2704 return getUnknown(PN);
2707 /// createNodeForGEP - Expand GEP instructions into add and multiply
2708 /// operations. This allows them to be analyzed by regular SCEV code.
2710 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
2712 bool InBounds = GEP->isInBounds();
2713 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
2714 Value *Base = GEP->getOperand(0);
2715 // Don't attempt to analyze GEPs over unsized objects.
2716 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2717 return getUnknown(GEP);
2718 const SCEV *TotalOffset = getIntegerSCEV(0, IntPtrTy);
2719 gep_type_iterator GTI = gep_type_begin(GEP);
2720 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2724 // Compute the (potentially symbolic) offset in bytes for this index.
2725 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2726 // For a struct, add the member offset.
2727 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2728 TotalOffset = getAddExpr(TotalOffset,
2729 getOffsetOfExpr(STy, FieldNo),
2730 /*HasNUW=*/false, /*HasNSW=*/InBounds);
2732 // For an array, add the element offset, explicitly scaled.
2733 const SCEV *LocalOffset = getSCEV(Index);
2734 // Getelementptr indicies are signed.
2735 LocalOffset = getTruncateOrSignExtend(LocalOffset, IntPtrTy);
2736 // Lower "inbounds" GEPs to NSW arithmetic.
2737 LocalOffset = getMulExpr(LocalOffset, getSizeOfExpr(*GTI),
2738 /*HasNUW=*/false, /*HasNSW=*/InBounds);
2739 TotalOffset = getAddExpr(TotalOffset, LocalOffset,
2740 /*HasNUW=*/false, /*HasNSW=*/InBounds);
2743 return getAddExpr(getSCEV(Base), TotalOffset,
2744 /*HasNUW=*/false, /*HasNSW=*/InBounds);
2747 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2748 /// guaranteed to end in (at every loop iteration). It is, at the same time,
2749 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2750 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
2752 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
2753 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2754 return C->getValue()->getValue().countTrailingZeros();
2756 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
2757 return std::min(GetMinTrailingZeros(T->getOperand()),
2758 (uint32_t)getTypeSizeInBits(T->getType()));
2760 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
2761 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2762 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2763 getTypeSizeInBits(E->getType()) : OpRes;
2766 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
2767 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2768 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2769 getTypeSizeInBits(E->getType()) : OpRes;
2772 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
2773 // The result is the min of all operands results.
2774 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2775 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2776 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2780 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
2781 // The result is the sum of all operands results.
2782 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2783 uint32_t BitWidth = getTypeSizeInBits(M->getType());
2784 for (unsigned i = 1, e = M->getNumOperands();
2785 SumOpRes != BitWidth && i != e; ++i)
2786 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
2791 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
2792 // The result is the min of all operands results.
2793 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2794 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2795 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2799 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
2800 // The result is the min of all operands results.
2801 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2802 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2803 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2807 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
2808 // The result is the min of all operands results.
2809 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2810 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2811 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2815 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2816 // For a SCEVUnknown, ask ValueTracking.
2817 unsigned BitWidth = getTypeSizeInBits(U->getType());
2818 APInt Mask = APInt::getAllOnesValue(BitWidth);
2819 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2820 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2821 return Zeros.countTrailingOnes();
2828 /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2831 ScalarEvolution::getUnsignedRange(const SCEV *S) {
2833 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2834 return ConstantRange(C->getValue()->getValue());
2836 unsigned BitWidth = getTypeSizeInBits(S->getType());
2837 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2839 // If the value has known zeros, the maximum unsigned value will have those
2840 // known zeros as well.
2841 uint32_t TZ = GetMinTrailingZeros(S);
2843 ConservativeResult =
2844 ConstantRange(APInt::getMinValue(BitWidth),
2845 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
2847 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2848 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2849 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2850 X = X.add(getUnsignedRange(Add->getOperand(i)));
2851 return ConservativeResult.intersectWith(X);
2854 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2855 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2856 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2857 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
2858 return ConservativeResult.intersectWith(X);
2861 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2862 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2863 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2864 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
2865 return ConservativeResult.intersectWith(X);
2868 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2869 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2870 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2871 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
2872 return ConservativeResult.intersectWith(X);
2875 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2876 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2877 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
2878 return ConservativeResult.intersectWith(X.udiv(Y));
2881 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2882 ConstantRange X = getUnsignedRange(ZExt->getOperand());
2883 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
2886 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2887 ConstantRange X = getUnsignedRange(SExt->getOperand());
2888 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
2891 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2892 ConstantRange X = getUnsignedRange(Trunc->getOperand());
2893 return ConservativeResult.intersectWith(X.truncate(BitWidth));
2896 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2897 // If there's no unsigned wrap, the value will never be less than its
2899 if (AddRec->hasNoUnsignedWrap())
2900 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
2901 ConservativeResult =
2902 ConstantRange(C->getValue()->getValue(),
2903 APInt(getTypeSizeInBits(C->getType()), 0));
2905 // TODO: non-affine addrec
2906 if (AddRec->isAffine()) {
2907 const Type *Ty = AddRec->getType();
2908 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2909 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
2910 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
2911 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2913 const SCEV *Start = AddRec->getStart();
2914 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2916 // Check for overflow.
2917 if (!AddRec->hasNoUnsignedWrap())
2918 return ConservativeResult;
2920 ConstantRange StartRange = getUnsignedRange(Start);
2921 ConstantRange EndRange = getUnsignedRange(End);
2922 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
2923 EndRange.getUnsignedMin());
2924 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
2925 EndRange.getUnsignedMax());
2926 if (Min.isMinValue() && Max.isMaxValue())
2927 return ConservativeResult;
2928 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
2932 return ConservativeResult;
2935 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2936 // For a SCEVUnknown, ask ValueTracking.
2937 APInt Mask = APInt::getAllOnesValue(BitWidth);
2938 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2939 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
2940 if (Ones == ~Zeros + 1)
2941 return ConservativeResult;
2942 return ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
2945 return ConservativeResult;
2948 /// getSignedRange - Determine the signed range for a particular SCEV.
2951 ScalarEvolution::getSignedRange(const SCEV *S) {
2953 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2954 return ConstantRange(C->getValue()->getValue());
2956 unsigned BitWidth = getTypeSizeInBits(S->getType());
2957 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2959 // If the value has known zeros, the maximum signed value will have those
2960 // known zeros as well.
2961 uint32_t TZ = GetMinTrailingZeros(S);
2963 ConservativeResult =
2964 ConstantRange(APInt::getSignedMinValue(BitWidth),
2965 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
2967 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2968 ConstantRange X = getSignedRange(Add->getOperand(0));
2969 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2970 X = X.add(getSignedRange(Add->getOperand(i)));
2971 return ConservativeResult.intersectWith(X);
2974 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2975 ConstantRange X = getSignedRange(Mul->getOperand(0));
2976 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2977 X = X.multiply(getSignedRange(Mul->getOperand(i)));
2978 return ConservativeResult.intersectWith(X);
2981 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2982 ConstantRange X = getSignedRange(SMax->getOperand(0));
2983 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2984 X = X.smax(getSignedRange(SMax->getOperand(i)));
2985 return ConservativeResult.intersectWith(X);
2988 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2989 ConstantRange X = getSignedRange(UMax->getOperand(0));
2990 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2991 X = X.umax(getSignedRange(UMax->getOperand(i)));
2992 return ConservativeResult.intersectWith(X);
2995 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2996 ConstantRange X = getSignedRange(UDiv->getLHS());
2997 ConstantRange Y = getSignedRange(UDiv->getRHS());
2998 return ConservativeResult.intersectWith(X.udiv(Y));
3001 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3002 ConstantRange X = getSignedRange(ZExt->getOperand());
3003 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
3006 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3007 ConstantRange X = getSignedRange(SExt->getOperand());
3008 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
3011 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3012 ConstantRange X = getSignedRange(Trunc->getOperand());
3013 return ConservativeResult.intersectWith(X.truncate(BitWidth));
3016 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
3017 // If there's no signed wrap, and all the operands have the same sign or
3018 // zero, the value won't ever change sign.
3019 if (AddRec->hasNoSignedWrap()) {
3020 bool AllNonNeg = true;
3021 bool AllNonPos = true;
3022 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3023 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3024 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3027 ConservativeResult = ConservativeResult.intersectWith(
3028 ConstantRange(APInt(BitWidth, 0),
3029 APInt::getSignedMinValue(BitWidth)));
3031 ConservativeResult = ConservativeResult.intersectWith(
3032 ConstantRange(APInt::getSignedMinValue(BitWidth),
3033 APInt(BitWidth, 1)));
3036 // TODO: non-affine addrec
3037 if (AddRec->isAffine()) {
3038 const Type *Ty = AddRec->getType();
3039 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
3040 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3041 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
3042 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3044 const SCEV *Start = AddRec->getStart();
3045 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
3047 // Check for overflow.
3048 if (!AddRec->hasNoSignedWrap())
3049 return ConservativeResult;
3051 ConstantRange StartRange = getSignedRange(Start);
3052 ConstantRange EndRange = getSignedRange(End);
3053 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3054 EndRange.getSignedMin());
3055 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3056 EndRange.getSignedMax());
3057 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
3058 return ConservativeResult;
3059 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
3063 return ConservativeResult;
3066 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3067 // For a SCEVUnknown, ask ValueTracking.
3068 if (!U->getValue()->getType()->isIntegerTy() && !TD)
3069 return ConservativeResult;
3070 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3072 return ConservativeResult;
3073 return ConservativeResult.intersectWith(
3074 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
3075 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1));
3078 return ConservativeResult;
3081 /// createSCEV - We know that there is no SCEV for the specified value.
3082 /// Analyze the expression.
3084 const SCEV *ScalarEvolution::createSCEV(Value *V) {
3085 if (!isSCEVable(V->getType()))
3086 return getUnknown(V);
3088 unsigned Opcode = Instruction::UserOp1;
3089 if (Instruction *I = dyn_cast<Instruction>(V))
3090 Opcode = I->getOpcode();
3091 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
3092 Opcode = CE->getOpcode();
3093 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3094 return getConstant(CI);
3095 else if (isa<ConstantPointerNull>(V))
3096 return getIntegerSCEV(0, V->getType());
3097 else if (isa<UndefValue>(V))
3098 return getIntegerSCEV(0, V->getType());
3099 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3100 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
3102 return getUnknown(V);
3104 Operator *U = cast<Operator>(V);
3106 case Instruction::Add:
3107 // Don't transfer the NSW and NUW bits from the Add instruction to the
3108 // Add expression, because the Instruction may be guarded by control
3109 // flow and the no-overflow bits may not be valid for the expression in
3111 return getAddExpr(getSCEV(U->getOperand(0)),
3112 getSCEV(U->getOperand(1)));
3113 case Instruction::Mul:
3114 // Don't transfer the NSW and NUW bits from the Mul instruction to the
3115 // Mul expression, as with Add.
3116 return getMulExpr(getSCEV(U->getOperand(0)),
3117 getSCEV(U->getOperand(1)));
3118 case Instruction::UDiv:
3119 return getUDivExpr(getSCEV(U->getOperand(0)),
3120 getSCEV(U->getOperand(1)));
3121 case Instruction::Sub:
3122 return getMinusSCEV(getSCEV(U->getOperand(0)),
3123 getSCEV(U->getOperand(1)));
3124 case Instruction::And:
3125 // For an expression like x&255 that merely masks off the high bits,
3126 // use zext(trunc(x)) as the SCEV expression.
3127 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3128 if (CI->isNullValue())
3129 return getSCEV(U->getOperand(1));
3130 if (CI->isAllOnesValue())
3131 return getSCEV(U->getOperand(0));
3132 const APInt &A = CI->getValue();
3134 // Instcombine's ShrinkDemandedConstant may strip bits out of
3135 // constants, obscuring what would otherwise be a low-bits mask.
3136 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3137 // knew about to reconstruct a low-bits mask value.
3138 unsigned LZ = A.countLeadingZeros();
3139 unsigned BitWidth = A.getBitWidth();
3140 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3141 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3142 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3144 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3146 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
3148 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
3149 IntegerType::get(getContext(), BitWidth - LZ)),
3154 case Instruction::Or:
3155 // If the RHS of the Or is a constant, we may have something like:
3156 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3157 // optimizations will transparently handle this case.
3159 // In order for this transformation to be safe, the LHS must be of the
3160 // form X*(2^n) and the Or constant must be less than 2^n.
3161 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3162 const SCEV *LHS = getSCEV(U->getOperand(0));
3163 const APInt &CIVal = CI->getValue();
3164 if (GetMinTrailingZeros(LHS) >=
3165 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3166 // Build a plain add SCEV.
3167 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3168 // If the LHS of the add was an addrec and it has no-wrap flags,
3169 // transfer the no-wrap flags, since an or won't introduce a wrap.
3170 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3171 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
3172 if (OldAR->hasNoUnsignedWrap())
3173 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoUnsignedWrap(true);
3174 if (OldAR->hasNoSignedWrap())
3175 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoSignedWrap(true);
3181 case Instruction::Xor:
3182 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3183 // If the RHS of the xor is a signbit, then this is just an add.
3184 // Instcombine turns add of signbit into xor as a strength reduction step.
3185 if (CI->getValue().isSignBit())
3186 return getAddExpr(getSCEV(U->getOperand(0)),
3187 getSCEV(U->getOperand(1)));
3189 // If the RHS of xor is -1, then this is a not operation.
3190 if (CI->isAllOnesValue())
3191 return getNotSCEV(getSCEV(U->getOperand(0)));
3193 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3194 // This is a variant of the check for xor with -1, and it handles
3195 // the case where instcombine has trimmed non-demanded bits out
3196 // of an xor with -1.
3197 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3198 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3199 if (BO->getOpcode() == Instruction::And &&
3200 LCI->getValue() == CI->getValue())
3201 if (const SCEVZeroExtendExpr *Z =
3202 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
3203 const Type *UTy = U->getType();
3204 const SCEV *Z0 = Z->getOperand();
3205 const Type *Z0Ty = Z0->getType();
3206 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3208 // If C is a low-bits mask, the zero extend is zerving to
3209 // mask off the high bits. Complement the operand and
3210 // re-apply the zext.
3211 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3212 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3214 // If C is a single bit, it may be in the sign-bit position
3215 // before the zero-extend. In this case, represent the xor
3216 // using an add, which is equivalent, and re-apply the zext.
3217 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
3218 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3220 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3226 case Instruction::Shl:
3227 // Turn shift left of a constant amount into a multiply.
3228 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3229 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
3230 Constant *X = ConstantInt::get(getContext(),
3231 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
3232 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3236 case Instruction::LShr:
3237 // Turn logical shift right of a constant into a unsigned divide.
3238 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3239 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
3240 Constant *X = ConstantInt::get(getContext(),
3241 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
3242 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3246 case Instruction::AShr:
3247 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3248 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
3249 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
3250 if (L->getOpcode() == Instruction::Shl &&
3251 L->getOperand(1) == U->getOperand(1)) {
3252 unsigned BitWidth = getTypeSizeInBits(U->getType());
3253 uint64_t Amt = BitWidth - CI->getZExtValue();
3254 if (Amt == BitWidth)
3255 return getSCEV(L->getOperand(0)); // shift by zero --> noop
3257 return getIntegerSCEV(0, U->getType()); // value is undefined
3259 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
3260 IntegerType::get(getContext(), Amt)),
3265 case Instruction::Trunc:
3266 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
3268 case Instruction::ZExt:
3269 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3271 case Instruction::SExt:
3272 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3274 case Instruction::BitCast:
3275 // BitCasts are no-op casts so we just eliminate the cast.
3276 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
3277 return getSCEV(U->getOperand(0));
3280 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3281 // lead to pointer expressions which cannot safely be expanded to GEPs,
3282 // because ScalarEvolution doesn't respect the GEP aliasing rules when
3283 // simplifying integer expressions.
3285 case Instruction::GetElementPtr:
3286 return createNodeForGEP(cast<GEPOperator>(U));
3288 case Instruction::PHI:
3289 return createNodeForPHI(cast<PHINode>(U));
3291 case Instruction::Select:
3292 // This could be a smax or umax that was lowered earlier.
3293 // Try to recover it.
3294 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3295 Value *LHS = ICI->getOperand(0);
3296 Value *RHS = ICI->getOperand(1);
3297 switch (ICI->getPredicate()) {
3298 case ICmpInst::ICMP_SLT:
3299 case ICmpInst::ICMP_SLE:
3300 std::swap(LHS, RHS);
3302 case ICmpInst::ICMP_SGT:
3303 case ICmpInst::ICMP_SGE:
3304 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
3305 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
3306 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
3307 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
3309 case ICmpInst::ICMP_ULT:
3310 case ICmpInst::ICMP_ULE:
3311 std::swap(LHS, RHS);
3313 case ICmpInst::ICMP_UGT:
3314 case ICmpInst::ICMP_UGE:
3315 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
3316 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
3317 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
3318 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
3320 case ICmpInst::ICMP_NE:
3321 // n != 0 ? n : 1 -> umax(n, 1)
3322 if (LHS == U->getOperand(1) &&
3323 isa<ConstantInt>(U->getOperand(2)) &&
3324 cast<ConstantInt>(U->getOperand(2))->isOne() &&
3325 isa<ConstantInt>(RHS) &&
3326 cast<ConstantInt>(RHS)->isZero())
3327 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
3329 case ICmpInst::ICMP_EQ:
3330 // n == 0 ? 1 : n -> umax(n, 1)
3331 if (LHS == U->getOperand(2) &&
3332 isa<ConstantInt>(U->getOperand(1)) &&
3333 cast<ConstantInt>(U->getOperand(1))->isOne() &&
3334 isa<ConstantInt>(RHS) &&
3335 cast<ConstantInt>(RHS)->isZero())
3336 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
3343 default: // We cannot analyze this expression.
3347 return getUnknown(V);
3352 //===----------------------------------------------------------------------===//
3353 // Iteration Count Computation Code
3356 /// getBackedgeTakenCount - If the specified loop has a predictable
3357 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3358 /// object. The backedge-taken count is the number of times the loop header
3359 /// will be branched to from within the loop. This is one less than the
3360 /// trip count of the loop, since it doesn't count the first iteration,
3361 /// when the header is branched to from outside the loop.
3363 /// Note that it is not valid to call this method on a loop without a
3364 /// loop-invariant backedge-taken count (see
3365 /// hasLoopInvariantBackedgeTakenCount).
3367 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
3368 return getBackedgeTakenInfo(L).Exact;
3371 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3372 /// return the least SCEV value that is known never to be less than the
3373 /// actual backedge taken count.
3374 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
3375 return getBackedgeTakenInfo(L).Max;
3378 /// PushLoopPHIs - Push PHI nodes in the header of the given loop
3379 /// onto the given Worklist.
3381 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3382 BasicBlock *Header = L->getHeader();
3384 // Push all Loop-header PHIs onto the Worklist stack.
3385 for (BasicBlock::iterator I = Header->begin();
3386 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3387 Worklist.push_back(PN);
3390 const ScalarEvolution::BackedgeTakenInfo &
3391 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
3392 // Initially insert a CouldNotCompute for this loop. If the insertion
3393 // succeeds, procede to actually compute a backedge-taken count and
3394 // update the value. The temporary CouldNotCompute value tells SCEV
3395 // code elsewhere that it shouldn't attempt to request a new
3396 // backedge-taken count, which could result in infinite recursion.
3397 std::pair<std::map<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
3398 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3400 BackedgeTakenInfo BECount = ComputeBackedgeTakenCount(L);
3401 if (BECount.Exact != getCouldNotCompute()) {
3402 assert(BECount.Exact->isLoopInvariant(L) &&
3403 BECount.Max->isLoopInvariant(L) &&
3404 "Computed backedge-taken count isn't loop invariant for loop!");
3405 ++NumTripCountsComputed;
3407 // Update the value in the map.
3408 Pair.first->second = BECount;
3410 if (BECount.Max != getCouldNotCompute())
3411 // Update the value in the map.
3412 Pair.first->second = BECount;
3413 if (isa<PHINode>(L->getHeader()->begin()))
3414 // Only count loops that have phi nodes as not being computable.
3415 ++NumTripCountsNotComputed;
3418 // Now that we know more about the trip count for this loop, forget any
3419 // existing SCEV values for PHI nodes in this loop since they are only
3420 // conservative estimates made without the benefit of trip count
3421 // information. This is similar to the code in forgetLoop, except that
3422 // it handles SCEVUnknown PHI nodes specially.
3423 if (BECount.hasAnyInfo()) {
3424 SmallVector<Instruction *, 16> Worklist;
3425 PushLoopPHIs(L, Worklist);
3427 SmallPtrSet<Instruction *, 8> Visited;
3428 while (!Worklist.empty()) {
3429 Instruction *I = Worklist.pop_back_val();
3430 if (!Visited.insert(I)) continue;
3432 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3433 Scalars.find(static_cast<Value *>(I));
3434 if (It != Scalars.end()) {
3435 // SCEVUnknown for a PHI either means that it has an unrecognized
3436 // structure, or it's a PHI that's in the progress of being computed
3437 // by createNodeForPHI. In the former case, additional loop trip
3438 // count information isn't going to change anything. In the later
3439 // case, createNodeForPHI will perform the necessary updates on its
3440 // own when it gets to that point.
3441 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
3442 ValuesAtScopes.erase(It->second);
3445 if (PHINode *PN = dyn_cast<PHINode>(I))
3446 ConstantEvolutionLoopExitValue.erase(PN);
3449 PushDefUseChildren(I, Worklist);
3453 return Pair.first->second;
3456 /// forgetLoop - This method should be called by the client when it has
3457 /// changed a loop in a way that may effect ScalarEvolution's ability to
3458 /// compute a trip count, or if the loop is deleted.
3459 void ScalarEvolution::forgetLoop(const Loop *L) {
3460 // Drop any stored trip count value.
3461 BackedgeTakenCounts.erase(L);
3463 // Drop information about expressions based on loop-header PHIs.
3464 SmallVector<Instruction *, 16> Worklist;
3465 PushLoopPHIs(L, Worklist);
3467 SmallPtrSet<Instruction *, 8> Visited;
3468 while (!Worklist.empty()) {
3469 Instruction *I = Worklist.pop_back_val();
3470 if (!Visited.insert(I)) continue;
3472 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3473 Scalars.find(static_cast<Value *>(I));
3474 if (It != Scalars.end()) {
3475 ValuesAtScopes.erase(It->second);
3477 if (PHINode *PN = dyn_cast<PHINode>(I))
3478 ConstantEvolutionLoopExitValue.erase(PN);
3481 PushDefUseChildren(I, Worklist);
3485 /// forgetValue - This method should be called by the client when it has
3486 /// changed a value in a way that may effect its value, or which may
3487 /// disconnect it from a def-use chain linking it to a loop.
3488 void ScalarEvolution::forgetValue(Value *V) {
3489 Instruction *I = dyn_cast<Instruction>(V);
3492 // Drop information about expressions based on loop-header PHIs.
3493 SmallVector<Instruction *, 16> Worklist;
3494 Worklist.push_back(I);
3496 SmallPtrSet<Instruction *, 8> Visited;
3497 while (!Worklist.empty()) {
3498 I = Worklist.pop_back_val();
3499 if (!Visited.insert(I)) continue;
3501 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3502 Scalars.find(static_cast<Value *>(I));
3503 if (It != Scalars.end()) {
3504 ValuesAtScopes.erase(It->second);
3506 if (PHINode *PN = dyn_cast<PHINode>(I))
3507 ConstantEvolutionLoopExitValue.erase(PN);
3510 PushDefUseChildren(I, Worklist);
3514 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
3515 /// of the specified loop will execute.
3516 ScalarEvolution::BackedgeTakenInfo
3517 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
3518 SmallVector<BasicBlock *, 8> ExitingBlocks;
3519 L->getExitingBlocks(ExitingBlocks);
3521 // Examine all exits and pick the most conservative values.
3522 const SCEV *BECount = getCouldNotCompute();
3523 const SCEV *MaxBECount = getCouldNotCompute();
3524 bool CouldNotComputeBECount = false;
3525 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3526 BackedgeTakenInfo NewBTI =
3527 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
3529 if (NewBTI.Exact == getCouldNotCompute()) {
3530 // We couldn't compute an exact value for this exit, so
3531 // we won't be able to compute an exact value for the loop.
3532 CouldNotComputeBECount = true;
3533 BECount = getCouldNotCompute();
3534 } else if (!CouldNotComputeBECount) {
3535 if (BECount == getCouldNotCompute())
3536 BECount = NewBTI.Exact;
3538 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
3540 if (MaxBECount == getCouldNotCompute())
3541 MaxBECount = NewBTI.Max;
3542 else if (NewBTI.Max != getCouldNotCompute())
3543 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
3546 return BackedgeTakenInfo(BECount, MaxBECount);
3549 /// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3550 /// of the specified loop will execute if it exits via the specified block.
3551 ScalarEvolution::BackedgeTakenInfo
3552 ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3553 BasicBlock *ExitingBlock) {
3555 // Okay, we've chosen an exiting block. See what condition causes us to
3556 // exit at this block.
3558 // FIXME: we should be able to handle switch instructions (with a single exit)
3559 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
3560 if (ExitBr == 0) return getCouldNotCompute();
3561 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
3563 // At this point, we know we have a conditional branch that determines whether
3564 // the loop is exited. However, we don't know if the branch is executed each
3565 // time through the loop. If not, then the execution count of the branch will
3566 // not be equal to the trip count of the loop.
3568 // Currently we check for this by checking to see if the Exit branch goes to
3569 // the loop header. If so, we know it will always execute the same number of
3570 // times as the loop. We also handle the case where the exit block *is* the
3571 // loop header. This is common for un-rotated loops.
3573 // If both of those tests fail, walk up the unique predecessor chain to the
3574 // header, stopping if there is an edge that doesn't exit the loop. If the
3575 // header is reached, the execution count of the branch will be equal to the
3576 // trip count of the loop.
3578 // More extensive analysis could be done to handle more cases here.
3580 if (ExitBr->getSuccessor(0) != L->getHeader() &&
3581 ExitBr->getSuccessor(1) != L->getHeader() &&
3582 ExitBr->getParent() != L->getHeader()) {
3583 // The simple checks failed, try climbing the unique predecessor chain
3584 // up to the header.
3586 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3587 BasicBlock *Pred = BB->getUniquePredecessor();
3589 return getCouldNotCompute();
3590 TerminatorInst *PredTerm = Pred->getTerminator();
3591 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3592 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3595 // If the predecessor has a successor that isn't BB and isn't
3596 // outside the loop, assume the worst.
3597 if (L->contains(PredSucc))
3598 return getCouldNotCompute();
3600 if (Pred == L->getHeader()) {
3607 return getCouldNotCompute();
3610 // Procede to the next level to examine the exit condition expression.
3611 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3612 ExitBr->getSuccessor(0),
3613 ExitBr->getSuccessor(1));
3616 /// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3617 /// backedge of the specified loop will execute if its exit condition
3618 /// were a conditional branch of ExitCond, TBB, and FBB.
3619 ScalarEvolution::BackedgeTakenInfo
3620 ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3624 // Check if the controlling expression for this loop is an And or Or.
3625 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3626 if (BO->getOpcode() == Instruction::And) {
3627 // Recurse on the operands of the and.
3628 BackedgeTakenInfo BTI0 =
3629 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3630 BackedgeTakenInfo BTI1 =
3631 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3632 const SCEV *BECount = getCouldNotCompute();
3633 const SCEV *MaxBECount = getCouldNotCompute();
3634 if (L->contains(TBB)) {
3635 // Both conditions must be true for the loop to continue executing.
3636 // Choose the less conservative count.
3637 if (BTI0.Exact == getCouldNotCompute() ||
3638 BTI1.Exact == getCouldNotCompute())
3639 BECount = getCouldNotCompute();
3641 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3642 if (BTI0.Max == getCouldNotCompute())
3643 MaxBECount = BTI1.Max;
3644 else if (BTI1.Max == getCouldNotCompute())
3645 MaxBECount = BTI0.Max;
3647 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3649 // Both conditions must be true for the loop to exit.
3650 assert(L->contains(FBB) && "Loop block has no successor in loop!");
3651 if (BTI0.Exact != getCouldNotCompute() &&
3652 BTI1.Exact != getCouldNotCompute())
3653 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3654 if (BTI0.Max != getCouldNotCompute() &&
3655 BTI1.Max != getCouldNotCompute())
3656 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3659 return BackedgeTakenInfo(BECount, MaxBECount);
3661 if (BO->getOpcode() == Instruction::Or) {
3662 // Recurse on the operands of the or.
3663 BackedgeTakenInfo BTI0 =
3664 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3665 BackedgeTakenInfo BTI1 =
3666 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3667 const SCEV *BECount = getCouldNotCompute();
3668 const SCEV *MaxBECount = getCouldNotCompute();
3669 if (L->contains(FBB)) {
3670 // Both conditions must be false for the loop to continue executing.
3671 // Choose the less conservative count.
3672 if (BTI0.Exact == getCouldNotCompute() ||
3673 BTI1.Exact == getCouldNotCompute())
3674 BECount = getCouldNotCompute();
3676 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3677 if (BTI0.Max == getCouldNotCompute())
3678 MaxBECount = BTI1.Max;
3679 else if (BTI1.Max == getCouldNotCompute())
3680 MaxBECount = BTI0.Max;
3682 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3684 // Both conditions must be false for the loop to exit.
3685 assert(L->contains(TBB) && "Loop block has no successor in loop!");
3686 if (BTI0.Exact != getCouldNotCompute() &&
3687 BTI1.Exact != getCouldNotCompute())
3688 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3689 if (BTI0.Max != getCouldNotCompute() &&
3690 BTI1.Max != getCouldNotCompute())
3691 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3694 return BackedgeTakenInfo(BECount, MaxBECount);
3698 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3699 // Procede to the next level to examine the icmp.
3700 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3701 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
3703 // Check for a constant condition. These are normally stripped out by
3704 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
3705 // preserve the CFG and is temporarily leaving constant conditions
3707 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
3708 if (L->contains(FBB) == !CI->getZExtValue())
3709 // The backedge is always taken.
3710 return getCouldNotCompute();
3712 // The backedge is never taken.
3713 return getIntegerSCEV(0, CI->getType());
3716 // If it's not an integer or pointer comparison then compute it the hard way.
3717 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3720 /// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3721 /// backedge of the specified loop will execute if its exit condition
3722 /// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3723 ScalarEvolution::BackedgeTakenInfo
3724 ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3729 // If the condition was exit on true, convert the condition to exit on false
3730 ICmpInst::Predicate Cond;
3731 if (!L->contains(FBB))
3732 Cond = ExitCond->getPredicate();
3734 Cond = ExitCond->getInversePredicate();
3736 // Handle common loops like: for (X = "string"; *X; ++X)
3737 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3738 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
3739 BackedgeTakenInfo ItCnt =
3740 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
3741 if (ItCnt.hasAnyInfo())
3745 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3746 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
3748 // Try to evaluate any dependencies out of the loop.
3749 LHS = getSCEVAtScope(LHS, L);
3750 RHS = getSCEVAtScope(RHS, L);
3752 // At this point, we would like to compute how many iterations of the
3753 // loop the predicate will return true for these inputs.
3754 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3755 // If there is a loop-invariant, force it into the RHS.
3756 std::swap(LHS, RHS);
3757 Cond = ICmpInst::getSwappedPredicate(Cond);
3760 // If we have a comparison of a chrec against a constant, try to use value
3761 // ranges to answer this query.
3762 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3763 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
3764 if (AddRec->getLoop() == L) {
3765 // Form the constant range.
3766 ConstantRange CompRange(
3767 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
3769 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
3770 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
3774 case ICmpInst::ICMP_NE: { // while (X != Y)
3775 // Convert to: while (X-Y != 0)
3776 BackedgeTakenInfo BTI = HowFarToZero(getMinusSCEV(LHS, RHS), L);
3777 if (BTI.hasAnyInfo()) return BTI;
3780 case ICmpInst::ICMP_EQ: { // while (X == Y)
3781 // Convert to: while (X-Y == 0)
3782 BackedgeTakenInfo BTI = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
3783 if (BTI.hasAnyInfo()) return BTI;
3786 case ICmpInst::ICMP_SLT: {
3787 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3788 if (BTI.hasAnyInfo()) return BTI;
3791 case ICmpInst::ICMP_SGT: {
3792 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3793 getNotSCEV(RHS), L, true);
3794 if (BTI.hasAnyInfo()) return BTI;
3797 case ICmpInst::ICMP_ULT: {
3798 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3799 if (BTI.hasAnyInfo()) return BTI;
3802 case ICmpInst::ICMP_UGT: {
3803 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3804 getNotSCEV(RHS), L, false);
3805 if (BTI.hasAnyInfo()) return BTI;
3810 dbgs() << "ComputeBackedgeTakenCount ";
3811 if (ExitCond->getOperand(0)->getType()->isUnsigned())
3812 dbgs() << "[unsigned] ";
3813 dbgs() << *LHS << " "
3814 << Instruction::getOpcodeName(Instruction::ICmp)
3815 << " " << *RHS << "\n";
3820 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3823 static ConstantInt *
3824 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3825 ScalarEvolution &SE) {
3826 const SCEV *InVal = SE.getConstant(C);
3827 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
3828 assert(isa<SCEVConstant>(Val) &&
3829 "Evaluation of SCEV at constant didn't fold correctly?");
3830 return cast<SCEVConstant>(Val)->getValue();
3833 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
3834 /// and a GEP expression (missing the pointer index) indexing into it, return
3835 /// the addressed element of the initializer or null if the index expression is
3838 GetAddressedElementFromGlobal(GlobalVariable *GV,
3839 const std::vector<ConstantInt*> &Indices) {
3840 Constant *Init = GV->getInitializer();
3841 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
3842 uint64_t Idx = Indices[i]->getZExtValue();
3843 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3844 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3845 Init = cast<Constant>(CS->getOperand(Idx));
3846 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3847 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3848 Init = cast<Constant>(CA->getOperand(Idx));
3849 } else if (isa<ConstantAggregateZero>(Init)) {
3850 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3851 assert(Idx < STy->getNumElements() && "Bad struct index!");
3852 Init = Constant::getNullValue(STy->getElementType(Idx));
3853 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3854 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
3855 Init = Constant::getNullValue(ATy->getElementType());
3857 llvm_unreachable("Unknown constant aggregate type!");
3861 return 0; // Unknown initializer type
3867 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3868 /// 'icmp op load X, cst', try to see if we can compute the backedge
3869 /// execution count.
3870 ScalarEvolution::BackedgeTakenInfo
3871 ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3875 ICmpInst::Predicate predicate) {
3876 if (LI->isVolatile()) return getCouldNotCompute();
3878 // Check to see if the loaded pointer is a getelementptr of a global.
3879 // TODO: Use SCEV instead of manually grubbing with GEPs.
3880 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
3881 if (!GEP) return getCouldNotCompute();
3883 // Make sure that it is really a constant global we are gepping, with an
3884 // initializer, and make sure the first IDX is really 0.
3885 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
3886 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
3887 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3888 !cast<Constant>(GEP->getOperand(1))->isNullValue())
3889 return getCouldNotCompute();
3891 // Okay, we allow one non-constant index into the GEP instruction.
3893 std::vector<ConstantInt*> Indexes;
3894 unsigned VarIdxNum = 0;
3895 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3896 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3897 Indexes.push_back(CI);
3898 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
3899 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
3900 VarIdx = GEP->getOperand(i);
3902 Indexes.push_back(0);
3905 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3906 // Check to see if X is a loop variant variable value now.
3907 const SCEV *Idx = getSCEV(VarIdx);
3908 Idx = getSCEVAtScope(Idx, L);
3910 // We can only recognize very limited forms of loop index expressions, in
3911 // particular, only affine AddRec's like {C1,+,C2}.
3912 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
3913 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3914 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3915 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
3916 return getCouldNotCompute();
3918 unsigned MaxSteps = MaxBruteForceIterations;
3919 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
3920 ConstantInt *ItCst = ConstantInt::get(
3921 cast<IntegerType>(IdxExpr->getType()), IterationNum);
3922 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
3924 // Form the GEP offset.
3925 Indexes[VarIdxNum] = Val;
3927 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
3928 if (Result == 0) break; // Cannot compute!
3930 // Evaluate the condition for this iteration.
3931 Result = ConstantExpr::getICmp(predicate, Result, RHS);
3932 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
3933 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
3935 dbgs() << "\n***\n*** Computed loop count " << *ItCst
3936 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3939 ++NumArrayLenItCounts;
3940 return getConstant(ItCst); // Found terminating iteration!
3943 return getCouldNotCompute();
3947 /// CanConstantFold - Return true if we can constant fold an instruction of the
3948 /// specified type, assuming that all operands were constants.
3949 static bool CanConstantFold(const Instruction *I) {
3950 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
3951 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3954 if (const CallInst *CI = dyn_cast<CallInst>(I))
3955 if (const Function *F = CI->getCalledFunction())
3956 return canConstantFoldCallTo(F);
3960 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3961 /// in the loop that V is derived from. We allow arbitrary operations along the
3962 /// way, but the operands of an operation must either be constants or a value
3963 /// derived from a constant PHI. If this expression does not fit with these
3964 /// constraints, return null.
3965 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3966 // If this is not an instruction, or if this is an instruction outside of the
3967 // loop, it can't be derived from a loop PHI.
3968 Instruction *I = dyn_cast<Instruction>(V);
3969 if (I == 0 || !L->contains(I)) return 0;
3971 if (PHINode *PN = dyn_cast<PHINode>(I)) {
3972 if (L->getHeader() == I->getParent())
3975 // We don't currently keep track of the control flow needed to evaluate
3976 // PHIs, so we cannot handle PHIs inside of loops.
3980 // If we won't be able to constant fold this expression even if the operands
3981 // are constants, return early.
3982 if (!CanConstantFold(I)) return 0;
3984 // Otherwise, we can evaluate this instruction if all of its operands are
3985 // constant or derived from a PHI node themselves.
3987 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3988 if (!(isa<Constant>(I->getOperand(Op)) ||
3989 isa<GlobalValue>(I->getOperand(Op)))) {
3990 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3991 if (P == 0) return 0; // Not evolving from PHI
3995 return 0; // Evolving from multiple different PHIs.
3998 // This is a expression evolving from a constant PHI!
4002 /// EvaluateExpression - Given an expression that passes the
4003 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
4004 /// in the loop has the value PHIVal. If we can't fold this expression for some
4005 /// reason, return null.
4006 static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
4007 const TargetData *TD) {
4008 if (isa<PHINode>(V)) return PHIVal;
4009 if (Constant *C = dyn_cast<Constant>(V)) return C;
4010 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
4011 Instruction *I = cast<Instruction>(V);
4013 std::vector<Constant*> Operands;
4014 Operands.resize(I->getNumOperands());
4016 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4017 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
4018 if (Operands[i] == 0) return 0;
4021 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4022 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
4024 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4025 &Operands[0], Operands.size(), TD);
4028 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
4029 /// in the header of its containing loop, we know the loop executes a
4030 /// constant number of times, and the PHI node is just a recurrence
4031 /// involving constants, fold it.
4033 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
4036 std::map<PHINode*, Constant*>::iterator I =
4037 ConstantEvolutionLoopExitValue.find(PN);
4038 if (I != ConstantEvolutionLoopExitValue.end())
4041 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
4042 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
4044 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
4046 // Since the loop is canonicalized, the PHI node must have two entries. One
4047 // entry must be a constant (coming in from outside of the loop), and the
4048 // second must be derived from the same PHI.
4049 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4050 Constant *StartCST =
4051 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4053 return RetVal = 0; // Must be a constant.
4055 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4056 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
4058 return RetVal = 0; // Not derived from same PHI.
4060 // Execute the loop symbolically to determine the exit value.
4061 if (BEs.getActiveBits() >= 32)
4062 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
4064 unsigned NumIterations = BEs.getZExtValue(); // must be in range
4065 unsigned IterationNum = 0;
4066 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
4067 if (IterationNum == NumIterations)
4068 return RetVal = PHIVal; // Got exit value!
4070 // Compute the value of the PHI node for the next iteration.
4071 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
4072 if (NextPHI == PHIVal)
4073 return RetVal = NextPHI; // Stopped evolving!
4075 return 0; // Couldn't evaluate!
4080 /// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
4081 /// constant number of times (the condition evolves only from constants),
4082 /// try to evaluate a few iterations of the loop until we get the exit
4083 /// condition gets a value of ExitWhen (true or false). If we cannot
4084 /// evaluate the trip count of the loop, return getCouldNotCompute().
4086 ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
4089 PHINode *PN = getConstantEvolvingPHI(Cond, L);
4090 if (PN == 0) return getCouldNotCompute();
4092 // Since the loop is canonicalized, the PHI node must have two entries. One
4093 // entry must be a constant (coming in from outside of the loop), and the
4094 // second must be derived from the same PHI.
4095 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4096 Constant *StartCST =
4097 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4098 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
4100 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4101 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
4102 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
4104 // Okay, we find a PHI node that defines the trip count of this loop. Execute
4105 // the loop symbolically to determine when the condition gets a value of
4107 unsigned IterationNum = 0;
4108 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
4109 for (Constant *PHIVal = StartCST;
4110 IterationNum != MaxIterations; ++IterationNum) {
4111 ConstantInt *CondVal =
4112 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
4114 // Couldn't symbolically evaluate.
4115 if (!CondVal) return getCouldNotCompute();
4117 if (CondVal->getValue() == uint64_t(ExitWhen)) {
4118 ++NumBruteForceTripCountsComputed;
4119 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
4122 // Compute the value of the PHI node for the next iteration.
4123 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
4124 if (NextPHI == 0 || NextPHI == PHIVal)
4125 return getCouldNotCompute();// Couldn't evaluate or not making progress...
4129 // Too many iterations were needed to evaluate.
4130 return getCouldNotCompute();
4133 /// getSCEVAtScope - Return a SCEV expression for the specified value
4134 /// at the specified scope in the program. The L value specifies a loop
4135 /// nest to evaluate the expression at, where null is the top-level or a
4136 /// specified loop is immediately inside of the loop.
4138 /// This method can be used to compute the exit value for a variable defined
4139 /// in a loop by querying what the value will hold in the parent loop.
4141 /// In the case that a relevant loop exit value cannot be computed, the
4142 /// original value V is returned.
4143 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
4144 // Check to see if we've folded this expression at this loop before.
4145 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4146 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4147 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4149 return Pair.first->second ? Pair.first->second : V;
4151 // Otherwise compute it.
4152 const SCEV *C = computeSCEVAtScope(V, L);
4153 ValuesAtScopes[V][L] = C;
4157 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
4158 if (isa<SCEVConstant>(V)) return V;
4160 // If this instruction is evolved from a constant-evolving PHI, compute the
4161 // exit value from the loop without using SCEVs.
4162 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
4163 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
4164 const Loop *LI = (*this->LI)[I->getParent()];
4165 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
4166 if (PHINode *PN = dyn_cast<PHINode>(I))
4167 if (PN->getParent() == LI->getHeader()) {
4168 // Okay, there is no closed form solution for the PHI node. Check
4169 // to see if the loop that contains it has a known backedge-taken
4170 // count. If so, we may be able to force computation of the exit
4172 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
4173 if (const SCEVConstant *BTCC =
4174 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
4175 // Okay, we know how many times the containing loop executes. If
4176 // this is a constant evolving PHI node, get the final value at
4177 // the specified iteration number.
4178 Constant *RV = getConstantEvolutionLoopExitValue(PN,
4179 BTCC->getValue()->getValue(),
4181 if (RV) return getSCEV(RV);
4185 // Okay, this is an expression that we cannot symbolically evaluate
4186 // into a SCEV. Check to see if it's possible to symbolically evaluate
4187 // the arguments into constants, and if so, try to constant propagate the
4188 // result. This is particularly useful for computing loop exit values.
4189 if (CanConstantFold(I)) {
4190 std::vector<Constant*> Operands;
4191 Operands.reserve(I->getNumOperands());
4192 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4193 Value *Op = I->getOperand(i);
4194 if (Constant *C = dyn_cast<Constant>(Op)) {
4195 Operands.push_back(C);
4197 // If any of the operands is non-constant and if they are
4198 // non-integer and non-pointer, don't even try to analyze them
4199 // with scev techniques.
4200 if (!isSCEVable(Op->getType()))
4203 const SCEV *OpV = getSCEVAtScope(Op, L);
4204 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
4205 Constant *C = SC->getValue();
4206 if (C->getType() != Op->getType())
4207 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4211 Operands.push_back(C);
4212 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
4213 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
4214 if (C->getType() != Op->getType())
4216 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4220 Operands.push_back(C);
4230 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4231 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
4232 Operands[0], Operands[1], TD);
4234 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4235 &Operands[0], Operands.size(), TD);
4240 // This is some other type of SCEVUnknown, just return it.
4244 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
4245 // Avoid performing the look-up in the common case where the specified
4246 // expression has no loop-variant portions.
4247 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
4248 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
4249 if (OpAtScope != Comm->getOperand(i)) {
4250 // Okay, at least one of these operands is loop variant but might be
4251 // foldable. Build a new instance of the folded commutative expression.
4252 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4253 Comm->op_begin()+i);
4254 NewOps.push_back(OpAtScope);
4256 for (++i; i != e; ++i) {
4257 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
4258 NewOps.push_back(OpAtScope);
4260 if (isa<SCEVAddExpr>(Comm))
4261 return getAddExpr(NewOps);
4262 if (isa<SCEVMulExpr>(Comm))
4263 return getMulExpr(NewOps);
4264 if (isa<SCEVSMaxExpr>(Comm))
4265 return getSMaxExpr(NewOps);
4266 if (isa<SCEVUMaxExpr>(Comm))
4267 return getUMaxExpr(NewOps);
4268 llvm_unreachable("Unknown commutative SCEV type!");
4271 // If we got here, all operands are loop invariant.
4275 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
4276 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4277 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
4278 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4279 return Div; // must be loop invariant
4280 return getUDivExpr(LHS, RHS);
4283 // If this is a loop recurrence for a loop that does not contain L, then we
4284 // are dealing with the final value computed by the loop.
4285 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4286 if (!L || !AddRec->getLoop()->contains(L)) {
4287 // To evaluate this recurrence, we need to know how many times the AddRec
4288 // loop iterates. Compute this now.
4289 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
4290 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
4292 // Then, evaluate the AddRec.
4293 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
4298 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
4299 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4300 if (Op == Cast->getOperand())
4301 return Cast; // must be loop invariant
4302 return getZeroExtendExpr(Op, Cast->getType());
4305 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
4306 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4307 if (Op == Cast->getOperand())
4308 return Cast; // must be loop invariant
4309 return getSignExtendExpr(Op, Cast->getType());
4312 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
4313 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4314 if (Op == Cast->getOperand())
4315 return Cast; // must be loop invariant
4316 return getTruncateExpr(Op, Cast->getType());
4319 llvm_unreachable("Unknown SCEV type!");
4323 /// getSCEVAtScope - This is a convenience function which does
4324 /// getSCEVAtScope(getSCEV(V), L).
4325 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
4326 return getSCEVAtScope(getSCEV(V), L);
4329 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4330 /// following equation:
4332 /// A * X = B (mod N)
4334 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4335 /// A and B isn't important.
4337 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
4338 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
4339 ScalarEvolution &SE) {
4340 uint32_t BW = A.getBitWidth();
4341 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4342 assert(A != 0 && "A must be non-zero.");
4346 // The gcd of A and N may have only one prime factor: 2. The number of
4347 // trailing zeros in A is its multiplicity
4348 uint32_t Mult2 = A.countTrailingZeros();
4351 // 2. Check if B is divisible by D.
4353 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4354 // is not less than multiplicity of this prime factor for D.
4355 if (B.countTrailingZeros() < Mult2)
4356 return SE.getCouldNotCompute();
4358 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4361 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4362 // bit width during computations.
4363 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4364 APInt Mod(BW + 1, 0);
4365 Mod.set(BW - Mult2); // Mod = N / D
4366 APInt I = AD.multiplicativeInverse(Mod);
4368 // 4. Compute the minimum unsigned root of the equation:
4369 // I * (B / D) mod (N / D)
4370 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4372 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4374 return SE.getConstant(Result.trunc(BW));
4377 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4378 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4379 /// might be the same) or two SCEVCouldNotCompute objects.
4381 static std::pair<const SCEV *,const SCEV *>
4382 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
4383 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
4384 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4385 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4386 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
4388 // We currently can only solve this if the coefficients are constants.
4389 if (!LC || !MC || !NC) {
4390 const SCEV *CNC = SE.getCouldNotCompute();
4391 return std::make_pair(CNC, CNC);
4394 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
4395 const APInt &L = LC->getValue()->getValue();
4396 const APInt &M = MC->getValue()->getValue();
4397 const APInt &N = NC->getValue()->getValue();
4398 APInt Two(BitWidth, 2);
4399 APInt Four(BitWidth, 4);
4402 using namespace APIntOps;
4404 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4405 // The B coefficient is M-N/2
4409 // The A coefficient is N/2
4410 APInt A(N.sdiv(Two));
4412 // Compute the B^2-4ac term.
4415 SqrtTerm -= Four * (A * C);
4417 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4418 // integer value or else APInt::sqrt() will assert.
4419 APInt SqrtVal(SqrtTerm.sqrt());
4421 // Compute the two solutions for the quadratic formula.
4422 // The divisions must be performed as signed divisions.
4424 APInt TwoA( A << 1 );
4425 if (TwoA.isMinValue()) {
4426 const SCEV *CNC = SE.getCouldNotCompute();
4427 return std::make_pair(CNC, CNC);
4430 LLVMContext &Context = SE.getContext();
4432 ConstantInt *Solution1 =
4433 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
4434 ConstantInt *Solution2 =
4435 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
4437 return std::make_pair(SE.getConstant(Solution1),
4438 SE.getConstant(Solution2));
4439 } // end APIntOps namespace
4442 /// HowFarToZero - Return the number of times a backedge comparing the specified
4443 /// value to zero will execute. If not computable, return CouldNotCompute.
4444 ScalarEvolution::BackedgeTakenInfo
4445 ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
4446 // If the value is a constant
4447 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
4448 // If the value is already zero, the branch will execute zero times.
4449 if (C->getValue()->isZero()) return C;
4450 return getCouldNotCompute(); // Otherwise it will loop infinitely.
4453 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
4454 if (!AddRec || AddRec->getLoop() != L)
4455 return getCouldNotCompute();
4457 if (AddRec->isAffine()) {
4458 // If this is an affine expression, the execution count of this branch is
4459 // the minimum unsigned root of the following equation:
4461 // Start + Step*N = 0 (mod 2^BW)
4465 // Step*N = -Start (mod 2^BW)
4467 // where BW is the common bit width of Start and Step.
4469 // Get the initial value for the loop.
4470 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4471 L->getParentLoop());
4472 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4473 L->getParentLoop());
4475 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
4476 // For now we handle only constant steps.
4478 // First, handle unitary steps.
4479 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
4480 return getNegativeSCEV(Start); // N = -Start (as unsigned)
4481 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4482 return Start; // N = Start (as unsigned)
4484 // Then, try to solve the above equation provided that Start is constant.
4485 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
4486 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
4487 -StartC->getValue()->getValue(),
4490 } else if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
4491 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4492 // the quadratic equation to solve it.
4493 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
4495 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4496 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
4499 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
4500 << " sol#2: " << *R2 << "\n";
4502 // Pick the smallest positive root value.
4503 if (ConstantInt *CB =
4504 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
4505 R1->getValue(), R2->getValue()))) {
4506 if (CB->getZExtValue() == false)
4507 std::swap(R1, R2); // R1 is the minimum root now.
4509 // We can only use this value if the chrec ends up with an exact zero
4510 // value at this index. When solving for "X*X != 5", for example, we
4511 // should not accept a root of 2.
4512 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
4514 return R1; // We found a quadratic root!
4519 return getCouldNotCompute();
4522 /// HowFarToNonZero - Return the number of times a backedge checking the
4523 /// specified value for nonzero will execute. If not computable, return
4525 ScalarEvolution::BackedgeTakenInfo
4526 ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
4527 // Loops that look like: while (X == 0) are very strange indeed. We don't
4528 // handle them yet except for the trivial case. This could be expanded in the
4529 // future as needed.
4531 // If the value is a constant, check to see if it is known to be non-zero
4532 // already. If so, the backedge will execute zero times.
4533 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
4534 if (!C->getValue()->isNullValue())
4535 return getIntegerSCEV(0, C->getType());
4536 return getCouldNotCompute(); // Otherwise it will loop infinitely.
4539 // We could implement others, but I really doubt anyone writes loops like
4540 // this, and if they did, they would already be constant folded.
4541 return getCouldNotCompute();
4544 /// getLoopPredecessor - If the given loop's header has exactly one unique
4545 /// predecessor outside the loop, return it. Otherwise return null.
4547 BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
4548 BasicBlock *Header = L->getHeader();
4549 BasicBlock *Pred = 0;
4550 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
4552 if (!L->contains(*PI)) {
4553 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
4559 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4560 /// (which may not be an immediate predecessor) which has exactly one
4561 /// successor from which BB is reachable, or null if no such block is
4565 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
4566 // If the block has a unique predecessor, then there is no path from the
4567 // predecessor to the block that does not go through the direct edge
4568 // from the predecessor to the block.
4569 if (BasicBlock *Pred = BB->getSinglePredecessor())
4572 // A loop's header is defined to be a block that dominates the loop.
4573 // If the header has a unique predecessor outside the loop, it must be
4574 // a block that has exactly one successor that can reach the loop.
4575 if (Loop *L = LI->getLoopFor(BB))
4576 return getLoopPredecessor(L);
4581 /// HasSameValue - SCEV structural equivalence is usually sufficient for
4582 /// testing whether two expressions are equal, however for the purposes of
4583 /// looking for a condition guarding a loop, it can be useful to be a little
4584 /// more general, since a front-end may have replicated the controlling
4587 static bool HasSameValue(const SCEV *A, const SCEV *B) {
4588 // Quick check to see if they are the same SCEV.
4589 if (A == B) return true;
4591 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4592 // two different instructions with the same value. Check for this case.
4593 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4594 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4595 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4596 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
4597 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
4600 // Otherwise assume they may have a different value.
4604 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
4605 return getSignedRange(S).getSignedMax().isNegative();
4608 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
4609 return getSignedRange(S).getSignedMin().isStrictlyPositive();
4612 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
4613 return !getSignedRange(S).getSignedMin().isNegative();
4616 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
4617 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
4620 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
4621 return isKnownNegative(S) || isKnownPositive(S);
4624 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
4625 const SCEV *LHS, const SCEV *RHS) {
4627 if (HasSameValue(LHS, RHS))
4628 return ICmpInst::isTrueWhenEqual(Pred);
4632 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4634 case ICmpInst::ICMP_SGT:
4635 Pred = ICmpInst::ICMP_SLT;
4636 std::swap(LHS, RHS);
4637 case ICmpInst::ICMP_SLT: {
4638 ConstantRange LHSRange = getSignedRange(LHS);
4639 ConstantRange RHSRange = getSignedRange(RHS);
4640 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
4642 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
4646 case ICmpInst::ICMP_SGE:
4647 Pred = ICmpInst::ICMP_SLE;
4648 std::swap(LHS, RHS);
4649 case ICmpInst::ICMP_SLE: {
4650 ConstantRange LHSRange = getSignedRange(LHS);
4651 ConstantRange RHSRange = getSignedRange(RHS);
4652 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
4654 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
4658 case ICmpInst::ICMP_UGT:
4659 Pred = ICmpInst::ICMP_ULT;
4660 std::swap(LHS, RHS);
4661 case ICmpInst::ICMP_ULT: {
4662 ConstantRange LHSRange = getUnsignedRange(LHS);
4663 ConstantRange RHSRange = getUnsignedRange(RHS);
4664 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
4666 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
4670 case ICmpInst::ICMP_UGE:
4671 Pred = ICmpInst::ICMP_ULE;
4672 std::swap(LHS, RHS);
4673 case ICmpInst::ICMP_ULE: {
4674 ConstantRange LHSRange = getUnsignedRange(LHS);
4675 ConstantRange RHSRange = getUnsignedRange(RHS);
4676 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
4678 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
4682 case ICmpInst::ICMP_NE: {
4683 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
4685 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
4688 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4689 if (isKnownNonZero(Diff))
4693 case ICmpInst::ICMP_EQ:
4694 // The check at the top of the function catches the case where
4695 // the values are known to be equal.
4701 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
4702 /// protected by a conditional between LHS and RHS. This is used to
4703 /// to eliminate casts.
4705 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
4706 ICmpInst::Predicate Pred,
4707 const SCEV *LHS, const SCEV *RHS) {
4708 // Interpret a null as meaning no loop, where there is obviously no guard
4709 // (interprocedural conditions notwithstanding).
4710 if (!L) return true;
4712 BasicBlock *Latch = L->getLoopLatch();
4716 BranchInst *LoopContinuePredicate =
4717 dyn_cast<BranchInst>(Latch->getTerminator());
4718 if (!LoopContinuePredicate ||
4719 LoopContinuePredicate->isUnconditional())
4722 return isImpliedCond(LoopContinuePredicate->getCondition(), Pred, LHS, RHS,
4723 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
4726 /// isLoopGuardedByCond - Test whether entry to the loop is protected
4727 /// by a conditional between LHS and RHS. This is used to help avoid max
4728 /// expressions in loop trip counts, and to eliminate casts.
4730 ScalarEvolution::isLoopGuardedByCond(const Loop *L,
4731 ICmpInst::Predicate Pred,
4732 const SCEV *LHS, const SCEV *RHS) {
4733 // Interpret a null as meaning no loop, where there is obviously no guard
4734 // (interprocedural conditions notwithstanding).
4735 if (!L) return false;
4737 BasicBlock *Predecessor = getLoopPredecessor(L);
4738 BasicBlock *PredecessorDest = L->getHeader();
4740 // Starting at the loop predecessor, climb up the predecessor chain, as long
4741 // as there are predecessors that can be found that have unique successors
4742 // leading to the original header.
4744 PredecessorDest = Predecessor,
4745 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
4747 BranchInst *LoopEntryPredicate =
4748 dyn_cast<BranchInst>(Predecessor->getTerminator());
4749 if (!LoopEntryPredicate ||
4750 LoopEntryPredicate->isUnconditional())
4753 if (isImpliedCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
4754 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
4761 /// isImpliedCond - Test whether the condition described by Pred, LHS,
4762 /// and RHS is true whenever the given Cond value evaluates to true.
4763 bool ScalarEvolution::isImpliedCond(Value *CondValue,
4764 ICmpInst::Predicate Pred,
4765 const SCEV *LHS, const SCEV *RHS,
4767 // Recursivly handle And and Or conditions.
4768 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
4769 if (BO->getOpcode() == Instruction::And) {
4771 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4772 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4773 } else if (BO->getOpcode() == Instruction::Or) {
4775 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4776 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4780 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
4781 if (!ICI) return false;
4783 // Bail if the ICmp's operands' types are wider than the needed type
4784 // before attempting to call getSCEV on them. This avoids infinite
4785 // recursion, since the analysis of widening casts can require loop
4786 // exit condition information for overflow checking, which would
4788 if (getTypeSizeInBits(LHS->getType()) <
4789 getTypeSizeInBits(ICI->getOperand(0)->getType()))
4792 // Now that we found a conditional branch that dominates the loop, check to
4793 // see if it is the comparison we are looking for.
4794 ICmpInst::Predicate FoundPred;
4796 FoundPred = ICI->getInversePredicate();
4798 FoundPred = ICI->getPredicate();
4800 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
4801 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
4803 // Balance the types. The case where FoundLHS' type is wider than
4804 // LHS' type is checked for above.
4805 if (getTypeSizeInBits(LHS->getType()) >
4806 getTypeSizeInBits(FoundLHS->getType())) {
4807 if (CmpInst::isSigned(Pred)) {
4808 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
4809 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
4811 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
4812 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
4816 // Canonicalize the query to match the way instcombine will have
4817 // canonicalized the comparison.
4818 // First, put a constant operand on the right.
4819 if (isa<SCEVConstant>(LHS)) {
4820 std::swap(LHS, RHS);
4821 Pred = ICmpInst::getSwappedPredicate(Pred);
4823 // Then, canonicalize comparisons with boundary cases.
4824 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4825 const APInt &RA = RC->getValue()->getValue();
4827 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4828 case ICmpInst::ICMP_EQ:
4829 case ICmpInst::ICMP_NE:
4831 case ICmpInst::ICMP_UGE:
4832 if ((RA - 1).isMinValue()) {
4833 Pred = ICmpInst::ICMP_NE;
4834 RHS = getConstant(RA - 1);
4837 if (RA.isMaxValue()) {
4838 Pred = ICmpInst::ICMP_EQ;
4841 if (RA.isMinValue()) return true;
4843 case ICmpInst::ICMP_ULE:
4844 if ((RA + 1).isMaxValue()) {
4845 Pred = ICmpInst::ICMP_NE;
4846 RHS = getConstant(RA + 1);
4849 if (RA.isMinValue()) {
4850 Pred = ICmpInst::ICMP_EQ;
4853 if (RA.isMaxValue()) return true;
4855 case ICmpInst::ICMP_SGE:
4856 if ((RA - 1).isMinSignedValue()) {
4857 Pred = ICmpInst::ICMP_NE;
4858 RHS = getConstant(RA - 1);
4861 if (RA.isMaxSignedValue()) {
4862 Pred = ICmpInst::ICMP_EQ;
4865 if (RA.isMinSignedValue()) return true;
4867 case ICmpInst::ICMP_SLE:
4868 if ((RA + 1).isMaxSignedValue()) {
4869 Pred = ICmpInst::ICMP_NE;
4870 RHS = getConstant(RA + 1);
4873 if (RA.isMinSignedValue()) {
4874 Pred = ICmpInst::ICMP_EQ;
4877 if (RA.isMaxSignedValue()) return true;
4879 case ICmpInst::ICMP_UGT:
4880 if (RA.isMinValue()) {
4881 Pred = ICmpInst::ICMP_NE;
4884 if ((RA + 1).isMaxValue()) {
4885 Pred = ICmpInst::ICMP_EQ;
4886 RHS = getConstant(RA + 1);
4889 if (RA.isMaxValue()) return false;
4891 case ICmpInst::ICMP_ULT:
4892 if (RA.isMaxValue()) {
4893 Pred = ICmpInst::ICMP_NE;
4896 if ((RA - 1).isMinValue()) {
4897 Pred = ICmpInst::ICMP_EQ;
4898 RHS = getConstant(RA - 1);
4901 if (RA.isMinValue()) return false;
4903 case ICmpInst::ICMP_SGT:
4904 if (RA.isMinSignedValue()) {
4905 Pred = ICmpInst::ICMP_NE;
4908 if ((RA + 1).isMaxSignedValue()) {
4909 Pred = ICmpInst::ICMP_EQ;
4910 RHS = getConstant(RA + 1);
4913 if (RA.isMaxSignedValue()) return false;
4915 case ICmpInst::ICMP_SLT:
4916 if (RA.isMaxSignedValue()) {
4917 Pred = ICmpInst::ICMP_NE;
4920 if ((RA - 1).isMinSignedValue()) {
4921 Pred = ICmpInst::ICMP_EQ;
4922 RHS = getConstant(RA - 1);
4925 if (RA.isMinSignedValue()) return false;
4930 // Check to see if we can make the LHS or RHS match.
4931 if (LHS == FoundRHS || RHS == FoundLHS) {
4932 if (isa<SCEVConstant>(RHS)) {
4933 std::swap(FoundLHS, FoundRHS);
4934 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
4936 std::swap(LHS, RHS);
4937 Pred = ICmpInst::getSwappedPredicate(Pred);
4941 // Check whether the found predicate is the same as the desired predicate.
4942 if (FoundPred == Pred)
4943 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
4945 // Check whether swapping the found predicate makes it the same as the
4946 // desired predicate.
4947 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
4948 if (isa<SCEVConstant>(RHS))
4949 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
4951 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
4952 RHS, LHS, FoundLHS, FoundRHS);
4955 // Check whether the actual condition is beyond sufficient.
4956 if (FoundPred == ICmpInst::ICMP_EQ)
4957 if (ICmpInst::isTrueWhenEqual(Pred))
4958 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
4960 if (Pred == ICmpInst::ICMP_NE)
4961 if (!ICmpInst::isTrueWhenEqual(FoundPred))
4962 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
4965 // Otherwise assume the worst.
4969 /// isImpliedCondOperands - Test whether the condition described by Pred,
4970 /// LHS, and RHS is true whenever the condition desribed by Pred, FoundLHS,
4971 /// and FoundRHS is true.
4972 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
4973 const SCEV *LHS, const SCEV *RHS,
4974 const SCEV *FoundLHS,
4975 const SCEV *FoundRHS) {
4976 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
4977 FoundLHS, FoundRHS) ||
4978 // ~x < ~y --> x > y
4979 isImpliedCondOperandsHelper(Pred, LHS, RHS,
4980 getNotSCEV(FoundRHS),
4981 getNotSCEV(FoundLHS));
4984 /// isImpliedCondOperandsHelper - Test whether the condition described by
4985 /// Pred, LHS, and RHS is true whenever the condition desribed by Pred,
4986 /// FoundLHS, and FoundRHS is true.
4988 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
4989 const SCEV *LHS, const SCEV *RHS,
4990 const SCEV *FoundLHS,
4991 const SCEV *FoundRHS) {
4993 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4994 case ICmpInst::ICMP_EQ:
4995 case ICmpInst::ICMP_NE:
4996 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
4999 case ICmpInst::ICMP_SLT:
5000 case ICmpInst::ICMP_SLE:
5001 if (isKnownPredicate(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
5002 isKnownPredicate(ICmpInst::ICMP_SGE, RHS, FoundRHS))
5005 case ICmpInst::ICMP_SGT:
5006 case ICmpInst::ICMP_SGE:
5007 if (isKnownPredicate(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
5008 isKnownPredicate(ICmpInst::ICMP_SLE, RHS, FoundRHS))
5011 case ICmpInst::ICMP_ULT:
5012 case ICmpInst::ICMP_ULE:
5013 if (isKnownPredicate(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
5014 isKnownPredicate(ICmpInst::ICMP_UGE, RHS, FoundRHS))
5017 case ICmpInst::ICMP_UGT:
5018 case ICmpInst::ICMP_UGE:
5019 if (isKnownPredicate(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
5020 isKnownPredicate(ICmpInst::ICMP_ULE, RHS, FoundRHS))
5028 /// getBECount - Subtract the end and start values and divide by the step,
5029 /// rounding up, to get the number of times the backedge is executed. Return
5030 /// CouldNotCompute if an intermediate computation overflows.
5031 const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
5035 assert(!isKnownNegative(Step) &&
5036 "This code doesn't handle negative strides yet!");
5038 const Type *Ty = Start->getType();
5039 const SCEV *NegOne = getIntegerSCEV(-1, Ty);
5040 const SCEV *Diff = getMinusSCEV(End, Start);
5041 const SCEV *RoundUp = getAddExpr(Step, NegOne);
5043 // Add an adjustment to the difference between End and Start so that
5044 // the division will effectively round up.
5045 const SCEV *Add = getAddExpr(Diff, RoundUp);
5048 // Check Add for unsigned overflow.
5049 // TODO: More sophisticated things could be done here.
5050 const Type *WideTy = IntegerType::get(getContext(),
5051 getTypeSizeInBits(Ty) + 1);
5052 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
5053 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
5054 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
5055 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
5056 return getCouldNotCompute();
5059 return getUDivExpr(Add, Step);
5062 /// HowManyLessThans - Return the number of times a backedge containing the
5063 /// specified less-than comparison will execute. If not computable, return
5064 /// CouldNotCompute.
5065 ScalarEvolution::BackedgeTakenInfo
5066 ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
5067 const Loop *L, bool isSigned) {
5068 // Only handle: "ADDREC < LoopInvariant".
5069 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
5071 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
5072 if (!AddRec || AddRec->getLoop() != L)
5073 return getCouldNotCompute();
5075 // Check to see if we have a flag which makes analysis easy.
5076 bool NoWrap = isSigned ? AddRec->hasNoSignedWrap() :
5077 AddRec->hasNoUnsignedWrap();
5079 if (AddRec->isAffine()) {
5080 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
5081 const SCEV *Step = AddRec->getStepRecurrence(*this);
5084 return getCouldNotCompute();
5085 if (Step->isOne()) {
5086 // With unit stride, the iteration never steps past the limit value.
5087 } else if (isKnownPositive(Step)) {
5088 // Test whether a positive iteration can step past the limit
5089 // value and past the maximum value for its type in a single step.
5090 // Note that it's not sufficient to check NoWrap here, because even
5091 // though the value after a wrap is undefined, it's not undefined
5092 // behavior, so if wrap does occur, the loop could either terminate or
5093 // loop infinitely, but in either case, the loop is guaranteed to
5094 // iterate at least until the iteration where the wrapping occurs.
5095 const SCEV *One = getIntegerSCEV(1, Step->getType());
5097 APInt Max = APInt::getSignedMaxValue(BitWidth);
5098 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
5099 .slt(getSignedRange(RHS).getSignedMax()))
5100 return getCouldNotCompute();
5102 APInt Max = APInt::getMaxValue(BitWidth);
5103 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
5104 .ult(getUnsignedRange(RHS).getUnsignedMax()))
5105 return getCouldNotCompute();
5108 // TODO: Handle negative strides here and below.
5109 return getCouldNotCompute();
5111 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
5112 // m. So, we count the number of iterations in which {n,+,s} < m is true.
5113 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
5114 // treat m-n as signed nor unsigned due to overflow possibility.
5116 // First, we get the value of the LHS in the first iteration: n
5117 const SCEV *Start = AddRec->getOperand(0);
5119 // Determine the minimum constant start value.
5120 const SCEV *MinStart = getConstant(isSigned ?
5121 getSignedRange(Start).getSignedMin() :
5122 getUnsignedRange(Start).getUnsignedMin());
5124 // If we know that the condition is true in order to enter the loop,
5125 // then we know that it will run exactly (m-n)/s times. Otherwise, we
5126 // only know that it will execute (max(m,n)-n)/s times. In both cases,
5127 // the division must round up.
5128 const SCEV *End = RHS;
5129 if (!isLoopGuardedByCond(L,
5130 isSigned ? ICmpInst::ICMP_SLT :
5132 getMinusSCEV(Start, Step), RHS))
5133 End = isSigned ? getSMaxExpr(RHS, Start)
5134 : getUMaxExpr(RHS, Start);
5136 // Determine the maximum constant end value.
5137 const SCEV *MaxEnd = getConstant(isSigned ?
5138 getSignedRange(End).getSignedMax() :
5139 getUnsignedRange(End).getUnsignedMax());
5141 // If MaxEnd is within a step of the maximum integer value in its type,
5142 // adjust it down to the minimum value which would produce the same effect.
5143 // This allows the subsequent ceiling divison of (N+(step-1))/step to
5144 // compute the correct value.
5145 const SCEV *StepMinusOne = getMinusSCEV(Step,
5146 getIntegerSCEV(1, Step->getType()));
5149 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
5152 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
5155 // Finally, we subtract these two values and divide, rounding up, to get
5156 // the number of times the backedge is executed.
5157 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
5159 // The maximum backedge count is similar, except using the minimum start
5160 // value and the maximum end value.
5161 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step, NoWrap);
5163 return BackedgeTakenInfo(BECount, MaxBECount);
5166 return getCouldNotCompute();
5169 /// getNumIterationsInRange - Return the number of iterations of this loop that
5170 /// produce values in the specified constant range. Another way of looking at
5171 /// this is that it returns the first iteration number where the value is not in
5172 /// the condition, thus computing the exit count. If the iteration count can't
5173 /// be computed, an instance of SCEVCouldNotCompute is returned.
5174 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
5175 ScalarEvolution &SE) const {
5176 if (Range.isFullSet()) // Infinite loop.
5177 return SE.getCouldNotCompute();
5179 // If the start is a non-zero constant, shift the range to simplify things.
5180 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
5181 if (!SC->getValue()->isZero()) {
5182 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
5183 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
5184 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
5185 if (const SCEVAddRecExpr *ShiftedAddRec =
5186 dyn_cast<SCEVAddRecExpr>(Shifted))
5187 return ShiftedAddRec->getNumIterationsInRange(
5188 Range.subtract(SC->getValue()->getValue()), SE);
5189 // This is strange and shouldn't happen.
5190 return SE.getCouldNotCompute();
5193 // The only time we can solve this is when we have all constant indices.
5194 // Otherwise, we cannot determine the overflow conditions.
5195 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5196 if (!isa<SCEVConstant>(getOperand(i)))
5197 return SE.getCouldNotCompute();
5200 // Okay at this point we know that all elements of the chrec are constants and
5201 // that the start element is zero.
5203 // First check to see if the range contains zero. If not, the first
5205 unsigned BitWidth = SE.getTypeSizeInBits(getType());
5206 if (!Range.contains(APInt(BitWidth, 0)))
5207 return SE.getIntegerSCEV(0, getType());
5210 // If this is an affine expression then we have this situation:
5211 // Solve {0,+,A} in Range === Ax in Range
5213 // We know that zero is in the range. If A is positive then we know that
5214 // the upper value of the range must be the first possible exit value.
5215 // If A is negative then the lower of the range is the last possible loop
5216 // value. Also note that we already checked for a full range.
5217 APInt One(BitWidth,1);
5218 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
5219 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
5221 // The exit value should be (End+A)/A.
5222 APInt ExitVal = (End + A).udiv(A);
5223 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
5225 // Evaluate at the exit value. If we really did fall out of the valid
5226 // range, then we computed our trip count, otherwise wrap around or other
5227 // things must have happened.
5228 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
5229 if (Range.contains(Val->getValue()))
5230 return SE.getCouldNotCompute(); // Something strange happened
5232 // Ensure that the previous value is in the range. This is a sanity check.
5233 assert(Range.contains(
5234 EvaluateConstantChrecAtConstant(this,
5235 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
5236 "Linear scev computation is off in a bad way!");
5237 return SE.getConstant(ExitValue);
5238 } else if (isQuadratic()) {
5239 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5240 // quadratic equation to solve it. To do this, we must frame our problem in
5241 // terms of figuring out when zero is crossed, instead of when
5242 // Range.getUpper() is crossed.
5243 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
5244 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
5245 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
5247 // Next, solve the constructed addrec
5248 std::pair<const SCEV *,const SCEV *> Roots =
5249 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
5250 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5251 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
5253 // Pick the smallest positive root value.
5254 if (ConstantInt *CB =
5255 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
5256 R1->getValue(), R2->getValue()))) {
5257 if (CB->getZExtValue() == false)
5258 std::swap(R1, R2); // R1 is the minimum root now.
5260 // Make sure the root is not off by one. The returned iteration should
5261 // not be in the range, but the previous one should be. When solving
5262 // for "X*X < 5", for example, we should not return a root of 2.
5263 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
5266 if (Range.contains(R1Val->getValue())) {
5267 // The next iteration must be out of the range...
5268 ConstantInt *NextVal =
5269 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
5271 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
5272 if (!Range.contains(R1Val->getValue()))
5273 return SE.getConstant(NextVal);
5274 return SE.getCouldNotCompute(); // Something strange happened
5277 // If R1 was not in the range, then it is a good return value. Make
5278 // sure that R1-1 WAS in the range though, just in case.
5279 ConstantInt *NextVal =
5280 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
5281 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
5282 if (Range.contains(R1Val->getValue()))
5284 return SE.getCouldNotCompute(); // Something strange happened
5289 return SE.getCouldNotCompute();
5294 //===----------------------------------------------------------------------===//
5295 // SCEVCallbackVH Class Implementation
5296 //===----------------------------------------------------------------------===//
5298 void ScalarEvolution::SCEVCallbackVH::deleted() {
5299 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
5300 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5301 SE->ConstantEvolutionLoopExitValue.erase(PN);
5302 SE->Scalars.erase(getValPtr());
5303 // this now dangles!
5306 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
5307 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
5309 // Forget all the expressions associated with users of the old value,
5310 // so that future queries will recompute the expressions using the new
5312 SmallVector<User *, 16> Worklist;
5313 SmallPtrSet<User *, 8> Visited;
5314 Value *Old = getValPtr();
5315 bool DeleteOld = false;
5316 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5318 Worklist.push_back(*UI);
5319 while (!Worklist.empty()) {
5320 User *U = Worklist.pop_back_val();
5321 // Deleting the Old value will cause this to dangle. Postpone
5322 // that until everything else is done.
5327 if (!Visited.insert(U))
5329 if (PHINode *PN = dyn_cast<PHINode>(U))
5330 SE->ConstantEvolutionLoopExitValue.erase(PN);
5331 SE->Scalars.erase(U);
5332 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5334 Worklist.push_back(*UI);
5336 // Delete the Old value if it (indirectly) references itself.
5338 if (PHINode *PN = dyn_cast<PHINode>(Old))
5339 SE->ConstantEvolutionLoopExitValue.erase(PN);
5340 SE->Scalars.erase(Old);
5341 // this now dangles!
5346 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
5347 : CallbackVH(V), SE(se) {}
5349 //===----------------------------------------------------------------------===//
5350 // ScalarEvolution Class Implementation
5351 //===----------------------------------------------------------------------===//
5353 ScalarEvolution::ScalarEvolution()
5354 : FunctionPass(&ID) {
5357 bool ScalarEvolution::runOnFunction(Function &F) {
5359 LI = &getAnalysis<LoopInfo>();
5360 TD = getAnalysisIfAvailable<TargetData>();
5361 DT = &getAnalysis<DominatorTree>();
5365 void ScalarEvolution::releaseMemory() {
5367 BackedgeTakenCounts.clear();
5368 ConstantEvolutionLoopExitValue.clear();
5369 ValuesAtScopes.clear();
5370 UniqueSCEVs.clear();
5371 SCEVAllocator.Reset();
5374 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5375 AU.setPreservesAll();
5376 AU.addRequiredTransitive<LoopInfo>();
5377 AU.addRequiredTransitive<DominatorTree>();
5380 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
5381 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
5384 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
5386 // Print all inner loops first
5387 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5388 PrintLoopInfo(OS, SE, *I);
5391 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5394 SmallVector<BasicBlock *, 8> ExitBlocks;
5395 L->getExitBlocks(ExitBlocks);
5396 if (ExitBlocks.size() != 1)
5397 OS << "<multiple exits> ";
5399 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5400 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
5402 OS << "Unpredictable backedge-taken count. ";
5407 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5410 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5411 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5413 OS << "Unpredictable max backedge-taken count. ";
5419 void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
5420 // ScalarEvolution's implementaiton of the print method is to print
5421 // out SCEV values of all instructions that are interesting. Doing
5422 // this potentially causes it to create new SCEV objects though,
5423 // which technically conflicts with the const qualifier. This isn't
5424 // observable from outside the class though, so casting away the
5425 // const isn't dangerous.
5426 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
5428 OS << "Classifying expressions for: ";
5429 WriteAsOperand(OS, F, /*PrintType=*/false);
5431 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
5432 if (isSCEVable(I->getType())) {
5435 const SCEV *SV = SE.getSCEV(&*I);
5438 const Loop *L = LI->getLoopFor((*I).getParent());
5440 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
5447 OS << "\t\t" "Exits: ";
5448 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
5449 if (!ExitValue->isLoopInvariant(L)) {
5450 OS << "<<Unknown>>";
5459 OS << "Determining loop execution counts for: ";
5460 WriteAsOperand(OS, F, /*PrintType=*/false);
5462 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5463 PrintLoopInfo(OS, &SE, *I);