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.erase(Ops.begin()+Idx);
1410 Ops.append(Add->op_begin(), Add->op_end());
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.append(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.erase(Ops.begin()+Idx);
1721 Ops.append(Mul->op_begin(), Mul->op_end());
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.append(StepChrec->op_begin(), StepChrec->op_end());
1944 return getAddRecExpr(Operands, L);
1947 Operands.push_back(Step);
1948 return getAddRecExpr(Operands, L, HasNUW, HasNSW);
1951 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1952 /// Simplify the expression as much as possible.
1954 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
1956 bool HasNUW, bool HasNSW) {
1957 if (Operands.size() == 1) return Operands[0];
1959 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1960 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1961 getEffectiveSCEVType(Operands[0]->getType()) &&
1962 "SCEVAddRecExpr operand types don't match!");
1965 if (Operands.back()->isZero()) {
1966 Operands.pop_back();
1967 return getAddRecExpr(Operands, L, HasNUW, HasNSW); // {X,+,0} --> X
1970 // It's tempting to want to call getMaxBackedgeTakenCount count here and
1971 // use that information to infer NUW and NSW flags. However, computing a
1972 // BE count requires calling getAddRecExpr, so we may not yet have a
1973 // meaningful BE count at this point (and if we don't, we'd be stuck
1974 // with a SCEVCouldNotCompute as the cached BE count).
1976 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1977 if (!HasNUW && HasNSW) {
1979 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1980 if (!isKnownNonNegative(Operands[i])) {
1984 if (All) HasNUW = true;
1987 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1988 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1989 const Loop *NestedLoop = NestedAR->getLoop();
1990 if (L->contains(NestedLoop->getHeader()) ?
1991 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
1992 (!NestedLoop->contains(L->getHeader()) &&
1993 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
1994 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
1995 NestedAR->op_end());
1996 Operands[0] = NestedAR->getStart();
1997 // AddRecs require their operands be loop-invariant with respect to their
1998 // loops. Don't perform this transformation if it would break this
2000 bool AllInvariant = true;
2001 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2002 if (!Operands[i]->isLoopInvariant(L)) {
2003 AllInvariant = false;
2007 NestedOperands[0] = getAddRecExpr(Operands, L);
2008 AllInvariant = true;
2009 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
2010 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
2011 AllInvariant = false;
2015 // Ok, both add recurrences are valid after the transformation.
2016 return getAddRecExpr(NestedOperands, NestedLoop, HasNUW, HasNSW);
2018 // Reset Operands to its original state.
2019 Operands[0] = NestedAR;
2023 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2024 // already have one, otherwise create a new one.
2025 FoldingSetNodeID ID;
2026 ID.AddInteger(scAddRecExpr);
2027 ID.AddInteger(Operands.size());
2028 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2029 ID.AddPointer(Operands[i]);
2033 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2035 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2036 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
2037 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2038 O, Operands.size(), L);
2039 UniqueSCEVs.InsertNode(S, IP);
2041 if (HasNUW) S->setHasNoUnsignedWrap(true);
2042 if (HasNSW) S->setHasNoSignedWrap(true);
2046 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2048 SmallVector<const SCEV *, 2> Ops;
2051 return getSMaxExpr(Ops);
2055 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2056 assert(!Ops.empty() && "Cannot get empty smax!");
2057 if (Ops.size() == 1) return Ops[0];
2059 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2060 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2061 getEffectiveSCEVType(Ops[0]->getType()) &&
2062 "SCEVSMaxExpr operand types don't match!");
2065 // Sort by complexity, this groups all similar expression types together.
2066 GroupByComplexity(Ops, LI);
2068 // If there are any constants, fold them together.
2070 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2072 assert(Idx < Ops.size());
2073 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2074 // We found two constants, fold them together!
2075 ConstantInt *Fold = ConstantInt::get(getContext(),
2076 APIntOps::smax(LHSC->getValue()->getValue(),
2077 RHSC->getValue()->getValue()));
2078 Ops[0] = getConstant(Fold);
2079 Ops.erase(Ops.begin()+1); // Erase the folded element
2080 if (Ops.size() == 1) return Ops[0];
2081 LHSC = cast<SCEVConstant>(Ops[0]);
2084 // If we are left with a constant minimum-int, strip it off.
2085 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2086 Ops.erase(Ops.begin());
2088 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2089 // If we have an smax with a constant maximum-int, it will always be
2094 if (Ops.size() == 1) return Ops[0];
2097 // Find the first SMax
2098 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2101 // Check to see if one of the operands is an SMax. If so, expand its operands
2102 // onto our operand list, and recurse to simplify.
2103 if (Idx < Ops.size()) {
2104 bool DeletedSMax = false;
2105 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
2106 Ops.erase(Ops.begin()+Idx);
2107 Ops.append(SMax->op_begin(), SMax->op_end());
2112 return getSMaxExpr(Ops);
2115 // Okay, check to see if the same value occurs in the operand list twice. If
2116 // so, delete one. Since we sorted the list, these values are required to
2118 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2119 // X smax Y smax Y --> X smax Y
2120 // X smax Y --> X, if X is always greater than Y
2121 if (Ops[i] == Ops[i+1] ||
2122 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
2123 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2125 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
2126 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2130 if (Ops.size() == 1) return Ops[0];
2132 assert(!Ops.empty() && "Reduced smax down to nothing!");
2134 // Okay, it looks like we really DO need an smax expr. Check to see if we
2135 // already have one, otherwise create a new one.
2136 FoldingSetNodeID ID;
2137 ID.AddInteger(scSMaxExpr);
2138 ID.AddInteger(Ops.size());
2139 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2140 ID.AddPointer(Ops[i]);
2142 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2143 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2144 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2145 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
2147 UniqueSCEVs.InsertNode(S, IP);
2151 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2153 SmallVector<const SCEV *, 2> Ops;
2156 return getUMaxExpr(Ops);
2160 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2161 assert(!Ops.empty() && "Cannot get empty umax!");
2162 if (Ops.size() == 1) return Ops[0];
2164 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2165 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2166 getEffectiveSCEVType(Ops[0]->getType()) &&
2167 "SCEVUMaxExpr operand types don't match!");
2170 // Sort by complexity, this groups all similar expression types together.
2171 GroupByComplexity(Ops, LI);
2173 // If there are any constants, fold them together.
2175 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2177 assert(Idx < Ops.size());
2178 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2179 // We found two constants, fold them together!
2180 ConstantInt *Fold = ConstantInt::get(getContext(),
2181 APIntOps::umax(LHSC->getValue()->getValue(),
2182 RHSC->getValue()->getValue()));
2183 Ops[0] = getConstant(Fold);
2184 Ops.erase(Ops.begin()+1); // Erase the folded element
2185 if (Ops.size() == 1) return Ops[0];
2186 LHSC = cast<SCEVConstant>(Ops[0]);
2189 // If we are left with a constant minimum-int, strip it off.
2190 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2191 Ops.erase(Ops.begin());
2193 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2194 // If we have an umax with a constant maximum-int, it will always be
2199 if (Ops.size() == 1) return Ops[0];
2202 // Find the first UMax
2203 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2206 // Check to see if one of the operands is a UMax. If so, expand its operands
2207 // onto our operand list, and recurse to simplify.
2208 if (Idx < Ops.size()) {
2209 bool DeletedUMax = false;
2210 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
2211 Ops.erase(Ops.begin()+Idx);
2212 Ops.append(UMax->op_begin(), UMax->op_end());
2217 return getUMaxExpr(Ops);
2220 // Okay, check to see if the same value occurs in the operand list twice. If
2221 // so, delete one. Since we sorted the list, these values are required to
2223 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2224 // X umax Y umax Y --> X umax Y
2225 // X umax Y --> X, if X is always greater than Y
2226 if (Ops[i] == Ops[i+1] ||
2227 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
2228 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2230 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
2231 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2235 if (Ops.size() == 1) return Ops[0];
2237 assert(!Ops.empty() && "Reduced umax down to nothing!");
2239 // Okay, it looks like we really DO need a umax expr. Check to see if we
2240 // already have one, otherwise create a new one.
2241 FoldingSetNodeID ID;
2242 ID.AddInteger(scUMaxExpr);
2243 ID.AddInteger(Ops.size());
2244 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2245 ID.AddPointer(Ops[i]);
2247 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2248 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2249 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2250 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
2252 UniqueSCEVs.InsertNode(S, IP);
2256 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2258 // ~smax(~x, ~y) == smin(x, y).
2259 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2262 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2264 // ~umax(~x, ~y) == umin(x, y)
2265 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2268 const SCEV *ScalarEvolution::getSizeOfExpr(const Type *AllocTy) {
2269 // If we have TargetData, we can bypass creating a target-independent
2270 // constant expression and then folding it back into a ConstantInt.
2271 // This is just a compile-time optimization.
2273 return getConstant(TD->getIntPtrType(getContext()),
2274 TD->getTypeAllocSize(AllocTy));
2276 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2277 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2278 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2280 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2281 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2284 const SCEV *ScalarEvolution::getAlignOfExpr(const Type *AllocTy) {
2285 Constant *C = ConstantExpr::getAlignOf(AllocTy);
2286 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2287 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2289 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2290 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2293 const SCEV *ScalarEvolution::getOffsetOfExpr(const StructType *STy,
2295 // If we have TargetData, we can bypass creating a target-independent
2296 // constant expression and then folding it back into a ConstantInt.
2297 // This is just a compile-time optimization.
2299 return getConstant(TD->getIntPtrType(getContext()),
2300 TD->getStructLayout(STy)->getElementOffset(FieldNo));
2302 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2303 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2304 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2306 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
2307 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2310 const SCEV *ScalarEvolution::getOffsetOfExpr(const Type *CTy,
2311 Constant *FieldNo) {
2312 Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
2313 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2314 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2316 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
2317 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2320 const SCEV *ScalarEvolution::getUnknown(Value *V) {
2321 // Don't attempt to do anything other than create a SCEVUnknown object
2322 // here. createSCEV only calls getUnknown after checking for all other
2323 // interesting possibilities, and any other code that calls getUnknown
2324 // is doing so in order to hide a value from SCEV canonicalization.
2326 FoldingSetNodeID ID;
2327 ID.AddInteger(scUnknown);
2330 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2331 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V);
2332 UniqueSCEVs.InsertNode(S, IP);
2336 //===----------------------------------------------------------------------===//
2337 // Basic SCEV Analysis and PHI Idiom Recognition Code
2340 /// isSCEVable - Test if values of the given type are analyzable within
2341 /// the SCEV framework. This primarily includes integer types, and it
2342 /// can optionally include pointer types if the ScalarEvolution class
2343 /// has access to target-specific information.
2344 bool ScalarEvolution::isSCEVable(const Type *Ty) const {
2345 // Integers and pointers are always SCEVable.
2346 return Ty->isIntegerTy() || Ty->isPointerTy();
2349 /// getTypeSizeInBits - Return the size in bits of the specified type,
2350 /// for which isSCEVable must return true.
2351 uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
2352 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2354 // If we have a TargetData, use it!
2356 return TD->getTypeSizeInBits(Ty);
2358 // Integer types have fixed sizes.
2359 if (Ty->isIntegerTy())
2360 return Ty->getPrimitiveSizeInBits();
2362 // The only other support type is pointer. Without TargetData, conservatively
2363 // assume pointers are 64-bit.
2364 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
2368 /// getEffectiveSCEVType - Return a type with the same bitwidth as
2369 /// the given type and which represents how SCEV will treat the given
2370 /// type, for which isSCEVable must return true. For pointer types,
2371 /// this is the pointer-sized integer type.
2372 const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
2373 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2375 if (Ty->isIntegerTy())
2378 // The only other support type is pointer.
2379 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
2380 if (TD) return TD->getIntPtrType(getContext());
2382 // Without TargetData, conservatively assume pointers are 64-bit.
2383 return Type::getInt64Ty(getContext());
2386 const SCEV *ScalarEvolution::getCouldNotCompute() {
2387 return &CouldNotCompute;
2390 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2391 /// expression and create a new one.
2392 const SCEV *ScalarEvolution::getSCEV(Value *V) {
2393 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
2395 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
2396 if (I != Scalars.end()) return I->second;
2397 const SCEV *S = createSCEV(V);
2398 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
2402 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2404 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
2405 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2407 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
2409 const Type *Ty = V->getType();
2410 Ty = getEffectiveSCEVType(Ty);
2411 return getMulExpr(V,
2412 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
2415 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
2416 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
2417 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2419 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
2421 const Type *Ty = V->getType();
2422 Ty = getEffectiveSCEVType(Ty);
2423 const SCEV *AllOnes =
2424 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
2425 return getMinusSCEV(AllOnes, V);
2428 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2430 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2433 return getAddExpr(LHS, getNegativeSCEV(RHS));
2436 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2437 /// input value to the specified type. If the type must be extended, it is zero
2440 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
2442 const Type *SrcTy = V->getType();
2443 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2444 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2445 "Cannot truncate or zero extend with non-integer arguments!");
2446 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2447 return V; // No conversion
2448 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2449 return getTruncateExpr(V, Ty);
2450 return getZeroExtendExpr(V, Ty);
2453 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2454 /// input value to the specified type. If the type must be extended, it is sign
2457 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
2459 const Type *SrcTy = V->getType();
2460 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2461 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2462 "Cannot truncate or zero extend with non-integer arguments!");
2463 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2464 return V; // No conversion
2465 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2466 return getTruncateExpr(V, Ty);
2467 return getSignExtendExpr(V, Ty);
2470 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2471 /// input value to the specified type. If the type must be extended, it is zero
2472 /// extended. The conversion must not be narrowing.
2474 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
2475 const Type *SrcTy = V->getType();
2476 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2477 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2478 "Cannot noop or zero extend with non-integer arguments!");
2479 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2480 "getNoopOrZeroExtend cannot truncate!");
2481 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2482 return V; // No conversion
2483 return getZeroExtendExpr(V, Ty);
2486 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2487 /// input value to the specified type. If the type must be extended, it is sign
2488 /// extended. The conversion must not be narrowing.
2490 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
2491 const Type *SrcTy = V->getType();
2492 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2493 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2494 "Cannot noop or sign extend with non-integer arguments!");
2495 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2496 "getNoopOrSignExtend cannot truncate!");
2497 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2498 return V; // No conversion
2499 return getSignExtendExpr(V, Ty);
2502 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2503 /// the input value to the specified type. If the type must be extended,
2504 /// it is extended with unspecified bits. The conversion must not be
2507 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
2508 const Type *SrcTy = V->getType();
2509 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2510 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2511 "Cannot noop or any extend with non-integer arguments!");
2512 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2513 "getNoopOrAnyExtend cannot truncate!");
2514 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2515 return V; // No conversion
2516 return getAnyExtendExpr(V, Ty);
2519 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2520 /// input value to the specified type. The conversion must not be widening.
2522 ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
2523 const Type *SrcTy = V->getType();
2524 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2525 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2526 "Cannot truncate or noop with non-integer arguments!");
2527 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2528 "getTruncateOrNoop cannot extend!");
2529 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2530 return V; // No conversion
2531 return getTruncateExpr(V, Ty);
2534 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2535 /// the types using zero-extension, and then perform a umax operation
2537 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2539 const SCEV *PromotedLHS = LHS;
2540 const SCEV *PromotedRHS = RHS;
2542 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2543 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2545 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2547 return getUMaxExpr(PromotedLHS, PromotedRHS);
2550 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
2551 /// the types using zero-extension, and then perform a umin operation
2553 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2555 const SCEV *PromotedLHS = LHS;
2556 const SCEV *PromotedRHS = RHS;
2558 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2559 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2561 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2563 return getUMinExpr(PromotedLHS, PromotedRHS);
2566 /// PushDefUseChildren - Push users of the given Instruction
2567 /// onto the given Worklist.
2569 PushDefUseChildren(Instruction *I,
2570 SmallVectorImpl<Instruction *> &Worklist) {
2571 // Push the def-use children onto the Worklist stack.
2572 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2574 Worklist.push_back(cast<Instruction>(UI));
2577 /// ForgetSymbolicValue - This looks up computed SCEV values for all
2578 /// instructions that depend on the given instruction and removes them from
2579 /// the Scalars map if they reference SymName. This is used during PHI
2582 ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
2583 SmallVector<Instruction *, 16> Worklist;
2584 PushDefUseChildren(PN, Worklist);
2586 SmallPtrSet<Instruction *, 8> Visited;
2588 while (!Worklist.empty()) {
2589 Instruction *I = Worklist.pop_back_val();
2590 if (!Visited.insert(I)) continue;
2592 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
2593 Scalars.find(static_cast<Value *>(I));
2594 if (It != Scalars.end()) {
2595 // Short-circuit the def-use traversal if the symbolic name
2596 // ceases to appear in expressions.
2597 if (It->second != SymName && !It->second->hasOperand(SymName))
2600 // SCEVUnknown for a PHI either means that it has an unrecognized
2601 // structure, it's a PHI that's in the progress of being computed
2602 // by createNodeForPHI, or it's a single-value PHI. In the first case,
2603 // additional loop trip count information isn't going to change anything.
2604 // In the second case, createNodeForPHI will perform the necessary
2605 // updates on its own when it gets to that point. In the third, we do
2606 // want to forget the SCEVUnknown.
2607 if (!isa<PHINode>(I) ||
2608 !isa<SCEVUnknown>(It->second) ||
2609 (I != PN && It->second == SymName)) {
2610 ValuesAtScopes.erase(It->second);
2615 PushDefUseChildren(I, Worklist);
2619 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2620 /// a loop header, making it a potential recurrence, or it doesn't.
2622 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
2623 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2624 if (L->getHeader() == PN->getParent()) {
2625 // The loop may have multiple entrances or multiple exits; we can analyze
2626 // this phi as an addrec if it has a unique entry value and a unique
2628 Value *BEValueV = 0, *StartValueV = 0;
2629 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2630 Value *V = PN->getIncomingValue(i);
2631 if (L->contains(PN->getIncomingBlock(i))) {
2634 } else if (BEValueV != V) {
2638 } else if (!StartValueV) {
2640 } else if (StartValueV != V) {
2645 if (BEValueV && StartValueV) {
2646 // While we are analyzing this PHI node, handle its value symbolically.
2647 const SCEV *SymbolicName = getUnknown(PN);
2648 assert(Scalars.find(PN) == Scalars.end() &&
2649 "PHI node already processed?");
2650 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
2652 // Using this symbolic name for the PHI, analyze the value coming around
2654 const SCEV *BEValue = getSCEV(BEValueV);
2656 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2657 // has a special value for the first iteration of the loop.
2659 // If the value coming around the backedge is an add with the symbolic
2660 // value we just inserted, then we found a simple induction variable!
2661 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
2662 // If there is a single occurrence of the symbolic value, replace it
2663 // with a recurrence.
2664 unsigned FoundIndex = Add->getNumOperands();
2665 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2666 if (Add->getOperand(i) == SymbolicName)
2667 if (FoundIndex == e) {
2672 if (FoundIndex != Add->getNumOperands()) {
2673 // Create an add with everything but the specified operand.
2674 SmallVector<const SCEV *, 8> Ops;
2675 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2676 if (i != FoundIndex)
2677 Ops.push_back(Add->getOperand(i));
2678 const SCEV *Accum = getAddExpr(Ops);
2680 // This is not a valid addrec if the step amount is varying each
2681 // loop iteration, but is not itself an addrec in this loop.
2682 if (Accum->isLoopInvariant(L) ||
2683 (isa<SCEVAddRecExpr>(Accum) &&
2684 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
2685 bool HasNUW = false;
2686 bool HasNSW = false;
2688 // If the increment doesn't overflow, then neither the addrec nor
2689 // the post-increment will overflow.
2690 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
2691 if (OBO->hasNoUnsignedWrap())
2693 if (OBO->hasNoSignedWrap())
2697 const SCEV *StartVal = getSCEV(StartValueV);
2698 const SCEV *PHISCEV =
2699 getAddRecExpr(StartVal, Accum, L, HasNUW, HasNSW);
2701 // Since the no-wrap flags are on the increment, they apply to the
2702 // post-incremented value as well.
2703 if (Accum->isLoopInvariant(L))
2704 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
2705 Accum, L, HasNUW, HasNSW);
2707 // Okay, for the entire analysis of this edge we assumed the PHI
2708 // to be symbolic. We now need to go back and purge all of the
2709 // entries for the scalars that use the symbolic expression.
2710 ForgetSymbolicName(PN, SymbolicName);
2711 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
2715 } else if (const SCEVAddRecExpr *AddRec =
2716 dyn_cast<SCEVAddRecExpr>(BEValue)) {
2717 // Otherwise, this could be a loop like this:
2718 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2719 // In this case, j = {1,+,1} and BEValue is j.
2720 // Because the other in-value of i (0) fits the evolution of BEValue
2721 // i really is an addrec evolution.
2722 if (AddRec->getLoop() == L && AddRec->isAffine()) {
2723 const SCEV *StartVal = getSCEV(StartValueV);
2725 // If StartVal = j.start - j.stride, we can use StartVal as the
2726 // initial step of the addrec evolution.
2727 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
2728 AddRec->getOperand(1))) {
2729 const SCEV *PHISCEV =
2730 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
2732 // Okay, for the entire analysis of this edge we assumed the PHI
2733 // to be symbolic. We now need to go back and purge all of the
2734 // entries for the scalars that use the symbolic expression.
2735 ForgetSymbolicName(PN, SymbolicName);
2736 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
2744 // If the PHI has a single incoming value, follow that value, unless the
2745 // PHI's incoming blocks are in a different loop, in which case doing so
2746 // risks breaking LCSSA form. Instcombine would normally zap these, but
2747 // it doesn't have DominatorTree information, so it may miss cases.
2748 if (Value *V = PN->hasConstantValue(DT)) {
2749 bool AllSameLoop = true;
2750 Loop *PNLoop = LI->getLoopFor(PN->getParent());
2751 for (size_t i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2752 if (LI->getLoopFor(PN->getIncomingBlock(i)) != PNLoop) {
2753 AllSameLoop = false;
2760 // If it's not a loop phi, we can't handle it yet.
2761 return getUnknown(PN);
2764 /// createNodeForGEP - Expand GEP instructions into add and multiply
2765 /// operations. This allows them to be analyzed by regular SCEV code.
2767 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
2769 bool InBounds = GEP->isInBounds();
2770 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
2771 Value *Base = GEP->getOperand(0);
2772 // Don't attempt to analyze GEPs over unsized objects.
2773 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2774 return getUnknown(GEP);
2775 const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
2776 gep_type_iterator GTI = gep_type_begin(GEP);
2777 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2781 // Compute the (potentially symbolic) offset in bytes for this index.
2782 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2783 // For a struct, add the member offset.
2784 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2785 TotalOffset = getAddExpr(TotalOffset,
2786 getOffsetOfExpr(STy, FieldNo),
2787 /*HasNUW=*/false, /*HasNSW=*/InBounds);
2789 // For an array, add the element offset, explicitly scaled.
2790 const SCEV *LocalOffset = getSCEV(Index);
2791 // Getelementptr indices are signed.
2792 LocalOffset = getTruncateOrSignExtend(LocalOffset, IntPtrTy);
2793 // Lower "inbounds" GEPs to NSW arithmetic.
2794 LocalOffset = getMulExpr(LocalOffset, getSizeOfExpr(*GTI),
2795 /*HasNUW=*/false, /*HasNSW=*/InBounds);
2796 TotalOffset = getAddExpr(TotalOffset, LocalOffset,
2797 /*HasNUW=*/false, /*HasNSW=*/InBounds);
2800 return getAddExpr(getSCEV(Base), TotalOffset,
2801 /*HasNUW=*/false, /*HasNSW=*/InBounds);
2804 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2805 /// guaranteed to end in (at every loop iteration). It is, at the same time,
2806 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2807 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
2809 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
2810 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2811 return C->getValue()->getValue().countTrailingZeros();
2813 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
2814 return std::min(GetMinTrailingZeros(T->getOperand()),
2815 (uint32_t)getTypeSizeInBits(T->getType()));
2817 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
2818 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2819 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2820 getTypeSizeInBits(E->getType()) : OpRes;
2823 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
2824 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2825 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2826 getTypeSizeInBits(E->getType()) : OpRes;
2829 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
2830 // The result is the min of all operands results.
2831 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2832 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2833 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2837 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
2838 // The result is the sum of all operands results.
2839 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2840 uint32_t BitWidth = getTypeSizeInBits(M->getType());
2841 for (unsigned i = 1, e = M->getNumOperands();
2842 SumOpRes != BitWidth && i != e; ++i)
2843 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
2848 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
2849 // The result is the min of all operands results.
2850 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2851 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2852 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2856 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
2857 // The result is the min of all operands results.
2858 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2859 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2860 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2864 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
2865 // The result is the min of all operands results.
2866 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2867 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2868 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2872 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2873 // For a SCEVUnknown, ask ValueTracking.
2874 unsigned BitWidth = getTypeSizeInBits(U->getType());
2875 APInt Mask = APInt::getAllOnesValue(BitWidth);
2876 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2877 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2878 return Zeros.countTrailingOnes();
2885 /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2888 ScalarEvolution::getUnsignedRange(const SCEV *S) {
2890 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2891 return ConstantRange(C->getValue()->getValue());
2893 unsigned BitWidth = getTypeSizeInBits(S->getType());
2894 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2896 // If the value has known zeros, the maximum unsigned value will have those
2897 // known zeros as well.
2898 uint32_t TZ = GetMinTrailingZeros(S);
2900 ConservativeResult =
2901 ConstantRange(APInt::getMinValue(BitWidth),
2902 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
2904 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2905 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2906 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2907 X = X.add(getUnsignedRange(Add->getOperand(i)));
2908 return ConservativeResult.intersectWith(X);
2911 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2912 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2913 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2914 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
2915 return ConservativeResult.intersectWith(X);
2918 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2919 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2920 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2921 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
2922 return ConservativeResult.intersectWith(X);
2925 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2926 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2927 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2928 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
2929 return ConservativeResult.intersectWith(X);
2932 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2933 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2934 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
2935 return ConservativeResult.intersectWith(X.udiv(Y));
2938 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2939 ConstantRange X = getUnsignedRange(ZExt->getOperand());
2940 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
2943 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2944 ConstantRange X = getUnsignedRange(SExt->getOperand());
2945 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
2948 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2949 ConstantRange X = getUnsignedRange(Trunc->getOperand());
2950 return ConservativeResult.intersectWith(X.truncate(BitWidth));
2953 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2954 // If there's no unsigned wrap, the value will never be less than its
2956 if (AddRec->hasNoUnsignedWrap())
2957 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
2958 if (!C->getValue()->isZero())
2959 ConservativeResult =
2960 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0));
2962 // TODO: non-affine addrec
2963 if (AddRec->isAffine()) {
2964 const Type *Ty = AddRec->getType();
2965 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2966 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
2967 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
2968 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2970 const SCEV *Start = AddRec->getStart();
2971 const SCEV *Step = AddRec->getStepRecurrence(*this);
2973 ConstantRange StartRange = getUnsignedRange(Start);
2974 ConstantRange StepRange = getSignedRange(Step);
2975 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
2976 ConstantRange EndRange =
2977 StartRange.add(MaxBECountRange.multiply(StepRange));
2979 // Check for overflow. This must be done with ConstantRange arithmetic
2980 // because we could be called from within the ScalarEvolution overflow
2982 ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
2983 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
2984 ConstantRange ExtMaxBECountRange =
2985 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
2986 ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
2987 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
2989 return ConservativeResult;
2991 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
2992 EndRange.getUnsignedMin());
2993 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
2994 EndRange.getUnsignedMax());
2995 if (Min.isMinValue() && Max.isMaxValue())
2996 return ConservativeResult;
2997 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
3001 return ConservativeResult;
3004 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3005 // For a SCEVUnknown, ask ValueTracking.
3006 APInt Mask = APInt::getAllOnesValue(BitWidth);
3007 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3008 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
3009 if (Ones == ~Zeros + 1)
3010 return ConservativeResult;
3011 return ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
3014 return ConservativeResult;
3017 /// getSignedRange - Determine the signed range for a particular SCEV.
3020 ScalarEvolution::getSignedRange(const SCEV *S) {
3022 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
3023 return ConstantRange(C->getValue()->getValue());
3025 unsigned BitWidth = getTypeSizeInBits(S->getType());
3026 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3028 // If the value has known zeros, the maximum signed value will have those
3029 // known zeros as well.
3030 uint32_t TZ = GetMinTrailingZeros(S);
3032 ConservativeResult =
3033 ConstantRange(APInt::getSignedMinValue(BitWidth),
3034 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
3036 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3037 ConstantRange X = getSignedRange(Add->getOperand(0));
3038 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3039 X = X.add(getSignedRange(Add->getOperand(i)));
3040 return ConservativeResult.intersectWith(X);
3043 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3044 ConstantRange X = getSignedRange(Mul->getOperand(0));
3045 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3046 X = X.multiply(getSignedRange(Mul->getOperand(i)));
3047 return ConservativeResult.intersectWith(X);
3050 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3051 ConstantRange X = getSignedRange(SMax->getOperand(0));
3052 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3053 X = X.smax(getSignedRange(SMax->getOperand(i)));
3054 return ConservativeResult.intersectWith(X);
3057 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3058 ConstantRange X = getSignedRange(UMax->getOperand(0));
3059 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3060 X = X.umax(getSignedRange(UMax->getOperand(i)));
3061 return ConservativeResult.intersectWith(X);
3064 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3065 ConstantRange X = getSignedRange(UDiv->getLHS());
3066 ConstantRange Y = getSignedRange(UDiv->getRHS());
3067 return ConservativeResult.intersectWith(X.udiv(Y));
3070 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3071 ConstantRange X = getSignedRange(ZExt->getOperand());
3072 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
3075 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3076 ConstantRange X = getSignedRange(SExt->getOperand());
3077 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
3080 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3081 ConstantRange X = getSignedRange(Trunc->getOperand());
3082 return ConservativeResult.intersectWith(X.truncate(BitWidth));
3085 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
3086 // If there's no signed wrap, and all the operands have the same sign or
3087 // zero, the value won't ever change sign.
3088 if (AddRec->hasNoSignedWrap()) {
3089 bool AllNonNeg = true;
3090 bool AllNonPos = true;
3091 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3092 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3093 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3096 ConservativeResult = ConservativeResult.intersectWith(
3097 ConstantRange(APInt(BitWidth, 0),
3098 APInt::getSignedMinValue(BitWidth)));
3100 ConservativeResult = ConservativeResult.intersectWith(
3101 ConstantRange(APInt::getSignedMinValue(BitWidth),
3102 APInt(BitWidth, 1)));
3105 // TODO: non-affine addrec
3106 if (AddRec->isAffine()) {
3107 const Type *Ty = AddRec->getType();
3108 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
3109 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3110 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
3111 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3113 const SCEV *Start = AddRec->getStart();
3114 const SCEV *Step = AddRec->getStepRecurrence(*this);
3116 ConstantRange StartRange = getSignedRange(Start);
3117 ConstantRange StepRange = getSignedRange(Step);
3118 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3119 ConstantRange EndRange =
3120 StartRange.add(MaxBECountRange.multiply(StepRange));
3122 // Check for overflow. This must be done with ConstantRange arithmetic
3123 // because we could be called from within the ScalarEvolution overflow
3125 ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
3126 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3127 ConstantRange ExtMaxBECountRange =
3128 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3129 ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
3130 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3132 return ConservativeResult;
3134 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3135 EndRange.getSignedMin());
3136 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3137 EndRange.getSignedMax());
3138 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
3139 return ConservativeResult;
3140 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
3144 return ConservativeResult;
3147 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3148 // For a SCEVUnknown, ask ValueTracking.
3149 if (!U->getValue()->getType()->isIntegerTy() && !TD)
3150 return ConservativeResult;
3151 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3153 return ConservativeResult;
3154 return ConservativeResult.intersectWith(
3155 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
3156 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1));
3159 return ConservativeResult;
3162 /// createSCEV - We know that there is no SCEV for the specified value.
3163 /// Analyze the expression.
3165 const SCEV *ScalarEvolution::createSCEV(Value *V) {
3166 if (!isSCEVable(V->getType()))
3167 return getUnknown(V);
3169 unsigned Opcode = Instruction::UserOp1;
3170 if (Instruction *I = dyn_cast<Instruction>(V)) {
3171 Opcode = I->getOpcode();
3173 // Don't attempt to analyze instructions in blocks that aren't
3174 // reachable. Such instructions don't matter, and they aren't required
3175 // to obey basic rules for definitions dominating uses which this
3176 // analysis depends on.
3177 if (!DT->isReachableFromEntry(I->getParent()))
3178 return getUnknown(V);
3179 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
3180 Opcode = CE->getOpcode();
3181 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3182 return getConstant(CI);
3183 else if (isa<ConstantPointerNull>(V))
3184 return getConstant(V->getType(), 0);
3185 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3186 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
3188 return getUnknown(V);
3190 Operator *U = cast<Operator>(V);
3192 case Instruction::Add:
3193 // Don't transfer the NSW and NUW bits from the Add instruction to the
3194 // Add expression, because the Instruction may be guarded by control
3195 // flow and the no-overflow bits may not be valid for the expression in
3197 return getAddExpr(getSCEV(U->getOperand(0)),
3198 getSCEV(U->getOperand(1)));
3199 case Instruction::Mul:
3200 // Don't transfer the NSW and NUW bits from the Mul instruction to the
3201 // Mul expression, as with Add.
3202 return getMulExpr(getSCEV(U->getOperand(0)),
3203 getSCEV(U->getOperand(1)));
3204 case Instruction::UDiv:
3205 return getUDivExpr(getSCEV(U->getOperand(0)),
3206 getSCEV(U->getOperand(1)));
3207 case Instruction::Sub:
3208 return getMinusSCEV(getSCEV(U->getOperand(0)),
3209 getSCEV(U->getOperand(1)));
3210 case Instruction::And:
3211 // For an expression like x&255 that merely masks off the high bits,
3212 // use zext(trunc(x)) as the SCEV expression.
3213 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3214 if (CI->isNullValue())
3215 return getSCEV(U->getOperand(1));
3216 if (CI->isAllOnesValue())
3217 return getSCEV(U->getOperand(0));
3218 const APInt &A = CI->getValue();
3220 // Instcombine's ShrinkDemandedConstant may strip bits out of
3221 // constants, obscuring what would otherwise be a low-bits mask.
3222 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3223 // knew about to reconstruct a low-bits mask value.
3224 unsigned LZ = A.countLeadingZeros();
3225 unsigned BitWidth = A.getBitWidth();
3226 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3227 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3228 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3230 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3232 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
3234 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
3235 IntegerType::get(getContext(), BitWidth - LZ)),
3240 case Instruction::Or:
3241 // If the RHS of the Or is a constant, we may have something like:
3242 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3243 // optimizations will transparently handle this case.
3245 // In order for this transformation to be safe, the LHS must be of the
3246 // form X*(2^n) and the Or constant must be less than 2^n.
3247 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3248 const SCEV *LHS = getSCEV(U->getOperand(0));
3249 const APInt &CIVal = CI->getValue();
3250 if (GetMinTrailingZeros(LHS) >=
3251 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3252 // Build a plain add SCEV.
3253 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3254 // If the LHS of the add was an addrec and it has no-wrap flags,
3255 // transfer the no-wrap flags, since an or won't introduce a wrap.
3256 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3257 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
3258 if (OldAR->hasNoUnsignedWrap())
3259 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoUnsignedWrap(true);
3260 if (OldAR->hasNoSignedWrap())
3261 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoSignedWrap(true);
3267 case Instruction::Xor:
3268 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3269 // If the RHS of the xor is a signbit, then this is just an add.
3270 // Instcombine turns add of signbit into xor as a strength reduction step.
3271 if (CI->getValue().isSignBit())
3272 return getAddExpr(getSCEV(U->getOperand(0)),
3273 getSCEV(U->getOperand(1)));
3275 // If the RHS of xor is -1, then this is a not operation.
3276 if (CI->isAllOnesValue())
3277 return getNotSCEV(getSCEV(U->getOperand(0)));
3279 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3280 // This is a variant of the check for xor with -1, and it handles
3281 // the case where instcombine has trimmed non-demanded bits out
3282 // of an xor with -1.
3283 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3284 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3285 if (BO->getOpcode() == Instruction::And &&
3286 LCI->getValue() == CI->getValue())
3287 if (const SCEVZeroExtendExpr *Z =
3288 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
3289 const Type *UTy = U->getType();
3290 const SCEV *Z0 = Z->getOperand();
3291 const Type *Z0Ty = Z0->getType();
3292 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3294 // If C is a low-bits mask, the zero extend is serving to
3295 // mask off the high bits. Complement the operand and
3296 // re-apply the zext.
3297 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3298 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3300 // If C is a single bit, it may be in the sign-bit position
3301 // before the zero-extend. In this case, represent the xor
3302 // using an add, which is equivalent, and re-apply the zext.
3303 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
3304 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3306 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3312 case Instruction::Shl:
3313 // Turn shift left of a constant amount into a multiply.
3314 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3315 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
3317 // If the shift count is not less than the bitwidth, the result of
3318 // the shift is undefined. Don't try to analyze it, because the
3319 // resolution chosen here may differ from the resolution chosen in
3320 // other parts of the compiler.
3321 if (SA->getValue().uge(BitWidth))
3324 Constant *X = ConstantInt::get(getContext(),
3325 APInt(BitWidth, 1).shl(SA->getZExtValue()));
3326 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3330 case Instruction::LShr:
3331 // Turn logical shift right of a constant into a unsigned divide.
3332 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3333 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
3335 // If the shift count is not less than the bitwidth, the result of
3336 // the shift is undefined. Don't try to analyze it, because the
3337 // resolution chosen here may differ from the resolution chosen in
3338 // other parts of the compiler.
3339 if (SA->getValue().uge(BitWidth))
3342 Constant *X = ConstantInt::get(getContext(),
3343 APInt(BitWidth, 1).shl(SA->getZExtValue()));
3344 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3348 case Instruction::AShr:
3349 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3350 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
3351 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
3352 if (L->getOpcode() == Instruction::Shl &&
3353 L->getOperand(1) == U->getOperand(1)) {
3354 uint64_t BitWidth = getTypeSizeInBits(U->getType());
3356 // If the shift count is not less than the bitwidth, the result of
3357 // the shift is undefined. Don't try to analyze it, because the
3358 // resolution chosen here may differ from the resolution chosen in
3359 // other parts of the compiler.
3360 if (CI->getValue().uge(BitWidth))
3363 uint64_t Amt = BitWidth - CI->getZExtValue();
3364 if (Amt == BitWidth)
3365 return getSCEV(L->getOperand(0)); // shift by zero --> noop
3367 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
3368 IntegerType::get(getContext(),
3374 case Instruction::Trunc:
3375 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
3377 case Instruction::ZExt:
3378 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3380 case Instruction::SExt:
3381 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3383 case Instruction::BitCast:
3384 // BitCasts are no-op casts so we just eliminate the cast.
3385 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
3386 return getSCEV(U->getOperand(0));
3389 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3390 // lead to pointer expressions which cannot safely be expanded to GEPs,
3391 // because ScalarEvolution doesn't respect the GEP aliasing rules when
3392 // simplifying integer expressions.
3394 case Instruction::GetElementPtr:
3395 return createNodeForGEP(cast<GEPOperator>(U));
3397 case Instruction::PHI:
3398 return createNodeForPHI(cast<PHINode>(U));
3400 case Instruction::Select:
3401 // This could be a smax or umax that was lowered earlier.
3402 // Try to recover it.
3403 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3404 Value *LHS = ICI->getOperand(0);
3405 Value *RHS = ICI->getOperand(1);
3406 switch (ICI->getPredicate()) {
3407 case ICmpInst::ICMP_SLT:
3408 case ICmpInst::ICMP_SLE:
3409 std::swap(LHS, RHS);
3411 case ICmpInst::ICMP_SGT:
3412 case ICmpInst::ICMP_SGE:
3413 // a >s b ? a+x : b+x -> smax(a, b)+x
3414 // a >s b ? b+x : a+x -> smin(a, b)+x
3415 if (LHS->getType() == U->getType()) {
3416 const SCEV *LS = getSCEV(LHS);
3417 const SCEV *RS = getSCEV(RHS);
3418 const SCEV *LA = getSCEV(U->getOperand(1));
3419 const SCEV *RA = getSCEV(U->getOperand(2));
3420 const SCEV *LDiff = getMinusSCEV(LA, LS);
3421 const SCEV *RDiff = getMinusSCEV(RA, RS);
3423 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
3424 LDiff = getMinusSCEV(LA, RS);
3425 RDiff = getMinusSCEV(RA, LS);
3427 return getAddExpr(getSMinExpr(LS, RS), LDiff);
3430 case ICmpInst::ICMP_ULT:
3431 case ICmpInst::ICMP_ULE:
3432 std::swap(LHS, RHS);
3434 case ICmpInst::ICMP_UGT:
3435 case ICmpInst::ICMP_UGE:
3436 // a >u b ? a+x : b+x -> umax(a, b)+x
3437 // a >u b ? b+x : a+x -> umin(a, b)+x
3438 if (LHS->getType() == U->getType()) {
3439 const SCEV *LS = getSCEV(LHS);
3440 const SCEV *RS = getSCEV(RHS);
3441 const SCEV *LA = getSCEV(U->getOperand(1));
3442 const SCEV *RA = getSCEV(U->getOperand(2));
3443 const SCEV *LDiff = getMinusSCEV(LA, LS);
3444 const SCEV *RDiff = getMinusSCEV(RA, RS);
3446 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
3447 LDiff = getMinusSCEV(LA, RS);
3448 RDiff = getMinusSCEV(RA, LS);
3450 return getAddExpr(getUMinExpr(LS, RS), LDiff);
3453 case ICmpInst::ICMP_NE:
3454 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
3455 if (LHS->getType() == U->getType() &&
3456 isa<ConstantInt>(RHS) &&
3457 cast<ConstantInt>(RHS)->isZero()) {
3458 const SCEV *One = getConstant(LHS->getType(), 1);
3459 const SCEV *LS = getSCEV(LHS);
3460 const SCEV *LA = getSCEV(U->getOperand(1));
3461 const SCEV *RA = getSCEV(U->getOperand(2));
3462 const SCEV *LDiff = getMinusSCEV(LA, LS);
3463 const SCEV *RDiff = getMinusSCEV(RA, One);
3465 return getAddExpr(getUMaxExpr(LS, One), LDiff);
3468 case ICmpInst::ICMP_EQ:
3469 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
3470 if (LHS->getType() == U->getType() &&
3471 isa<ConstantInt>(RHS) &&
3472 cast<ConstantInt>(RHS)->isZero()) {
3473 const SCEV *One = getConstant(LHS->getType(), 1);
3474 const SCEV *LS = getSCEV(LHS);
3475 const SCEV *LA = getSCEV(U->getOperand(1));
3476 const SCEV *RA = getSCEV(U->getOperand(2));
3477 const SCEV *LDiff = getMinusSCEV(LA, One);
3478 const SCEV *RDiff = getMinusSCEV(RA, LS);
3480 return getAddExpr(getUMaxExpr(LS, One), LDiff);
3488 default: // We cannot analyze this expression.
3492 return getUnknown(V);
3497 //===----------------------------------------------------------------------===//
3498 // Iteration Count Computation Code
3501 /// getBackedgeTakenCount - If the specified loop has a predictable
3502 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3503 /// object. The backedge-taken count is the number of times the loop header
3504 /// will be branched to from within the loop. This is one less than the
3505 /// trip count of the loop, since it doesn't count the first iteration,
3506 /// when the header is branched to from outside the loop.
3508 /// Note that it is not valid to call this method on a loop without a
3509 /// loop-invariant backedge-taken count (see
3510 /// hasLoopInvariantBackedgeTakenCount).
3512 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
3513 return getBackedgeTakenInfo(L).Exact;
3516 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3517 /// return the least SCEV value that is known never to be less than the
3518 /// actual backedge taken count.
3519 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
3520 return getBackedgeTakenInfo(L).Max;
3523 /// PushLoopPHIs - Push PHI nodes in the header of the given loop
3524 /// onto the given Worklist.
3526 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3527 BasicBlock *Header = L->getHeader();
3529 // Push all Loop-header PHIs onto the Worklist stack.
3530 for (BasicBlock::iterator I = Header->begin();
3531 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3532 Worklist.push_back(PN);
3535 const ScalarEvolution::BackedgeTakenInfo &
3536 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
3537 // Initially insert a CouldNotCompute for this loop. If the insertion
3538 // succeeds, proceed to actually compute a backedge-taken count and
3539 // update the value. The temporary CouldNotCompute value tells SCEV
3540 // code elsewhere that it shouldn't attempt to request a new
3541 // backedge-taken count, which could result in infinite recursion.
3542 std::pair<std::map<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
3543 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3545 BackedgeTakenInfo BECount = ComputeBackedgeTakenCount(L);
3546 if (BECount.Exact != getCouldNotCompute()) {
3547 assert(BECount.Exact->isLoopInvariant(L) &&
3548 BECount.Max->isLoopInvariant(L) &&
3549 "Computed backedge-taken count isn't loop invariant for loop!");
3550 ++NumTripCountsComputed;
3552 // Update the value in the map.
3553 Pair.first->second = BECount;
3555 if (BECount.Max != getCouldNotCompute())
3556 // Update the value in the map.
3557 Pair.first->second = BECount;
3558 if (isa<PHINode>(L->getHeader()->begin()))
3559 // Only count loops that have phi nodes as not being computable.
3560 ++NumTripCountsNotComputed;
3563 // Now that we know more about the trip count for this loop, forget any
3564 // existing SCEV values for PHI nodes in this loop since they are only
3565 // conservative estimates made without the benefit of trip count
3566 // information. This is similar to the code in forgetLoop, except that
3567 // it handles SCEVUnknown PHI nodes specially.
3568 if (BECount.hasAnyInfo()) {
3569 SmallVector<Instruction *, 16> Worklist;
3570 PushLoopPHIs(L, Worklist);
3572 SmallPtrSet<Instruction *, 8> Visited;
3573 while (!Worklist.empty()) {
3574 Instruction *I = Worklist.pop_back_val();
3575 if (!Visited.insert(I)) continue;
3577 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3578 Scalars.find(static_cast<Value *>(I));
3579 if (It != Scalars.end()) {
3580 // SCEVUnknown for a PHI either means that it has an unrecognized
3581 // structure, or it's a PHI that's in the progress of being computed
3582 // by createNodeForPHI. In the former case, additional loop trip
3583 // count information isn't going to change anything. In the later
3584 // case, createNodeForPHI will perform the necessary updates on its
3585 // own when it gets to that point.
3586 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
3587 ValuesAtScopes.erase(It->second);
3590 if (PHINode *PN = dyn_cast<PHINode>(I))
3591 ConstantEvolutionLoopExitValue.erase(PN);
3594 PushDefUseChildren(I, Worklist);
3598 return Pair.first->second;
3601 /// forgetLoop - This method should be called by the client when it has
3602 /// changed a loop in a way that may effect ScalarEvolution's ability to
3603 /// compute a trip count, or if the loop is deleted.
3604 void ScalarEvolution::forgetLoop(const Loop *L) {
3605 // Drop any stored trip count value.
3606 BackedgeTakenCounts.erase(L);
3608 // Drop information about expressions based on loop-header PHIs.
3609 SmallVector<Instruction *, 16> Worklist;
3610 PushLoopPHIs(L, Worklist);
3612 SmallPtrSet<Instruction *, 8> Visited;
3613 while (!Worklist.empty()) {
3614 Instruction *I = Worklist.pop_back_val();
3615 if (!Visited.insert(I)) continue;
3617 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3618 Scalars.find(static_cast<Value *>(I));
3619 if (It != Scalars.end()) {
3620 ValuesAtScopes.erase(It->second);
3622 if (PHINode *PN = dyn_cast<PHINode>(I))
3623 ConstantEvolutionLoopExitValue.erase(PN);
3626 PushDefUseChildren(I, Worklist);
3630 /// forgetValue - This method should be called by the client when it has
3631 /// changed a value in a way that may effect its value, or which may
3632 /// disconnect it from a def-use chain linking it to a loop.
3633 void ScalarEvolution::forgetValue(Value *V) {
3634 Instruction *I = dyn_cast<Instruction>(V);
3637 // Drop information about expressions based on loop-header PHIs.
3638 SmallVector<Instruction *, 16> Worklist;
3639 Worklist.push_back(I);
3641 SmallPtrSet<Instruction *, 8> Visited;
3642 while (!Worklist.empty()) {
3643 I = Worklist.pop_back_val();
3644 if (!Visited.insert(I)) continue;
3646 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3647 Scalars.find(static_cast<Value *>(I));
3648 if (It != Scalars.end()) {
3649 ValuesAtScopes.erase(It->second);
3651 if (PHINode *PN = dyn_cast<PHINode>(I))
3652 ConstantEvolutionLoopExitValue.erase(PN);
3655 PushDefUseChildren(I, Worklist);
3659 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
3660 /// of the specified loop will execute.
3661 ScalarEvolution::BackedgeTakenInfo
3662 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
3663 SmallVector<BasicBlock *, 8> ExitingBlocks;
3664 L->getExitingBlocks(ExitingBlocks);
3666 // Examine all exits and pick the most conservative values.
3667 const SCEV *BECount = getCouldNotCompute();
3668 const SCEV *MaxBECount = getCouldNotCompute();
3669 bool CouldNotComputeBECount = false;
3670 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3671 BackedgeTakenInfo NewBTI =
3672 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
3674 if (NewBTI.Exact == getCouldNotCompute()) {
3675 // We couldn't compute an exact value for this exit, so
3676 // we won't be able to compute an exact value for the loop.
3677 CouldNotComputeBECount = true;
3678 BECount = getCouldNotCompute();
3679 } else if (!CouldNotComputeBECount) {
3680 if (BECount == getCouldNotCompute())
3681 BECount = NewBTI.Exact;
3683 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
3685 if (MaxBECount == getCouldNotCompute())
3686 MaxBECount = NewBTI.Max;
3687 else if (NewBTI.Max != getCouldNotCompute())
3688 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
3691 return BackedgeTakenInfo(BECount, MaxBECount);
3694 /// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3695 /// of the specified loop will execute if it exits via the specified block.
3696 ScalarEvolution::BackedgeTakenInfo
3697 ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3698 BasicBlock *ExitingBlock) {
3700 // Okay, we've chosen an exiting block. See what condition causes us to
3701 // exit at this block.
3703 // FIXME: we should be able to handle switch instructions (with a single exit)
3704 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
3705 if (ExitBr == 0) return getCouldNotCompute();
3706 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
3708 // At this point, we know we have a conditional branch that determines whether
3709 // the loop is exited. However, we don't know if the branch is executed each
3710 // time through the loop. If not, then the execution count of the branch will
3711 // not be equal to the trip count of the loop.
3713 // Currently we check for this by checking to see if the Exit branch goes to
3714 // the loop header. If so, we know it will always execute the same number of
3715 // times as the loop. We also handle the case where the exit block *is* the
3716 // loop header. This is common for un-rotated loops.
3718 // If both of those tests fail, walk up the unique predecessor chain to the
3719 // header, stopping if there is an edge that doesn't exit the loop. If the
3720 // header is reached, the execution count of the branch will be equal to the
3721 // trip count of the loop.
3723 // More extensive analysis could be done to handle more cases here.
3725 if (ExitBr->getSuccessor(0) != L->getHeader() &&
3726 ExitBr->getSuccessor(1) != L->getHeader() &&
3727 ExitBr->getParent() != L->getHeader()) {
3728 // The simple checks failed, try climbing the unique predecessor chain
3729 // up to the header.
3731 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3732 BasicBlock *Pred = BB->getUniquePredecessor();
3734 return getCouldNotCompute();
3735 TerminatorInst *PredTerm = Pred->getTerminator();
3736 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3737 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3740 // If the predecessor has a successor that isn't BB and isn't
3741 // outside the loop, assume the worst.
3742 if (L->contains(PredSucc))
3743 return getCouldNotCompute();
3745 if (Pred == L->getHeader()) {
3752 return getCouldNotCompute();
3755 // Proceed to the next level to examine the exit condition expression.
3756 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3757 ExitBr->getSuccessor(0),
3758 ExitBr->getSuccessor(1));
3761 /// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3762 /// backedge of the specified loop will execute if its exit condition
3763 /// were a conditional branch of ExitCond, TBB, and FBB.
3764 ScalarEvolution::BackedgeTakenInfo
3765 ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3769 // Check if the controlling expression for this loop is an And or Or.
3770 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3771 if (BO->getOpcode() == Instruction::And) {
3772 // Recurse on the operands of the and.
3773 BackedgeTakenInfo BTI0 =
3774 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3775 BackedgeTakenInfo BTI1 =
3776 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3777 const SCEV *BECount = getCouldNotCompute();
3778 const SCEV *MaxBECount = getCouldNotCompute();
3779 if (L->contains(TBB)) {
3780 // Both conditions must be true for the loop to continue executing.
3781 // Choose the less conservative count.
3782 if (BTI0.Exact == getCouldNotCompute() ||
3783 BTI1.Exact == getCouldNotCompute())
3784 BECount = getCouldNotCompute();
3786 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3787 if (BTI0.Max == getCouldNotCompute())
3788 MaxBECount = BTI1.Max;
3789 else if (BTI1.Max == getCouldNotCompute())
3790 MaxBECount = BTI0.Max;
3792 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3794 // Both conditions must be true for the loop to exit.
3795 assert(L->contains(FBB) && "Loop block has no successor in loop!");
3796 if (BTI0.Exact != getCouldNotCompute() &&
3797 BTI1.Exact != getCouldNotCompute())
3798 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3799 if (BTI0.Max != getCouldNotCompute() &&
3800 BTI1.Max != getCouldNotCompute())
3801 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3804 return BackedgeTakenInfo(BECount, MaxBECount);
3806 if (BO->getOpcode() == Instruction::Or) {
3807 // Recurse on the operands of the or.
3808 BackedgeTakenInfo BTI0 =
3809 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3810 BackedgeTakenInfo BTI1 =
3811 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3812 const SCEV *BECount = getCouldNotCompute();
3813 const SCEV *MaxBECount = getCouldNotCompute();
3814 if (L->contains(FBB)) {
3815 // Both conditions must be false for the loop to continue executing.
3816 // Choose the less conservative count.
3817 if (BTI0.Exact == getCouldNotCompute() ||
3818 BTI1.Exact == getCouldNotCompute())
3819 BECount = getCouldNotCompute();
3821 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3822 if (BTI0.Max == getCouldNotCompute())
3823 MaxBECount = BTI1.Max;
3824 else if (BTI1.Max == getCouldNotCompute())
3825 MaxBECount = BTI0.Max;
3827 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3829 // Both conditions must be false for the loop to exit.
3830 assert(L->contains(TBB) && "Loop block has no successor in loop!");
3831 if (BTI0.Exact != getCouldNotCompute() &&
3832 BTI1.Exact != getCouldNotCompute())
3833 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3834 if (BTI0.Max != getCouldNotCompute() &&
3835 BTI1.Max != getCouldNotCompute())
3836 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3839 return BackedgeTakenInfo(BECount, MaxBECount);
3843 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3844 // Proceed to the next level to examine the icmp.
3845 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3846 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
3848 // Check for a constant condition. These are normally stripped out by
3849 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
3850 // preserve the CFG and is temporarily leaving constant conditions
3852 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
3853 if (L->contains(FBB) == !CI->getZExtValue())
3854 // The backedge is always taken.
3855 return getCouldNotCompute();
3857 // The backedge is never taken.
3858 return getConstant(CI->getType(), 0);
3861 // If it's not an integer or pointer comparison then compute it the hard way.
3862 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3865 /// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3866 /// backedge of the specified loop will execute if its exit condition
3867 /// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3868 ScalarEvolution::BackedgeTakenInfo
3869 ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3874 // If the condition was exit on true, convert the condition to exit on false
3875 ICmpInst::Predicate Cond;
3876 if (!L->contains(FBB))
3877 Cond = ExitCond->getPredicate();
3879 Cond = ExitCond->getInversePredicate();
3881 // Handle common loops like: for (X = "string"; *X; ++X)
3882 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3883 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
3884 BackedgeTakenInfo ItCnt =
3885 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
3886 if (ItCnt.hasAnyInfo())
3890 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3891 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
3893 // Try to evaluate any dependencies out of the loop.
3894 LHS = getSCEVAtScope(LHS, L);
3895 RHS = getSCEVAtScope(RHS, L);
3897 // At this point, we would like to compute how many iterations of the
3898 // loop the predicate will return true for these inputs.
3899 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3900 // If there is a loop-invariant, force it into the RHS.
3901 std::swap(LHS, RHS);
3902 Cond = ICmpInst::getSwappedPredicate(Cond);
3905 // Simplify the operands before analyzing them.
3906 (void)SimplifyICmpOperands(Cond, LHS, RHS);
3908 // If we have a comparison of a chrec against a constant, try to use value
3909 // ranges to answer this query.
3910 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3911 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
3912 if (AddRec->getLoop() == L) {
3913 // Form the constant range.
3914 ConstantRange CompRange(
3915 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
3917 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
3918 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
3922 case ICmpInst::ICMP_NE: { // while (X != Y)
3923 // Convert to: while (X-Y != 0)
3924 BackedgeTakenInfo BTI = HowFarToZero(getMinusSCEV(LHS, RHS), L);
3925 if (BTI.hasAnyInfo()) return BTI;
3928 case ICmpInst::ICMP_EQ: { // while (X == Y)
3929 // Convert to: while (X-Y == 0)
3930 BackedgeTakenInfo BTI = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
3931 if (BTI.hasAnyInfo()) return BTI;
3934 case ICmpInst::ICMP_SLT: {
3935 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3936 if (BTI.hasAnyInfo()) return BTI;
3939 case ICmpInst::ICMP_SGT: {
3940 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3941 getNotSCEV(RHS), L, true);
3942 if (BTI.hasAnyInfo()) return BTI;
3945 case ICmpInst::ICMP_ULT: {
3946 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3947 if (BTI.hasAnyInfo()) return BTI;
3950 case ICmpInst::ICMP_UGT: {
3951 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3952 getNotSCEV(RHS), L, false);
3953 if (BTI.hasAnyInfo()) return BTI;
3958 dbgs() << "ComputeBackedgeTakenCount ";
3959 if (ExitCond->getOperand(0)->getType()->isUnsigned())
3960 dbgs() << "[unsigned] ";
3961 dbgs() << *LHS << " "
3962 << Instruction::getOpcodeName(Instruction::ICmp)
3963 << " " << *RHS << "\n";
3968 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3971 static ConstantInt *
3972 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3973 ScalarEvolution &SE) {
3974 const SCEV *InVal = SE.getConstant(C);
3975 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
3976 assert(isa<SCEVConstant>(Val) &&
3977 "Evaluation of SCEV at constant didn't fold correctly?");
3978 return cast<SCEVConstant>(Val)->getValue();
3981 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
3982 /// and a GEP expression (missing the pointer index) indexing into it, return
3983 /// the addressed element of the initializer or null if the index expression is
3986 GetAddressedElementFromGlobal(GlobalVariable *GV,
3987 const std::vector<ConstantInt*> &Indices) {
3988 Constant *Init = GV->getInitializer();
3989 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
3990 uint64_t Idx = Indices[i]->getZExtValue();
3991 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3992 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3993 Init = cast<Constant>(CS->getOperand(Idx));
3994 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3995 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3996 Init = cast<Constant>(CA->getOperand(Idx));
3997 } else if (isa<ConstantAggregateZero>(Init)) {
3998 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3999 assert(Idx < STy->getNumElements() && "Bad struct index!");
4000 Init = Constant::getNullValue(STy->getElementType(Idx));
4001 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
4002 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
4003 Init = Constant::getNullValue(ATy->getElementType());
4005 llvm_unreachable("Unknown constant aggregate type!");
4009 return 0; // Unknown initializer type
4015 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
4016 /// 'icmp op load X, cst', try to see if we can compute the backedge
4017 /// execution count.
4018 ScalarEvolution::BackedgeTakenInfo
4019 ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
4023 ICmpInst::Predicate predicate) {
4024 if (LI->isVolatile()) return getCouldNotCompute();
4026 // Check to see if the loaded pointer is a getelementptr of a global.
4027 // TODO: Use SCEV instead of manually grubbing with GEPs.
4028 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
4029 if (!GEP) return getCouldNotCompute();
4031 // Make sure that it is really a constant global we are gepping, with an
4032 // initializer, and make sure the first IDX is really 0.
4033 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
4034 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
4035 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
4036 !cast<Constant>(GEP->getOperand(1))->isNullValue())
4037 return getCouldNotCompute();
4039 // Okay, we allow one non-constant index into the GEP instruction.
4041 std::vector<ConstantInt*> Indexes;
4042 unsigned VarIdxNum = 0;
4043 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
4044 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4045 Indexes.push_back(CI);
4046 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
4047 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
4048 VarIdx = GEP->getOperand(i);
4050 Indexes.push_back(0);
4053 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
4054 // Check to see if X is a loop variant variable value now.
4055 const SCEV *Idx = getSCEV(VarIdx);
4056 Idx = getSCEVAtScope(Idx, L);
4058 // We can only recognize very limited forms of loop index expressions, in
4059 // particular, only affine AddRec's like {C1,+,C2}.
4060 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
4061 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
4062 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
4063 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
4064 return getCouldNotCompute();
4066 unsigned MaxSteps = MaxBruteForceIterations;
4067 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
4068 ConstantInt *ItCst = ConstantInt::get(
4069 cast<IntegerType>(IdxExpr->getType()), IterationNum);
4070 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
4072 // Form the GEP offset.
4073 Indexes[VarIdxNum] = Val;
4075 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
4076 if (Result == 0) break; // Cannot compute!
4078 // Evaluate the condition for this iteration.
4079 Result = ConstantExpr::getICmp(predicate, Result, RHS);
4080 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
4081 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
4083 dbgs() << "\n***\n*** Computed loop count " << *ItCst
4084 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
4087 ++NumArrayLenItCounts;
4088 return getConstant(ItCst); // Found terminating iteration!
4091 return getCouldNotCompute();
4095 /// CanConstantFold - Return true if we can constant fold an instruction of the
4096 /// specified type, assuming that all operands were constants.
4097 static bool CanConstantFold(const Instruction *I) {
4098 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
4099 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
4102 if (const CallInst *CI = dyn_cast<CallInst>(I))
4103 if (const Function *F = CI->getCalledFunction())
4104 return canConstantFoldCallTo(F);
4108 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
4109 /// in the loop that V is derived from. We allow arbitrary operations along the
4110 /// way, but the operands of an operation must either be constants or a value
4111 /// derived from a constant PHI. If this expression does not fit with these
4112 /// constraints, return null.
4113 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
4114 // If this is not an instruction, or if this is an instruction outside of the
4115 // loop, it can't be derived from a loop PHI.
4116 Instruction *I = dyn_cast<Instruction>(V);
4117 if (I == 0 || !L->contains(I)) return 0;
4119 if (PHINode *PN = dyn_cast<PHINode>(I)) {
4120 if (L->getHeader() == I->getParent())
4123 // We don't currently keep track of the control flow needed to evaluate
4124 // PHIs, so we cannot handle PHIs inside of loops.
4128 // If we won't be able to constant fold this expression even if the operands
4129 // are constants, return early.
4130 if (!CanConstantFold(I)) return 0;
4132 // Otherwise, we can evaluate this instruction if all of its operands are
4133 // constant or derived from a PHI node themselves.
4135 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
4136 if (!isa<Constant>(I->getOperand(Op))) {
4137 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
4138 if (P == 0) return 0; // Not evolving from PHI
4142 return 0; // Evolving from multiple different PHIs.
4145 // This is a expression evolving from a constant PHI!
4149 /// EvaluateExpression - Given an expression that passes the
4150 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
4151 /// in the loop has the value PHIVal. If we can't fold this expression for some
4152 /// reason, return null.
4153 static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
4154 const TargetData *TD) {
4155 if (isa<PHINode>(V)) return PHIVal;
4156 if (Constant *C = dyn_cast<Constant>(V)) return C;
4157 Instruction *I = cast<Instruction>(V);
4159 std::vector<Constant*> Operands(I->getNumOperands());
4161 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4162 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
4163 if (Operands[i] == 0) return 0;
4166 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4167 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
4169 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4170 &Operands[0], Operands.size(), TD);
4173 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
4174 /// in the header of its containing loop, we know the loop executes a
4175 /// constant number of times, and the PHI node is just a recurrence
4176 /// involving constants, fold it.
4178 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
4181 std::map<PHINode*, Constant*>::iterator I =
4182 ConstantEvolutionLoopExitValue.find(PN);
4183 if (I != ConstantEvolutionLoopExitValue.end())
4186 if (BEs.ugt(MaxBruteForceIterations))
4187 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
4189 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
4191 // Since the loop is canonicalized, the PHI node must have two entries. One
4192 // entry must be a constant (coming in from outside of the loop), and the
4193 // second must be derived from the same PHI.
4194 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4195 Constant *StartCST =
4196 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4198 return RetVal = 0; // Must be a constant.
4200 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4201 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4202 !isa<Constant>(BEValue))
4203 return RetVal = 0; // Not derived from same PHI.
4205 // Execute the loop symbolically to determine the exit value.
4206 if (BEs.getActiveBits() >= 32)
4207 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
4209 unsigned NumIterations = BEs.getZExtValue(); // must be in range
4210 unsigned IterationNum = 0;
4211 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
4212 if (IterationNum == NumIterations)
4213 return RetVal = PHIVal; // Got exit value!
4215 // Compute the value of the PHI node for the next iteration.
4216 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
4217 if (NextPHI == PHIVal)
4218 return RetVal = NextPHI; // Stopped evolving!
4220 return 0; // Couldn't evaluate!
4225 /// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
4226 /// constant number of times (the condition evolves only from constants),
4227 /// try to evaluate a few iterations of the loop until we get the exit
4228 /// condition gets a value of ExitWhen (true or false). If we cannot
4229 /// evaluate the trip count of the loop, return getCouldNotCompute().
4231 ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
4234 PHINode *PN = getConstantEvolvingPHI(Cond, L);
4235 if (PN == 0) return getCouldNotCompute();
4237 // If the loop is canonicalized, the PHI will have exactly two entries.
4238 // That's the only form we support here.
4239 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
4241 // One entry must be a constant (coming in from outside of the loop), and the
4242 // second must be derived from the same PHI.
4243 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4244 Constant *StartCST =
4245 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4246 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
4248 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4249 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4250 !isa<Constant>(BEValue))
4251 return getCouldNotCompute(); // Not derived from same PHI.
4253 // Okay, we find a PHI node that defines the trip count of this loop. Execute
4254 // the loop symbolically to determine when the condition gets a value of
4256 unsigned IterationNum = 0;
4257 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
4258 for (Constant *PHIVal = StartCST;
4259 IterationNum != MaxIterations; ++IterationNum) {
4260 ConstantInt *CondVal =
4261 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
4263 // Couldn't symbolically evaluate.
4264 if (!CondVal) return getCouldNotCompute();
4266 if (CondVal->getValue() == uint64_t(ExitWhen)) {
4267 ++NumBruteForceTripCountsComputed;
4268 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
4271 // Compute the value of the PHI node for the next iteration.
4272 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
4273 if (NextPHI == 0 || NextPHI == PHIVal)
4274 return getCouldNotCompute();// Couldn't evaluate or not making progress...
4278 // Too many iterations were needed to evaluate.
4279 return getCouldNotCompute();
4282 /// getSCEVAtScope - Return a SCEV expression for the specified value
4283 /// at the specified scope in the program. The L value specifies a loop
4284 /// nest to evaluate the expression at, where null is the top-level or a
4285 /// specified loop is immediately inside of the loop.
4287 /// This method can be used to compute the exit value for a variable defined
4288 /// in a loop by querying what the value will hold in the parent loop.
4290 /// In the case that a relevant loop exit value cannot be computed, the
4291 /// original value V is returned.
4292 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
4293 // Check to see if we've folded this expression at this loop before.
4294 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4295 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4296 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4298 return Pair.first->second ? Pair.first->second : V;
4300 // Otherwise compute it.
4301 const SCEV *C = computeSCEVAtScope(V, L);
4302 ValuesAtScopes[V][L] = C;
4306 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
4307 if (isa<SCEVConstant>(V)) return V;
4309 // If this instruction is evolved from a constant-evolving PHI, compute the
4310 // exit value from the loop without using SCEVs.
4311 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
4312 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
4313 const Loop *LI = (*this->LI)[I->getParent()];
4314 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
4315 if (PHINode *PN = dyn_cast<PHINode>(I))
4316 if (PN->getParent() == LI->getHeader()) {
4317 // Okay, there is no closed form solution for the PHI node. Check
4318 // to see if the loop that contains it has a known backedge-taken
4319 // count. If so, we may be able to force computation of the exit
4321 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
4322 if (const SCEVConstant *BTCC =
4323 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
4324 // Okay, we know how many times the containing loop executes. If
4325 // this is a constant evolving PHI node, get the final value at
4326 // the specified iteration number.
4327 Constant *RV = getConstantEvolutionLoopExitValue(PN,
4328 BTCC->getValue()->getValue(),
4330 if (RV) return getSCEV(RV);
4334 // Okay, this is an expression that we cannot symbolically evaluate
4335 // into a SCEV. Check to see if it's possible to symbolically evaluate
4336 // the arguments into constants, and if so, try to constant propagate the
4337 // result. This is particularly useful for computing loop exit values.
4338 if (CanConstantFold(I)) {
4339 std::vector<Constant*> Operands;
4340 Operands.reserve(I->getNumOperands());
4341 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4342 Value *Op = I->getOperand(i);
4343 if (Constant *C = dyn_cast<Constant>(Op)) {
4344 Operands.push_back(C);
4346 // If any of the operands is non-constant and if they are
4347 // non-integer and non-pointer, don't even try to analyze them
4348 // with scev techniques.
4349 if (!isSCEVable(Op->getType()))
4352 const SCEV *OpV = getSCEVAtScope(Op, L);
4353 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
4354 Constant *C = SC->getValue();
4355 if (C->getType() != Op->getType())
4356 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4360 Operands.push_back(C);
4361 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
4362 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
4363 if (C->getType() != Op->getType())
4365 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4369 Operands.push_back(C);
4379 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4380 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
4381 Operands[0], Operands[1], TD);
4383 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4384 &Operands[0], Operands.size(), TD);
4390 // This is some other type of SCEVUnknown, just return it.
4394 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
4395 // Avoid performing the look-up in the common case where the specified
4396 // expression has no loop-variant portions.
4397 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
4398 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
4399 if (OpAtScope != Comm->getOperand(i)) {
4400 // Okay, at least one of these operands is loop variant but might be
4401 // foldable. Build a new instance of the folded commutative expression.
4402 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4403 Comm->op_begin()+i);
4404 NewOps.push_back(OpAtScope);
4406 for (++i; i != e; ++i) {
4407 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
4408 NewOps.push_back(OpAtScope);
4410 if (isa<SCEVAddExpr>(Comm))
4411 return getAddExpr(NewOps);
4412 if (isa<SCEVMulExpr>(Comm))
4413 return getMulExpr(NewOps);
4414 if (isa<SCEVSMaxExpr>(Comm))
4415 return getSMaxExpr(NewOps);
4416 if (isa<SCEVUMaxExpr>(Comm))
4417 return getUMaxExpr(NewOps);
4418 llvm_unreachable("Unknown commutative SCEV type!");
4421 // If we got here, all operands are loop invariant.
4425 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
4426 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4427 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
4428 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4429 return Div; // must be loop invariant
4430 return getUDivExpr(LHS, RHS);
4433 // If this is a loop recurrence for a loop that does not contain L, then we
4434 // are dealing with the final value computed by the loop.
4435 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4436 if (!L || !AddRec->getLoop()->contains(L)) {
4437 // To evaluate this recurrence, we need to know how many times the AddRec
4438 // loop iterates. Compute this now.
4439 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
4440 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
4442 // Then, evaluate the AddRec.
4443 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
4448 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
4449 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4450 if (Op == Cast->getOperand())
4451 return Cast; // must be loop invariant
4452 return getZeroExtendExpr(Op, Cast->getType());
4455 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
4456 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4457 if (Op == Cast->getOperand())
4458 return Cast; // must be loop invariant
4459 return getSignExtendExpr(Op, Cast->getType());
4462 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
4463 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4464 if (Op == Cast->getOperand())
4465 return Cast; // must be loop invariant
4466 return getTruncateExpr(Op, Cast->getType());
4469 llvm_unreachable("Unknown SCEV type!");
4473 /// getSCEVAtScope - This is a convenience function which does
4474 /// getSCEVAtScope(getSCEV(V), L).
4475 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
4476 return getSCEVAtScope(getSCEV(V), L);
4479 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4480 /// following equation:
4482 /// A * X = B (mod N)
4484 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4485 /// A and B isn't important.
4487 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
4488 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
4489 ScalarEvolution &SE) {
4490 uint32_t BW = A.getBitWidth();
4491 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4492 assert(A != 0 && "A must be non-zero.");
4496 // The gcd of A and N may have only one prime factor: 2. The number of
4497 // trailing zeros in A is its multiplicity
4498 uint32_t Mult2 = A.countTrailingZeros();
4501 // 2. Check if B is divisible by D.
4503 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4504 // is not less than multiplicity of this prime factor for D.
4505 if (B.countTrailingZeros() < Mult2)
4506 return SE.getCouldNotCompute();
4508 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4511 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4512 // bit width during computations.
4513 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4514 APInt Mod(BW + 1, 0);
4515 Mod.set(BW - Mult2); // Mod = N / D
4516 APInt I = AD.multiplicativeInverse(Mod);
4518 // 4. Compute the minimum unsigned root of the equation:
4519 // I * (B / D) mod (N / D)
4520 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4522 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4524 return SE.getConstant(Result.trunc(BW));
4527 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4528 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4529 /// might be the same) or two SCEVCouldNotCompute objects.
4531 static std::pair<const SCEV *,const SCEV *>
4532 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
4533 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
4534 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4535 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4536 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
4538 // We currently can only solve this if the coefficients are constants.
4539 if (!LC || !MC || !NC) {
4540 const SCEV *CNC = SE.getCouldNotCompute();
4541 return std::make_pair(CNC, CNC);
4544 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
4545 const APInt &L = LC->getValue()->getValue();
4546 const APInt &M = MC->getValue()->getValue();
4547 const APInt &N = NC->getValue()->getValue();
4548 APInt Two(BitWidth, 2);
4549 APInt Four(BitWidth, 4);
4552 using namespace APIntOps;
4554 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4555 // The B coefficient is M-N/2
4559 // The A coefficient is N/2
4560 APInt A(N.sdiv(Two));
4562 // Compute the B^2-4ac term.
4565 SqrtTerm -= Four * (A * C);
4567 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4568 // integer value or else APInt::sqrt() will assert.
4569 APInt SqrtVal(SqrtTerm.sqrt());
4571 // Compute the two solutions for the quadratic formula.
4572 // The divisions must be performed as signed divisions.
4574 APInt TwoA( A << 1 );
4575 if (TwoA.isMinValue()) {
4576 const SCEV *CNC = SE.getCouldNotCompute();
4577 return std::make_pair(CNC, CNC);
4580 LLVMContext &Context = SE.getContext();
4582 ConstantInt *Solution1 =
4583 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
4584 ConstantInt *Solution2 =
4585 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
4587 return std::make_pair(SE.getConstant(Solution1),
4588 SE.getConstant(Solution2));
4589 } // end APIntOps namespace
4592 /// HowFarToZero - Return the number of times a backedge comparing the specified
4593 /// value to zero will execute. If not computable, return CouldNotCompute.
4594 ScalarEvolution::BackedgeTakenInfo
4595 ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
4596 // If the value is a constant
4597 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
4598 // If the value is already zero, the branch will execute zero times.
4599 if (C->getValue()->isZero()) return C;
4600 return getCouldNotCompute(); // Otherwise it will loop infinitely.
4603 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
4604 if (!AddRec || AddRec->getLoop() != L)
4605 return getCouldNotCompute();
4607 if (AddRec->isAffine()) {
4608 // If this is an affine expression, the execution count of this branch is
4609 // the minimum unsigned root of the following equation:
4611 // Start + Step*N = 0 (mod 2^BW)
4615 // Step*N = -Start (mod 2^BW)
4617 // where BW is the common bit width of Start and Step.
4619 // Get the initial value for the loop.
4620 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4621 L->getParentLoop());
4622 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4623 L->getParentLoop());
4625 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
4626 // For now we handle only constant steps.
4628 // First, handle unitary steps.
4629 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
4630 return getNegativeSCEV(Start); // N = -Start (as unsigned)
4631 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4632 return Start; // N = Start (as unsigned)
4634 // Then, try to solve the above equation provided that Start is constant.
4635 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
4636 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
4637 -StartC->getValue()->getValue(),
4640 } else if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
4641 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4642 // the quadratic equation to solve it.
4643 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
4645 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4646 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
4649 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
4650 << " sol#2: " << *R2 << "\n";
4652 // Pick the smallest positive root value.
4653 if (ConstantInt *CB =
4654 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
4655 R1->getValue(), R2->getValue()))) {
4656 if (CB->getZExtValue() == false)
4657 std::swap(R1, R2); // R1 is the minimum root now.
4659 // We can only use this value if the chrec ends up with an exact zero
4660 // value at this index. When solving for "X*X != 5", for example, we
4661 // should not accept a root of 2.
4662 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
4664 return R1; // We found a quadratic root!
4669 return getCouldNotCompute();
4672 /// HowFarToNonZero - Return the number of times a backedge checking the
4673 /// specified value for nonzero will execute. If not computable, return
4675 ScalarEvolution::BackedgeTakenInfo
4676 ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
4677 // Loops that look like: while (X == 0) are very strange indeed. We don't
4678 // handle them yet except for the trivial case. This could be expanded in the
4679 // future as needed.
4681 // If the value is a constant, check to see if it is known to be non-zero
4682 // already. If so, the backedge will execute zero times.
4683 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
4684 if (!C->getValue()->isNullValue())
4685 return getConstant(C->getType(), 0);
4686 return getCouldNotCompute(); // Otherwise it will loop infinitely.
4689 // We could implement others, but I really doubt anyone writes loops like
4690 // this, and if they did, they would already be constant folded.
4691 return getCouldNotCompute();
4694 /// getLoopPredecessor - If the given loop's header has exactly one unique
4695 /// predecessor outside the loop, return it. Otherwise return null.
4696 /// This is less strict that the loop "preheader" concept, which requires
4697 /// the predecessor to have only one single successor.
4699 BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
4700 BasicBlock *Header = L->getHeader();
4701 BasicBlock *Pred = 0;
4702 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
4704 if (!L->contains(*PI)) {
4705 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
4711 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4712 /// (which may not be an immediate predecessor) which has exactly one
4713 /// successor from which BB is reachable, or null if no such block is
4716 std::pair<BasicBlock *, BasicBlock *>
4717 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
4718 // If the block has a unique predecessor, then there is no path from the
4719 // predecessor to the block that does not go through the direct edge
4720 // from the predecessor to the block.
4721 if (BasicBlock *Pred = BB->getSinglePredecessor())
4722 return std::make_pair(Pred, BB);
4724 // A loop's header is defined to be a block that dominates the loop.
4725 // If the header has a unique predecessor outside the loop, it must be
4726 // a block that has exactly one successor that can reach the loop.
4727 if (Loop *L = LI->getLoopFor(BB))
4728 return std::make_pair(getLoopPredecessor(L), L->getHeader());
4730 return std::pair<BasicBlock *, BasicBlock *>();
4733 /// HasSameValue - SCEV structural equivalence is usually sufficient for
4734 /// testing whether two expressions are equal, however for the purposes of
4735 /// looking for a condition guarding a loop, it can be useful to be a little
4736 /// more general, since a front-end may have replicated the controlling
4739 static bool HasSameValue(const SCEV *A, const SCEV *B) {
4740 // Quick check to see if they are the same SCEV.
4741 if (A == B) return true;
4743 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4744 // two different instructions with the same value. Check for this case.
4745 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4746 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4747 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4748 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
4749 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
4752 // Otherwise assume they may have a different value.
4756 /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
4757 /// predicate Pred. Return true iff any changes were made.
4759 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
4760 const SCEV *&LHS, const SCEV *&RHS) {
4761 bool Changed = false;
4763 // Canonicalize a constant to the right side.
4764 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
4765 // Check for both operands constant.
4766 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
4767 if (ConstantExpr::getICmp(Pred,
4769 RHSC->getValue())->isNullValue())
4770 goto trivially_false;
4772 goto trivially_true;
4774 // Otherwise swap the operands to put the constant on the right.
4775 std::swap(LHS, RHS);
4776 Pred = ICmpInst::getSwappedPredicate(Pred);
4780 // If we're comparing an addrec with a value which is loop-invariant in the
4781 // addrec's loop, put the addrec on the left. Also make a dominance check,
4782 // as both operands could be addrecs loop-invariant in each other's loop.
4783 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
4784 const Loop *L = AR->getLoop();
4785 if (LHS->isLoopInvariant(L) && LHS->properlyDominates(L->getHeader(), DT)) {
4786 std::swap(LHS, RHS);
4787 Pred = ICmpInst::getSwappedPredicate(Pred);
4792 // If there's a constant operand, canonicalize comparisons with boundary
4793 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
4794 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4795 const APInt &RA = RC->getValue()->getValue();
4797 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4798 case ICmpInst::ICMP_EQ:
4799 case ICmpInst::ICMP_NE:
4801 case ICmpInst::ICMP_UGE:
4802 if ((RA - 1).isMinValue()) {
4803 Pred = ICmpInst::ICMP_NE;
4804 RHS = getConstant(RA - 1);
4808 if (RA.isMaxValue()) {
4809 Pred = ICmpInst::ICMP_EQ;
4813 if (RA.isMinValue()) goto trivially_true;
4815 Pred = ICmpInst::ICMP_UGT;
4816 RHS = getConstant(RA - 1);
4819 case ICmpInst::ICMP_ULE:
4820 if ((RA + 1).isMaxValue()) {
4821 Pred = ICmpInst::ICMP_NE;
4822 RHS = getConstant(RA + 1);
4826 if (RA.isMinValue()) {
4827 Pred = ICmpInst::ICMP_EQ;
4831 if (RA.isMaxValue()) goto trivially_true;
4833 Pred = ICmpInst::ICMP_ULT;
4834 RHS = getConstant(RA + 1);
4837 case ICmpInst::ICMP_SGE:
4838 if ((RA - 1).isMinSignedValue()) {
4839 Pred = ICmpInst::ICMP_NE;
4840 RHS = getConstant(RA - 1);
4844 if (RA.isMaxSignedValue()) {
4845 Pred = ICmpInst::ICMP_EQ;
4849 if (RA.isMinSignedValue()) goto trivially_true;
4851 Pred = ICmpInst::ICMP_SGT;
4852 RHS = getConstant(RA - 1);
4855 case ICmpInst::ICMP_SLE:
4856 if ((RA + 1).isMaxSignedValue()) {
4857 Pred = ICmpInst::ICMP_NE;
4858 RHS = getConstant(RA + 1);
4862 if (RA.isMinSignedValue()) {
4863 Pred = ICmpInst::ICMP_EQ;
4867 if (RA.isMaxSignedValue()) goto trivially_true;
4869 Pred = ICmpInst::ICMP_SLT;
4870 RHS = getConstant(RA + 1);
4873 case ICmpInst::ICMP_UGT:
4874 if (RA.isMinValue()) {
4875 Pred = ICmpInst::ICMP_NE;
4879 if ((RA + 1).isMaxValue()) {
4880 Pred = ICmpInst::ICMP_EQ;
4881 RHS = getConstant(RA + 1);
4885 if (RA.isMaxValue()) goto trivially_false;
4887 case ICmpInst::ICMP_ULT:
4888 if (RA.isMaxValue()) {
4889 Pred = ICmpInst::ICMP_NE;
4893 if ((RA - 1).isMinValue()) {
4894 Pred = ICmpInst::ICMP_EQ;
4895 RHS = getConstant(RA - 1);
4899 if (RA.isMinValue()) goto trivially_false;
4901 case ICmpInst::ICMP_SGT:
4902 if (RA.isMinSignedValue()) {
4903 Pred = ICmpInst::ICMP_NE;
4907 if ((RA + 1).isMaxSignedValue()) {
4908 Pred = ICmpInst::ICMP_EQ;
4909 RHS = getConstant(RA + 1);
4913 if (RA.isMaxSignedValue()) goto trivially_false;
4915 case ICmpInst::ICMP_SLT:
4916 if (RA.isMaxSignedValue()) {
4917 Pred = ICmpInst::ICMP_NE;
4921 if ((RA - 1).isMinSignedValue()) {
4922 Pred = ICmpInst::ICMP_EQ;
4923 RHS = getConstant(RA - 1);
4927 if (RA.isMinSignedValue()) goto trivially_false;
4932 // Check for obvious equality.
4933 if (HasSameValue(LHS, RHS)) {
4934 if (ICmpInst::isTrueWhenEqual(Pred))
4935 goto trivially_true;
4936 if (ICmpInst::isFalseWhenEqual(Pred))
4937 goto trivially_false;
4940 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
4941 // adding or subtracting 1 from one of the operands.
4943 case ICmpInst::ICMP_SLE:
4944 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
4945 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
4946 /*HasNUW=*/false, /*HasNSW=*/true);
4947 Pred = ICmpInst::ICMP_SLT;
4949 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
4950 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
4951 /*HasNUW=*/false, /*HasNSW=*/true);
4952 Pred = ICmpInst::ICMP_SLT;
4956 case ICmpInst::ICMP_SGE:
4957 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
4958 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
4959 /*HasNUW=*/false, /*HasNSW=*/true);
4960 Pred = ICmpInst::ICMP_SGT;
4962 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
4963 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
4964 /*HasNUW=*/false, /*HasNSW=*/true);
4965 Pred = ICmpInst::ICMP_SGT;
4969 case ICmpInst::ICMP_ULE:
4970 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
4971 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
4972 /*HasNUW=*/true, /*HasNSW=*/false);
4973 Pred = ICmpInst::ICMP_ULT;
4975 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
4976 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
4977 /*HasNUW=*/true, /*HasNSW=*/false);
4978 Pred = ICmpInst::ICMP_ULT;
4982 case ICmpInst::ICMP_UGE:
4983 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
4984 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
4985 /*HasNUW=*/true, /*HasNSW=*/false);
4986 Pred = ICmpInst::ICMP_UGT;
4988 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
4989 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
4990 /*HasNUW=*/true, /*HasNSW=*/false);
4991 Pred = ICmpInst::ICMP_UGT;
4999 // TODO: More simplifications are possible here.
5005 LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
5006 Pred = ICmpInst::ICMP_EQ;
5011 LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
5012 Pred = ICmpInst::ICMP_NE;
5016 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
5017 return getSignedRange(S).getSignedMax().isNegative();
5020 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
5021 return getSignedRange(S).getSignedMin().isStrictlyPositive();
5024 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
5025 return !getSignedRange(S).getSignedMin().isNegative();
5028 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
5029 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
5032 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
5033 return isKnownNegative(S) || isKnownPositive(S);
5036 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
5037 const SCEV *LHS, const SCEV *RHS) {
5038 // Canonicalize the inputs first.
5039 (void)SimplifyICmpOperands(Pred, LHS, RHS);
5041 // If LHS or RHS is an addrec, check to see if the condition is true in
5042 // every iteration of the loop.
5043 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
5044 if (isLoopEntryGuardedByCond(
5045 AR->getLoop(), Pred, AR->getStart(), RHS) &&
5046 isLoopBackedgeGuardedByCond(
5047 AR->getLoop(), Pred, AR->getPostIncExpr(*this), RHS))
5049 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS))
5050 if (isLoopEntryGuardedByCond(
5051 AR->getLoop(), Pred, LHS, AR->getStart()) &&
5052 isLoopBackedgeGuardedByCond(
5053 AR->getLoop(), Pred, LHS, AR->getPostIncExpr(*this)))
5056 // Otherwise see what can be done with known constant ranges.
5057 return isKnownPredicateWithRanges(Pred, LHS, RHS);
5061 ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
5062 const SCEV *LHS, const SCEV *RHS) {
5063 if (HasSameValue(LHS, RHS))
5064 return ICmpInst::isTrueWhenEqual(Pred);
5066 // This code is split out from isKnownPredicate because it is called from
5067 // within isLoopEntryGuardedByCond.
5070 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5072 case ICmpInst::ICMP_SGT:
5073 Pred = ICmpInst::ICMP_SLT;
5074 std::swap(LHS, RHS);
5075 case ICmpInst::ICMP_SLT: {
5076 ConstantRange LHSRange = getSignedRange(LHS);
5077 ConstantRange RHSRange = getSignedRange(RHS);
5078 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
5080 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
5084 case ICmpInst::ICMP_SGE:
5085 Pred = ICmpInst::ICMP_SLE;
5086 std::swap(LHS, RHS);
5087 case ICmpInst::ICMP_SLE: {
5088 ConstantRange LHSRange = getSignedRange(LHS);
5089 ConstantRange RHSRange = getSignedRange(RHS);
5090 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
5092 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
5096 case ICmpInst::ICMP_UGT:
5097 Pred = ICmpInst::ICMP_ULT;
5098 std::swap(LHS, RHS);
5099 case ICmpInst::ICMP_ULT: {
5100 ConstantRange LHSRange = getUnsignedRange(LHS);
5101 ConstantRange RHSRange = getUnsignedRange(RHS);
5102 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
5104 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
5108 case ICmpInst::ICMP_UGE:
5109 Pred = ICmpInst::ICMP_ULE;
5110 std::swap(LHS, RHS);
5111 case ICmpInst::ICMP_ULE: {
5112 ConstantRange LHSRange = getUnsignedRange(LHS);
5113 ConstantRange RHSRange = getUnsignedRange(RHS);
5114 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
5116 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
5120 case ICmpInst::ICMP_NE: {
5121 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
5123 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
5126 const SCEV *Diff = getMinusSCEV(LHS, RHS);
5127 if (isKnownNonZero(Diff))
5131 case ICmpInst::ICMP_EQ:
5132 // The check at the top of the function catches the case where
5133 // the values are known to be equal.
5139 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
5140 /// protected by a conditional between LHS and RHS. This is used to
5141 /// to eliminate casts.
5143 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
5144 ICmpInst::Predicate Pred,
5145 const SCEV *LHS, const SCEV *RHS) {
5146 // Interpret a null as meaning no loop, where there is obviously no guard
5147 // (interprocedural conditions notwithstanding).
5148 if (!L) return true;
5150 BasicBlock *Latch = L->getLoopLatch();
5154 BranchInst *LoopContinuePredicate =
5155 dyn_cast<BranchInst>(Latch->getTerminator());
5156 if (!LoopContinuePredicate ||
5157 LoopContinuePredicate->isUnconditional())
5160 return isImpliedCond(LoopContinuePredicate->getCondition(), Pred, LHS, RHS,
5161 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
5164 /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
5165 /// by a conditional between LHS and RHS. This is used to help avoid max
5166 /// expressions in loop trip counts, and to eliminate casts.
5168 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
5169 ICmpInst::Predicate Pred,
5170 const SCEV *LHS, const SCEV *RHS) {
5171 // Interpret a null as meaning no loop, where there is obviously no guard
5172 // (interprocedural conditions notwithstanding).
5173 if (!L) return false;
5175 // Starting at the loop predecessor, climb up the predecessor chain, as long
5176 // as there are predecessors that can be found that have unique successors
5177 // leading to the original header.
5178 for (std::pair<BasicBlock *, BasicBlock *>
5179 Pair(getLoopPredecessor(L), L->getHeader());
5181 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
5183 BranchInst *LoopEntryPredicate =
5184 dyn_cast<BranchInst>(Pair.first->getTerminator());
5185 if (!LoopEntryPredicate ||
5186 LoopEntryPredicate->isUnconditional())
5189 if (isImpliedCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
5190 LoopEntryPredicate->getSuccessor(0) != Pair.second))
5197 /// isImpliedCond - Test whether the condition described by Pred, LHS,
5198 /// and RHS is true whenever the given Cond value evaluates to true.
5199 bool ScalarEvolution::isImpliedCond(Value *CondValue,
5200 ICmpInst::Predicate Pred,
5201 const SCEV *LHS, const SCEV *RHS,
5203 // Recursively handle And and Or conditions.
5204 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
5205 if (BO->getOpcode() == Instruction::And) {
5207 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
5208 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
5209 } else if (BO->getOpcode() == Instruction::Or) {
5211 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
5212 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
5216 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
5217 if (!ICI) return false;
5219 // Bail if the ICmp's operands' types are wider than the needed type
5220 // before attempting to call getSCEV on them. This avoids infinite
5221 // recursion, since the analysis of widening casts can require loop
5222 // exit condition information for overflow checking, which would
5224 if (getTypeSizeInBits(LHS->getType()) <
5225 getTypeSizeInBits(ICI->getOperand(0)->getType()))
5228 // Now that we found a conditional branch that dominates the loop, check to
5229 // see if it is the comparison we are looking for.
5230 ICmpInst::Predicate FoundPred;
5232 FoundPred = ICI->getInversePredicate();
5234 FoundPred = ICI->getPredicate();
5236 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
5237 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
5239 // Balance the types. The case where FoundLHS' type is wider than
5240 // LHS' type is checked for above.
5241 if (getTypeSizeInBits(LHS->getType()) >
5242 getTypeSizeInBits(FoundLHS->getType())) {
5243 if (CmpInst::isSigned(Pred)) {
5244 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
5245 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
5247 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
5248 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
5252 // Canonicalize the query to match the way instcombine will have
5253 // canonicalized the comparison.
5254 if (SimplifyICmpOperands(Pred, LHS, RHS))
5256 return CmpInst::isTrueWhenEqual(Pred);
5257 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
5258 if (FoundLHS == FoundRHS)
5259 return CmpInst::isFalseWhenEqual(Pred);
5261 // Check to see if we can make the LHS or RHS match.
5262 if (LHS == FoundRHS || RHS == FoundLHS) {
5263 if (isa<SCEVConstant>(RHS)) {
5264 std::swap(FoundLHS, FoundRHS);
5265 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
5267 std::swap(LHS, RHS);
5268 Pred = ICmpInst::getSwappedPredicate(Pred);
5272 // Check whether the found predicate is the same as the desired predicate.
5273 if (FoundPred == Pred)
5274 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
5276 // Check whether swapping the found predicate makes it the same as the
5277 // desired predicate.
5278 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
5279 if (isa<SCEVConstant>(RHS))
5280 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
5282 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
5283 RHS, LHS, FoundLHS, FoundRHS);
5286 // Check whether the actual condition is beyond sufficient.
5287 if (FoundPred == ICmpInst::ICMP_EQ)
5288 if (ICmpInst::isTrueWhenEqual(Pred))
5289 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
5291 if (Pred == ICmpInst::ICMP_NE)
5292 if (!ICmpInst::isTrueWhenEqual(FoundPred))
5293 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
5296 // Otherwise assume the worst.
5300 /// isImpliedCondOperands - Test whether the condition described by Pred,
5301 /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
5302 /// and FoundRHS is true.
5303 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
5304 const SCEV *LHS, const SCEV *RHS,
5305 const SCEV *FoundLHS,
5306 const SCEV *FoundRHS) {
5307 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
5308 FoundLHS, FoundRHS) ||
5309 // ~x < ~y --> x > y
5310 isImpliedCondOperandsHelper(Pred, LHS, RHS,
5311 getNotSCEV(FoundRHS),
5312 getNotSCEV(FoundLHS));
5315 /// isImpliedCondOperandsHelper - Test whether the condition described by
5316 /// Pred, LHS, and RHS is true whenever the condition described by Pred,
5317 /// FoundLHS, and FoundRHS is true.
5319 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
5320 const SCEV *LHS, const SCEV *RHS,
5321 const SCEV *FoundLHS,
5322 const SCEV *FoundRHS) {
5324 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5325 case ICmpInst::ICMP_EQ:
5326 case ICmpInst::ICMP_NE:
5327 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
5330 case ICmpInst::ICMP_SLT:
5331 case ICmpInst::ICMP_SLE:
5332 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
5333 isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS))
5336 case ICmpInst::ICMP_SGT:
5337 case ICmpInst::ICMP_SGE:
5338 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
5339 isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS))
5342 case ICmpInst::ICMP_ULT:
5343 case ICmpInst::ICMP_ULE:
5344 if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
5345 isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS))
5348 case ICmpInst::ICMP_UGT:
5349 case ICmpInst::ICMP_UGE:
5350 if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
5351 isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS))
5359 /// getBECount - Subtract the end and start values and divide by the step,
5360 /// rounding up, to get the number of times the backedge is executed. Return
5361 /// CouldNotCompute if an intermediate computation overflows.
5362 const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
5366 assert(!isKnownNegative(Step) &&
5367 "This code doesn't handle negative strides yet!");
5369 const Type *Ty = Start->getType();
5370 const SCEV *NegOne = getConstant(Ty, (uint64_t)-1);
5371 const SCEV *Diff = getMinusSCEV(End, Start);
5372 const SCEV *RoundUp = getAddExpr(Step, NegOne);
5374 // Add an adjustment to the difference between End and Start so that
5375 // the division will effectively round up.
5376 const SCEV *Add = getAddExpr(Diff, RoundUp);
5379 // Check Add for unsigned overflow.
5380 // TODO: More sophisticated things could be done here.
5381 const Type *WideTy = IntegerType::get(getContext(),
5382 getTypeSizeInBits(Ty) + 1);
5383 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
5384 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
5385 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
5386 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
5387 return getCouldNotCompute();
5390 return getUDivExpr(Add, Step);
5393 /// HowManyLessThans - Return the number of times a backedge containing the
5394 /// specified less-than comparison will execute. If not computable, return
5395 /// CouldNotCompute.
5396 ScalarEvolution::BackedgeTakenInfo
5397 ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
5398 const Loop *L, bool isSigned) {
5399 // Only handle: "ADDREC < LoopInvariant".
5400 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
5402 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
5403 if (!AddRec || AddRec->getLoop() != L)
5404 return getCouldNotCompute();
5406 // Check to see if we have a flag which makes analysis easy.
5407 bool NoWrap = isSigned ? AddRec->hasNoSignedWrap() :
5408 AddRec->hasNoUnsignedWrap();
5410 if (AddRec->isAffine()) {
5411 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
5412 const SCEV *Step = AddRec->getStepRecurrence(*this);
5415 return getCouldNotCompute();
5416 if (Step->isOne()) {
5417 // With unit stride, the iteration never steps past the limit value.
5418 } else if (isKnownPositive(Step)) {
5419 // Test whether a positive iteration can step past the limit
5420 // value and past the maximum value for its type in a single step.
5421 // Note that it's not sufficient to check NoWrap here, because even
5422 // though the value after a wrap is undefined, it's not undefined
5423 // behavior, so if wrap does occur, the loop could either terminate or
5424 // loop infinitely, but in either case, the loop is guaranteed to
5425 // iterate at least until the iteration where the wrapping occurs.
5426 const SCEV *One = getConstant(Step->getType(), 1);
5428 APInt Max = APInt::getSignedMaxValue(BitWidth);
5429 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
5430 .slt(getSignedRange(RHS).getSignedMax()))
5431 return getCouldNotCompute();
5433 APInt Max = APInt::getMaxValue(BitWidth);
5434 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
5435 .ult(getUnsignedRange(RHS).getUnsignedMax()))
5436 return getCouldNotCompute();
5439 // TODO: Handle negative strides here and below.
5440 return getCouldNotCompute();
5442 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
5443 // m. So, we count the number of iterations in which {n,+,s} < m is true.
5444 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
5445 // treat m-n as signed nor unsigned due to overflow possibility.
5447 // First, we get the value of the LHS in the first iteration: n
5448 const SCEV *Start = AddRec->getOperand(0);
5450 // Determine the minimum constant start value.
5451 const SCEV *MinStart = getConstant(isSigned ?
5452 getSignedRange(Start).getSignedMin() :
5453 getUnsignedRange(Start).getUnsignedMin());
5455 // If we know that the condition is true in order to enter the loop,
5456 // then we know that it will run exactly (m-n)/s times. Otherwise, we
5457 // only know that it will execute (max(m,n)-n)/s times. In both cases,
5458 // the division must round up.
5459 const SCEV *End = RHS;
5460 if (!isLoopEntryGuardedByCond(L,
5461 isSigned ? ICmpInst::ICMP_SLT :
5463 getMinusSCEV(Start, Step), RHS))
5464 End = isSigned ? getSMaxExpr(RHS, Start)
5465 : getUMaxExpr(RHS, Start);
5467 // Determine the maximum constant end value.
5468 const SCEV *MaxEnd = getConstant(isSigned ?
5469 getSignedRange(End).getSignedMax() :
5470 getUnsignedRange(End).getUnsignedMax());
5472 // If MaxEnd is within a step of the maximum integer value in its type,
5473 // adjust it down to the minimum value which would produce the same effect.
5474 // This allows the subsequent ceiling division of (N+(step-1))/step to
5475 // compute the correct value.
5476 const SCEV *StepMinusOne = getMinusSCEV(Step,
5477 getConstant(Step->getType(), 1));
5480 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
5483 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
5486 // Finally, we subtract these two values and divide, rounding up, to get
5487 // the number of times the backedge is executed.
5488 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
5490 // The maximum backedge count is similar, except using the minimum start
5491 // value and the maximum end value.
5492 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step, NoWrap);
5494 return BackedgeTakenInfo(BECount, MaxBECount);
5497 return getCouldNotCompute();
5500 /// getNumIterationsInRange - Return the number of iterations of this loop that
5501 /// produce values in the specified constant range. Another way of looking at
5502 /// this is that it returns the first iteration number where the value is not in
5503 /// the condition, thus computing the exit count. If the iteration count can't
5504 /// be computed, an instance of SCEVCouldNotCompute is returned.
5505 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
5506 ScalarEvolution &SE) const {
5507 if (Range.isFullSet()) // Infinite loop.
5508 return SE.getCouldNotCompute();
5510 // If the start is a non-zero constant, shift the range to simplify things.
5511 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
5512 if (!SC->getValue()->isZero()) {
5513 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
5514 Operands[0] = SE.getConstant(SC->getType(), 0);
5515 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
5516 if (const SCEVAddRecExpr *ShiftedAddRec =
5517 dyn_cast<SCEVAddRecExpr>(Shifted))
5518 return ShiftedAddRec->getNumIterationsInRange(
5519 Range.subtract(SC->getValue()->getValue()), SE);
5520 // This is strange and shouldn't happen.
5521 return SE.getCouldNotCompute();
5524 // The only time we can solve this is when we have all constant indices.
5525 // Otherwise, we cannot determine the overflow conditions.
5526 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5527 if (!isa<SCEVConstant>(getOperand(i)))
5528 return SE.getCouldNotCompute();
5531 // Okay at this point we know that all elements of the chrec are constants and
5532 // that the start element is zero.
5534 // First check to see if the range contains zero. If not, the first
5536 unsigned BitWidth = SE.getTypeSizeInBits(getType());
5537 if (!Range.contains(APInt(BitWidth, 0)))
5538 return SE.getConstant(getType(), 0);
5541 // If this is an affine expression then we have this situation:
5542 // Solve {0,+,A} in Range === Ax in Range
5544 // We know that zero is in the range. If A is positive then we know that
5545 // the upper value of the range must be the first possible exit value.
5546 // If A is negative then the lower of the range is the last possible loop
5547 // value. Also note that we already checked for a full range.
5548 APInt One(BitWidth,1);
5549 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
5550 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
5552 // The exit value should be (End+A)/A.
5553 APInt ExitVal = (End + A).udiv(A);
5554 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
5556 // Evaluate at the exit value. If we really did fall out of the valid
5557 // range, then we computed our trip count, otherwise wrap around or other
5558 // things must have happened.
5559 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
5560 if (Range.contains(Val->getValue()))
5561 return SE.getCouldNotCompute(); // Something strange happened
5563 // Ensure that the previous value is in the range. This is a sanity check.
5564 assert(Range.contains(
5565 EvaluateConstantChrecAtConstant(this,
5566 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
5567 "Linear scev computation is off in a bad way!");
5568 return SE.getConstant(ExitValue);
5569 } else if (isQuadratic()) {
5570 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5571 // quadratic equation to solve it. To do this, we must frame our problem in
5572 // terms of figuring out when zero is crossed, instead of when
5573 // Range.getUpper() is crossed.
5574 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
5575 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
5576 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
5578 // Next, solve the constructed addrec
5579 std::pair<const SCEV *,const SCEV *> Roots =
5580 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
5581 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5582 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
5584 // Pick the smallest positive root value.
5585 if (ConstantInt *CB =
5586 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
5587 R1->getValue(), R2->getValue()))) {
5588 if (CB->getZExtValue() == false)
5589 std::swap(R1, R2); // R1 is the minimum root now.
5591 // Make sure the root is not off by one. The returned iteration should
5592 // not be in the range, but the previous one should be. When solving
5593 // for "X*X < 5", for example, we should not return a root of 2.
5594 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
5597 if (Range.contains(R1Val->getValue())) {
5598 // The next iteration must be out of the range...
5599 ConstantInt *NextVal =
5600 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
5602 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
5603 if (!Range.contains(R1Val->getValue()))
5604 return SE.getConstant(NextVal);
5605 return SE.getCouldNotCompute(); // Something strange happened
5608 // If R1 was not in the range, then it is a good return value. Make
5609 // sure that R1-1 WAS in the range though, just in case.
5610 ConstantInt *NextVal =
5611 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
5612 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
5613 if (Range.contains(R1Val->getValue()))
5615 return SE.getCouldNotCompute(); // Something strange happened
5620 return SE.getCouldNotCompute();
5625 //===----------------------------------------------------------------------===//
5626 // SCEVCallbackVH Class Implementation
5627 //===----------------------------------------------------------------------===//
5629 void ScalarEvolution::SCEVCallbackVH::deleted() {
5630 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
5631 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5632 SE->ConstantEvolutionLoopExitValue.erase(PN);
5633 SE->Scalars.erase(getValPtr());
5634 // this now dangles!
5637 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
5638 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
5640 // Forget all the expressions associated with users of the old value,
5641 // so that future queries will recompute the expressions using the new
5643 SmallVector<User *, 16> Worklist;
5644 SmallPtrSet<User *, 8> Visited;
5645 Value *Old = getValPtr();
5646 bool DeleteOld = false;
5647 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5649 Worklist.push_back(*UI);
5650 while (!Worklist.empty()) {
5651 User *U = Worklist.pop_back_val();
5652 // Deleting the Old value will cause this to dangle. Postpone
5653 // that until everything else is done.
5658 if (!Visited.insert(U))
5660 if (PHINode *PN = dyn_cast<PHINode>(U))
5661 SE->ConstantEvolutionLoopExitValue.erase(PN);
5662 SE->Scalars.erase(U);
5663 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5665 Worklist.push_back(*UI);
5667 // Delete the Old value if it (indirectly) references itself.
5669 if (PHINode *PN = dyn_cast<PHINode>(Old))
5670 SE->ConstantEvolutionLoopExitValue.erase(PN);
5671 SE->Scalars.erase(Old);
5672 // this now dangles!
5677 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
5678 : CallbackVH(V), SE(se) {}
5680 //===----------------------------------------------------------------------===//
5681 // ScalarEvolution Class Implementation
5682 //===----------------------------------------------------------------------===//
5684 ScalarEvolution::ScalarEvolution()
5685 : FunctionPass(&ID) {
5688 bool ScalarEvolution::runOnFunction(Function &F) {
5690 LI = &getAnalysis<LoopInfo>();
5691 TD = getAnalysisIfAvailable<TargetData>();
5692 DT = &getAnalysis<DominatorTree>();
5696 void ScalarEvolution::releaseMemory() {
5698 BackedgeTakenCounts.clear();
5699 ConstantEvolutionLoopExitValue.clear();
5700 ValuesAtScopes.clear();
5701 UniqueSCEVs.clear();
5702 SCEVAllocator.Reset();
5705 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5706 AU.setPreservesAll();
5707 AU.addRequiredTransitive<LoopInfo>();
5708 AU.addRequiredTransitive<DominatorTree>();
5711 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
5712 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
5715 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
5717 // Print all inner loops first
5718 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5719 PrintLoopInfo(OS, SE, *I);
5722 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5725 SmallVector<BasicBlock *, 8> ExitBlocks;
5726 L->getExitBlocks(ExitBlocks);
5727 if (ExitBlocks.size() != 1)
5728 OS << "<multiple exits> ";
5730 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5731 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
5733 OS << "Unpredictable backedge-taken count. ";
5738 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5741 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5742 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5744 OS << "Unpredictable max backedge-taken count. ";
5750 void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
5751 // ScalarEvolution's implementation of the print method is to print
5752 // out SCEV values of all instructions that are interesting. Doing
5753 // this potentially causes it to create new SCEV objects though,
5754 // which technically conflicts with the const qualifier. This isn't
5755 // observable from outside the class though, so casting away the
5756 // const isn't dangerous.
5757 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
5759 OS << "Classifying expressions for: ";
5760 WriteAsOperand(OS, F, /*PrintType=*/false);
5762 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
5763 if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) {
5766 const SCEV *SV = SE.getSCEV(&*I);
5769 const Loop *L = LI->getLoopFor((*I).getParent());
5771 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
5778 OS << "\t\t" "Exits: ";
5779 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
5780 if (!ExitValue->isLoopInvariant(L)) {
5781 OS << "<<Unknown>>";
5790 OS << "Determining loop execution counts for: ";
5791 WriteAsOperand(OS, F, /*PrintType=*/false);
5793 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5794 PrintLoopInfo(OS, &SE, *I);