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(FoldingSetNodeIDRef(), 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 = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
181 UniqueSCEVs.InsertNode(S, IP);
185 const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
186 return getConstant(ConstantInt::get(getContext(), Val));
190 ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
191 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
192 return getConstant(ConstantInt::get(ITy, V, isSigned));
195 const Type *SCEVConstant::getType() const { return V->getType(); }
197 void SCEVConstant::print(raw_ostream &OS) const {
198 WriteAsOperand(OS, V, false);
201 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
202 unsigned SCEVTy, const SCEV *op, const Type *ty)
203 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
205 bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
206 return Op->dominates(BB, DT);
209 bool SCEVCastExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
210 return Op->properlyDominates(BB, DT);
213 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
214 const SCEV *op, const Type *ty)
215 : SCEVCastExpr(ID, scTruncate, op, ty) {
216 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
217 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
218 "Cannot truncate non-integer value!");
221 void SCEVTruncateExpr::print(raw_ostream &OS) const {
222 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
225 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
226 const SCEV *op, const Type *ty)
227 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
228 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
229 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
230 "Cannot zero extend non-integer value!");
233 void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
234 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
237 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
238 const SCEV *op, const Type *ty)
239 : SCEVCastExpr(ID, scSignExtend, op, ty) {
240 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
241 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
242 "Cannot sign extend non-integer value!");
245 void SCEVSignExtendExpr::print(raw_ostream &OS) const {
246 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
249 void SCEVCommutativeExpr::print(raw_ostream &OS) const {
250 const char *OpStr = getOperationStr();
252 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I) {
260 bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
261 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
262 if (!getOperand(i)->dominates(BB, DT))
268 bool SCEVNAryExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
269 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
270 if (!getOperand(i)->properlyDominates(BB, DT))
276 bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
277 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
280 bool SCEVUDivExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
281 return LHS->properlyDominates(BB, DT) && RHS->properlyDominates(BB, DT);
284 void SCEVUDivExpr::print(raw_ostream &OS) const {
285 OS << "(" << *LHS << " /u " << *RHS << ")";
288 const Type *SCEVUDivExpr::getType() const {
289 // In most cases the types of LHS and RHS will be the same, but in some
290 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
291 // depend on the type for correctness, but handling types carefully can
292 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
293 // a pointer type than the RHS, so use the RHS' type here.
294 return RHS->getType();
297 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
298 // Add recurrences are never invariant in the function-body (null loop).
302 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
303 if (QueryLoop->contains(L))
306 // This recurrence is variant w.r.t. QueryLoop if any of its operands
308 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
309 if (!getOperand(i)->isLoopInvariant(QueryLoop))
312 // Otherwise it's loop-invariant.
317 SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
318 return DT->dominates(L->getHeader(), BB) &&
319 SCEVNAryExpr::dominates(BB, DT);
323 SCEVAddRecExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
324 // This uses a "dominates" query instead of "properly dominates" query because
325 // the instruction which produces the addrec's value is a PHI, and a PHI
326 // effectively properly dominates its entire containing block.
327 return DT->dominates(L->getHeader(), BB) &&
328 SCEVNAryExpr::properlyDominates(BB, DT);
331 void SCEVAddRecExpr::print(raw_ostream &OS) const {
332 OS << "{" << *Operands[0];
333 for (unsigned i = 1, e = NumOperands; i != e; ++i)
334 OS << ",+," << *Operands[i];
336 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
340 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
341 // All non-instruction values are loop invariant. All instructions are loop
342 // invariant if they are not contained in the specified loop.
343 // Instructions are never considered invariant in the function body
344 // (null loop) because they are defined within the "loop".
345 if (Instruction *I = dyn_cast<Instruction>(V))
346 return L && !L->contains(I);
350 bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
351 if (Instruction *I = dyn_cast<Instruction>(getValue()))
352 return DT->dominates(I->getParent(), BB);
356 bool SCEVUnknown::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
357 if (Instruction *I = dyn_cast<Instruction>(getValue()))
358 return DT->properlyDominates(I->getParent(), BB);
362 const Type *SCEVUnknown::getType() const {
366 bool SCEVUnknown::isSizeOf(const Type *&AllocTy) const {
367 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
368 if (VCE->getOpcode() == Instruction::PtrToInt)
369 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
370 if (CE->getOpcode() == Instruction::GetElementPtr &&
371 CE->getOperand(0)->isNullValue() &&
372 CE->getNumOperands() == 2)
373 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
375 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
383 bool SCEVUnknown::isAlignOf(const Type *&AllocTy) const {
384 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
385 if (VCE->getOpcode() == Instruction::PtrToInt)
386 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
387 if (CE->getOpcode() == Instruction::GetElementPtr &&
388 CE->getOperand(0)->isNullValue()) {
390 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
391 if (const StructType *STy = dyn_cast<StructType>(Ty))
392 if (!STy->isPacked() &&
393 CE->getNumOperands() == 3 &&
394 CE->getOperand(1)->isNullValue()) {
395 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
397 STy->getNumElements() == 2 &&
398 STy->getElementType(0)->isIntegerTy(1)) {
399 AllocTy = STy->getElementType(1);
408 bool SCEVUnknown::isOffsetOf(const Type *&CTy, Constant *&FieldNo) const {
409 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
410 if (VCE->getOpcode() == Instruction::PtrToInt)
411 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
412 if (CE->getOpcode() == Instruction::GetElementPtr &&
413 CE->getNumOperands() == 3 &&
414 CE->getOperand(0)->isNullValue() &&
415 CE->getOperand(1)->isNullValue()) {
417 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
418 // Ignore vector types here so that ScalarEvolutionExpander doesn't
419 // emit getelementptrs that index into vectors.
420 if (Ty->isStructTy() || Ty->isArrayTy()) {
422 FieldNo = CE->getOperand(2);
430 void SCEVUnknown::print(raw_ostream &OS) const {
432 if (isSizeOf(AllocTy)) {
433 OS << "sizeof(" << *AllocTy << ")";
436 if (isAlignOf(AllocTy)) {
437 OS << "alignof(" << *AllocTy << ")";
443 if (isOffsetOf(CTy, FieldNo)) {
444 OS << "offsetof(" << *CTy << ", ";
445 WriteAsOperand(OS, FieldNo, false);
450 // Otherwise just print it normally.
451 WriteAsOperand(OS, V, false);
454 //===----------------------------------------------------------------------===//
456 //===----------------------------------------------------------------------===//
458 static bool CompareTypes(const Type *A, const Type *B) {
459 if (A->getTypeID() != B->getTypeID())
460 return A->getTypeID() < B->getTypeID();
461 if (const IntegerType *AI = dyn_cast<IntegerType>(A)) {
462 const IntegerType *BI = cast<IntegerType>(B);
463 return AI->getBitWidth() < BI->getBitWidth();
465 if (const PointerType *AI = dyn_cast<PointerType>(A)) {
466 const PointerType *BI = cast<PointerType>(B);
467 return CompareTypes(AI->getElementType(), BI->getElementType());
469 if (const ArrayType *AI = dyn_cast<ArrayType>(A)) {
470 const ArrayType *BI = cast<ArrayType>(B);
471 if (AI->getNumElements() != BI->getNumElements())
472 return AI->getNumElements() < BI->getNumElements();
473 return CompareTypes(AI->getElementType(), BI->getElementType());
475 if (const VectorType *AI = dyn_cast<VectorType>(A)) {
476 const VectorType *BI = cast<VectorType>(B);
477 if (AI->getNumElements() != BI->getNumElements())
478 return AI->getNumElements() < BI->getNumElements();
479 return CompareTypes(AI->getElementType(), BI->getElementType());
481 if (const StructType *AI = dyn_cast<StructType>(A)) {
482 const StructType *BI = cast<StructType>(B);
483 if (AI->getNumElements() != BI->getNumElements())
484 return AI->getNumElements() < BI->getNumElements();
485 for (unsigned i = 0, e = AI->getNumElements(); i != e; ++i)
486 if (CompareTypes(AI->getElementType(i), BI->getElementType(i)) ||
487 CompareTypes(BI->getElementType(i), AI->getElementType(i)))
488 return CompareTypes(AI->getElementType(i), BI->getElementType(i));
494 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
495 /// than the complexity of the RHS. This comparator is used to canonicalize
497 class SCEVComplexityCompare {
500 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
502 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
503 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
507 // Primarily, sort the SCEVs by their getSCEVType().
508 if (LHS->getSCEVType() != RHS->getSCEVType())
509 return LHS->getSCEVType() < RHS->getSCEVType();
511 // Aside from the getSCEVType() ordering, the particular ordering
512 // isn't very important except that it's beneficial to be consistent,
513 // so that (a + b) and (b + a) don't end up as different expressions.
515 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
516 // not as complete as it could be.
517 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
518 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
520 // Order pointer values after integer values. This helps SCEVExpander
522 if (LU->getType()->isPointerTy() && !RU->getType()->isPointerTy())
524 if (RU->getType()->isPointerTy() && !LU->getType()->isPointerTy())
527 // Compare getValueID values.
528 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
529 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
531 // Sort arguments by their position.
532 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
533 const Argument *RA = cast<Argument>(RU->getValue());
534 return LA->getArgNo() < RA->getArgNo();
537 // For instructions, compare their loop depth, and their opcode.
538 // This is pretty loose.
539 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
540 Instruction *RV = cast<Instruction>(RU->getValue());
542 // Compare loop depths.
543 if (LI->getLoopDepth(LV->getParent()) !=
544 LI->getLoopDepth(RV->getParent()))
545 return LI->getLoopDepth(LV->getParent()) <
546 LI->getLoopDepth(RV->getParent());
549 if (LV->getOpcode() != RV->getOpcode())
550 return LV->getOpcode() < RV->getOpcode();
552 // Compare the number of operands.
553 if (LV->getNumOperands() != RV->getNumOperands())
554 return LV->getNumOperands() < RV->getNumOperands();
560 // Compare constant values.
561 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
562 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
563 if (LC->getValue()->getBitWidth() != RC->getValue()->getBitWidth())
564 return LC->getValue()->getBitWidth() < RC->getValue()->getBitWidth();
565 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
568 // Compare addrec loop depths.
569 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
570 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
571 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
572 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
575 // Lexicographically compare n-ary expressions.
576 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
577 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
578 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
579 if (i >= RC->getNumOperands())
581 if (operator()(LC->getOperand(i), RC->getOperand(i)))
583 if (operator()(RC->getOperand(i), LC->getOperand(i)))
586 return LC->getNumOperands() < RC->getNumOperands();
589 // Lexicographically compare udiv expressions.
590 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
591 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
592 if (operator()(LC->getLHS(), RC->getLHS()))
594 if (operator()(RC->getLHS(), LC->getLHS()))
596 if (operator()(LC->getRHS(), RC->getRHS()))
598 if (operator()(RC->getRHS(), LC->getRHS()))
603 // Compare cast expressions by operand.
604 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
605 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
606 return operator()(LC->getOperand(), RC->getOperand());
609 llvm_unreachable("Unknown SCEV kind!");
615 /// GroupByComplexity - Given a list of SCEV objects, order them by their
616 /// complexity, and group objects of the same complexity together by value.
617 /// When this routine is finished, we know that any duplicates in the vector are
618 /// consecutive and that complexity is monotonically increasing.
620 /// Note that we go take special precautions to ensure that we get deterministic
621 /// results from this routine. In other words, we don't want the results of
622 /// this to depend on where the addresses of various SCEV objects happened to
625 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
627 if (Ops.size() < 2) return; // Noop
628 if (Ops.size() == 2) {
629 // This is the common case, which also happens to be trivially simple.
631 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
632 std::swap(Ops[0], Ops[1]);
636 // Do the rough sort by complexity.
637 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
639 // Now that we are sorted by complexity, group elements of the same
640 // complexity. Note that this is, at worst, N^2, but the vector is likely to
641 // be extremely short in practice. Note that we take this approach because we
642 // do not want to depend on the addresses of the objects we are grouping.
643 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
644 const SCEV *S = Ops[i];
645 unsigned Complexity = S->getSCEVType();
647 // If there are any objects of the same complexity and same value as this
649 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
650 if (Ops[j] == S) { // Found a duplicate.
651 // Move it to immediately after i'th element.
652 std::swap(Ops[i+1], Ops[j]);
653 ++i; // no need to rescan it.
654 if (i == e-2) return; // Done!
662 //===----------------------------------------------------------------------===//
663 // Simple SCEV method implementations
664 //===----------------------------------------------------------------------===//
666 /// BinomialCoefficient - Compute BC(It, K). The result has width W.
668 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
670 const Type* ResultTy) {
671 // Handle the simplest case efficiently.
673 return SE.getTruncateOrZeroExtend(It, ResultTy);
675 // We are using the following formula for BC(It, K):
677 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
679 // Suppose, W is the bitwidth of the return value. We must be prepared for
680 // overflow. Hence, we must assure that the result of our computation is
681 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
682 // safe in modular arithmetic.
684 // However, this code doesn't use exactly that formula; the formula it uses
685 // is something like the following, where T is the number of factors of 2 in
686 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
689 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
691 // This formula is trivially equivalent to the previous formula. However,
692 // this formula can be implemented much more efficiently. The trick is that
693 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
694 // arithmetic. To do exact division in modular arithmetic, all we have
695 // to do is multiply by the inverse. Therefore, this step can be done at
698 // The next issue is how to safely do the division by 2^T. The way this
699 // is done is by doing the multiplication step at a width of at least W + T
700 // bits. This way, the bottom W+T bits of the product are accurate. Then,
701 // when we perform the division by 2^T (which is equivalent to a right shift
702 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
703 // truncated out after the division by 2^T.
705 // In comparison to just directly using the first formula, this technique
706 // is much more efficient; using the first formula requires W * K bits,
707 // but this formula less than W + K bits. Also, the first formula requires
708 // a division step, whereas this formula only requires multiplies and shifts.
710 // It doesn't matter whether the subtraction step is done in the calculation
711 // width or the input iteration count's width; if the subtraction overflows,
712 // the result must be zero anyway. We prefer here to do it in the width of
713 // the induction variable because it helps a lot for certain cases; CodeGen
714 // isn't smart enough to ignore the overflow, which leads to much less
715 // efficient code if the width of the subtraction is wider than the native
718 // (It's possible to not widen at all by pulling out factors of 2 before
719 // the multiplication; for example, K=2 can be calculated as
720 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
721 // extra arithmetic, so it's not an obvious win, and it gets
722 // much more complicated for K > 3.)
724 // Protection from insane SCEVs; this bound is conservative,
725 // but it probably doesn't matter.
727 return SE.getCouldNotCompute();
729 unsigned W = SE.getTypeSizeInBits(ResultTy);
731 // Calculate K! / 2^T and T; we divide out the factors of two before
732 // multiplying for calculating K! / 2^T to avoid overflow.
733 // Other overflow doesn't matter because we only care about the bottom
734 // W bits of the result.
735 APInt OddFactorial(W, 1);
737 for (unsigned i = 3; i <= K; ++i) {
739 unsigned TwoFactors = Mult.countTrailingZeros();
741 Mult = Mult.lshr(TwoFactors);
742 OddFactorial *= Mult;
745 // We need at least W + T bits for the multiplication step
746 unsigned CalculationBits = W + T;
748 // Calculate 2^T, at width T+W.
749 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
751 // Calculate the multiplicative inverse of K! / 2^T;
752 // this multiplication factor will perform the exact division by
754 APInt Mod = APInt::getSignedMinValue(W+1);
755 APInt MultiplyFactor = OddFactorial.zext(W+1);
756 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
757 MultiplyFactor = MultiplyFactor.trunc(W);
759 // Calculate the product, at width T+W
760 const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
762 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
763 for (unsigned i = 1; i != K; ++i) {
764 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
765 Dividend = SE.getMulExpr(Dividend,
766 SE.getTruncateOrZeroExtend(S, CalculationTy));
770 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
772 // Truncate the result, and divide by K! / 2^T.
774 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
775 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
778 /// evaluateAtIteration - Return the value of this chain of recurrences at
779 /// the specified iteration number. We can evaluate this recurrence by
780 /// multiplying each element in the chain by the binomial coefficient
781 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
783 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
785 /// where BC(It, k) stands for binomial coefficient.
787 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
788 ScalarEvolution &SE) const {
789 const SCEV *Result = getStart();
790 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
791 // The computation is correct in the face of overflow provided that the
792 // multiplication is performed _after_ the evaluation of the binomial
794 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
795 if (isa<SCEVCouldNotCompute>(Coeff))
798 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
803 //===----------------------------------------------------------------------===//
804 // SCEV Expression folder implementations
805 //===----------------------------------------------------------------------===//
807 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
809 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
810 "This is not a truncating conversion!");
811 assert(isSCEVable(Ty) &&
812 "This is not a conversion to a SCEVable type!");
813 Ty = getEffectiveSCEVType(Ty);
816 ID.AddInteger(scTruncate);
820 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
822 // Fold if the operand is constant.
823 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
825 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
827 // trunc(trunc(x)) --> trunc(x)
828 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
829 return getTruncateExpr(ST->getOperand(), Ty);
831 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
832 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
833 return getTruncateOrSignExtend(SS->getOperand(), Ty);
835 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
836 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
837 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
839 // If the input value is a chrec scev, truncate the chrec's operands.
840 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
841 SmallVector<const SCEV *, 4> Operands;
842 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
843 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
844 return getAddRecExpr(Operands, AddRec->getLoop());
847 // The cast wasn't folded; create an explicit cast node.
848 // Recompute the insert position, as it may have been invalidated.
849 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
850 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
852 UniqueSCEVs.InsertNode(S, IP);
856 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
858 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
859 "This is not an extending conversion!");
860 assert(isSCEVable(Ty) &&
861 "This is not a conversion to a SCEVable type!");
862 Ty = getEffectiveSCEVType(Ty);
864 // Fold if the operand is constant.
865 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
866 const Type *IntTy = getEffectiveSCEVType(Ty);
867 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
868 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
869 return getConstant(cast<ConstantInt>(C));
872 // zext(zext(x)) --> zext(x)
873 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
874 return getZeroExtendExpr(SZ->getOperand(), Ty);
876 // Before doing any expensive analysis, check to see if we've already
877 // computed a SCEV for this Op and Ty.
879 ID.AddInteger(scZeroExtend);
883 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
885 // If the input value is a chrec scev, and we can prove that the value
886 // did not overflow the old, smaller, value, we can zero extend all of the
887 // operands (often constants). This allows analysis of something like
888 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
889 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
890 if (AR->isAffine()) {
891 const SCEV *Start = AR->getStart();
892 const SCEV *Step = AR->getStepRecurrence(*this);
893 unsigned BitWidth = getTypeSizeInBits(AR->getType());
894 const Loop *L = AR->getLoop();
896 // If we have special knowledge that this addrec won't overflow,
897 // we don't need to do any further analysis.
898 if (AR->hasNoUnsignedWrap())
899 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
900 getZeroExtendExpr(Step, Ty),
903 // Check whether the backedge-taken count is SCEVCouldNotCompute.
904 // Note that this serves two purposes: It filters out loops that are
905 // simply not analyzable, and it covers the case where this code is
906 // being called from within backedge-taken count analysis, such that
907 // attempting to ask for the backedge-taken count would likely result
908 // in infinite recursion. In the later case, the analysis code will
909 // cope with a conservative value, and it will take care to purge
910 // that value once it has finished.
911 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
912 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
913 // Manually compute the final value for AR, checking for
916 // Check whether the backedge-taken count can be losslessly casted to
917 // the addrec's type. The count is always unsigned.
918 const SCEV *CastedMaxBECount =
919 getTruncateOrZeroExtend(MaxBECount, Start->getType());
920 const SCEV *RecastedMaxBECount =
921 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
922 if (MaxBECount == RecastedMaxBECount) {
923 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
924 // Check whether Start+Step*MaxBECount has no unsigned overflow.
925 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
926 const SCEV *Add = getAddExpr(Start, ZMul);
927 const SCEV *OperandExtendedAdd =
928 getAddExpr(getZeroExtendExpr(Start, WideTy),
929 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
930 getZeroExtendExpr(Step, WideTy)));
931 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
932 // Return the expression with the addrec on the outside.
933 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
934 getZeroExtendExpr(Step, Ty),
937 // Similar to above, only this time treat the step value as signed.
938 // This covers loops that count down.
939 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
940 Add = getAddExpr(Start, SMul);
942 getAddExpr(getZeroExtendExpr(Start, WideTy),
943 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
944 getSignExtendExpr(Step, WideTy)));
945 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
946 // Return the expression with the addrec on the outside.
947 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
948 getSignExtendExpr(Step, Ty),
952 // If the backedge is guarded by a comparison with the pre-inc value
953 // the addrec is safe. Also, if the entry is guarded by a comparison
954 // with the start value and the backedge is guarded by a comparison
955 // with the post-inc value, the addrec is safe.
956 if (isKnownPositive(Step)) {
957 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
958 getUnsignedRange(Step).getUnsignedMax());
959 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
960 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
961 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
962 AR->getPostIncExpr(*this), N)))
963 // Return the expression with the addrec on the outside.
964 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
965 getZeroExtendExpr(Step, Ty),
967 } else if (isKnownNegative(Step)) {
968 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
969 getSignedRange(Step).getSignedMin());
970 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
971 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
972 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
973 AR->getPostIncExpr(*this), N)))
974 // Return the expression with the addrec on the outside.
975 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
976 getSignExtendExpr(Step, Ty),
982 // The cast wasn't folded; create an explicit cast node.
983 // Recompute the insert position, as it may have been invalidated.
984 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
985 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
987 UniqueSCEVs.InsertNode(S, IP);
991 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
993 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
994 "This is not an extending conversion!");
995 assert(isSCEVable(Ty) &&
996 "This is not a conversion to a SCEVable type!");
997 Ty = getEffectiveSCEVType(Ty);
999 // Fold if the operand is constant.
1000 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
1001 const Type *IntTy = getEffectiveSCEVType(Ty);
1002 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
1003 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
1004 return getConstant(cast<ConstantInt>(C));
1007 // sext(sext(x)) --> sext(x)
1008 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1009 return getSignExtendExpr(SS->getOperand(), Ty);
1011 // Before doing any expensive analysis, check to see if we've already
1012 // computed a SCEV for this Op and Ty.
1013 FoldingSetNodeID ID;
1014 ID.AddInteger(scSignExtend);
1018 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1020 // If the input value is a chrec scev, and we can prove that the value
1021 // did not overflow the old, smaller, value, we can sign extend all of the
1022 // operands (often constants). This allows analysis of something like
1023 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1024 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1025 if (AR->isAffine()) {
1026 const SCEV *Start = AR->getStart();
1027 const SCEV *Step = AR->getStepRecurrence(*this);
1028 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1029 const Loop *L = AR->getLoop();
1031 // If we have special knowledge that this addrec won't overflow,
1032 // we don't need to do any further analysis.
1033 if (AR->hasNoSignedWrap())
1034 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1035 getSignExtendExpr(Step, Ty),
1038 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1039 // Note that this serves two purposes: It filters out loops that are
1040 // simply not analyzable, and it covers the case where this code is
1041 // being called from within backedge-taken count analysis, such that
1042 // attempting to ask for the backedge-taken count would likely result
1043 // in infinite recursion. In the later case, the analysis code will
1044 // cope with a conservative value, and it will take care to purge
1045 // that value once it has finished.
1046 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1047 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1048 // Manually compute the final value for AR, checking for
1051 // Check whether the backedge-taken count can be losslessly casted to
1052 // the addrec's type. The count is always unsigned.
1053 const SCEV *CastedMaxBECount =
1054 getTruncateOrZeroExtend(MaxBECount, Start->getType());
1055 const SCEV *RecastedMaxBECount =
1056 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1057 if (MaxBECount == RecastedMaxBECount) {
1058 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1059 // Check whether Start+Step*MaxBECount has no signed overflow.
1060 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
1061 const SCEV *Add = getAddExpr(Start, SMul);
1062 const SCEV *OperandExtendedAdd =
1063 getAddExpr(getSignExtendExpr(Start, WideTy),
1064 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1065 getSignExtendExpr(Step, WideTy)));
1066 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
1067 // Return the expression with the addrec on the outside.
1068 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1069 getSignExtendExpr(Step, Ty),
1072 // Similar to above, only this time treat the step value as unsigned.
1073 // This covers loops that count up with an unsigned step.
1074 const SCEV *UMul = getMulExpr(CastedMaxBECount, Step);
1075 Add = getAddExpr(Start, UMul);
1076 OperandExtendedAdd =
1077 getAddExpr(getSignExtendExpr(Start, WideTy),
1078 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1079 getZeroExtendExpr(Step, WideTy)));
1080 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
1081 // Return the expression with the addrec on the outside.
1082 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1083 getZeroExtendExpr(Step, Ty),
1087 // If the backedge is guarded by a comparison with the pre-inc value
1088 // the addrec is safe. Also, if the entry is guarded by a comparison
1089 // with the start value and the backedge is guarded by a comparison
1090 // with the post-inc value, the addrec is safe.
1091 if (isKnownPositive(Step)) {
1092 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
1093 getSignedRange(Step).getSignedMax());
1094 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
1095 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
1096 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
1097 AR->getPostIncExpr(*this), N)))
1098 // Return the expression with the addrec on the outside.
1099 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1100 getSignExtendExpr(Step, Ty),
1102 } else if (isKnownNegative(Step)) {
1103 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1104 getSignedRange(Step).getSignedMin());
1105 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
1106 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
1107 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1108 AR->getPostIncExpr(*this), N)))
1109 // Return the expression with the addrec on the outside.
1110 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1111 getSignExtendExpr(Step, Ty),
1117 // The cast wasn't folded; create an explicit cast node.
1118 // Recompute the insert position, as it may have been invalidated.
1119 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1120 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1122 UniqueSCEVs.InsertNode(S, IP);
1126 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1127 /// unspecified bits out to the given type.
1129 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1131 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1132 "This is not an extending conversion!");
1133 assert(isSCEVable(Ty) &&
1134 "This is not a conversion to a SCEVable type!");
1135 Ty = getEffectiveSCEVType(Ty);
1137 // Sign-extend negative constants.
1138 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1139 if (SC->getValue()->getValue().isNegative())
1140 return getSignExtendExpr(Op, Ty);
1142 // Peel off a truncate cast.
1143 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
1144 const SCEV *NewOp = T->getOperand();
1145 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1146 return getAnyExtendExpr(NewOp, Ty);
1147 return getTruncateOrNoop(NewOp, Ty);
1150 // Next try a zext cast. If the cast is folded, use it.
1151 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
1152 if (!isa<SCEVZeroExtendExpr>(ZExt))
1155 // Next try a sext cast. If the cast is folded, use it.
1156 const SCEV *SExt = getSignExtendExpr(Op, Ty);
1157 if (!isa<SCEVSignExtendExpr>(SExt))
1160 // Force the cast to be folded into the operands of an addrec.
1161 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1162 SmallVector<const SCEV *, 4> Ops;
1163 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
1165 Ops.push_back(getAnyExtendExpr(*I, Ty));
1166 return getAddRecExpr(Ops, AR->getLoop());
1169 // If the expression is obviously signed, use the sext cast value.
1170 if (isa<SCEVSMaxExpr>(Op))
1173 // Absent any other information, use the zext cast value.
1177 /// CollectAddOperandsWithScales - Process the given Ops list, which is
1178 /// a list of operands to be added under the given scale, update the given
1179 /// map. This is a helper function for getAddRecExpr. As an example of
1180 /// what it does, given a sequence of operands that would form an add
1181 /// expression like this:
1183 /// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1185 /// where A and B are constants, update the map with these values:
1187 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1189 /// and add 13 + A*B*29 to AccumulatedConstant.
1190 /// This will allow getAddRecExpr to produce this:
1192 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1194 /// This form often exposes folding opportunities that are hidden in
1195 /// the original operand list.
1197 /// Return true iff it appears that any interesting folding opportunities
1198 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
1199 /// the common case where no interesting opportunities are present, and
1200 /// is also used as a check to avoid infinite recursion.
1203 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1204 SmallVector<const SCEV *, 8> &NewOps,
1205 APInt &AccumulatedConstant,
1206 const SCEV *const *Ops, size_t NumOperands,
1208 ScalarEvolution &SE) {
1209 bool Interesting = false;
1211 // Iterate over the add operands. They are sorted, with constants first.
1213 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1215 // Pull a buried constant out to the outside.
1216 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1218 AccumulatedConstant += Scale * C->getValue()->getValue();
1221 // Next comes everything else. We're especially interested in multiplies
1222 // here, but they're in the middle, so just visit the rest with one loop.
1223 for (; i != NumOperands; ++i) {
1224 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1225 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1227 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1228 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1229 // A multiplication of a constant with another add; recurse.
1230 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
1232 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1233 Add->op_begin(), Add->getNumOperands(),
1236 // A multiplication of a constant with some other value. Update
1238 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1239 const SCEV *Key = SE.getMulExpr(MulOps);
1240 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1241 M.insert(std::make_pair(Key, NewScale));
1243 NewOps.push_back(Pair.first->first);
1245 Pair.first->second += NewScale;
1246 // The map already had an entry for this value, which may indicate
1247 // a folding opportunity.
1252 // An ordinary operand. Update the map.
1253 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1254 M.insert(std::make_pair(Ops[i], Scale));
1256 NewOps.push_back(Pair.first->first);
1258 Pair.first->second += Scale;
1259 // The map already had an entry for this value, which may indicate
1260 // a folding opportunity.
1270 struct APIntCompare {
1271 bool operator()(const APInt &LHS, const APInt &RHS) const {
1272 return LHS.ult(RHS);
1277 /// getAddExpr - Get a canonical add expression, or something simpler if
1279 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1280 bool HasNUW, bool HasNSW) {
1281 assert(!Ops.empty() && "Cannot get empty add!");
1282 if (Ops.size() == 1) return Ops[0];
1284 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
1285 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1286 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
1287 "SCEVAddExpr operand types don't match!");
1290 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1291 if (!HasNUW && HasNSW) {
1293 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1294 if (!isKnownNonNegative(Ops[i])) {
1298 if (All) HasNUW = true;
1301 // Sort by complexity, this groups all similar expression types together.
1302 GroupByComplexity(Ops, LI);
1304 // If there are any constants, fold them together.
1306 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1308 assert(Idx < Ops.size());
1309 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1310 // We found two constants, fold them together!
1311 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1312 RHSC->getValue()->getValue());
1313 if (Ops.size() == 2) return Ops[0];
1314 Ops.erase(Ops.begin()+1); // Erase the folded element
1315 LHSC = cast<SCEVConstant>(Ops[0]);
1318 // If we are left with a constant zero being added, strip it off.
1319 if (LHSC->getValue()->isZero()) {
1320 Ops.erase(Ops.begin());
1324 if (Ops.size() == 1) return Ops[0];
1327 // Okay, check to see if the same value occurs in the operand list twice. If
1328 // so, merge them together into an multiply expression. Since we sorted the
1329 // list, these values are required to be adjacent.
1330 const Type *Ty = Ops[0]->getType();
1331 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1332 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1333 // Found a match, merge the two values into a multiply, and add any
1334 // remaining values to the result.
1335 const SCEV *Two = getConstant(Ty, 2);
1336 const SCEV *Mul = getMulExpr(Ops[i], Two);
1337 if (Ops.size() == 2)
1339 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1341 return getAddExpr(Ops, HasNUW, HasNSW);
1344 // Check for truncates. If all the operands are truncated from the same
1345 // type, see if factoring out the truncate would permit the result to be
1346 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1347 // if the contents of the resulting outer trunc fold to something simple.
1348 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1349 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1350 const Type *DstType = Trunc->getType();
1351 const Type *SrcType = Trunc->getOperand()->getType();
1352 SmallVector<const SCEV *, 8> LargeOps;
1354 // Check all the operands to see if they can be represented in the
1355 // source type of the truncate.
1356 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1357 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1358 if (T->getOperand()->getType() != SrcType) {
1362 LargeOps.push_back(T->getOperand());
1363 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1364 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
1365 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
1366 SmallVector<const SCEV *, 8> LargeMulOps;
1367 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1368 if (const SCEVTruncateExpr *T =
1369 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1370 if (T->getOperand()->getType() != SrcType) {
1374 LargeMulOps.push_back(T->getOperand());
1375 } else if (const SCEVConstant *C =
1376 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1377 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
1384 LargeOps.push_back(getMulExpr(LargeMulOps));
1391 // Evaluate the expression in the larger type.
1392 const SCEV *Fold = getAddExpr(LargeOps, HasNUW, HasNSW);
1393 // If it folds to something simple, use it. Otherwise, don't.
1394 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1395 return getTruncateExpr(Fold, DstType);
1399 // Skip past any other cast SCEVs.
1400 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1403 // If there are add operands they would be next.
1404 if (Idx < Ops.size()) {
1405 bool DeletedAdd = false;
1406 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
1407 // If we have an add, expand the add operands onto the end of the operands
1409 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1410 Ops.erase(Ops.begin()+Idx);
1414 // If we deleted at least one add, we added operands to the end of the list,
1415 // and they are not necessarily sorted. Recurse to resort and resimplify
1416 // any operands we just acquired.
1418 return getAddExpr(Ops);
1421 // Skip over the add expression until we get to a multiply.
1422 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1425 // Check to see if there are any folding opportunities present with
1426 // operands multiplied by constant values.
1427 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1428 uint64_t BitWidth = getTypeSizeInBits(Ty);
1429 DenseMap<const SCEV *, APInt> M;
1430 SmallVector<const SCEV *, 8> NewOps;
1431 APInt AccumulatedConstant(BitWidth, 0);
1432 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1433 Ops.data(), Ops.size(),
1434 APInt(BitWidth, 1), *this)) {
1435 // Some interesting folding opportunity is present, so its worthwhile to
1436 // re-generate the operands list. Group the operands by constant scale,
1437 // to avoid multiplying by the same constant scale multiple times.
1438 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1439 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
1440 E = NewOps.end(); I != E; ++I)
1441 MulOpLists[M.find(*I)->second].push_back(*I);
1442 // Re-generate the operands list.
1444 if (AccumulatedConstant != 0)
1445 Ops.push_back(getConstant(AccumulatedConstant));
1446 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1447 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
1449 Ops.push_back(getMulExpr(getConstant(I->first),
1450 getAddExpr(I->second)));
1452 return getConstant(Ty, 0);
1453 if (Ops.size() == 1)
1455 return getAddExpr(Ops);
1459 // If we are adding something to a multiply expression, make sure the
1460 // something is not already an operand of the multiply. If so, merge it into
1462 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
1463 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
1464 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
1465 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
1466 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
1467 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
1468 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1469 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
1470 if (Mul->getNumOperands() != 2) {
1471 // If the multiply has more than two operands, we must get the
1473 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
1474 MulOps.erase(MulOps.begin()+MulOp);
1475 InnerMul = getMulExpr(MulOps);
1477 const SCEV *One = getConstant(Ty, 1);
1478 const SCEV *AddOne = getAddExpr(InnerMul, One);
1479 const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
1480 if (Ops.size() == 2) return OuterMul;
1482 Ops.erase(Ops.begin()+AddOp);
1483 Ops.erase(Ops.begin()+Idx-1);
1485 Ops.erase(Ops.begin()+Idx);
1486 Ops.erase(Ops.begin()+AddOp-1);
1488 Ops.push_back(OuterMul);
1489 return getAddExpr(Ops);
1492 // Check this multiply against other multiplies being added together.
1493 for (unsigned OtherMulIdx = Idx+1;
1494 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1496 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
1497 // If MulOp occurs in OtherMul, we can fold the two multiplies
1499 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1500 OMulOp != e; ++OMulOp)
1501 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1502 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1503 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
1504 if (Mul->getNumOperands() != 2) {
1505 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1507 MulOps.erase(MulOps.begin()+MulOp);
1508 InnerMul1 = getMulExpr(MulOps);
1510 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1511 if (OtherMul->getNumOperands() != 2) {
1512 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1513 OtherMul->op_end());
1514 MulOps.erase(MulOps.begin()+OMulOp);
1515 InnerMul2 = getMulExpr(MulOps);
1517 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1518 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
1519 if (Ops.size() == 2) return OuterMul;
1520 Ops.erase(Ops.begin()+Idx);
1521 Ops.erase(Ops.begin()+OtherMulIdx-1);
1522 Ops.push_back(OuterMul);
1523 return getAddExpr(Ops);
1529 // If there are any add recurrences in the operands list, see if any other
1530 // added values are loop invariant. If so, we can fold them into the
1532 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1535 // Scan over all recurrences, trying to fold loop invariants into them.
1536 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1537 // Scan all of the other operands to this add and add them to the vector if
1538 // they are loop invariant w.r.t. the recurrence.
1539 SmallVector<const SCEV *, 8> LIOps;
1540 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1541 const Loop *AddRecLoop = AddRec->getLoop();
1542 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1543 if (Ops[i]->isLoopInvariant(AddRecLoop)) {
1544 LIOps.push_back(Ops[i]);
1545 Ops.erase(Ops.begin()+i);
1549 // If we found some loop invariants, fold them into the recurrence.
1550 if (!LIOps.empty()) {
1551 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
1552 LIOps.push_back(AddRec->getStart());
1554 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
1556 AddRecOps[0] = getAddExpr(LIOps);
1558 // It's tempting to propagate NUW/NSW flags here, but nuw/nsw addition
1559 // is not associative so this isn't necessarily safe.
1560 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop);
1562 // If all of the other operands were loop invariant, we are done.
1563 if (Ops.size() == 1) return NewRec;
1565 // Otherwise, add the folded AddRec by the non-liv parts.
1566 for (unsigned i = 0;; ++i)
1567 if (Ops[i] == AddRec) {
1571 return getAddExpr(Ops);
1574 // Okay, if there weren't any loop invariants to be folded, check to see if
1575 // there are multiple AddRec's with the same loop induction variable being
1576 // added together. If so, we can fold them.
1577 for (unsigned OtherIdx = Idx+1;
1578 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1579 if (OtherIdx != Idx) {
1580 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1581 if (AddRecLoop == OtherAddRec->getLoop()) {
1582 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1583 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1585 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1586 if (i >= NewOps.size()) {
1587 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1588 OtherAddRec->op_end());
1591 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
1593 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRecLoop);
1595 if (Ops.size() == 2) return NewAddRec;
1597 Ops.erase(Ops.begin()+Idx);
1598 Ops.erase(Ops.begin()+OtherIdx-1);
1599 Ops.push_back(NewAddRec);
1600 return getAddExpr(Ops);
1604 // Otherwise couldn't fold anything into this recurrence. Move onto the
1608 // Okay, it looks like we really DO need an add expr. Check to see if we
1609 // already have one, otherwise create a new one.
1610 FoldingSetNodeID ID;
1611 ID.AddInteger(scAddExpr);
1612 ID.AddInteger(Ops.size());
1613 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1614 ID.AddPointer(Ops[i]);
1617 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1619 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1620 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
1621 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
1623 UniqueSCEVs.InsertNode(S, IP);
1625 if (HasNUW) S->setHasNoUnsignedWrap(true);
1626 if (HasNSW) S->setHasNoSignedWrap(true);
1630 /// getMulExpr - Get a canonical multiply expression, or something simpler if
1632 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1633 bool HasNUW, bool HasNSW) {
1634 assert(!Ops.empty() && "Cannot get empty mul!");
1635 if (Ops.size() == 1) return Ops[0];
1637 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1638 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1639 getEffectiveSCEVType(Ops[0]->getType()) &&
1640 "SCEVMulExpr operand types don't match!");
1643 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1644 if (!HasNUW && HasNSW) {
1646 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1647 if (!isKnownNonNegative(Ops[i])) {
1651 if (All) HasNUW = true;
1654 // Sort by complexity, this groups all similar expression types together.
1655 GroupByComplexity(Ops, LI);
1657 // If there are any constants, fold them together.
1659 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1661 // C1*(C2+V) -> C1*C2 + C1*V
1662 if (Ops.size() == 2)
1663 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1664 if (Add->getNumOperands() == 2 &&
1665 isa<SCEVConstant>(Add->getOperand(0)))
1666 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1667 getMulExpr(LHSC, Add->getOperand(1)));
1670 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1671 // We found two constants, fold them together!
1672 ConstantInt *Fold = ConstantInt::get(getContext(),
1673 LHSC->getValue()->getValue() *
1674 RHSC->getValue()->getValue());
1675 Ops[0] = getConstant(Fold);
1676 Ops.erase(Ops.begin()+1); // Erase the folded element
1677 if (Ops.size() == 1) return Ops[0];
1678 LHSC = cast<SCEVConstant>(Ops[0]);
1681 // If we are left with a constant one being multiplied, strip it off.
1682 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1683 Ops.erase(Ops.begin());
1685 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1686 // If we have a multiply of zero, it will always be zero.
1688 } else if (Ops[0]->isAllOnesValue()) {
1689 // If we have a mul by -1 of an add, try distributing the -1 among the
1691 if (Ops.size() == 2)
1692 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1693 SmallVector<const SCEV *, 4> NewOps;
1694 bool AnyFolded = false;
1695 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1697 const SCEV *Mul = getMulExpr(Ops[0], *I);
1698 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1699 NewOps.push_back(Mul);
1702 return getAddExpr(NewOps);
1706 if (Ops.size() == 1)
1710 // Skip over the add expression until we get to a multiply.
1711 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1714 // If there are mul operands inline them all into this expression.
1715 if (Idx < Ops.size()) {
1716 bool DeletedMul = false;
1717 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1718 // If we have an mul, expand the mul operands onto the end of the operands
1720 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1721 Ops.erase(Ops.begin()+Idx);
1725 // If we deleted at least one mul, we added operands to the end of the list,
1726 // and they are not necessarily sorted. Recurse to resort and resimplify
1727 // any operands we just acquired.
1729 return getMulExpr(Ops);
1732 // If there are any add recurrences in the operands list, see if any other
1733 // added values are loop invariant. If so, we can fold them into the
1735 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1738 // Scan over all recurrences, trying to fold loop invariants into them.
1739 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1740 // Scan all of the other operands to this mul and add them to the vector if
1741 // they are loop invariant w.r.t. the recurrence.
1742 SmallVector<const SCEV *, 8> LIOps;
1743 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1744 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1745 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1746 LIOps.push_back(Ops[i]);
1747 Ops.erase(Ops.begin()+i);
1751 // If we found some loop invariants, fold them into the recurrence.
1752 if (!LIOps.empty()) {
1753 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
1754 SmallVector<const SCEV *, 4> NewOps;
1755 NewOps.reserve(AddRec->getNumOperands());
1756 const SCEV *Scale = getMulExpr(LIOps);
1757 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1758 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1760 // It's tempting to propagate the NSW flag here, but nsw multiplication
1761 // is not associative so this isn't necessarily safe.
1762 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(),
1763 HasNUW && AddRec->hasNoUnsignedWrap(),
1766 // If all of the other operands were loop invariant, we are done.
1767 if (Ops.size() == 1) return NewRec;
1769 // Otherwise, multiply the folded AddRec by the non-liv parts.
1770 for (unsigned i = 0;; ++i)
1771 if (Ops[i] == AddRec) {
1775 return getMulExpr(Ops);
1778 // Okay, if there weren't any loop invariants to be folded, check to see if
1779 // there are multiple AddRec's with the same loop induction variable being
1780 // multiplied together. If so, we can fold them.
1781 for (unsigned OtherIdx = Idx+1;
1782 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1783 if (OtherIdx != Idx) {
1784 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1785 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1786 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1787 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1788 const SCEV *NewStart = getMulExpr(F->getStart(),
1790 const SCEV *B = F->getStepRecurrence(*this);
1791 const SCEV *D = G->getStepRecurrence(*this);
1792 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
1795 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
1797 if (Ops.size() == 2) return NewAddRec;
1799 Ops.erase(Ops.begin()+Idx);
1800 Ops.erase(Ops.begin()+OtherIdx-1);
1801 Ops.push_back(NewAddRec);
1802 return getMulExpr(Ops);
1806 // Otherwise couldn't fold anything into this recurrence. Move onto the
1810 // Okay, it looks like we really DO need an mul expr. Check to see if we
1811 // already have one, otherwise create a new one.
1812 FoldingSetNodeID ID;
1813 ID.AddInteger(scMulExpr);
1814 ID.AddInteger(Ops.size());
1815 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1816 ID.AddPointer(Ops[i]);
1819 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1821 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1822 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
1823 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
1825 UniqueSCEVs.InsertNode(S, IP);
1827 if (HasNUW) S->setHasNoUnsignedWrap(true);
1828 if (HasNSW) S->setHasNoSignedWrap(true);
1832 /// getUDivExpr - Get a canonical unsigned division expression, or something
1833 /// simpler if possible.
1834 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1836 assert(getEffectiveSCEVType(LHS->getType()) ==
1837 getEffectiveSCEVType(RHS->getType()) &&
1838 "SCEVUDivExpr operand types don't match!");
1840 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1841 if (RHSC->getValue()->equalsInt(1))
1842 return LHS; // X udiv 1 --> x
1843 // If the denominator is zero, the result of the udiv is undefined. Don't
1844 // try to analyze it, because the resolution chosen here may differ from
1845 // the resolution chosen in other parts of the compiler.
1846 if (!RHSC->getValue()->isZero()) {
1847 // Determine if the division can be folded into the operands of
1849 // TODO: Generalize this to non-constants by using known-bits information.
1850 const Type *Ty = LHS->getType();
1851 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1852 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1853 // For non-power-of-two values, effectively round the value up to the
1854 // nearest power of two.
1855 if (!RHSC->getValue()->getValue().isPowerOf2())
1857 const IntegerType *ExtTy =
1858 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
1859 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1860 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1861 if (const SCEVConstant *Step =
1862 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1863 if (!Step->getValue()->getValue()
1864 .urem(RHSC->getValue()->getValue()) &&
1865 getZeroExtendExpr(AR, ExtTy) ==
1866 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1867 getZeroExtendExpr(Step, ExtTy),
1869 SmallVector<const SCEV *, 4> Operands;
1870 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1871 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1872 return getAddRecExpr(Operands, AR->getLoop());
1874 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1875 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1876 SmallVector<const SCEV *, 4> Operands;
1877 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1878 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1879 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
1880 // Find an operand that's safely divisible.
1881 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1882 const SCEV *Op = M->getOperand(i);
1883 const SCEV *Div = getUDivExpr(Op, RHSC);
1884 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1885 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
1888 return getMulExpr(Operands);
1892 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
1893 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1894 SmallVector<const SCEV *, 4> Operands;
1895 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1896 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1897 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1899 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1900 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
1901 if (isa<SCEVUDivExpr>(Op) ||
1902 getMulExpr(Op, RHS) != A->getOperand(i))
1904 Operands.push_back(Op);
1906 if (Operands.size() == A->getNumOperands())
1907 return getAddExpr(Operands);
1911 // Fold if both operands are constant.
1912 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1913 Constant *LHSCV = LHSC->getValue();
1914 Constant *RHSCV = RHSC->getValue();
1915 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1921 FoldingSetNodeID ID;
1922 ID.AddInteger(scUDivExpr);
1926 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1927 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
1929 UniqueSCEVs.InsertNode(S, IP);
1934 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1935 /// Simplify the expression as much as possible.
1936 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
1937 const SCEV *Step, const Loop *L,
1938 bool HasNUW, bool HasNSW) {
1939 SmallVector<const SCEV *, 4> Operands;
1940 Operands.push_back(Start);
1941 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1942 if (StepChrec->getLoop() == L) {
1943 Operands.insert(Operands.end(), StepChrec->op_begin(),
1944 StepChrec->op_end());
1945 return getAddRecExpr(Operands, L);
1948 Operands.push_back(Step);
1949 return getAddRecExpr(Operands, L, HasNUW, HasNSW);
1952 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1953 /// Simplify the expression as much as possible.
1955 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
1957 bool HasNUW, bool HasNSW) {
1958 if (Operands.size() == 1) return Operands[0];
1960 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1961 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1962 getEffectiveSCEVType(Operands[0]->getType()) &&
1963 "SCEVAddRecExpr operand types don't match!");
1966 if (Operands.back()->isZero()) {
1967 Operands.pop_back();
1968 return getAddRecExpr(Operands, L, HasNUW, HasNSW); // {X,+,0} --> X
1971 // It's tempting to want to call getMaxBackedgeTakenCount count here and
1972 // use that information to infer NUW and NSW flags. However, computing a
1973 // BE count requires calling getAddRecExpr, so we may not yet have a
1974 // meaningful BE count at this point (and if we don't, we'd be stuck
1975 // with a SCEVCouldNotCompute as the cached BE count).
1977 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1978 if (!HasNUW && HasNSW) {
1980 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1981 if (!isKnownNonNegative(Operands[i])) {
1985 if (All) HasNUW = true;
1988 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1989 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1990 const Loop *NestedLoop = NestedAR->getLoop();
1991 if (L->contains(NestedLoop->getHeader()) ?
1992 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
1993 (!NestedLoop->contains(L->getHeader()) &&
1994 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
1995 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
1996 NestedAR->op_end());
1997 Operands[0] = NestedAR->getStart();
1998 // AddRecs require their operands be loop-invariant with respect to their
1999 // loops. Don't perform this transformation if it would break this
2001 bool AllInvariant = true;
2002 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2003 if (!Operands[i]->isLoopInvariant(L)) {
2004 AllInvariant = false;
2008 NestedOperands[0] = getAddRecExpr(Operands, L);
2009 AllInvariant = true;
2010 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
2011 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
2012 AllInvariant = false;
2016 // Ok, both add recurrences are valid after the transformation.
2017 return getAddRecExpr(NestedOperands, NestedLoop, HasNUW, HasNSW);
2019 // Reset Operands to its original state.
2020 Operands[0] = NestedAR;
2024 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2025 // already have one, otherwise create a new one.
2026 FoldingSetNodeID ID;
2027 ID.AddInteger(scAddRecExpr);
2028 ID.AddInteger(Operands.size());
2029 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2030 ID.AddPointer(Operands[i]);
2034 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2036 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2037 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
2038 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2039 O, Operands.size(), L);
2040 UniqueSCEVs.InsertNode(S, IP);
2042 if (HasNUW) S->setHasNoUnsignedWrap(true);
2043 if (HasNSW) S->setHasNoSignedWrap(true);
2047 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2049 SmallVector<const SCEV *, 2> Ops;
2052 return getSMaxExpr(Ops);
2056 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2057 assert(!Ops.empty() && "Cannot get empty smax!");
2058 if (Ops.size() == 1) return Ops[0];
2060 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2061 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2062 getEffectiveSCEVType(Ops[0]->getType()) &&
2063 "SCEVSMaxExpr operand types don't match!");
2066 // Sort by complexity, this groups all similar expression types together.
2067 GroupByComplexity(Ops, LI);
2069 // If there are any constants, fold them together.
2071 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2073 assert(Idx < Ops.size());
2074 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2075 // We found two constants, fold them together!
2076 ConstantInt *Fold = ConstantInt::get(getContext(),
2077 APIntOps::smax(LHSC->getValue()->getValue(),
2078 RHSC->getValue()->getValue()));
2079 Ops[0] = getConstant(Fold);
2080 Ops.erase(Ops.begin()+1); // Erase the folded element
2081 if (Ops.size() == 1) return Ops[0];
2082 LHSC = cast<SCEVConstant>(Ops[0]);
2085 // If we are left with a constant minimum-int, strip it off.
2086 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2087 Ops.erase(Ops.begin());
2089 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2090 // If we have an smax with a constant maximum-int, it will always be
2095 if (Ops.size() == 1) return Ops[0];
2098 // Find the first SMax
2099 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2102 // Check to see if one of the operands is an SMax. If so, expand its operands
2103 // onto our operand list, and recurse to simplify.
2104 if (Idx < Ops.size()) {
2105 bool DeletedSMax = false;
2106 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
2107 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
2108 Ops.erase(Ops.begin()+Idx);
2113 return getSMaxExpr(Ops);
2116 // Okay, check to see if the same value occurs in the operand list twice. If
2117 // so, delete one. Since we sorted the list, these values are required to
2119 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2120 // X smax Y smax Y --> X smax Y
2121 // X smax Y --> X, if X is always greater than Y
2122 if (Ops[i] == Ops[i+1] ||
2123 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
2124 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2126 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
2127 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2131 if (Ops.size() == 1) return Ops[0];
2133 assert(!Ops.empty() && "Reduced smax down to nothing!");
2135 // Okay, it looks like we really DO need an smax expr. Check to see if we
2136 // already have one, otherwise create a new one.
2137 FoldingSetNodeID ID;
2138 ID.AddInteger(scSMaxExpr);
2139 ID.AddInteger(Ops.size());
2140 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2141 ID.AddPointer(Ops[i]);
2143 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2144 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2145 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2146 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
2148 UniqueSCEVs.InsertNode(S, IP);
2152 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2154 SmallVector<const SCEV *, 2> Ops;
2157 return getUMaxExpr(Ops);
2161 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2162 assert(!Ops.empty() && "Cannot get empty umax!");
2163 if (Ops.size() == 1) return Ops[0];
2165 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2166 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2167 getEffectiveSCEVType(Ops[0]->getType()) &&
2168 "SCEVUMaxExpr operand types don't match!");
2171 // Sort by complexity, this groups all similar expression types together.
2172 GroupByComplexity(Ops, LI);
2174 // If there are any constants, fold them together.
2176 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2178 assert(Idx < Ops.size());
2179 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2180 // We found two constants, fold them together!
2181 ConstantInt *Fold = ConstantInt::get(getContext(),
2182 APIntOps::umax(LHSC->getValue()->getValue(),
2183 RHSC->getValue()->getValue()));
2184 Ops[0] = getConstant(Fold);
2185 Ops.erase(Ops.begin()+1); // Erase the folded element
2186 if (Ops.size() == 1) return Ops[0];
2187 LHSC = cast<SCEVConstant>(Ops[0]);
2190 // If we are left with a constant minimum-int, strip it off.
2191 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2192 Ops.erase(Ops.begin());
2194 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2195 // If we have an umax with a constant maximum-int, it will always be
2200 if (Ops.size() == 1) return Ops[0];
2203 // Find the first UMax
2204 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2207 // Check to see if one of the operands is a UMax. If so, expand its operands
2208 // onto our operand list, and recurse to simplify.
2209 if (Idx < Ops.size()) {
2210 bool DeletedUMax = false;
2211 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
2212 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
2213 Ops.erase(Ops.begin()+Idx);
2218 return getUMaxExpr(Ops);
2221 // Okay, check to see if the same value occurs in the operand list twice. If
2222 // so, delete one. Since we sorted the list, these values are required to
2224 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2225 // X umax Y umax Y --> X umax Y
2226 // X umax Y --> X, if X is always greater than Y
2227 if (Ops[i] == Ops[i+1] ||
2228 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
2229 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2231 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
2232 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2236 if (Ops.size() == 1) return Ops[0];
2238 assert(!Ops.empty() && "Reduced umax down to nothing!");
2240 // Okay, it looks like we really DO need a umax expr. Check to see if we
2241 // already have one, otherwise create a new one.
2242 FoldingSetNodeID ID;
2243 ID.AddInteger(scUMaxExpr);
2244 ID.AddInteger(Ops.size());
2245 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2246 ID.AddPointer(Ops[i]);
2248 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2249 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2250 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2251 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
2253 UniqueSCEVs.InsertNode(S, IP);
2257 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2259 // ~smax(~x, ~y) == smin(x, y).
2260 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2263 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2265 // ~umax(~x, ~y) == umin(x, y)
2266 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2269 const SCEV *ScalarEvolution::getSizeOfExpr(const Type *AllocTy) {
2270 // If we have TargetData, we can bypass creating a target-independent
2271 // constant expression and then folding it back into a ConstantInt.
2272 // This is just a compile-time optimization.
2274 return getConstant(TD->getIntPtrType(getContext()),
2275 TD->getTypeAllocSize(AllocTy));
2277 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2278 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2279 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2281 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2282 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2285 const SCEV *ScalarEvolution::getAlignOfExpr(const Type *AllocTy) {
2286 Constant *C = ConstantExpr::getAlignOf(AllocTy);
2287 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2288 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2290 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2291 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2294 const SCEV *ScalarEvolution::getOffsetOfExpr(const StructType *STy,
2296 // If we have TargetData, we can bypass creating a target-independent
2297 // constant expression and then folding it back into a ConstantInt.
2298 // This is just a compile-time optimization.
2300 return getConstant(TD->getIntPtrType(getContext()),
2301 TD->getStructLayout(STy)->getElementOffset(FieldNo));
2303 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2304 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2305 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2307 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
2308 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2311 const SCEV *ScalarEvolution::getOffsetOfExpr(const Type *CTy,
2312 Constant *FieldNo) {
2313 Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
2314 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2315 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2317 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
2318 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2321 const SCEV *ScalarEvolution::getUnknown(Value *V) {
2322 // Don't attempt to do anything other than create a SCEVUnknown object
2323 // here. createSCEV only calls getUnknown after checking for all other
2324 // interesting possibilities, and any other code that calls getUnknown
2325 // is doing so in order to hide a value from SCEV canonicalization.
2327 FoldingSetNodeID ID;
2328 ID.AddInteger(scUnknown);
2331 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2332 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V);
2333 UniqueSCEVs.InsertNode(S, IP);
2337 //===----------------------------------------------------------------------===//
2338 // Basic SCEV Analysis and PHI Idiom Recognition Code
2341 /// isSCEVable - Test if values of the given type are analyzable within
2342 /// the SCEV framework. This primarily includes integer types, and it
2343 /// can optionally include pointer types if the ScalarEvolution class
2344 /// has access to target-specific information.
2345 bool ScalarEvolution::isSCEVable(const Type *Ty) const {
2346 // Integers and pointers are always SCEVable.
2347 return Ty->isIntegerTy() || Ty->isPointerTy();
2350 /// getTypeSizeInBits - Return the size in bits of the specified type,
2351 /// for which isSCEVable must return true.
2352 uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
2353 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2355 // If we have a TargetData, use it!
2357 return TD->getTypeSizeInBits(Ty);
2359 // Integer types have fixed sizes.
2360 if (Ty->isIntegerTy())
2361 return Ty->getPrimitiveSizeInBits();
2363 // The only other support type is pointer. Without TargetData, conservatively
2364 // assume pointers are 64-bit.
2365 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
2369 /// getEffectiveSCEVType - Return a type with the same bitwidth as
2370 /// the given type and which represents how SCEV will treat the given
2371 /// type, for which isSCEVable must return true. For pointer types,
2372 /// this is the pointer-sized integer type.
2373 const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
2374 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2376 if (Ty->isIntegerTy())
2379 // The only other support type is pointer.
2380 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
2381 if (TD) return TD->getIntPtrType(getContext());
2383 // Without TargetData, conservatively assume pointers are 64-bit.
2384 return Type::getInt64Ty(getContext());
2387 const SCEV *ScalarEvolution::getCouldNotCompute() {
2388 return &CouldNotCompute;
2391 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2392 /// expression and create a new one.
2393 const SCEV *ScalarEvolution::getSCEV(Value *V) {
2394 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
2396 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
2397 if (I != Scalars.end()) return I->second;
2398 const SCEV *S = createSCEV(V);
2399 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
2403 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2405 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
2406 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2408 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
2410 const Type *Ty = V->getType();
2411 Ty = getEffectiveSCEVType(Ty);
2412 return getMulExpr(V,
2413 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
2416 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
2417 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
2418 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2420 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
2422 const Type *Ty = V->getType();
2423 Ty = getEffectiveSCEVType(Ty);
2424 const SCEV *AllOnes =
2425 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
2426 return getMinusSCEV(AllOnes, V);
2429 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2431 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2434 return getAddExpr(LHS, getNegativeSCEV(RHS));
2437 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2438 /// input value to the specified type. If the type must be extended, it is zero
2441 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
2443 const Type *SrcTy = V->getType();
2444 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2445 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2446 "Cannot truncate or zero extend with non-integer arguments!");
2447 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2448 return V; // No conversion
2449 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2450 return getTruncateExpr(V, Ty);
2451 return getZeroExtendExpr(V, Ty);
2454 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2455 /// input value to the specified type. If the type must be extended, it is sign
2458 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
2460 const Type *SrcTy = V->getType();
2461 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2462 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2463 "Cannot truncate or zero extend with non-integer arguments!");
2464 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2465 return V; // No conversion
2466 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2467 return getTruncateExpr(V, Ty);
2468 return getSignExtendExpr(V, Ty);
2471 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2472 /// input value to the specified type. If the type must be extended, it is zero
2473 /// extended. The conversion must not be narrowing.
2475 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
2476 const Type *SrcTy = V->getType();
2477 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2478 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2479 "Cannot noop or zero extend with non-integer arguments!");
2480 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2481 "getNoopOrZeroExtend cannot truncate!");
2482 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2483 return V; // No conversion
2484 return getZeroExtendExpr(V, Ty);
2487 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2488 /// input value to the specified type. If the type must be extended, it is sign
2489 /// extended. The conversion must not be narrowing.
2491 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
2492 const Type *SrcTy = V->getType();
2493 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2494 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2495 "Cannot noop or sign extend with non-integer arguments!");
2496 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2497 "getNoopOrSignExtend cannot truncate!");
2498 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2499 return V; // No conversion
2500 return getSignExtendExpr(V, Ty);
2503 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2504 /// the input value to the specified type. If the type must be extended,
2505 /// it is extended with unspecified bits. The conversion must not be
2508 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
2509 const Type *SrcTy = V->getType();
2510 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2511 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2512 "Cannot noop or any extend with non-integer arguments!");
2513 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2514 "getNoopOrAnyExtend cannot truncate!");
2515 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2516 return V; // No conversion
2517 return getAnyExtendExpr(V, Ty);
2520 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2521 /// input value to the specified type. The conversion must not be widening.
2523 ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
2524 const Type *SrcTy = V->getType();
2525 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2526 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2527 "Cannot truncate or noop with non-integer arguments!");
2528 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2529 "getTruncateOrNoop cannot extend!");
2530 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2531 return V; // No conversion
2532 return getTruncateExpr(V, Ty);
2535 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2536 /// the types using zero-extension, and then perform a umax operation
2538 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2540 const SCEV *PromotedLHS = LHS;
2541 const SCEV *PromotedRHS = RHS;
2543 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2544 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2546 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2548 return getUMaxExpr(PromotedLHS, PromotedRHS);
2551 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
2552 /// the types using zero-extension, and then perform a umin operation
2554 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2556 const SCEV *PromotedLHS = LHS;
2557 const SCEV *PromotedRHS = RHS;
2559 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2560 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2562 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2564 return getUMinExpr(PromotedLHS, PromotedRHS);
2567 /// PushDefUseChildren - Push users of the given Instruction
2568 /// onto the given Worklist.
2570 PushDefUseChildren(Instruction *I,
2571 SmallVectorImpl<Instruction *> &Worklist) {
2572 // Push the def-use children onto the Worklist stack.
2573 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2575 Worklist.push_back(cast<Instruction>(UI));
2578 /// ForgetSymbolicValue - This looks up computed SCEV values for all
2579 /// instructions that depend on the given instruction and removes them from
2580 /// the Scalars map if they reference SymName. This is used during PHI
2583 ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
2584 SmallVector<Instruction *, 16> Worklist;
2585 PushDefUseChildren(PN, Worklist);
2587 SmallPtrSet<Instruction *, 8> Visited;
2589 while (!Worklist.empty()) {
2590 Instruction *I = Worklist.pop_back_val();
2591 if (!Visited.insert(I)) continue;
2593 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
2594 Scalars.find(static_cast<Value *>(I));
2595 if (It != Scalars.end()) {
2596 // Short-circuit the def-use traversal if the symbolic name
2597 // ceases to appear in expressions.
2598 if (It->second != SymName && !It->second->hasOperand(SymName))
2601 // SCEVUnknown for a PHI either means that it has an unrecognized
2602 // structure, it's a PHI that's in the progress of being computed
2603 // by createNodeForPHI, or it's a single-value PHI. In the first case,
2604 // additional loop trip count information isn't going to change anything.
2605 // In the second case, createNodeForPHI will perform the necessary
2606 // updates on its own when it gets to that point. In the third, we do
2607 // want to forget the SCEVUnknown.
2608 if (!isa<PHINode>(I) ||
2609 !isa<SCEVUnknown>(It->second) ||
2610 (I != PN && It->second == SymName)) {
2611 ValuesAtScopes.erase(It->second);
2616 PushDefUseChildren(I, Worklist);
2620 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2621 /// a loop header, making it a potential recurrence, or it doesn't.
2623 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
2624 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2625 if (L->getHeader() == PN->getParent()) {
2626 // The loop may have multiple entrances or multiple exits; we can analyze
2627 // this phi as an addrec if it has a unique entry value and a unique
2629 Value *BEValueV = 0, *StartValueV = 0;
2630 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2631 Value *V = PN->getIncomingValue(i);
2632 if (L->contains(PN->getIncomingBlock(i))) {
2635 } else if (BEValueV != V) {
2639 } else if (!StartValueV) {
2641 } else if (StartValueV != V) {
2646 if (BEValueV && StartValueV) {
2647 // While we are analyzing this PHI node, handle its value symbolically.
2648 const SCEV *SymbolicName = getUnknown(PN);
2649 assert(Scalars.find(PN) == Scalars.end() &&
2650 "PHI node already processed?");
2651 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
2653 // Using this symbolic name for the PHI, analyze the value coming around
2655 const SCEV *BEValue = getSCEV(BEValueV);
2657 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2658 // has a special value for the first iteration of the loop.
2660 // If the value coming around the backedge is an add with the symbolic
2661 // value we just inserted, then we found a simple induction variable!
2662 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
2663 // If there is a single occurrence of the symbolic value, replace it
2664 // with a recurrence.
2665 unsigned FoundIndex = Add->getNumOperands();
2666 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2667 if (Add->getOperand(i) == SymbolicName)
2668 if (FoundIndex == e) {
2673 if (FoundIndex != Add->getNumOperands()) {
2674 // Create an add with everything but the specified operand.
2675 SmallVector<const SCEV *, 8> Ops;
2676 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2677 if (i != FoundIndex)
2678 Ops.push_back(Add->getOperand(i));
2679 const SCEV *Accum = getAddExpr(Ops);
2681 // This is not a valid addrec if the step amount is varying each
2682 // loop iteration, but is not itself an addrec in this loop.
2683 if (Accum->isLoopInvariant(L) ||
2684 (isa<SCEVAddRecExpr>(Accum) &&
2685 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
2686 bool HasNUW = false;
2687 bool HasNSW = false;
2689 // If the increment doesn't overflow, then neither the addrec nor
2690 // the post-increment will overflow.
2691 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
2692 if (OBO->hasNoUnsignedWrap())
2694 if (OBO->hasNoSignedWrap())
2698 const SCEV *StartVal = getSCEV(StartValueV);
2699 const SCEV *PHISCEV =
2700 getAddRecExpr(StartVal, Accum, L, HasNUW, HasNSW);
2702 // Since the no-wrap flags are on the increment, they apply to the
2703 // post-incremented value as well.
2704 if (Accum->isLoopInvariant(L))
2705 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
2706 Accum, L, HasNUW, HasNSW);
2708 // Okay, for the entire analysis of this edge we assumed the PHI
2709 // to be symbolic. We now need to go back and purge all of the
2710 // entries for the scalars that use the symbolic expression.
2711 ForgetSymbolicName(PN, SymbolicName);
2712 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
2716 } else if (const SCEVAddRecExpr *AddRec =
2717 dyn_cast<SCEVAddRecExpr>(BEValue)) {
2718 // Otherwise, this could be a loop like this:
2719 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2720 // In this case, j = {1,+,1} and BEValue is j.
2721 // Because the other in-value of i (0) fits the evolution of BEValue
2722 // i really is an addrec evolution.
2723 if (AddRec->getLoop() == L && AddRec->isAffine()) {
2724 const SCEV *StartVal = getSCEV(StartValueV);
2726 // If StartVal = j.start - j.stride, we can use StartVal as the
2727 // initial step of the addrec evolution.
2728 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
2729 AddRec->getOperand(1))) {
2730 const SCEV *PHISCEV =
2731 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
2733 // Okay, for the entire analysis of this edge we assumed the PHI
2734 // to be symbolic. We now need to go back and purge all of the
2735 // entries for the scalars that use the symbolic expression.
2736 ForgetSymbolicName(PN, SymbolicName);
2737 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
2745 // If the PHI has a single incoming value, follow that value, unless the
2746 // PHI's incoming blocks are in a different loop, in which case doing so
2747 // risks breaking LCSSA form. Instcombine would normally zap these, but
2748 // it doesn't have DominatorTree information, so it may miss cases.
2749 if (Value *V = PN->hasConstantValue(DT)) {
2750 bool AllSameLoop = true;
2751 Loop *PNLoop = LI->getLoopFor(PN->getParent());
2752 for (size_t i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2753 if (LI->getLoopFor(PN->getIncomingBlock(i)) != PNLoop) {
2754 AllSameLoop = false;
2761 // If it's not a loop phi, we can't handle it yet.
2762 return getUnknown(PN);
2765 /// createNodeForGEP - Expand GEP instructions into add and multiply
2766 /// operations. This allows them to be analyzed by regular SCEV code.
2768 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
2770 bool InBounds = GEP->isInBounds();
2771 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
2772 Value *Base = GEP->getOperand(0);
2773 // Don't attempt to analyze GEPs over unsized objects.
2774 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2775 return getUnknown(GEP);
2776 const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
2777 gep_type_iterator GTI = gep_type_begin(GEP);
2778 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2782 // Compute the (potentially symbolic) offset in bytes for this index.
2783 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2784 // For a struct, add the member offset.
2785 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2786 TotalOffset = getAddExpr(TotalOffset,
2787 getOffsetOfExpr(STy, FieldNo),
2788 /*HasNUW=*/false, /*HasNSW=*/InBounds);
2790 // For an array, add the element offset, explicitly scaled.
2791 const SCEV *LocalOffset = getSCEV(Index);
2792 // Getelementptr indices are signed.
2793 LocalOffset = getTruncateOrSignExtend(LocalOffset, IntPtrTy);
2794 // Lower "inbounds" GEPs to NSW arithmetic.
2795 LocalOffset = getMulExpr(LocalOffset, getSizeOfExpr(*GTI),
2796 /*HasNUW=*/false, /*HasNSW=*/InBounds);
2797 TotalOffset = getAddExpr(TotalOffset, LocalOffset,
2798 /*HasNUW=*/false, /*HasNSW=*/InBounds);
2801 return getAddExpr(getSCEV(Base), TotalOffset,
2802 /*HasNUW=*/false, /*HasNSW=*/InBounds);
2805 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2806 /// guaranteed to end in (at every loop iteration). It is, at the same time,
2807 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2808 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
2810 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
2811 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2812 return C->getValue()->getValue().countTrailingZeros();
2814 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
2815 return std::min(GetMinTrailingZeros(T->getOperand()),
2816 (uint32_t)getTypeSizeInBits(T->getType()));
2818 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
2819 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2820 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2821 getTypeSizeInBits(E->getType()) : OpRes;
2824 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
2825 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2826 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2827 getTypeSizeInBits(E->getType()) : OpRes;
2830 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
2831 // The result is the min of all operands results.
2832 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2833 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2834 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2838 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
2839 // The result is the sum of all operands results.
2840 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2841 uint32_t BitWidth = getTypeSizeInBits(M->getType());
2842 for (unsigned i = 1, e = M->getNumOperands();
2843 SumOpRes != BitWidth && i != e; ++i)
2844 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
2849 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
2850 // The result is the min of all operands results.
2851 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2852 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2853 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2857 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
2858 // The result is the min of all operands results.
2859 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2860 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2861 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2865 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
2866 // The result is the min of all operands results.
2867 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2868 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2869 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2873 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2874 // For a SCEVUnknown, ask ValueTracking.
2875 unsigned BitWidth = getTypeSizeInBits(U->getType());
2876 APInt Mask = APInt::getAllOnesValue(BitWidth);
2877 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2878 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2879 return Zeros.countTrailingOnes();
2886 /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2889 ScalarEvolution::getUnsignedRange(const SCEV *S) {
2891 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2892 return ConstantRange(C->getValue()->getValue());
2894 unsigned BitWidth = getTypeSizeInBits(S->getType());
2895 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2897 // If the value has known zeros, the maximum unsigned value will have those
2898 // known zeros as well.
2899 uint32_t TZ = GetMinTrailingZeros(S);
2901 ConservativeResult =
2902 ConstantRange(APInt::getMinValue(BitWidth),
2903 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
2905 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2906 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2907 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2908 X = X.add(getUnsignedRange(Add->getOperand(i)));
2909 return ConservativeResult.intersectWith(X);
2912 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2913 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2914 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2915 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
2916 return ConservativeResult.intersectWith(X);
2919 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2920 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2921 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2922 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
2923 return ConservativeResult.intersectWith(X);
2926 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2927 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2928 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2929 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
2930 return ConservativeResult.intersectWith(X);
2933 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2934 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2935 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
2936 return ConservativeResult.intersectWith(X.udiv(Y));
2939 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2940 ConstantRange X = getUnsignedRange(ZExt->getOperand());
2941 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
2944 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2945 ConstantRange X = getUnsignedRange(SExt->getOperand());
2946 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
2949 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2950 ConstantRange X = getUnsignedRange(Trunc->getOperand());
2951 return ConservativeResult.intersectWith(X.truncate(BitWidth));
2954 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2955 // If there's no unsigned wrap, the value will never be less than its
2957 if (AddRec->hasNoUnsignedWrap())
2958 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
2959 if (!C->getValue()->isZero())
2960 ConservativeResult =
2961 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0));
2963 // TODO: non-affine addrec
2964 if (AddRec->isAffine()) {
2965 const Type *Ty = AddRec->getType();
2966 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2967 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
2968 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
2969 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2971 const SCEV *Start = AddRec->getStart();
2972 const SCEV *Step = AddRec->getStepRecurrence(*this);
2974 ConstantRange StartRange = getUnsignedRange(Start);
2975 ConstantRange StepRange = getSignedRange(Step);
2976 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
2977 ConstantRange EndRange =
2978 StartRange.add(MaxBECountRange.multiply(StepRange));
2980 // Check for overflow. This must be done with ConstantRange arithmetic
2981 // because we could be called from within the ScalarEvolution overflow
2983 ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
2984 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
2985 ConstantRange ExtMaxBECountRange =
2986 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
2987 ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
2988 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
2990 return ConservativeResult;
2992 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
2993 EndRange.getUnsignedMin());
2994 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
2995 EndRange.getUnsignedMax());
2996 if (Min.isMinValue() && Max.isMaxValue())
2997 return ConservativeResult;
2998 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
3002 return ConservativeResult;
3005 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3006 // For a SCEVUnknown, ask ValueTracking.
3007 APInt Mask = APInt::getAllOnesValue(BitWidth);
3008 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3009 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
3010 if (Ones == ~Zeros + 1)
3011 return ConservativeResult;
3012 return ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
3015 return ConservativeResult;
3018 /// getSignedRange - Determine the signed range for a particular SCEV.
3021 ScalarEvolution::getSignedRange(const SCEV *S) {
3023 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
3024 return ConstantRange(C->getValue()->getValue());
3026 unsigned BitWidth = getTypeSizeInBits(S->getType());
3027 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3029 // If the value has known zeros, the maximum signed value will have those
3030 // known zeros as well.
3031 uint32_t TZ = GetMinTrailingZeros(S);
3033 ConservativeResult =
3034 ConstantRange(APInt::getSignedMinValue(BitWidth),
3035 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
3037 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3038 ConstantRange X = getSignedRange(Add->getOperand(0));
3039 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3040 X = X.add(getSignedRange(Add->getOperand(i)));
3041 return ConservativeResult.intersectWith(X);
3044 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3045 ConstantRange X = getSignedRange(Mul->getOperand(0));
3046 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3047 X = X.multiply(getSignedRange(Mul->getOperand(i)));
3048 return ConservativeResult.intersectWith(X);
3051 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3052 ConstantRange X = getSignedRange(SMax->getOperand(0));
3053 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3054 X = X.smax(getSignedRange(SMax->getOperand(i)));
3055 return ConservativeResult.intersectWith(X);
3058 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3059 ConstantRange X = getSignedRange(UMax->getOperand(0));
3060 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3061 X = X.umax(getSignedRange(UMax->getOperand(i)));
3062 return ConservativeResult.intersectWith(X);
3065 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3066 ConstantRange X = getSignedRange(UDiv->getLHS());
3067 ConstantRange Y = getSignedRange(UDiv->getRHS());
3068 return ConservativeResult.intersectWith(X.udiv(Y));
3071 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3072 ConstantRange X = getSignedRange(ZExt->getOperand());
3073 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
3076 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3077 ConstantRange X = getSignedRange(SExt->getOperand());
3078 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
3081 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3082 ConstantRange X = getSignedRange(Trunc->getOperand());
3083 return ConservativeResult.intersectWith(X.truncate(BitWidth));
3086 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
3087 // If there's no signed wrap, and all the operands have the same sign or
3088 // zero, the value won't ever change sign.
3089 if (AddRec->hasNoSignedWrap()) {
3090 bool AllNonNeg = true;
3091 bool AllNonPos = true;
3092 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3093 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3094 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3097 ConservativeResult = ConservativeResult.intersectWith(
3098 ConstantRange(APInt(BitWidth, 0),
3099 APInt::getSignedMinValue(BitWidth)));
3101 ConservativeResult = ConservativeResult.intersectWith(
3102 ConstantRange(APInt::getSignedMinValue(BitWidth),
3103 APInt(BitWidth, 1)));
3106 // TODO: non-affine addrec
3107 if (AddRec->isAffine()) {
3108 const Type *Ty = AddRec->getType();
3109 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
3110 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3111 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
3112 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3114 const SCEV *Start = AddRec->getStart();
3115 const SCEV *Step = AddRec->getStepRecurrence(*this);
3117 ConstantRange StartRange = getSignedRange(Start);
3118 ConstantRange StepRange = getSignedRange(Step);
3119 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3120 ConstantRange EndRange =
3121 StartRange.add(MaxBECountRange.multiply(StepRange));
3123 // Check for overflow. This must be done with ConstantRange arithmetic
3124 // because we could be called from within the ScalarEvolution overflow
3126 ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
3127 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3128 ConstantRange ExtMaxBECountRange =
3129 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3130 ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
3131 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3133 return ConservativeResult;
3135 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3136 EndRange.getSignedMin());
3137 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3138 EndRange.getSignedMax());
3139 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
3140 return ConservativeResult;
3141 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
3145 return ConservativeResult;
3148 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3149 // For a SCEVUnknown, ask ValueTracking.
3150 if (!U->getValue()->getType()->isIntegerTy() && !TD)
3151 return ConservativeResult;
3152 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3154 return ConservativeResult;
3155 return ConservativeResult.intersectWith(
3156 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
3157 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1));
3160 return ConservativeResult;
3163 /// createSCEV - We know that there is no SCEV for the specified value.
3164 /// Analyze the expression.
3166 const SCEV *ScalarEvolution::createSCEV(Value *V) {
3167 if (!isSCEVable(V->getType()))
3168 return getUnknown(V);
3170 unsigned Opcode = Instruction::UserOp1;
3171 if (Instruction *I = dyn_cast<Instruction>(V)) {
3172 Opcode = I->getOpcode();
3174 // Don't attempt to analyze instructions in blocks that aren't
3175 // reachable. Such instructions don't matter, and they aren't required
3176 // to obey basic rules for definitions dominating uses which this
3177 // analysis depends on.
3178 if (!DT->isReachableFromEntry(I->getParent()))
3179 return getUnknown(V);
3180 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
3181 Opcode = CE->getOpcode();
3182 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3183 return getConstant(CI);
3184 else if (isa<ConstantPointerNull>(V))
3185 return getConstant(V->getType(), 0);
3186 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3187 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
3189 return getUnknown(V);
3191 Operator *U = cast<Operator>(V);
3193 case Instruction::Add:
3194 // Don't transfer the NSW and NUW bits from the Add instruction to the
3195 // Add expression, because the Instruction may be guarded by control
3196 // flow and the no-overflow bits may not be valid for the expression in
3198 return getAddExpr(getSCEV(U->getOperand(0)),
3199 getSCEV(U->getOperand(1)));
3200 case Instruction::Mul:
3201 // Don't transfer the NSW and NUW bits from the Mul instruction to the
3202 // Mul expression, as with Add.
3203 return getMulExpr(getSCEV(U->getOperand(0)),
3204 getSCEV(U->getOperand(1)));
3205 case Instruction::UDiv:
3206 return getUDivExpr(getSCEV(U->getOperand(0)),
3207 getSCEV(U->getOperand(1)));
3208 case Instruction::Sub:
3209 return getMinusSCEV(getSCEV(U->getOperand(0)),
3210 getSCEV(U->getOperand(1)));
3211 case Instruction::And:
3212 // For an expression like x&255 that merely masks off the high bits,
3213 // use zext(trunc(x)) as the SCEV expression.
3214 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3215 if (CI->isNullValue())
3216 return getSCEV(U->getOperand(1));
3217 if (CI->isAllOnesValue())
3218 return getSCEV(U->getOperand(0));
3219 const APInt &A = CI->getValue();
3221 // Instcombine's ShrinkDemandedConstant may strip bits out of
3222 // constants, obscuring what would otherwise be a low-bits mask.
3223 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3224 // knew about to reconstruct a low-bits mask value.
3225 unsigned LZ = A.countLeadingZeros();
3226 unsigned BitWidth = A.getBitWidth();
3227 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3228 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3229 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3231 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3233 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
3235 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
3236 IntegerType::get(getContext(), BitWidth - LZ)),
3241 case Instruction::Or:
3242 // If the RHS of the Or is a constant, we may have something like:
3243 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3244 // optimizations will transparently handle this case.
3246 // In order for this transformation to be safe, the LHS must be of the
3247 // form X*(2^n) and the Or constant must be less than 2^n.
3248 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3249 const SCEV *LHS = getSCEV(U->getOperand(0));
3250 const APInt &CIVal = CI->getValue();
3251 if (GetMinTrailingZeros(LHS) >=
3252 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3253 // Build a plain add SCEV.
3254 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3255 // If the LHS of the add was an addrec and it has no-wrap flags,
3256 // transfer the no-wrap flags, since an or won't introduce a wrap.
3257 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3258 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
3259 if (OldAR->hasNoUnsignedWrap())
3260 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoUnsignedWrap(true);
3261 if (OldAR->hasNoSignedWrap())
3262 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoSignedWrap(true);
3268 case Instruction::Xor:
3269 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3270 // If the RHS of the xor is a signbit, then this is just an add.
3271 // Instcombine turns add of signbit into xor as a strength reduction step.
3272 if (CI->getValue().isSignBit())
3273 return getAddExpr(getSCEV(U->getOperand(0)),
3274 getSCEV(U->getOperand(1)));
3276 // If the RHS of xor is -1, then this is a not operation.
3277 if (CI->isAllOnesValue())
3278 return getNotSCEV(getSCEV(U->getOperand(0)));
3280 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3281 // This is a variant of the check for xor with -1, and it handles
3282 // the case where instcombine has trimmed non-demanded bits out
3283 // of an xor with -1.
3284 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3285 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3286 if (BO->getOpcode() == Instruction::And &&
3287 LCI->getValue() == CI->getValue())
3288 if (const SCEVZeroExtendExpr *Z =
3289 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
3290 const Type *UTy = U->getType();
3291 const SCEV *Z0 = Z->getOperand();
3292 const Type *Z0Ty = Z0->getType();
3293 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3295 // If C is a low-bits mask, the zero extend is serving to
3296 // mask off the high bits. Complement the operand and
3297 // re-apply the zext.
3298 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3299 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3301 // If C is a single bit, it may be in the sign-bit position
3302 // before the zero-extend. In this case, represent the xor
3303 // using an add, which is equivalent, and re-apply the zext.
3304 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
3305 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3307 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3313 case Instruction::Shl:
3314 // Turn shift left of a constant amount into a multiply.
3315 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3316 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
3318 // If the shift count is not less than the bitwidth, the result of
3319 // the shift is undefined. Don't try to analyze it, because the
3320 // resolution chosen here may differ from the resolution chosen in
3321 // other parts of the compiler.
3322 if (SA->getValue().uge(BitWidth))
3325 Constant *X = ConstantInt::get(getContext(),
3326 APInt(BitWidth, 1).shl(SA->getZExtValue()));
3327 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3331 case Instruction::LShr:
3332 // Turn logical shift right of a constant into a unsigned divide.
3333 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3334 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
3336 // If the shift count is not less than the bitwidth, the result of
3337 // the shift is undefined. Don't try to analyze it, because the
3338 // resolution chosen here may differ from the resolution chosen in
3339 // other parts of the compiler.
3340 if (SA->getValue().uge(BitWidth))
3343 Constant *X = ConstantInt::get(getContext(),
3344 APInt(BitWidth, 1).shl(SA->getZExtValue()));
3345 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3349 case Instruction::AShr:
3350 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3351 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
3352 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
3353 if (L->getOpcode() == Instruction::Shl &&
3354 L->getOperand(1) == U->getOperand(1)) {
3355 uint64_t BitWidth = getTypeSizeInBits(U->getType());
3357 // If the shift count is not less than the bitwidth, the result of
3358 // the shift is undefined. Don't try to analyze it, because the
3359 // resolution chosen here may differ from the resolution chosen in
3360 // other parts of the compiler.
3361 if (CI->getValue().uge(BitWidth))
3364 uint64_t Amt = BitWidth - CI->getZExtValue();
3365 if (Amt == BitWidth)
3366 return getSCEV(L->getOperand(0)); // shift by zero --> noop
3368 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
3369 IntegerType::get(getContext(),
3375 case Instruction::Trunc:
3376 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
3378 case Instruction::ZExt:
3379 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3381 case Instruction::SExt:
3382 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3384 case Instruction::BitCast:
3385 // BitCasts are no-op casts so we just eliminate the cast.
3386 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
3387 return getSCEV(U->getOperand(0));
3390 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3391 // lead to pointer expressions which cannot safely be expanded to GEPs,
3392 // because ScalarEvolution doesn't respect the GEP aliasing rules when
3393 // simplifying integer expressions.
3395 case Instruction::GetElementPtr:
3396 return createNodeForGEP(cast<GEPOperator>(U));
3398 case Instruction::PHI:
3399 return createNodeForPHI(cast<PHINode>(U));
3401 case Instruction::Select:
3402 // This could be a smax or umax that was lowered earlier.
3403 // Try to recover it.
3404 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3405 Value *LHS = ICI->getOperand(0);
3406 Value *RHS = ICI->getOperand(1);
3407 switch (ICI->getPredicate()) {
3408 case ICmpInst::ICMP_SLT:
3409 case ICmpInst::ICMP_SLE:
3410 std::swap(LHS, RHS);
3412 case ICmpInst::ICMP_SGT:
3413 case ICmpInst::ICMP_SGE:
3414 // a >s b ? a+x : b+x -> smax(a, b)+x
3415 // a >s b ? b+x : a+x -> smin(a, b)+x
3416 if (LHS->getType() == U->getType()) {
3417 const SCEV *LS = getSCEV(LHS);
3418 const SCEV *RS = getSCEV(RHS);
3419 const SCEV *LA = getSCEV(U->getOperand(1));
3420 const SCEV *RA = getSCEV(U->getOperand(2));
3421 const SCEV *LDiff = getMinusSCEV(LA, LS);
3422 const SCEV *RDiff = getMinusSCEV(RA, RS);
3424 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
3425 LDiff = getMinusSCEV(LA, RS);
3426 RDiff = getMinusSCEV(RA, LS);
3428 return getAddExpr(getSMinExpr(LS, RS), LDiff);
3431 case ICmpInst::ICMP_ULT:
3432 case ICmpInst::ICMP_ULE:
3433 std::swap(LHS, RHS);
3435 case ICmpInst::ICMP_UGT:
3436 case ICmpInst::ICMP_UGE:
3437 // a >u b ? a+x : b+x -> umax(a, b)+x
3438 // a >u b ? b+x : a+x -> umin(a, b)+x
3439 if (LHS->getType() == U->getType()) {
3440 const SCEV *LS = getSCEV(LHS);
3441 const SCEV *RS = getSCEV(RHS);
3442 const SCEV *LA = getSCEV(U->getOperand(1));
3443 const SCEV *RA = getSCEV(U->getOperand(2));
3444 const SCEV *LDiff = getMinusSCEV(LA, LS);
3445 const SCEV *RDiff = getMinusSCEV(RA, RS);
3447 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
3448 LDiff = getMinusSCEV(LA, RS);
3449 RDiff = getMinusSCEV(RA, LS);
3451 return getAddExpr(getUMinExpr(LS, RS), LDiff);
3454 case ICmpInst::ICMP_NE:
3455 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
3456 if (LHS->getType() == U->getType() &&
3457 isa<ConstantInt>(RHS) &&
3458 cast<ConstantInt>(RHS)->isZero()) {
3459 const SCEV *One = getConstant(LHS->getType(), 1);
3460 const SCEV *LS = getSCEV(LHS);
3461 const SCEV *LA = getSCEV(U->getOperand(1));
3462 const SCEV *RA = getSCEV(U->getOperand(2));
3463 const SCEV *LDiff = getMinusSCEV(LA, LS);
3464 const SCEV *RDiff = getMinusSCEV(RA, One);
3466 return getAddExpr(getUMaxExpr(LS, One), LDiff);
3469 case ICmpInst::ICMP_EQ:
3470 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
3471 if (LHS->getType() == U->getType() &&
3472 isa<ConstantInt>(RHS) &&
3473 cast<ConstantInt>(RHS)->isZero()) {
3474 const SCEV *One = getConstant(LHS->getType(), 1);
3475 const SCEV *LS = getSCEV(LHS);
3476 const SCEV *LA = getSCEV(U->getOperand(1));
3477 const SCEV *RA = getSCEV(U->getOperand(2));
3478 const SCEV *LDiff = getMinusSCEV(LA, One);
3479 const SCEV *RDiff = getMinusSCEV(RA, LS);
3481 return getAddExpr(getUMaxExpr(LS, One), LDiff);
3489 default: // We cannot analyze this expression.
3493 return getUnknown(V);
3498 //===----------------------------------------------------------------------===//
3499 // Iteration Count Computation Code
3502 /// getBackedgeTakenCount - If the specified loop has a predictable
3503 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3504 /// object. The backedge-taken count is the number of times the loop header
3505 /// will be branched to from within the loop. This is one less than the
3506 /// trip count of the loop, since it doesn't count the first iteration,
3507 /// when the header is branched to from outside the loop.
3509 /// Note that it is not valid to call this method on a loop without a
3510 /// loop-invariant backedge-taken count (see
3511 /// hasLoopInvariantBackedgeTakenCount).
3513 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
3514 return getBackedgeTakenInfo(L).Exact;
3517 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3518 /// return the least SCEV value that is known never to be less than the
3519 /// actual backedge taken count.
3520 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
3521 return getBackedgeTakenInfo(L).Max;
3524 /// PushLoopPHIs - Push PHI nodes in the header of the given loop
3525 /// onto the given Worklist.
3527 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3528 BasicBlock *Header = L->getHeader();
3530 // Push all Loop-header PHIs onto the Worklist stack.
3531 for (BasicBlock::iterator I = Header->begin();
3532 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3533 Worklist.push_back(PN);
3536 const ScalarEvolution::BackedgeTakenInfo &
3537 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
3538 // Initially insert a CouldNotCompute for this loop. If the insertion
3539 // succeeds, proceed to actually compute a backedge-taken count and
3540 // update the value. The temporary CouldNotCompute value tells SCEV
3541 // code elsewhere that it shouldn't attempt to request a new
3542 // backedge-taken count, which could result in infinite recursion.
3543 std::pair<std::map<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
3544 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3546 BackedgeTakenInfo BECount = ComputeBackedgeTakenCount(L);
3547 if (BECount.Exact != getCouldNotCompute()) {
3548 assert(BECount.Exact->isLoopInvariant(L) &&
3549 BECount.Max->isLoopInvariant(L) &&
3550 "Computed backedge-taken count isn't loop invariant for loop!");
3551 ++NumTripCountsComputed;
3553 // Update the value in the map.
3554 Pair.first->second = BECount;
3556 if (BECount.Max != getCouldNotCompute())
3557 // Update the value in the map.
3558 Pair.first->second = BECount;
3559 if (isa<PHINode>(L->getHeader()->begin()))
3560 // Only count loops that have phi nodes as not being computable.
3561 ++NumTripCountsNotComputed;
3564 // Now that we know more about the trip count for this loop, forget any
3565 // existing SCEV values for PHI nodes in this loop since they are only
3566 // conservative estimates made without the benefit of trip count
3567 // information. This is similar to the code in forgetLoop, except that
3568 // it handles SCEVUnknown PHI nodes specially.
3569 if (BECount.hasAnyInfo()) {
3570 SmallVector<Instruction *, 16> Worklist;
3571 PushLoopPHIs(L, Worklist);
3573 SmallPtrSet<Instruction *, 8> Visited;
3574 while (!Worklist.empty()) {
3575 Instruction *I = Worklist.pop_back_val();
3576 if (!Visited.insert(I)) continue;
3578 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3579 Scalars.find(static_cast<Value *>(I));
3580 if (It != Scalars.end()) {
3581 // SCEVUnknown for a PHI either means that it has an unrecognized
3582 // structure, or it's a PHI that's in the progress of being computed
3583 // by createNodeForPHI. In the former case, additional loop trip
3584 // count information isn't going to change anything. In the later
3585 // case, createNodeForPHI will perform the necessary updates on its
3586 // own when it gets to that point.
3587 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
3588 ValuesAtScopes.erase(It->second);
3591 if (PHINode *PN = dyn_cast<PHINode>(I))
3592 ConstantEvolutionLoopExitValue.erase(PN);
3595 PushDefUseChildren(I, Worklist);
3599 return Pair.first->second;
3602 /// forgetLoop - This method should be called by the client when it has
3603 /// changed a loop in a way that may effect ScalarEvolution's ability to
3604 /// compute a trip count, or if the loop is deleted.
3605 void ScalarEvolution::forgetLoop(const Loop *L) {
3606 // Drop any stored trip count value.
3607 BackedgeTakenCounts.erase(L);
3609 // Drop information about expressions based on loop-header PHIs.
3610 SmallVector<Instruction *, 16> Worklist;
3611 PushLoopPHIs(L, Worklist);
3613 SmallPtrSet<Instruction *, 8> Visited;
3614 while (!Worklist.empty()) {
3615 Instruction *I = Worklist.pop_back_val();
3616 if (!Visited.insert(I)) continue;
3618 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3619 Scalars.find(static_cast<Value *>(I));
3620 if (It != Scalars.end()) {
3621 ValuesAtScopes.erase(It->second);
3623 if (PHINode *PN = dyn_cast<PHINode>(I))
3624 ConstantEvolutionLoopExitValue.erase(PN);
3627 PushDefUseChildren(I, Worklist);
3631 /// forgetValue - This method should be called by the client when it has
3632 /// changed a value in a way that may effect its value, or which may
3633 /// disconnect it from a def-use chain linking it to a loop.
3634 void ScalarEvolution::forgetValue(Value *V) {
3635 Instruction *I = dyn_cast<Instruction>(V);
3638 // Drop information about expressions based on loop-header PHIs.
3639 SmallVector<Instruction *, 16> Worklist;
3640 Worklist.push_back(I);
3642 SmallPtrSet<Instruction *, 8> Visited;
3643 while (!Worklist.empty()) {
3644 I = Worklist.pop_back_val();
3645 if (!Visited.insert(I)) continue;
3647 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3648 Scalars.find(static_cast<Value *>(I));
3649 if (It != Scalars.end()) {
3650 ValuesAtScopes.erase(It->second);
3652 if (PHINode *PN = dyn_cast<PHINode>(I))
3653 ConstantEvolutionLoopExitValue.erase(PN);
3656 PushDefUseChildren(I, Worklist);
3660 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
3661 /// of the specified loop will execute.
3662 ScalarEvolution::BackedgeTakenInfo
3663 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
3664 SmallVector<BasicBlock *, 8> ExitingBlocks;
3665 L->getExitingBlocks(ExitingBlocks);
3667 // Examine all exits and pick the most conservative values.
3668 const SCEV *BECount = getCouldNotCompute();
3669 const SCEV *MaxBECount = getCouldNotCompute();
3670 bool CouldNotComputeBECount = false;
3671 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3672 BackedgeTakenInfo NewBTI =
3673 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
3675 if (NewBTI.Exact == getCouldNotCompute()) {
3676 // We couldn't compute an exact value for this exit, so
3677 // we won't be able to compute an exact value for the loop.
3678 CouldNotComputeBECount = true;
3679 BECount = getCouldNotCompute();
3680 } else if (!CouldNotComputeBECount) {
3681 if (BECount == getCouldNotCompute())
3682 BECount = NewBTI.Exact;
3684 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
3686 if (MaxBECount == getCouldNotCompute())
3687 MaxBECount = NewBTI.Max;
3688 else if (NewBTI.Max != getCouldNotCompute())
3689 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
3692 return BackedgeTakenInfo(BECount, MaxBECount);
3695 /// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3696 /// of the specified loop will execute if it exits via the specified block.
3697 ScalarEvolution::BackedgeTakenInfo
3698 ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3699 BasicBlock *ExitingBlock) {
3701 // Okay, we've chosen an exiting block. See what condition causes us to
3702 // exit at this block.
3704 // FIXME: we should be able to handle switch instructions (with a single exit)
3705 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
3706 if (ExitBr == 0) return getCouldNotCompute();
3707 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
3709 // At this point, we know we have a conditional branch that determines whether
3710 // the loop is exited. However, we don't know if the branch is executed each
3711 // time through the loop. If not, then the execution count of the branch will
3712 // not be equal to the trip count of the loop.
3714 // Currently we check for this by checking to see if the Exit branch goes to
3715 // the loop header. If so, we know it will always execute the same number of
3716 // times as the loop. We also handle the case where the exit block *is* the
3717 // loop header. This is common for un-rotated loops.
3719 // If both of those tests fail, walk up the unique predecessor chain to the
3720 // header, stopping if there is an edge that doesn't exit the loop. If the
3721 // header is reached, the execution count of the branch will be equal to the
3722 // trip count of the loop.
3724 // More extensive analysis could be done to handle more cases here.
3726 if (ExitBr->getSuccessor(0) != L->getHeader() &&
3727 ExitBr->getSuccessor(1) != L->getHeader() &&
3728 ExitBr->getParent() != L->getHeader()) {
3729 // The simple checks failed, try climbing the unique predecessor chain
3730 // up to the header.
3732 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3733 BasicBlock *Pred = BB->getUniquePredecessor();
3735 return getCouldNotCompute();
3736 TerminatorInst *PredTerm = Pred->getTerminator();
3737 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3738 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3741 // If the predecessor has a successor that isn't BB and isn't
3742 // outside the loop, assume the worst.
3743 if (L->contains(PredSucc))
3744 return getCouldNotCompute();
3746 if (Pred == L->getHeader()) {
3753 return getCouldNotCompute();
3756 // Proceed to the next level to examine the exit condition expression.
3757 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3758 ExitBr->getSuccessor(0),
3759 ExitBr->getSuccessor(1));
3762 /// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3763 /// backedge of the specified loop will execute if its exit condition
3764 /// were a conditional branch of ExitCond, TBB, and FBB.
3765 ScalarEvolution::BackedgeTakenInfo
3766 ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3770 // Check if the controlling expression for this loop is an And or Or.
3771 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3772 if (BO->getOpcode() == Instruction::And) {
3773 // Recurse on the operands of the and.
3774 BackedgeTakenInfo BTI0 =
3775 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3776 BackedgeTakenInfo BTI1 =
3777 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3778 const SCEV *BECount = getCouldNotCompute();
3779 const SCEV *MaxBECount = getCouldNotCompute();
3780 if (L->contains(TBB)) {
3781 // Both conditions must be true for the loop to continue executing.
3782 // Choose the less conservative count.
3783 if (BTI0.Exact == getCouldNotCompute() ||
3784 BTI1.Exact == getCouldNotCompute())
3785 BECount = getCouldNotCompute();
3787 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3788 if (BTI0.Max == getCouldNotCompute())
3789 MaxBECount = BTI1.Max;
3790 else if (BTI1.Max == getCouldNotCompute())
3791 MaxBECount = BTI0.Max;
3793 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3795 // Both conditions must be true for the loop to exit.
3796 assert(L->contains(FBB) && "Loop block has no successor in loop!");
3797 if (BTI0.Exact != getCouldNotCompute() &&
3798 BTI1.Exact != getCouldNotCompute())
3799 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3800 if (BTI0.Max != getCouldNotCompute() &&
3801 BTI1.Max != getCouldNotCompute())
3802 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3805 return BackedgeTakenInfo(BECount, MaxBECount);
3807 if (BO->getOpcode() == Instruction::Or) {
3808 // Recurse on the operands of the or.
3809 BackedgeTakenInfo BTI0 =
3810 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3811 BackedgeTakenInfo BTI1 =
3812 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3813 const SCEV *BECount = getCouldNotCompute();
3814 const SCEV *MaxBECount = getCouldNotCompute();
3815 if (L->contains(FBB)) {
3816 // Both conditions must be false for the loop to continue executing.
3817 // Choose the less conservative count.
3818 if (BTI0.Exact == getCouldNotCompute() ||
3819 BTI1.Exact == getCouldNotCompute())
3820 BECount = getCouldNotCompute();
3822 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3823 if (BTI0.Max == getCouldNotCompute())
3824 MaxBECount = BTI1.Max;
3825 else if (BTI1.Max == getCouldNotCompute())
3826 MaxBECount = BTI0.Max;
3828 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3830 // Both conditions must be false for the loop to exit.
3831 assert(L->contains(TBB) && "Loop block has no successor in loop!");
3832 if (BTI0.Exact != getCouldNotCompute() &&
3833 BTI1.Exact != getCouldNotCompute())
3834 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3835 if (BTI0.Max != getCouldNotCompute() &&
3836 BTI1.Max != getCouldNotCompute())
3837 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3840 return BackedgeTakenInfo(BECount, MaxBECount);
3844 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3845 // Proceed to the next level to examine the icmp.
3846 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3847 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
3849 // Check for a constant condition. These are normally stripped out by
3850 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
3851 // preserve the CFG and is temporarily leaving constant conditions
3853 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
3854 if (L->contains(FBB) == !CI->getZExtValue())
3855 // The backedge is always taken.
3856 return getCouldNotCompute();
3858 // The backedge is never taken.
3859 return getConstant(CI->getType(), 0);
3862 // If it's not an integer or pointer comparison then compute it the hard way.
3863 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3866 /// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3867 /// backedge of the specified loop will execute if its exit condition
3868 /// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3869 ScalarEvolution::BackedgeTakenInfo
3870 ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3875 // If the condition was exit on true, convert the condition to exit on false
3876 ICmpInst::Predicate Cond;
3877 if (!L->contains(FBB))
3878 Cond = ExitCond->getPredicate();
3880 Cond = ExitCond->getInversePredicate();
3882 // Handle common loops like: for (X = "string"; *X; ++X)
3883 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3884 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
3885 BackedgeTakenInfo ItCnt =
3886 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
3887 if (ItCnt.hasAnyInfo())
3891 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3892 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
3894 // Try to evaluate any dependencies out of the loop.
3895 LHS = getSCEVAtScope(LHS, L);
3896 RHS = getSCEVAtScope(RHS, L);
3898 // At this point, we would like to compute how many iterations of the
3899 // loop the predicate will return true for these inputs.
3900 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3901 // If there is a loop-invariant, force it into the RHS.
3902 std::swap(LHS, RHS);
3903 Cond = ICmpInst::getSwappedPredicate(Cond);
3906 // Simplify the operands before analyzing them.
3907 (void)SimplifyICmpOperands(Cond, LHS, RHS);
3909 // If we have a comparison of a chrec against a constant, try to use value
3910 // ranges to answer this query.
3911 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3912 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
3913 if (AddRec->getLoop() == L) {
3914 // Form the constant range.
3915 ConstantRange CompRange(
3916 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
3918 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
3919 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
3923 case ICmpInst::ICMP_NE: { // while (X != Y)
3924 // Convert to: while (X-Y != 0)
3925 BackedgeTakenInfo BTI = HowFarToZero(getMinusSCEV(LHS, RHS), L);
3926 if (BTI.hasAnyInfo()) return BTI;
3929 case ICmpInst::ICMP_EQ: { // while (X == Y)
3930 // Convert to: while (X-Y == 0)
3931 BackedgeTakenInfo BTI = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
3932 if (BTI.hasAnyInfo()) return BTI;
3935 case ICmpInst::ICMP_SLT: {
3936 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3937 if (BTI.hasAnyInfo()) return BTI;
3940 case ICmpInst::ICMP_SGT: {
3941 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3942 getNotSCEV(RHS), L, true);
3943 if (BTI.hasAnyInfo()) return BTI;
3946 case ICmpInst::ICMP_ULT: {
3947 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3948 if (BTI.hasAnyInfo()) return BTI;
3951 case ICmpInst::ICMP_UGT: {
3952 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3953 getNotSCEV(RHS), L, false);
3954 if (BTI.hasAnyInfo()) return BTI;
3959 dbgs() << "ComputeBackedgeTakenCount ";
3960 if (ExitCond->getOperand(0)->getType()->isUnsigned())
3961 dbgs() << "[unsigned] ";
3962 dbgs() << *LHS << " "
3963 << Instruction::getOpcodeName(Instruction::ICmp)
3964 << " " << *RHS << "\n";
3969 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3972 static ConstantInt *
3973 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3974 ScalarEvolution &SE) {
3975 const SCEV *InVal = SE.getConstant(C);
3976 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
3977 assert(isa<SCEVConstant>(Val) &&
3978 "Evaluation of SCEV at constant didn't fold correctly?");
3979 return cast<SCEVConstant>(Val)->getValue();
3982 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
3983 /// and a GEP expression (missing the pointer index) indexing into it, return
3984 /// the addressed element of the initializer or null if the index expression is
3987 GetAddressedElementFromGlobal(GlobalVariable *GV,
3988 const std::vector<ConstantInt*> &Indices) {
3989 Constant *Init = GV->getInitializer();
3990 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
3991 uint64_t Idx = Indices[i]->getZExtValue();
3992 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3993 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3994 Init = cast<Constant>(CS->getOperand(Idx));
3995 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3996 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3997 Init = cast<Constant>(CA->getOperand(Idx));
3998 } else if (isa<ConstantAggregateZero>(Init)) {
3999 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
4000 assert(Idx < STy->getNumElements() && "Bad struct index!");
4001 Init = Constant::getNullValue(STy->getElementType(Idx));
4002 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
4003 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
4004 Init = Constant::getNullValue(ATy->getElementType());
4006 llvm_unreachable("Unknown constant aggregate type!");
4010 return 0; // Unknown initializer type
4016 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
4017 /// 'icmp op load X, cst', try to see if we can compute the backedge
4018 /// execution count.
4019 ScalarEvolution::BackedgeTakenInfo
4020 ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
4024 ICmpInst::Predicate predicate) {
4025 if (LI->isVolatile()) return getCouldNotCompute();
4027 // Check to see if the loaded pointer is a getelementptr of a global.
4028 // TODO: Use SCEV instead of manually grubbing with GEPs.
4029 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
4030 if (!GEP) return getCouldNotCompute();
4032 // Make sure that it is really a constant global we are gepping, with an
4033 // initializer, and make sure the first IDX is really 0.
4034 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
4035 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
4036 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
4037 !cast<Constant>(GEP->getOperand(1))->isNullValue())
4038 return getCouldNotCompute();
4040 // Okay, we allow one non-constant index into the GEP instruction.
4042 std::vector<ConstantInt*> Indexes;
4043 unsigned VarIdxNum = 0;
4044 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
4045 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4046 Indexes.push_back(CI);
4047 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
4048 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
4049 VarIdx = GEP->getOperand(i);
4051 Indexes.push_back(0);
4054 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
4055 // Check to see if X is a loop variant variable value now.
4056 const SCEV *Idx = getSCEV(VarIdx);
4057 Idx = getSCEVAtScope(Idx, L);
4059 // We can only recognize very limited forms of loop index expressions, in
4060 // particular, only affine AddRec's like {C1,+,C2}.
4061 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
4062 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
4063 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
4064 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
4065 return getCouldNotCompute();
4067 unsigned MaxSteps = MaxBruteForceIterations;
4068 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
4069 ConstantInt *ItCst = ConstantInt::get(
4070 cast<IntegerType>(IdxExpr->getType()), IterationNum);
4071 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
4073 // Form the GEP offset.
4074 Indexes[VarIdxNum] = Val;
4076 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
4077 if (Result == 0) break; // Cannot compute!
4079 // Evaluate the condition for this iteration.
4080 Result = ConstantExpr::getICmp(predicate, Result, RHS);
4081 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
4082 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
4084 dbgs() << "\n***\n*** Computed loop count " << *ItCst
4085 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
4088 ++NumArrayLenItCounts;
4089 return getConstant(ItCst); // Found terminating iteration!
4092 return getCouldNotCompute();
4096 /// CanConstantFold - Return true if we can constant fold an instruction of the
4097 /// specified type, assuming that all operands were constants.
4098 static bool CanConstantFold(const Instruction *I) {
4099 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
4100 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
4103 if (const CallInst *CI = dyn_cast<CallInst>(I))
4104 if (const Function *F = CI->getCalledFunction())
4105 return canConstantFoldCallTo(F);
4109 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
4110 /// in the loop that V is derived from. We allow arbitrary operations along the
4111 /// way, but the operands of an operation must either be constants or a value
4112 /// derived from a constant PHI. If this expression does not fit with these
4113 /// constraints, return null.
4114 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
4115 // If this is not an instruction, or if this is an instruction outside of the
4116 // loop, it can't be derived from a loop PHI.
4117 Instruction *I = dyn_cast<Instruction>(V);
4118 if (I == 0 || !L->contains(I)) return 0;
4120 if (PHINode *PN = dyn_cast<PHINode>(I)) {
4121 if (L->getHeader() == I->getParent())
4124 // We don't currently keep track of the control flow needed to evaluate
4125 // PHIs, so we cannot handle PHIs inside of loops.
4129 // If we won't be able to constant fold this expression even if the operands
4130 // are constants, return early.
4131 if (!CanConstantFold(I)) return 0;
4133 // Otherwise, we can evaluate this instruction if all of its operands are
4134 // constant or derived from a PHI node themselves.
4136 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
4137 if (!(isa<Constant>(I->getOperand(Op)) ||
4138 isa<GlobalValue>(I->getOperand(Op)))) {
4139 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
4140 if (P == 0) return 0; // Not evolving from PHI
4144 return 0; // Evolving from multiple different PHIs.
4147 // This is a expression evolving from a constant PHI!
4151 /// EvaluateExpression - Given an expression that passes the
4152 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
4153 /// in the loop has the value PHIVal. If we can't fold this expression for some
4154 /// reason, return null.
4155 static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
4156 const TargetData *TD) {
4157 if (isa<PHINode>(V)) return PHIVal;
4158 if (Constant *C = dyn_cast<Constant>(V)) return C;
4159 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
4160 Instruction *I = cast<Instruction>(V);
4162 std::vector<Constant*> Operands;
4163 Operands.resize(I->getNumOperands());
4165 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4166 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
4167 if (Operands[i] == 0) return 0;
4170 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4171 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
4173 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4174 &Operands[0], Operands.size(), TD);
4177 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
4178 /// in the header of its containing loop, we know the loop executes a
4179 /// constant number of times, and the PHI node is just a recurrence
4180 /// involving constants, fold it.
4182 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
4185 std::map<PHINode*, Constant*>::iterator I =
4186 ConstantEvolutionLoopExitValue.find(PN);
4187 if (I != ConstantEvolutionLoopExitValue.end())
4190 if (BEs.ugt(MaxBruteForceIterations))
4191 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
4193 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
4195 // Since the loop is canonicalized, the PHI node must have two entries. One
4196 // entry must be a constant (coming in from outside of the loop), and the
4197 // second must be derived from the same PHI.
4198 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4199 Constant *StartCST =
4200 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4202 return RetVal = 0; // Must be a constant.
4204 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4205 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
4207 return RetVal = 0; // Not derived from same PHI.
4209 // Execute the loop symbolically to determine the exit value.
4210 if (BEs.getActiveBits() >= 32)
4211 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
4213 unsigned NumIterations = BEs.getZExtValue(); // must be in range
4214 unsigned IterationNum = 0;
4215 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
4216 if (IterationNum == NumIterations)
4217 return RetVal = PHIVal; // Got exit value!
4219 // Compute the value of the PHI node for the next iteration.
4220 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
4221 if (NextPHI == PHIVal)
4222 return RetVal = NextPHI; // Stopped evolving!
4224 return 0; // Couldn't evaluate!
4229 /// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
4230 /// constant number of times (the condition evolves only from constants),
4231 /// try to evaluate a few iterations of the loop until we get the exit
4232 /// condition gets a value of ExitWhen (true or false). If we cannot
4233 /// evaluate the trip count of the loop, return getCouldNotCompute().
4235 ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
4238 PHINode *PN = getConstantEvolvingPHI(Cond, L);
4239 if (PN == 0) return getCouldNotCompute();
4241 // If the loop is canonicalized, the PHI will have exactly two entries.
4242 // That's the only form we support here.
4243 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
4245 // One entry must be a constant (coming in from outside of the loop), and the
4246 // second must be derived from the same PHI.
4247 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4248 Constant *StartCST =
4249 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4250 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
4252 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4253 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
4254 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
4256 // Okay, we find a PHI node that defines the trip count of this loop. Execute
4257 // the loop symbolically to determine when the condition gets a value of
4259 unsigned IterationNum = 0;
4260 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
4261 for (Constant *PHIVal = StartCST;
4262 IterationNum != MaxIterations; ++IterationNum) {
4263 ConstantInt *CondVal =
4264 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
4266 // Couldn't symbolically evaluate.
4267 if (!CondVal) return getCouldNotCompute();
4269 if (CondVal->getValue() == uint64_t(ExitWhen)) {
4270 ++NumBruteForceTripCountsComputed;
4271 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
4274 // Compute the value of the PHI node for the next iteration.
4275 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
4276 if (NextPHI == 0 || NextPHI == PHIVal)
4277 return getCouldNotCompute();// Couldn't evaluate or not making progress...
4281 // Too many iterations were needed to evaluate.
4282 return getCouldNotCompute();
4285 /// getSCEVAtScope - Return a SCEV expression for the specified value
4286 /// at the specified scope in the program. The L value specifies a loop
4287 /// nest to evaluate the expression at, where null is the top-level or a
4288 /// specified loop is immediately inside of the loop.
4290 /// This method can be used to compute the exit value for a variable defined
4291 /// in a loop by querying what the value will hold in the parent loop.
4293 /// In the case that a relevant loop exit value cannot be computed, the
4294 /// original value V is returned.
4295 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
4296 // Check to see if we've folded this expression at this loop before.
4297 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4298 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4299 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4301 return Pair.first->second ? Pair.first->second : V;
4303 // Otherwise compute it.
4304 const SCEV *C = computeSCEVAtScope(V, L);
4305 ValuesAtScopes[V][L] = C;
4309 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
4310 if (isa<SCEVConstant>(V)) return V;
4312 // If this instruction is evolved from a constant-evolving PHI, compute the
4313 // exit value from the loop without using SCEVs.
4314 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
4315 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
4316 const Loop *LI = (*this->LI)[I->getParent()];
4317 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
4318 if (PHINode *PN = dyn_cast<PHINode>(I))
4319 if (PN->getParent() == LI->getHeader()) {
4320 // Okay, there is no closed form solution for the PHI node. Check
4321 // to see if the loop that contains it has a known backedge-taken
4322 // count. If so, we may be able to force computation of the exit
4324 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
4325 if (const SCEVConstant *BTCC =
4326 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
4327 // Okay, we know how many times the containing loop executes. If
4328 // this is a constant evolving PHI node, get the final value at
4329 // the specified iteration number.
4330 Constant *RV = getConstantEvolutionLoopExitValue(PN,
4331 BTCC->getValue()->getValue(),
4333 if (RV) return getSCEV(RV);
4337 // Okay, this is an expression that we cannot symbolically evaluate
4338 // into a SCEV. Check to see if it's possible to symbolically evaluate
4339 // the arguments into constants, and if so, try to constant propagate the
4340 // result. This is particularly useful for computing loop exit values.
4341 if (CanConstantFold(I)) {
4342 std::vector<Constant*> Operands;
4343 Operands.reserve(I->getNumOperands());
4344 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4345 Value *Op = I->getOperand(i);
4346 if (Constant *C = dyn_cast<Constant>(Op)) {
4347 Operands.push_back(C);
4349 // If any of the operands is non-constant and if they are
4350 // non-integer and non-pointer, don't even try to analyze them
4351 // with scev techniques.
4352 if (!isSCEVable(Op->getType()))
4355 const SCEV *OpV = getSCEVAtScope(Op, L);
4356 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
4357 Constant *C = SC->getValue();
4358 if (C->getType() != Op->getType())
4359 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4363 Operands.push_back(C);
4364 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
4365 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
4366 if (C->getType() != Op->getType())
4368 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4372 Operands.push_back(C);
4382 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4383 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
4384 Operands[0], Operands[1], TD);
4386 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4387 &Operands[0], Operands.size(), TD);
4393 // This is some other type of SCEVUnknown, just return it.
4397 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
4398 // Avoid performing the look-up in the common case where the specified
4399 // expression has no loop-variant portions.
4400 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
4401 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
4402 if (OpAtScope != Comm->getOperand(i)) {
4403 // Okay, at least one of these operands is loop variant but might be
4404 // foldable. Build a new instance of the folded commutative expression.
4405 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4406 Comm->op_begin()+i);
4407 NewOps.push_back(OpAtScope);
4409 for (++i; i != e; ++i) {
4410 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
4411 NewOps.push_back(OpAtScope);
4413 if (isa<SCEVAddExpr>(Comm))
4414 return getAddExpr(NewOps);
4415 if (isa<SCEVMulExpr>(Comm))
4416 return getMulExpr(NewOps);
4417 if (isa<SCEVSMaxExpr>(Comm))
4418 return getSMaxExpr(NewOps);
4419 if (isa<SCEVUMaxExpr>(Comm))
4420 return getUMaxExpr(NewOps);
4421 llvm_unreachable("Unknown commutative SCEV type!");
4424 // If we got here, all operands are loop invariant.
4428 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
4429 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4430 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
4431 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4432 return Div; // must be loop invariant
4433 return getUDivExpr(LHS, RHS);
4436 // If this is a loop recurrence for a loop that does not contain L, then we
4437 // are dealing with the final value computed by the loop.
4438 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4439 if (!L || !AddRec->getLoop()->contains(L)) {
4440 // To evaluate this recurrence, we need to know how many times the AddRec
4441 // loop iterates. Compute this now.
4442 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
4443 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
4445 // Then, evaluate the AddRec.
4446 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
4451 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
4452 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4453 if (Op == Cast->getOperand())
4454 return Cast; // must be loop invariant
4455 return getZeroExtendExpr(Op, Cast->getType());
4458 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
4459 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4460 if (Op == Cast->getOperand())
4461 return Cast; // must be loop invariant
4462 return getSignExtendExpr(Op, Cast->getType());
4465 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
4466 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4467 if (Op == Cast->getOperand())
4468 return Cast; // must be loop invariant
4469 return getTruncateExpr(Op, Cast->getType());
4472 llvm_unreachable("Unknown SCEV type!");
4476 /// getSCEVAtScope - This is a convenience function which does
4477 /// getSCEVAtScope(getSCEV(V), L).
4478 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
4479 return getSCEVAtScope(getSCEV(V), L);
4482 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4483 /// following equation:
4485 /// A * X = B (mod N)
4487 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4488 /// A and B isn't important.
4490 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
4491 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
4492 ScalarEvolution &SE) {
4493 uint32_t BW = A.getBitWidth();
4494 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4495 assert(A != 0 && "A must be non-zero.");
4499 // The gcd of A and N may have only one prime factor: 2. The number of
4500 // trailing zeros in A is its multiplicity
4501 uint32_t Mult2 = A.countTrailingZeros();
4504 // 2. Check if B is divisible by D.
4506 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4507 // is not less than multiplicity of this prime factor for D.
4508 if (B.countTrailingZeros() < Mult2)
4509 return SE.getCouldNotCompute();
4511 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4514 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4515 // bit width during computations.
4516 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4517 APInt Mod(BW + 1, 0);
4518 Mod.set(BW - Mult2); // Mod = N / D
4519 APInt I = AD.multiplicativeInverse(Mod);
4521 // 4. Compute the minimum unsigned root of the equation:
4522 // I * (B / D) mod (N / D)
4523 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4525 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4527 return SE.getConstant(Result.trunc(BW));
4530 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4531 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4532 /// might be the same) or two SCEVCouldNotCompute objects.
4534 static std::pair<const SCEV *,const SCEV *>
4535 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
4536 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
4537 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4538 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4539 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
4541 // We currently can only solve this if the coefficients are constants.
4542 if (!LC || !MC || !NC) {
4543 const SCEV *CNC = SE.getCouldNotCompute();
4544 return std::make_pair(CNC, CNC);
4547 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
4548 const APInt &L = LC->getValue()->getValue();
4549 const APInt &M = MC->getValue()->getValue();
4550 const APInt &N = NC->getValue()->getValue();
4551 APInt Two(BitWidth, 2);
4552 APInt Four(BitWidth, 4);
4555 using namespace APIntOps;
4557 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4558 // The B coefficient is M-N/2
4562 // The A coefficient is N/2
4563 APInt A(N.sdiv(Two));
4565 // Compute the B^2-4ac term.
4568 SqrtTerm -= Four * (A * C);
4570 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4571 // integer value or else APInt::sqrt() will assert.
4572 APInt SqrtVal(SqrtTerm.sqrt());
4574 // Compute the two solutions for the quadratic formula.
4575 // The divisions must be performed as signed divisions.
4577 APInt TwoA( A << 1 );
4578 if (TwoA.isMinValue()) {
4579 const SCEV *CNC = SE.getCouldNotCompute();
4580 return std::make_pair(CNC, CNC);
4583 LLVMContext &Context = SE.getContext();
4585 ConstantInt *Solution1 =
4586 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
4587 ConstantInt *Solution2 =
4588 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
4590 return std::make_pair(SE.getConstant(Solution1),
4591 SE.getConstant(Solution2));
4592 } // end APIntOps namespace
4595 /// HowFarToZero - Return the number of times a backedge comparing the specified
4596 /// value to zero will execute. If not computable, return CouldNotCompute.
4597 ScalarEvolution::BackedgeTakenInfo
4598 ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
4599 // If the value is a constant
4600 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
4601 // If the value is already zero, the branch will execute zero times.
4602 if (C->getValue()->isZero()) return C;
4603 return getCouldNotCompute(); // Otherwise it will loop infinitely.
4606 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
4607 if (!AddRec || AddRec->getLoop() != L)
4608 return getCouldNotCompute();
4610 if (AddRec->isAffine()) {
4611 // If this is an affine expression, the execution count of this branch is
4612 // the minimum unsigned root of the following equation:
4614 // Start + Step*N = 0 (mod 2^BW)
4618 // Step*N = -Start (mod 2^BW)
4620 // where BW is the common bit width of Start and Step.
4622 // Get the initial value for the loop.
4623 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4624 L->getParentLoop());
4625 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4626 L->getParentLoop());
4628 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
4629 // For now we handle only constant steps.
4631 // First, handle unitary steps.
4632 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
4633 return getNegativeSCEV(Start); // N = -Start (as unsigned)
4634 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4635 return Start; // N = Start (as unsigned)
4637 // Then, try to solve the above equation provided that Start is constant.
4638 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
4639 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
4640 -StartC->getValue()->getValue(),
4643 } else if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
4644 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4645 // the quadratic equation to solve it.
4646 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
4648 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4649 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
4652 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
4653 << " sol#2: " << *R2 << "\n";
4655 // Pick the smallest positive root value.
4656 if (ConstantInt *CB =
4657 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
4658 R1->getValue(), R2->getValue()))) {
4659 if (CB->getZExtValue() == false)
4660 std::swap(R1, R2); // R1 is the minimum root now.
4662 // We can only use this value if the chrec ends up with an exact zero
4663 // value at this index. When solving for "X*X != 5", for example, we
4664 // should not accept a root of 2.
4665 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
4667 return R1; // We found a quadratic root!
4672 return getCouldNotCompute();
4675 /// HowFarToNonZero - Return the number of times a backedge checking the
4676 /// specified value for nonzero will execute. If not computable, return
4678 ScalarEvolution::BackedgeTakenInfo
4679 ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
4680 // Loops that look like: while (X == 0) are very strange indeed. We don't
4681 // handle them yet except for the trivial case. This could be expanded in the
4682 // future as needed.
4684 // If the value is a constant, check to see if it is known to be non-zero
4685 // already. If so, the backedge will execute zero times.
4686 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
4687 if (!C->getValue()->isNullValue())
4688 return getConstant(C->getType(), 0);
4689 return getCouldNotCompute(); // Otherwise it will loop infinitely.
4692 // We could implement others, but I really doubt anyone writes loops like
4693 // this, and if they did, they would already be constant folded.
4694 return getCouldNotCompute();
4697 /// getLoopPredecessor - If the given loop's header has exactly one unique
4698 /// predecessor outside the loop, return it. Otherwise return null.
4699 /// This is less strict that the loop "preheader" concept, which requires
4700 /// the predecessor to have only one single successor.
4702 BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
4703 BasicBlock *Header = L->getHeader();
4704 BasicBlock *Pred = 0;
4705 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
4707 if (!L->contains(*PI)) {
4708 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
4714 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4715 /// (which may not be an immediate predecessor) which has exactly one
4716 /// successor from which BB is reachable, or null if no such block is
4719 std::pair<BasicBlock *, BasicBlock *>
4720 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
4721 // If the block has a unique predecessor, then there is no path from the
4722 // predecessor to the block that does not go through the direct edge
4723 // from the predecessor to the block.
4724 if (BasicBlock *Pred = BB->getSinglePredecessor())
4725 return std::make_pair(Pred, BB);
4727 // A loop's header is defined to be a block that dominates the loop.
4728 // If the header has a unique predecessor outside the loop, it must be
4729 // a block that has exactly one successor that can reach the loop.
4730 if (Loop *L = LI->getLoopFor(BB))
4731 return std::make_pair(getLoopPredecessor(L), L->getHeader());
4733 return std::pair<BasicBlock *, BasicBlock *>();
4736 /// HasSameValue - SCEV structural equivalence is usually sufficient for
4737 /// testing whether two expressions are equal, however for the purposes of
4738 /// looking for a condition guarding a loop, it can be useful to be a little
4739 /// more general, since a front-end may have replicated the controlling
4742 static bool HasSameValue(const SCEV *A, const SCEV *B) {
4743 // Quick check to see if they are the same SCEV.
4744 if (A == B) return true;
4746 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4747 // two different instructions with the same value. Check for this case.
4748 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4749 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4750 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4751 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
4752 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
4755 // Otherwise assume they may have a different value.
4759 /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
4760 /// predicate Pred. Return true iff any changes were made.
4762 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
4763 const SCEV *&LHS, const SCEV *&RHS) {
4764 bool Changed = false;
4766 // Canonicalize a constant to the right side.
4767 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
4768 // Check for both operands constant.
4769 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
4770 if (ConstantExpr::getICmp(Pred,
4772 RHSC->getValue())->isNullValue())
4773 goto trivially_false;
4775 goto trivially_true;
4777 // Otherwise swap the operands to put the constant on the right.
4778 std::swap(LHS, RHS);
4779 Pred = ICmpInst::getSwappedPredicate(Pred);
4783 // If we're comparing an addrec with a value which is loop-invariant in the
4784 // addrec's loop, put the addrec on the left. Also make a dominance check,
4785 // as both operands could be addrecs loop-invariant in each other's loop.
4786 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
4787 const Loop *L = AR->getLoop();
4788 if (LHS->isLoopInvariant(L) && LHS->properlyDominates(L->getHeader(), DT)) {
4789 std::swap(LHS, RHS);
4790 Pred = ICmpInst::getSwappedPredicate(Pred);
4795 // If there's a constant operand, canonicalize comparisons with boundary
4796 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
4797 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4798 const APInt &RA = RC->getValue()->getValue();
4800 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4801 case ICmpInst::ICMP_EQ:
4802 case ICmpInst::ICMP_NE:
4804 case ICmpInst::ICMP_UGE:
4805 if ((RA - 1).isMinValue()) {
4806 Pred = ICmpInst::ICMP_NE;
4807 RHS = getConstant(RA - 1);
4811 if (RA.isMaxValue()) {
4812 Pred = ICmpInst::ICMP_EQ;
4816 if (RA.isMinValue()) goto trivially_true;
4818 Pred = ICmpInst::ICMP_UGT;
4819 RHS = getConstant(RA - 1);
4822 case ICmpInst::ICMP_ULE:
4823 if ((RA + 1).isMaxValue()) {
4824 Pred = ICmpInst::ICMP_NE;
4825 RHS = getConstant(RA + 1);
4829 if (RA.isMinValue()) {
4830 Pred = ICmpInst::ICMP_EQ;
4834 if (RA.isMaxValue()) goto trivially_true;
4836 Pred = ICmpInst::ICMP_ULT;
4837 RHS = getConstant(RA + 1);
4840 case ICmpInst::ICMP_SGE:
4841 if ((RA - 1).isMinSignedValue()) {
4842 Pred = ICmpInst::ICMP_NE;
4843 RHS = getConstant(RA - 1);
4847 if (RA.isMaxSignedValue()) {
4848 Pred = ICmpInst::ICMP_EQ;
4852 if (RA.isMinSignedValue()) goto trivially_true;
4854 Pred = ICmpInst::ICMP_SGT;
4855 RHS = getConstant(RA - 1);
4858 case ICmpInst::ICMP_SLE:
4859 if ((RA + 1).isMaxSignedValue()) {
4860 Pred = ICmpInst::ICMP_NE;
4861 RHS = getConstant(RA + 1);
4865 if (RA.isMinSignedValue()) {
4866 Pred = ICmpInst::ICMP_EQ;
4870 if (RA.isMaxSignedValue()) goto trivially_true;
4872 Pred = ICmpInst::ICMP_SLT;
4873 RHS = getConstant(RA + 1);
4876 case ICmpInst::ICMP_UGT:
4877 if (RA.isMinValue()) {
4878 Pred = ICmpInst::ICMP_NE;
4882 if ((RA + 1).isMaxValue()) {
4883 Pred = ICmpInst::ICMP_EQ;
4884 RHS = getConstant(RA + 1);
4888 if (RA.isMaxValue()) goto trivially_false;
4890 case ICmpInst::ICMP_ULT:
4891 if (RA.isMaxValue()) {
4892 Pred = ICmpInst::ICMP_NE;
4896 if ((RA - 1).isMinValue()) {
4897 Pred = ICmpInst::ICMP_EQ;
4898 RHS = getConstant(RA - 1);
4902 if (RA.isMinValue()) goto trivially_false;
4904 case ICmpInst::ICMP_SGT:
4905 if (RA.isMinSignedValue()) {
4906 Pred = ICmpInst::ICMP_NE;
4910 if ((RA + 1).isMaxSignedValue()) {
4911 Pred = ICmpInst::ICMP_EQ;
4912 RHS = getConstant(RA + 1);
4916 if (RA.isMaxSignedValue()) goto trivially_false;
4918 case ICmpInst::ICMP_SLT:
4919 if (RA.isMaxSignedValue()) {
4920 Pred = ICmpInst::ICMP_NE;
4924 if ((RA - 1).isMinSignedValue()) {
4925 Pred = ICmpInst::ICMP_EQ;
4926 RHS = getConstant(RA - 1);
4930 if (RA.isMinSignedValue()) goto trivially_false;
4935 // Check for obvious equality.
4936 if (HasSameValue(LHS, RHS)) {
4937 if (ICmpInst::isTrueWhenEqual(Pred))
4938 goto trivially_true;
4939 if (ICmpInst::isFalseWhenEqual(Pred))
4940 goto trivially_false;
4943 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
4944 // adding or subtracting 1 from one of the operands.
4946 case ICmpInst::ICMP_SLE:
4947 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
4948 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
4949 /*HasNUW=*/false, /*HasNSW=*/true);
4950 Pred = ICmpInst::ICMP_SLT;
4952 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
4953 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
4954 /*HasNUW=*/false, /*HasNSW=*/true);
4955 Pred = ICmpInst::ICMP_SLT;
4959 case ICmpInst::ICMP_SGE:
4960 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
4961 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
4962 /*HasNUW=*/false, /*HasNSW=*/true);
4963 Pred = ICmpInst::ICMP_SGT;
4965 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
4966 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
4967 /*HasNUW=*/false, /*HasNSW=*/true);
4968 Pred = ICmpInst::ICMP_SGT;
4972 case ICmpInst::ICMP_ULE:
4973 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
4974 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
4975 /*HasNUW=*/true, /*HasNSW=*/false);
4976 Pred = ICmpInst::ICMP_ULT;
4978 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
4979 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
4980 /*HasNUW=*/true, /*HasNSW=*/false);
4981 Pred = ICmpInst::ICMP_ULT;
4985 case ICmpInst::ICMP_UGE:
4986 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
4987 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
4988 /*HasNUW=*/true, /*HasNSW=*/false);
4989 Pred = ICmpInst::ICMP_UGT;
4991 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
4992 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
4993 /*HasNUW=*/true, /*HasNSW=*/false);
4994 Pred = ICmpInst::ICMP_UGT;
5002 // TODO: More simplifications are possible here.
5008 LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
5009 Pred = ICmpInst::ICMP_EQ;
5014 LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
5015 Pred = ICmpInst::ICMP_NE;
5019 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
5020 return getSignedRange(S).getSignedMax().isNegative();
5023 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
5024 return getSignedRange(S).getSignedMin().isStrictlyPositive();
5027 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
5028 return !getSignedRange(S).getSignedMin().isNegative();
5031 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
5032 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
5035 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
5036 return isKnownNegative(S) || isKnownPositive(S);
5039 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
5040 const SCEV *LHS, const SCEV *RHS) {
5041 // Canonicalize the inputs first.
5042 (void)SimplifyICmpOperands(Pred, LHS, RHS);
5044 // If LHS or RHS is an addrec, check to see if the condition is true in
5045 // every iteration of the loop.
5046 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
5047 if (isLoopEntryGuardedByCond(
5048 AR->getLoop(), Pred, AR->getStart(), RHS) &&
5049 isLoopBackedgeGuardedByCond(
5050 AR->getLoop(), Pred, AR->getPostIncExpr(*this), RHS))
5052 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS))
5053 if (isLoopEntryGuardedByCond(
5054 AR->getLoop(), Pred, LHS, AR->getStart()) &&
5055 isLoopBackedgeGuardedByCond(
5056 AR->getLoop(), Pred, LHS, AR->getPostIncExpr(*this)))
5059 // Otherwise see what can be done with known constant ranges.
5060 return isKnownPredicateWithRanges(Pred, LHS, RHS);
5064 ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
5065 const SCEV *LHS, const SCEV *RHS) {
5066 if (HasSameValue(LHS, RHS))
5067 return ICmpInst::isTrueWhenEqual(Pred);
5069 // This code is split out from isKnownPredicate because it is called from
5070 // within isLoopEntryGuardedByCond.
5073 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5075 case ICmpInst::ICMP_SGT:
5076 Pred = ICmpInst::ICMP_SLT;
5077 std::swap(LHS, RHS);
5078 case ICmpInst::ICMP_SLT: {
5079 ConstantRange LHSRange = getSignedRange(LHS);
5080 ConstantRange RHSRange = getSignedRange(RHS);
5081 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
5083 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
5087 case ICmpInst::ICMP_SGE:
5088 Pred = ICmpInst::ICMP_SLE;
5089 std::swap(LHS, RHS);
5090 case ICmpInst::ICMP_SLE: {
5091 ConstantRange LHSRange = getSignedRange(LHS);
5092 ConstantRange RHSRange = getSignedRange(RHS);
5093 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
5095 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
5099 case ICmpInst::ICMP_UGT:
5100 Pred = ICmpInst::ICMP_ULT;
5101 std::swap(LHS, RHS);
5102 case ICmpInst::ICMP_ULT: {
5103 ConstantRange LHSRange = getUnsignedRange(LHS);
5104 ConstantRange RHSRange = getUnsignedRange(RHS);
5105 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
5107 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
5111 case ICmpInst::ICMP_UGE:
5112 Pred = ICmpInst::ICMP_ULE;
5113 std::swap(LHS, RHS);
5114 case ICmpInst::ICMP_ULE: {
5115 ConstantRange LHSRange = getUnsignedRange(LHS);
5116 ConstantRange RHSRange = getUnsignedRange(RHS);
5117 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
5119 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
5123 case ICmpInst::ICMP_NE: {
5124 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
5126 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
5129 const SCEV *Diff = getMinusSCEV(LHS, RHS);
5130 if (isKnownNonZero(Diff))
5134 case ICmpInst::ICMP_EQ:
5135 // The check at the top of the function catches the case where
5136 // the values are known to be equal.
5142 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
5143 /// protected by a conditional between LHS and RHS. This is used to
5144 /// to eliminate casts.
5146 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
5147 ICmpInst::Predicate Pred,
5148 const SCEV *LHS, const SCEV *RHS) {
5149 // Interpret a null as meaning no loop, where there is obviously no guard
5150 // (interprocedural conditions notwithstanding).
5151 if (!L) return true;
5153 BasicBlock *Latch = L->getLoopLatch();
5157 BranchInst *LoopContinuePredicate =
5158 dyn_cast<BranchInst>(Latch->getTerminator());
5159 if (!LoopContinuePredicate ||
5160 LoopContinuePredicate->isUnconditional())
5163 return isImpliedCond(LoopContinuePredicate->getCondition(), Pred, LHS, RHS,
5164 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
5167 /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
5168 /// by a conditional between LHS and RHS. This is used to help avoid max
5169 /// expressions in loop trip counts, and to eliminate casts.
5171 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
5172 ICmpInst::Predicate Pred,
5173 const SCEV *LHS, const SCEV *RHS) {
5174 // Interpret a null as meaning no loop, where there is obviously no guard
5175 // (interprocedural conditions notwithstanding).
5176 if (!L) return false;
5178 // Starting at the loop predecessor, climb up the predecessor chain, as long
5179 // as there are predecessors that can be found that have unique successors
5180 // leading to the original header.
5181 for (std::pair<BasicBlock *, BasicBlock *>
5182 Pair(getLoopPredecessor(L), L->getHeader());
5184 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
5186 BranchInst *LoopEntryPredicate =
5187 dyn_cast<BranchInst>(Pair.first->getTerminator());
5188 if (!LoopEntryPredicate ||
5189 LoopEntryPredicate->isUnconditional())
5192 if (isImpliedCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
5193 LoopEntryPredicate->getSuccessor(0) != Pair.second))
5200 /// isImpliedCond - Test whether the condition described by Pred, LHS,
5201 /// and RHS is true whenever the given Cond value evaluates to true.
5202 bool ScalarEvolution::isImpliedCond(Value *CondValue,
5203 ICmpInst::Predicate Pred,
5204 const SCEV *LHS, const SCEV *RHS,
5206 // Recursively handle And and Or conditions.
5207 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
5208 if (BO->getOpcode() == Instruction::And) {
5210 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
5211 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
5212 } else if (BO->getOpcode() == Instruction::Or) {
5214 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
5215 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
5219 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
5220 if (!ICI) return false;
5222 // Bail if the ICmp's operands' types are wider than the needed type
5223 // before attempting to call getSCEV on them. This avoids infinite
5224 // recursion, since the analysis of widening casts can require loop
5225 // exit condition information for overflow checking, which would
5227 if (getTypeSizeInBits(LHS->getType()) <
5228 getTypeSizeInBits(ICI->getOperand(0)->getType()))
5231 // Now that we found a conditional branch that dominates the loop, check to
5232 // see if it is the comparison we are looking for.
5233 ICmpInst::Predicate FoundPred;
5235 FoundPred = ICI->getInversePredicate();
5237 FoundPred = ICI->getPredicate();
5239 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
5240 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
5242 // Balance the types. The case where FoundLHS' type is wider than
5243 // LHS' type is checked for above.
5244 if (getTypeSizeInBits(LHS->getType()) >
5245 getTypeSizeInBits(FoundLHS->getType())) {
5246 if (CmpInst::isSigned(Pred)) {
5247 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
5248 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
5250 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
5251 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
5255 // Canonicalize the query to match the way instcombine will have
5256 // canonicalized the comparison.
5257 if (SimplifyICmpOperands(Pred, LHS, RHS))
5259 return CmpInst::isTrueWhenEqual(Pred);
5260 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
5261 if (FoundLHS == FoundRHS)
5262 return CmpInst::isFalseWhenEqual(Pred);
5264 // Check to see if we can make the LHS or RHS match.
5265 if (LHS == FoundRHS || RHS == FoundLHS) {
5266 if (isa<SCEVConstant>(RHS)) {
5267 std::swap(FoundLHS, FoundRHS);
5268 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
5270 std::swap(LHS, RHS);
5271 Pred = ICmpInst::getSwappedPredicate(Pred);
5275 // Check whether the found predicate is the same as the desired predicate.
5276 if (FoundPred == Pred)
5277 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
5279 // Check whether swapping the found predicate makes it the same as the
5280 // desired predicate.
5281 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
5282 if (isa<SCEVConstant>(RHS))
5283 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
5285 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
5286 RHS, LHS, FoundLHS, FoundRHS);
5289 // Check whether the actual condition is beyond sufficient.
5290 if (FoundPred == ICmpInst::ICMP_EQ)
5291 if (ICmpInst::isTrueWhenEqual(Pred))
5292 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
5294 if (Pred == ICmpInst::ICMP_NE)
5295 if (!ICmpInst::isTrueWhenEqual(FoundPred))
5296 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
5299 // Otherwise assume the worst.
5303 /// isImpliedCondOperands - Test whether the condition described by Pred,
5304 /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
5305 /// and FoundRHS is true.
5306 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
5307 const SCEV *LHS, const SCEV *RHS,
5308 const SCEV *FoundLHS,
5309 const SCEV *FoundRHS) {
5310 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
5311 FoundLHS, FoundRHS) ||
5312 // ~x < ~y --> x > y
5313 isImpliedCondOperandsHelper(Pred, LHS, RHS,
5314 getNotSCEV(FoundRHS),
5315 getNotSCEV(FoundLHS));
5318 /// isImpliedCondOperandsHelper - Test whether the condition described by
5319 /// Pred, LHS, and RHS is true whenever the condition described by Pred,
5320 /// FoundLHS, and FoundRHS is true.
5322 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
5323 const SCEV *LHS, const SCEV *RHS,
5324 const SCEV *FoundLHS,
5325 const SCEV *FoundRHS) {
5327 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5328 case ICmpInst::ICMP_EQ:
5329 case ICmpInst::ICMP_NE:
5330 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
5333 case ICmpInst::ICMP_SLT:
5334 case ICmpInst::ICMP_SLE:
5335 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
5336 isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS))
5339 case ICmpInst::ICMP_SGT:
5340 case ICmpInst::ICMP_SGE:
5341 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
5342 isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS))
5345 case ICmpInst::ICMP_ULT:
5346 case ICmpInst::ICMP_ULE:
5347 if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
5348 isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS))
5351 case ICmpInst::ICMP_UGT:
5352 case ICmpInst::ICMP_UGE:
5353 if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
5354 isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS))
5362 /// getBECount - Subtract the end and start values and divide by the step,
5363 /// rounding up, to get the number of times the backedge is executed. Return
5364 /// CouldNotCompute if an intermediate computation overflows.
5365 const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
5369 assert(!isKnownNegative(Step) &&
5370 "This code doesn't handle negative strides yet!");
5372 const Type *Ty = Start->getType();
5373 const SCEV *NegOne = getConstant(Ty, (uint64_t)-1);
5374 const SCEV *Diff = getMinusSCEV(End, Start);
5375 const SCEV *RoundUp = getAddExpr(Step, NegOne);
5377 // Add an adjustment to the difference between End and Start so that
5378 // the division will effectively round up.
5379 const SCEV *Add = getAddExpr(Diff, RoundUp);
5382 // Check Add for unsigned overflow.
5383 // TODO: More sophisticated things could be done here.
5384 const Type *WideTy = IntegerType::get(getContext(),
5385 getTypeSizeInBits(Ty) + 1);
5386 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
5387 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
5388 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
5389 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
5390 return getCouldNotCompute();
5393 return getUDivExpr(Add, Step);
5396 /// HowManyLessThans - Return the number of times a backedge containing the
5397 /// specified less-than comparison will execute. If not computable, return
5398 /// CouldNotCompute.
5399 ScalarEvolution::BackedgeTakenInfo
5400 ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
5401 const Loop *L, bool isSigned) {
5402 // Only handle: "ADDREC < LoopInvariant".
5403 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
5405 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
5406 if (!AddRec || AddRec->getLoop() != L)
5407 return getCouldNotCompute();
5409 // Check to see if we have a flag which makes analysis easy.
5410 bool NoWrap = isSigned ? AddRec->hasNoSignedWrap() :
5411 AddRec->hasNoUnsignedWrap();
5413 if (AddRec->isAffine()) {
5414 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
5415 const SCEV *Step = AddRec->getStepRecurrence(*this);
5418 return getCouldNotCompute();
5419 if (Step->isOne()) {
5420 // With unit stride, the iteration never steps past the limit value.
5421 } else if (isKnownPositive(Step)) {
5422 // Test whether a positive iteration can step past the limit
5423 // value and past the maximum value for its type in a single step.
5424 // Note that it's not sufficient to check NoWrap here, because even
5425 // though the value after a wrap is undefined, it's not undefined
5426 // behavior, so if wrap does occur, the loop could either terminate or
5427 // loop infinitely, but in either case, the loop is guaranteed to
5428 // iterate at least until the iteration where the wrapping occurs.
5429 const SCEV *One = getConstant(Step->getType(), 1);
5431 APInt Max = APInt::getSignedMaxValue(BitWidth);
5432 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
5433 .slt(getSignedRange(RHS).getSignedMax()))
5434 return getCouldNotCompute();
5436 APInt Max = APInt::getMaxValue(BitWidth);
5437 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
5438 .ult(getUnsignedRange(RHS).getUnsignedMax()))
5439 return getCouldNotCompute();
5442 // TODO: Handle negative strides here and below.
5443 return getCouldNotCompute();
5445 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
5446 // m. So, we count the number of iterations in which {n,+,s} < m is true.
5447 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
5448 // treat m-n as signed nor unsigned due to overflow possibility.
5450 // First, we get the value of the LHS in the first iteration: n
5451 const SCEV *Start = AddRec->getOperand(0);
5453 // Determine the minimum constant start value.
5454 const SCEV *MinStart = getConstant(isSigned ?
5455 getSignedRange(Start).getSignedMin() :
5456 getUnsignedRange(Start).getUnsignedMin());
5458 // If we know that the condition is true in order to enter the loop,
5459 // then we know that it will run exactly (m-n)/s times. Otherwise, we
5460 // only know that it will execute (max(m,n)-n)/s times. In both cases,
5461 // the division must round up.
5462 const SCEV *End = RHS;
5463 if (!isLoopEntryGuardedByCond(L,
5464 isSigned ? ICmpInst::ICMP_SLT :
5466 getMinusSCEV(Start, Step), RHS))
5467 End = isSigned ? getSMaxExpr(RHS, Start)
5468 : getUMaxExpr(RHS, Start);
5470 // Determine the maximum constant end value.
5471 const SCEV *MaxEnd = getConstant(isSigned ?
5472 getSignedRange(End).getSignedMax() :
5473 getUnsignedRange(End).getUnsignedMax());
5475 // If MaxEnd is within a step of the maximum integer value in its type,
5476 // adjust it down to the minimum value which would produce the same effect.
5477 // This allows the subsequent ceiling division of (N+(step-1))/step to
5478 // compute the correct value.
5479 const SCEV *StepMinusOne = getMinusSCEV(Step,
5480 getConstant(Step->getType(), 1));
5483 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
5486 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
5489 // Finally, we subtract these two values and divide, rounding up, to get
5490 // the number of times the backedge is executed.
5491 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
5493 // The maximum backedge count is similar, except using the minimum start
5494 // value and the maximum end value.
5495 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step, NoWrap);
5497 return BackedgeTakenInfo(BECount, MaxBECount);
5500 return getCouldNotCompute();
5503 /// getNumIterationsInRange - Return the number of iterations of this loop that
5504 /// produce values in the specified constant range. Another way of looking at
5505 /// this is that it returns the first iteration number where the value is not in
5506 /// the condition, thus computing the exit count. If the iteration count can't
5507 /// be computed, an instance of SCEVCouldNotCompute is returned.
5508 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
5509 ScalarEvolution &SE) const {
5510 if (Range.isFullSet()) // Infinite loop.
5511 return SE.getCouldNotCompute();
5513 // If the start is a non-zero constant, shift the range to simplify things.
5514 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
5515 if (!SC->getValue()->isZero()) {
5516 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
5517 Operands[0] = SE.getConstant(SC->getType(), 0);
5518 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
5519 if (const SCEVAddRecExpr *ShiftedAddRec =
5520 dyn_cast<SCEVAddRecExpr>(Shifted))
5521 return ShiftedAddRec->getNumIterationsInRange(
5522 Range.subtract(SC->getValue()->getValue()), SE);
5523 // This is strange and shouldn't happen.
5524 return SE.getCouldNotCompute();
5527 // The only time we can solve this is when we have all constant indices.
5528 // Otherwise, we cannot determine the overflow conditions.
5529 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5530 if (!isa<SCEVConstant>(getOperand(i)))
5531 return SE.getCouldNotCompute();
5534 // Okay at this point we know that all elements of the chrec are constants and
5535 // that the start element is zero.
5537 // First check to see if the range contains zero. If not, the first
5539 unsigned BitWidth = SE.getTypeSizeInBits(getType());
5540 if (!Range.contains(APInt(BitWidth, 0)))
5541 return SE.getConstant(getType(), 0);
5544 // If this is an affine expression then we have this situation:
5545 // Solve {0,+,A} in Range === Ax in Range
5547 // We know that zero is in the range. If A is positive then we know that
5548 // the upper value of the range must be the first possible exit value.
5549 // If A is negative then the lower of the range is the last possible loop
5550 // value. Also note that we already checked for a full range.
5551 APInt One(BitWidth,1);
5552 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
5553 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
5555 // The exit value should be (End+A)/A.
5556 APInt ExitVal = (End + A).udiv(A);
5557 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
5559 // Evaluate at the exit value. If we really did fall out of the valid
5560 // range, then we computed our trip count, otherwise wrap around or other
5561 // things must have happened.
5562 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
5563 if (Range.contains(Val->getValue()))
5564 return SE.getCouldNotCompute(); // Something strange happened
5566 // Ensure that the previous value is in the range. This is a sanity check.
5567 assert(Range.contains(
5568 EvaluateConstantChrecAtConstant(this,
5569 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
5570 "Linear scev computation is off in a bad way!");
5571 return SE.getConstant(ExitValue);
5572 } else if (isQuadratic()) {
5573 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5574 // quadratic equation to solve it. To do this, we must frame our problem in
5575 // terms of figuring out when zero is crossed, instead of when
5576 // Range.getUpper() is crossed.
5577 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
5578 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
5579 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
5581 // Next, solve the constructed addrec
5582 std::pair<const SCEV *,const SCEV *> Roots =
5583 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
5584 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5585 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
5587 // Pick the smallest positive root value.
5588 if (ConstantInt *CB =
5589 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
5590 R1->getValue(), R2->getValue()))) {
5591 if (CB->getZExtValue() == false)
5592 std::swap(R1, R2); // R1 is the minimum root now.
5594 // Make sure the root is not off by one. The returned iteration should
5595 // not be in the range, but the previous one should be. When solving
5596 // for "X*X < 5", for example, we should not return a root of 2.
5597 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
5600 if (Range.contains(R1Val->getValue())) {
5601 // The next iteration must be out of the range...
5602 ConstantInt *NextVal =
5603 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
5605 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
5606 if (!Range.contains(R1Val->getValue()))
5607 return SE.getConstant(NextVal);
5608 return SE.getCouldNotCompute(); // Something strange happened
5611 // If R1 was not in the range, then it is a good return value. Make
5612 // sure that R1-1 WAS in the range though, just in case.
5613 ConstantInt *NextVal =
5614 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
5615 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
5616 if (Range.contains(R1Val->getValue()))
5618 return SE.getCouldNotCompute(); // Something strange happened
5623 return SE.getCouldNotCompute();
5628 //===----------------------------------------------------------------------===//
5629 // SCEVCallbackVH Class Implementation
5630 //===----------------------------------------------------------------------===//
5632 void ScalarEvolution::SCEVCallbackVH::deleted() {
5633 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
5634 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5635 SE->ConstantEvolutionLoopExitValue.erase(PN);
5636 SE->Scalars.erase(getValPtr());
5637 // this now dangles!
5640 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
5641 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
5643 // Forget all the expressions associated with users of the old value,
5644 // so that future queries will recompute the expressions using the new
5646 SmallVector<User *, 16> Worklist;
5647 SmallPtrSet<User *, 8> Visited;
5648 Value *Old = getValPtr();
5649 bool DeleteOld = false;
5650 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5652 Worklist.push_back(*UI);
5653 while (!Worklist.empty()) {
5654 User *U = Worklist.pop_back_val();
5655 // Deleting the Old value will cause this to dangle. Postpone
5656 // that until everything else is done.
5661 if (!Visited.insert(U))
5663 if (PHINode *PN = dyn_cast<PHINode>(U))
5664 SE->ConstantEvolutionLoopExitValue.erase(PN);
5665 SE->Scalars.erase(U);
5666 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5668 Worklist.push_back(*UI);
5670 // Delete the Old value if it (indirectly) references itself.
5672 if (PHINode *PN = dyn_cast<PHINode>(Old))
5673 SE->ConstantEvolutionLoopExitValue.erase(PN);
5674 SE->Scalars.erase(Old);
5675 // this now dangles!
5680 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
5681 : CallbackVH(V), SE(se) {}
5683 //===----------------------------------------------------------------------===//
5684 // ScalarEvolution Class Implementation
5685 //===----------------------------------------------------------------------===//
5687 ScalarEvolution::ScalarEvolution()
5688 : FunctionPass(&ID) {
5691 bool ScalarEvolution::runOnFunction(Function &F) {
5693 LI = &getAnalysis<LoopInfo>();
5694 TD = getAnalysisIfAvailable<TargetData>();
5695 DT = &getAnalysis<DominatorTree>();
5699 void ScalarEvolution::releaseMemory() {
5701 BackedgeTakenCounts.clear();
5702 ConstantEvolutionLoopExitValue.clear();
5703 ValuesAtScopes.clear();
5704 UniqueSCEVs.clear();
5705 SCEVAllocator.Reset();
5708 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5709 AU.setPreservesAll();
5710 AU.addRequiredTransitive<LoopInfo>();
5711 AU.addRequiredTransitive<DominatorTree>();
5714 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
5715 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
5718 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
5720 // Print all inner loops first
5721 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5722 PrintLoopInfo(OS, SE, *I);
5725 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5728 SmallVector<BasicBlock *, 8> ExitBlocks;
5729 L->getExitBlocks(ExitBlocks);
5730 if (ExitBlocks.size() != 1)
5731 OS << "<multiple exits> ";
5733 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5734 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
5736 OS << "Unpredictable backedge-taken count. ";
5741 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5744 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5745 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5747 OS << "Unpredictable max backedge-taken count. ";
5753 void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
5754 // ScalarEvolution's implementation of the print method is to print
5755 // out SCEV values of all instructions that are interesting. Doing
5756 // this potentially causes it to create new SCEV objects though,
5757 // which technically conflicts with the const qualifier. This isn't
5758 // observable from outside the class though, so casting away the
5759 // const isn't dangerous.
5760 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
5762 OS << "Classifying expressions for: ";
5763 WriteAsOperand(OS, F, /*PrintType=*/false);
5765 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
5766 if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) {
5769 const SCEV *SV = SE.getSCEV(&*I);
5772 const Loop *L = LI->getLoopFor((*I).getParent());
5774 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
5781 OS << "\t\t" "Exits: ";
5782 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
5783 if (!ExitValue->isLoopInvariant(L)) {
5784 OS << "<<Unknown>>";
5793 OS << "Determining loop execution counts for: ";
5794 WriteAsOperand(OS, F, /*PrintType=*/false);
5796 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5797 PrintLoopInfo(OS, &SE, *I);