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 INITIALIZE_PASS(ScalarEvolution, "scalar-evolution",
107 "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) {
254 if (llvm::next(I) != E)
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 invariant w.r.t. QueryLoop if L contains QueryLoop.
307 if (L->contains(QueryLoop))
310 // This recurrence is variant w.r.t. QueryLoop if any of its operands
312 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
313 if (!getOperand(i)->isLoopInvariant(QueryLoop))
316 // Otherwise it's loop-invariant.
321 SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
322 return DT->dominates(L->getHeader(), BB) &&
323 SCEVNAryExpr::dominates(BB, DT);
327 SCEVAddRecExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
328 // This uses a "dominates" query instead of "properly dominates" query because
329 // the instruction which produces the addrec's value is a PHI, and a PHI
330 // effectively properly dominates its entire containing block.
331 return DT->dominates(L->getHeader(), BB) &&
332 SCEVNAryExpr::properlyDominates(BB, DT);
335 void SCEVAddRecExpr::print(raw_ostream &OS) const {
336 OS << "{" << *Operands[0];
337 for (unsigned i = 1, e = NumOperands; i != e; ++i)
338 OS << ",+," << *Operands[i];
340 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
344 void SCEVUnknown::deleted() {
345 // Clear this SCEVUnknown from ValuesAtScopes.
346 SE->ValuesAtScopes.erase(this);
348 // Remove this SCEVUnknown from the uniquing map.
349 SE->UniqueSCEVs.RemoveNode(this);
351 // Release the value.
355 void SCEVUnknown::allUsesReplacedWith(Value *New) {
356 // Clear this SCEVUnknown from ValuesAtScopes.
357 SE->ValuesAtScopes.erase(this);
359 // Remove this SCEVUnknown from the uniquing map.
360 SE->UniqueSCEVs.RemoveNode(this);
362 // Update this SCEVUnknown to point to the new value. This is needed
363 // because there may still be outstanding SCEVs which still point to
368 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
369 // All non-instruction values are loop invariant. All instructions are loop
370 // invariant if they are not contained in the specified loop.
371 // Instructions are never considered invariant in the function body
372 // (null loop) because they are defined within the "loop".
373 if (Instruction *I = dyn_cast<Instruction>(getValue()))
374 return L && !L->contains(I);
378 bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
379 if (Instruction *I = dyn_cast<Instruction>(getValue()))
380 return DT->dominates(I->getParent(), BB);
384 bool SCEVUnknown::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
385 if (Instruction *I = dyn_cast<Instruction>(getValue()))
386 return DT->properlyDominates(I->getParent(), BB);
390 const Type *SCEVUnknown::getType() const {
391 return getValue()->getType();
394 bool SCEVUnknown::isSizeOf(const Type *&AllocTy) const {
395 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
396 if (VCE->getOpcode() == Instruction::PtrToInt)
397 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
398 if (CE->getOpcode() == Instruction::GetElementPtr &&
399 CE->getOperand(0)->isNullValue() &&
400 CE->getNumOperands() == 2)
401 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
403 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
411 bool SCEVUnknown::isAlignOf(const Type *&AllocTy) const {
412 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
413 if (VCE->getOpcode() == Instruction::PtrToInt)
414 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
415 if (CE->getOpcode() == Instruction::GetElementPtr &&
416 CE->getOperand(0)->isNullValue()) {
418 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
419 if (const StructType *STy = dyn_cast<StructType>(Ty))
420 if (!STy->isPacked() &&
421 CE->getNumOperands() == 3 &&
422 CE->getOperand(1)->isNullValue()) {
423 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
425 STy->getNumElements() == 2 &&
426 STy->getElementType(0)->isIntegerTy(1)) {
427 AllocTy = STy->getElementType(1);
436 bool SCEVUnknown::isOffsetOf(const Type *&CTy, Constant *&FieldNo) const {
437 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
438 if (VCE->getOpcode() == Instruction::PtrToInt)
439 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
440 if (CE->getOpcode() == Instruction::GetElementPtr &&
441 CE->getNumOperands() == 3 &&
442 CE->getOperand(0)->isNullValue() &&
443 CE->getOperand(1)->isNullValue()) {
445 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
446 // Ignore vector types here so that ScalarEvolutionExpander doesn't
447 // emit getelementptrs that index into vectors.
448 if (Ty->isStructTy() || Ty->isArrayTy()) {
450 FieldNo = CE->getOperand(2);
458 void SCEVUnknown::print(raw_ostream &OS) const {
460 if (isSizeOf(AllocTy)) {
461 OS << "sizeof(" << *AllocTy << ")";
464 if (isAlignOf(AllocTy)) {
465 OS << "alignof(" << *AllocTy << ")";
471 if (isOffsetOf(CTy, FieldNo)) {
472 OS << "offsetof(" << *CTy << ", ";
473 WriteAsOperand(OS, FieldNo, false);
478 // Otherwise just print it normally.
479 WriteAsOperand(OS, getValue(), false);
482 //===----------------------------------------------------------------------===//
484 //===----------------------------------------------------------------------===//
487 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
488 /// than the complexity of the RHS. This comparator is used to canonicalize
490 class SCEVComplexityCompare {
491 const LoopInfo *const LI;
493 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
495 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
496 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
500 // Primarily, sort the SCEVs by their getSCEVType().
501 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
503 return LType < RType;
505 // Aside from the getSCEVType() ordering, the particular ordering
506 // isn't very important except that it's beneficial to be consistent,
507 // so that (a + b) and (b + a) don't end up as different expressions.
509 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
510 // not as complete as it could be.
511 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
512 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
513 const Value *LV = LU->getValue(), *RV = RU->getValue();
515 // Order pointer values after integer values. This helps SCEVExpander
517 bool LIsPointer = LV->getType()->isPointerTy(),
518 RIsPointer = RV->getType()->isPointerTy();
519 if (LIsPointer != RIsPointer)
522 // Compare getValueID values.
523 unsigned LID = LV->getValueID(),
524 RID = RV->getValueID();
528 // Sort arguments by their position.
529 if (const Argument *LA = dyn_cast<Argument>(LV)) {
530 const Argument *RA = cast<Argument>(RV);
531 return LA->getArgNo() < RA->getArgNo();
534 // For instructions, compare their loop depth, and their opcode.
535 // This is pretty loose.
536 if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
537 const Instruction *RInst = cast<Instruction>(RV);
539 // Compare loop depths.
540 const BasicBlock *LParent = LInst->getParent(),
541 *RParent = RInst->getParent();
542 if (LParent != RParent) {
543 unsigned LDepth = LI->getLoopDepth(LParent),
544 RDepth = LI->getLoopDepth(RParent);
545 if (LDepth != RDepth)
546 return LDepth < RDepth;
549 // Compare the number of operands.
550 unsigned LNumOps = LInst->getNumOperands(),
551 RNumOps = RInst->getNumOperands();
552 if (LNumOps != RNumOps)
553 return LNumOps < RNumOps;
559 // Compare constant values.
560 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
561 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
562 const ConstantInt *LCC = LC->getValue();
563 const ConstantInt *RCC = RC->getValue();
564 unsigned LBitWidth = LCC->getBitWidth(), RBitWidth = RCC->getBitWidth();
565 if (LBitWidth != RBitWidth)
566 return LBitWidth < RBitWidth;
567 return LCC->getValue().ult(RCC->getValue());
570 // Compare addrec loop depths.
571 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
572 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
573 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
574 if (LLoop != RLoop) {
575 unsigned LDepth = LLoop->getLoopDepth(),
576 RDepth = RLoop->getLoopDepth();
577 if (LDepth != RDepth)
578 return LDepth < RDepth;
582 // Lexicographically compare n-ary expressions.
583 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
584 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
585 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
586 for (unsigned i = 0; i != LNumOps; ++i) {
589 const SCEV *LOp = LC->getOperand(i), *ROp = RC->getOperand(i);
590 if (operator()(LOp, ROp))
592 if (operator()(ROp, LOp))
595 return LNumOps < RNumOps;
598 // Lexicographically compare udiv expressions.
599 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
600 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
601 const SCEV *LL = LC->getLHS(), *LR = LC->getRHS(),
602 *RL = RC->getLHS(), *RR = RC->getRHS();
603 if (operator()(LL, RL))
605 if (operator()(RL, LL))
607 if (operator()(LR, RR))
609 if (operator()(RR, LR))
614 // Compare cast expressions by operand.
615 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
616 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
617 return operator()(LC->getOperand(), RC->getOperand());
620 llvm_unreachable("Unknown SCEV kind!");
626 /// GroupByComplexity - Given a list of SCEV objects, order them by their
627 /// complexity, and group objects of the same complexity together by value.
628 /// When this routine is finished, we know that any duplicates in the vector are
629 /// consecutive and that complexity is monotonically increasing.
631 /// Note that we go take special precautions to ensure that we get deterministic
632 /// results from this routine. In other words, we don't want the results of
633 /// this to depend on where the addresses of various SCEV objects happened to
636 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
638 if (Ops.size() < 2) return; // Noop
639 if (Ops.size() == 2) {
640 // This is the common case, which also happens to be trivially simple.
642 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
643 std::swap(Ops[0], Ops[1]);
647 // Do the rough sort by complexity.
648 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
650 // Now that we are sorted by complexity, group elements of the same
651 // complexity. Note that this is, at worst, N^2, but the vector is likely to
652 // be extremely short in practice. Note that we take this approach because we
653 // do not want to depend on the addresses of the objects we are grouping.
654 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
655 const SCEV *S = Ops[i];
656 unsigned Complexity = S->getSCEVType();
658 // If there are any objects of the same complexity and same value as this
660 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
661 if (Ops[j] == S) { // Found a duplicate.
662 // Move it to immediately after i'th element.
663 std::swap(Ops[i+1], Ops[j]);
664 ++i; // no need to rescan it.
665 if (i == e-2) return; // Done!
673 //===----------------------------------------------------------------------===//
674 // Simple SCEV method implementations
675 //===----------------------------------------------------------------------===//
677 /// BinomialCoefficient - Compute BC(It, K). The result has width W.
679 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
681 const Type* ResultTy) {
682 // Handle the simplest case efficiently.
684 return SE.getTruncateOrZeroExtend(It, ResultTy);
686 // We are using the following formula for BC(It, K):
688 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
690 // Suppose, W is the bitwidth of the return value. We must be prepared for
691 // overflow. Hence, we must assure that the result of our computation is
692 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
693 // safe in modular arithmetic.
695 // However, this code doesn't use exactly that formula; the formula it uses
696 // is something like the following, where T is the number of factors of 2 in
697 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
700 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
702 // This formula is trivially equivalent to the previous formula. However,
703 // this formula can be implemented much more efficiently. The trick is that
704 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
705 // arithmetic. To do exact division in modular arithmetic, all we have
706 // to do is multiply by the inverse. Therefore, this step can be done at
709 // The next issue is how to safely do the division by 2^T. The way this
710 // is done is by doing the multiplication step at a width of at least W + T
711 // bits. This way, the bottom W+T bits of the product are accurate. Then,
712 // when we perform the division by 2^T (which is equivalent to a right shift
713 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
714 // truncated out after the division by 2^T.
716 // In comparison to just directly using the first formula, this technique
717 // is much more efficient; using the first formula requires W * K bits,
718 // but this formula less than W + K bits. Also, the first formula requires
719 // a division step, whereas this formula only requires multiplies and shifts.
721 // It doesn't matter whether the subtraction step is done in the calculation
722 // width or the input iteration count's width; if the subtraction overflows,
723 // the result must be zero anyway. We prefer here to do it in the width of
724 // the induction variable because it helps a lot for certain cases; CodeGen
725 // isn't smart enough to ignore the overflow, which leads to much less
726 // efficient code if the width of the subtraction is wider than the native
729 // (It's possible to not widen at all by pulling out factors of 2 before
730 // the multiplication; for example, K=2 can be calculated as
731 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
732 // extra arithmetic, so it's not an obvious win, and it gets
733 // much more complicated for K > 3.)
735 // Protection from insane SCEVs; this bound is conservative,
736 // but it probably doesn't matter.
738 return SE.getCouldNotCompute();
740 unsigned W = SE.getTypeSizeInBits(ResultTy);
742 // Calculate K! / 2^T and T; we divide out the factors of two before
743 // multiplying for calculating K! / 2^T to avoid overflow.
744 // Other overflow doesn't matter because we only care about the bottom
745 // W bits of the result.
746 APInt OddFactorial(W, 1);
748 for (unsigned i = 3; i <= K; ++i) {
750 unsigned TwoFactors = Mult.countTrailingZeros();
752 Mult = Mult.lshr(TwoFactors);
753 OddFactorial *= Mult;
756 // We need at least W + T bits for the multiplication step
757 unsigned CalculationBits = W + T;
759 // Calculate 2^T, at width T+W.
760 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
762 // Calculate the multiplicative inverse of K! / 2^T;
763 // this multiplication factor will perform the exact division by
765 APInt Mod = APInt::getSignedMinValue(W+1);
766 APInt MultiplyFactor = OddFactorial.zext(W+1);
767 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
768 MultiplyFactor = MultiplyFactor.trunc(W);
770 // Calculate the product, at width T+W
771 const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
773 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
774 for (unsigned i = 1; i != K; ++i) {
775 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
776 Dividend = SE.getMulExpr(Dividend,
777 SE.getTruncateOrZeroExtend(S, CalculationTy));
781 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
783 // Truncate the result, and divide by K! / 2^T.
785 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
786 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
789 /// evaluateAtIteration - Return the value of this chain of recurrences at
790 /// the specified iteration number. We can evaluate this recurrence by
791 /// multiplying each element in the chain by the binomial coefficient
792 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
794 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
796 /// where BC(It, k) stands for binomial coefficient.
798 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
799 ScalarEvolution &SE) const {
800 const SCEV *Result = getStart();
801 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
802 // The computation is correct in the face of overflow provided that the
803 // multiplication is performed _after_ the evaluation of the binomial
805 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
806 if (isa<SCEVCouldNotCompute>(Coeff))
809 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
814 //===----------------------------------------------------------------------===//
815 // SCEV Expression folder implementations
816 //===----------------------------------------------------------------------===//
818 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
820 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
821 "This is not a truncating conversion!");
822 assert(isSCEVable(Ty) &&
823 "This is not a conversion to a SCEVable type!");
824 Ty = getEffectiveSCEVType(Ty);
827 ID.AddInteger(scTruncate);
831 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
833 // Fold if the operand is constant.
834 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
836 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(),
837 getEffectiveSCEVType(Ty))));
839 // trunc(trunc(x)) --> trunc(x)
840 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
841 return getTruncateExpr(ST->getOperand(), Ty);
843 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
844 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
845 return getTruncateOrSignExtend(SS->getOperand(), Ty);
847 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
848 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
849 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
851 // If the input value is a chrec scev, truncate the chrec's operands.
852 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
853 SmallVector<const SCEV *, 4> Operands;
854 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
855 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
856 return getAddRecExpr(Operands, AddRec->getLoop());
859 // As a special case, fold trunc(undef) to undef. We don't want to
860 // know too much about SCEVUnknowns, but this special case is handy
862 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
863 if (isa<UndefValue>(U->getValue()))
864 return getSCEV(UndefValue::get(Ty));
866 // The cast wasn't folded; create an explicit cast node. We can reuse
867 // the existing insert position since if we get here, we won't have
868 // made any changes which would invalidate it.
869 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
871 UniqueSCEVs.InsertNode(S, IP);
875 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
877 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
878 "This is not an extending conversion!");
879 assert(isSCEVable(Ty) &&
880 "This is not a conversion to a SCEVable type!");
881 Ty = getEffectiveSCEVType(Ty);
883 // Fold if the operand is constant.
884 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
886 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(),
887 getEffectiveSCEVType(Ty))));
889 // zext(zext(x)) --> zext(x)
890 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
891 return getZeroExtendExpr(SZ->getOperand(), Ty);
893 // Before doing any expensive analysis, check to see if we've already
894 // computed a SCEV for this Op and Ty.
896 ID.AddInteger(scZeroExtend);
900 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
902 // If the input value is a chrec scev, and we can prove that the value
903 // did not overflow the old, smaller, value, we can zero extend all of the
904 // operands (often constants). This allows analysis of something like
905 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
906 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
907 if (AR->isAffine()) {
908 const SCEV *Start = AR->getStart();
909 const SCEV *Step = AR->getStepRecurrence(*this);
910 unsigned BitWidth = getTypeSizeInBits(AR->getType());
911 const Loop *L = AR->getLoop();
913 // If we have special knowledge that this addrec won't overflow,
914 // we don't need to do any further analysis.
915 if (AR->hasNoUnsignedWrap())
916 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
917 getZeroExtendExpr(Step, Ty),
920 // Check whether the backedge-taken count is SCEVCouldNotCompute.
921 // Note that this serves two purposes: It filters out loops that are
922 // simply not analyzable, and it covers the case where this code is
923 // being called from within backedge-taken count analysis, such that
924 // attempting to ask for the backedge-taken count would likely result
925 // in infinite recursion. In the later case, the analysis code will
926 // cope with a conservative value, and it will take care to purge
927 // that value once it has finished.
928 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
929 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
930 // Manually compute the final value for AR, checking for
933 // Check whether the backedge-taken count can be losslessly casted to
934 // the addrec's type. The count is always unsigned.
935 const SCEV *CastedMaxBECount =
936 getTruncateOrZeroExtend(MaxBECount, Start->getType());
937 const SCEV *RecastedMaxBECount =
938 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
939 if (MaxBECount == RecastedMaxBECount) {
940 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
941 // Check whether Start+Step*MaxBECount has no unsigned overflow.
942 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
943 const SCEV *Add = getAddExpr(Start, ZMul);
944 const SCEV *OperandExtendedAdd =
945 getAddExpr(getZeroExtendExpr(Start, WideTy),
946 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
947 getZeroExtendExpr(Step, WideTy)));
948 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
949 // Return the expression with the addrec on the outside.
950 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
951 getZeroExtendExpr(Step, Ty),
954 // Similar to above, only this time treat the step value as signed.
955 // This covers loops that count down.
956 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
957 Add = getAddExpr(Start, SMul);
959 getAddExpr(getZeroExtendExpr(Start, WideTy),
960 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
961 getSignExtendExpr(Step, WideTy)));
962 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
963 // Return the expression with the addrec on the outside.
964 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
965 getSignExtendExpr(Step, Ty),
969 // If the backedge is guarded by a comparison with the pre-inc value
970 // the addrec is safe. Also, if the entry is guarded by a comparison
971 // with the start value and the backedge is guarded by a comparison
972 // with the post-inc value, the addrec is safe.
973 if (isKnownPositive(Step)) {
974 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
975 getUnsignedRange(Step).getUnsignedMax());
976 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
977 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
978 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
979 AR->getPostIncExpr(*this), N)))
980 // Return the expression with the addrec on the outside.
981 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
982 getZeroExtendExpr(Step, Ty),
984 } else if (isKnownNegative(Step)) {
985 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
986 getSignedRange(Step).getSignedMin());
987 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
988 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
989 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
990 AR->getPostIncExpr(*this), N)))
991 // Return the expression with the addrec on the outside.
992 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
993 getSignExtendExpr(Step, Ty),
999 // The cast wasn't folded; create an explicit cast node.
1000 // Recompute the insert position, as it may have been invalidated.
1001 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1002 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1004 UniqueSCEVs.InsertNode(S, IP);
1008 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
1010 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1011 "This is not an extending conversion!");
1012 assert(isSCEVable(Ty) &&
1013 "This is not a conversion to a SCEVable type!");
1014 Ty = getEffectiveSCEVType(Ty);
1016 // Fold if the operand is constant.
1017 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1019 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(),
1020 getEffectiveSCEVType(Ty))));
1022 // sext(sext(x)) --> sext(x)
1023 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1024 return getSignExtendExpr(SS->getOperand(), Ty);
1026 // Before doing any expensive analysis, check to see if we've already
1027 // computed a SCEV for this Op and Ty.
1028 FoldingSetNodeID ID;
1029 ID.AddInteger(scSignExtend);
1033 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1035 // If the input value is a chrec scev, and we can prove that the value
1036 // did not overflow the old, smaller, value, we can sign extend all of the
1037 // operands (often constants). This allows analysis of something like
1038 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1039 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1040 if (AR->isAffine()) {
1041 const SCEV *Start = AR->getStart();
1042 const SCEV *Step = AR->getStepRecurrence(*this);
1043 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1044 const Loop *L = AR->getLoop();
1046 // If we have special knowledge that this addrec won't overflow,
1047 // we don't need to do any further analysis.
1048 if (AR->hasNoSignedWrap())
1049 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1050 getSignExtendExpr(Step, Ty),
1053 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1054 // Note that this serves two purposes: It filters out loops that are
1055 // simply not analyzable, and it covers the case where this code is
1056 // being called from within backedge-taken count analysis, such that
1057 // attempting to ask for the backedge-taken count would likely result
1058 // in infinite recursion. In the later case, the analysis code will
1059 // cope with a conservative value, and it will take care to purge
1060 // that value once it has finished.
1061 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1062 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1063 // Manually compute the final value for AR, checking for
1066 // Check whether the backedge-taken count can be losslessly casted to
1067 // the addrec's type. The count is always unsigned.
1068 const SCEV *CastedMaxBECount =
1069 getTruncateOrZeroExtend(MaxBECount, Start->getType());
1070 const SCEV *RecastedMaxBECount =
1071 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1072 if (MaxBECount == RecastedMaxBECount) {
1073 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1074 // Check whether Start+Step*MaxBECount has no signed overflow.
1075 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
1076 const SCEV *Add = getAddExpr(Start, SMul);
1077 const SCEV *OperandExtendedAdd =
1078 getAddExpr(getSignExtendExpr(Start, WideTy),
1079 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1080 getSignExtendExpr(Step, WideTy)));
1081 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
1082 // Return the expression with the addrec on the outside.
1083 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1084 getSignExtendExpr(Step, Ty),
1087 // Similar to above, only this time treat the step value as unsigned.
1088 // This covers loops that count up with an unsigned step.
1089 const SCEV *UMul = getMulExpr(CastedMaxBECount, Step);
1090 Add = getAddExpr(Start, UMul);
1091 OperandExtendedAdd =
1092 getAddExpr(getSignExtendExpr(Start, WideTy),
1093 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1094 getZeroExtendExpr(Step, WideTy)));
1095 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
1096 // Return the expression with the addrec on the outside.
1097 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1098 getZeroExtendExpr(Step, Ty),
1102 // If the backedge is guarded by a comparison with the pre-inc value
1103 // the addrec is safe. Also, if the entry is guarded by a comparison
1104 // with the start value and the backedge is guarded by a comparison
1105 // with the post-inc value, the addrec is safe.
1106 if (isKnownPositive(Step)) {
1107 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
1108 getSignedRange(Step).getSignedMax());
1109 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
1110 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
1111 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
1112 AR->getPostIncExpr(*this), N)))
1113 // Return the expression with the addrec on the outside.
1114 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1115 getSignExtendExpr(Step, Ty),
1117 } else if (isKnownNegative(Step)) {
1118 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1119 getSignedRange(Step).getSignedMin());
1120 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
1121 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
1122 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1123 AR->getPostIncExpr(*this), N)))
1124 // Return the expression with the addrec on the outside.
1125 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1126 getSignExtendExpr(Step, Ty),
1132 // The cast wasn't folded; create an explicit cast node.
1133 // Recompute the insert position, as it may have been invalidated.
1134 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1135 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1137 UniqueSCEVs.InsertNode(S, IP);
1141 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1142 /// unspecified bits out to the given type.
1144 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1146 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1147 "This is not an extending conversion!");
1148 assert(isSCEVable(Ty) &&
1149 "This is not a conversion to a SCEVable type!");
1150 Ty = getEffectiveSCEVType(Ty);
1152 // Sign-extend negative constants.
1153 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1154 if (SC->getValue()->getValue().isNegative())
1155 return getSignExtendExpr(Op, Ty);
1157 // Peel off a truncate cast.
1158 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
1159 const SCEV *NewOp = T->getOperand();
1160 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1161 return getAnyExtendExpr(NewOp, Ty);
1162 return getTruncateOrNoop(NewOp, Ty);
1165 // Next try a zext cast. If the cast is folded, use it.
1166 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
1167 if (!isa<SCEVZeroExtendExpr>(ZExt))
1170 // Next try a sext cast. If the cast is folded, use it.
1171 const SCEV *SExt = getSignExtendExpr(Op, Ty);
1172 if (!isa<SCEVSignExtendExpr>(SExt))
1175 // Force the cast to be folded into the operands of an addrec.
1176 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1177 SmallVector<const SCEV *, 4> Ops;
1178 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
1180 Ops.push_back(getAnyExtendExpr(*I, Ty));
1181 return getAddRecExpr(Ops, AR->getLoop());
1184 // As a special case, fold anyext(undef) to undef. We don't want to
1185 // know too much about SCEVUnknowns, but this special case is handy
1187 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
1188 if (isa<UndefValue>(U->getValue()))
1189 return getSCEV(UndefValue::get(Ty));
1191 // If the expression is obviously signed, use the sext cast value.
1192 if (isa<SCEVSMaxExpr>(Op))
1195 // Absent any other information, use the zext cast value.
1199 /// CollectAddOperandsWithScales - Process the given Ops list, which is
1200 /// a list of operands to be added under the given scale, update the given
1201 /// map. This is a helper function for getAddRecExpr. As an example of
1202 /// what it does, given a sequence of operands that would form an add
1203 /// expression like this:
1205 /// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1207 /// where A and B are constants, update the map with these values:
1209 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1211 /// and add 13 + A*B*29 to AccumulatedConstant.
1212 /// This will allow getAddRecExpr to produce this:
1214 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1216 /// This form often exposes folding opportunities that are hidden in
1217 /// the original operand list.
1219 /// Return true iff it appears that any interesting folding opportunities
1220 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
1221 /// the common case where no interesting opportunities are present, and
1222 /// is also used as a check to avoid infinite recursion.
1225 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1226 SmallVector<const SCEV *, 8> &NewOps,
1227 APInt &AccumulatedConstant,
1228 const SCEV *const *Ops, size_t NumOperands,
1230 ScalarEvolution &SE) {
1231 bool Interesting = false;
1233 // Iterate over the add operands. They are sorted, with constants first.
1235 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1237 // Pull a buried constant out to the outside.
1238 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1240 AccumulatedConstant += Scale * C->getValue()->getValue();
1243 // Next comes everything else. We're especially interested in multiplies
1244 // here, but they're in the middle, so just visit the rest with one loop.
1245 for (; i != NumOperands; ++i) {
1246 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1247 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1249 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1250 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1251 // A multiplication of a constant with another add; recurse.
1252 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
1254 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1255 Add->op_begin(), Add->getNumOperands(),
1258 // A multiplication of a constant with some other value. Update
1260 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1261 const SCEV *Key = SE.getMulExpr(MulOps);
1262 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1263 M.insert(std::make_pair(Key, NewScale));
1265 NewOps.push_back(Pair.first->first);
1267 Pair.first->second += NewScale;
1268 // The map already had an entry for this value, which may indicate
1269 // a folding opportunity.
1274 // An ordinary operand. Update the map.
1275 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1276 M.insert(std::make_pair(Ops[i], Scale));
1278 NewOps.push_back(Pair.first->first);
1280 Pair.first->second += Scale;
1281 // The map already had an entry for this value, which may indicate
1282 // a folding opportunity.
1292 struct APIntCompare {
1293 bool operator()(const APInt &LHS, const APInt &RHS) const {
1294 return LHS.ult(RHS);
1299 /// getAddExpr - Get a canonical add expression, or something simpler if
1301 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1302 bool HasNUW, bool HasNSW) {
1303 assert(!Ops.empty() && "Cannot get empty add!");
1304 if (Ops.size() == 1) return Ops[0];
1306 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
1307 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1308 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
1309 "SCEVAddExpr operand types don't match!");
1312 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1313 if (!HasNUW && HasNSW) {
1315 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1316 if (!isKnownNonNegative(Ops[i])) {
1320 if (All) HasNUW = true;
1323 // Sort by complexity, this groups all similar expression types together.
1324 GroupByComplexity(Ops, LI);
1326 // If there are any constants, fold them together.
1328 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1330 assert(Idx < Ops.size());
1331 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1332 // We found two constants, fold them together!
1333 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1334 RHSC->getValue()->getValue());
1335 if (Ops.size() == 2) return Ops[0];
1336 Ops.erase(Ops.begin()+1); // Erase the folded element
1337 LHSC = cast<SCEVConstant>(Ops[0]);
1340 // If we are left with a constant zero being added, strip it off.
1341 if (LHSC->getValue()->isZero()) {
1342 Ops.erase(Ops.begin());
1346 if (Ops.size() == 1) return Ops[0];
1349 // Okay, check to see if the same value occurs in the operand list twice. If
1350 // so, merge them together into an multiply expression. Since we sorted the
1351 // list, these values are required to be adjacent.
1352 const Type *Ty = Ops[0]->getType();
1353 bool FoundMatch = false;
1354 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1355 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1356 // Found a match, merge the two values into a multiply, and add any
1357 // remaining values to the result.
1358 const SCEV *Two = getConstant(Ty, 2);
1359 const SCEV *Mul = getMulExpr(Two, Ops[i]);
1360 if (Ops.size() == 2)
1363 Ops.erase(Ops.begin()+i+1);
1368 return getAddExpr(Ops, HasNUW, HasNSW);
1370 // Check for truncates. If all the operands are truncated from the same
1371 // type, see if factoring out the truncate would permit the result to be
1372 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1373 // if the contents of the resulting outer trunc fold to something simple.
1374 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1375 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1376 const Type *DstType = Trunc->getType();
1377 const Type *SrcType = Trunc->getOperand()->getType();
1378 SmallVector<const SCEV *, 8> LargeOps;
1380 // Check all the operands to see if they can be represented in the
1381 // source type of the truncate.
1382 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1383 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1384 if (T->getOperand()->getType() != SrcType) {
1388 LargeOps.push_back(T->getOperand());
1389 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1390 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
1391 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
1392 SmallVector<const SCEV *, 8> LargeMulOps;
1393 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1394 if (const SCEVTruncateExpr *T =
1395 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1396 if (T->getOperand()->getType() != SrcType) {
1400 LargeMulOps.push_back(T->getOperand());
1401 } else if (const SCEVConstant *C =
1402 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1403 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
1410 LargeOps.push_back(getMulExpr(LargeMulOps));
1417 // Evaluate the expression in the larger type.
1418 const SCEV *Fold = getAddExpr(LargeOps, HasNUW, HasNSW);
1419 // If it folds to something simple, use it. Otherwise, don't.
1420 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1421 return getTruncateExpr(Fold, DstType);
1425 // Skip past any other cast SCEVs.
1426 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1429 // If there are add operands they would be next.
1430 if (Idx < Ops.size()) {
1431 bool DeletedAdd = false;
1432 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
1433 // If we have an add, expand the add operands onto the end of the operands
1435 Ops.erase(Ops.begin()+Idx);
1436 Ops.append(Add->op_begin(), Add->op_end());
1440 // If we deleted at least one add, we added operands to the end of the list,
1441 // and they are not necessarily sorted. Recurse to resort and resimplify
1442 // any operands we just acquired.
1444 return getAddExpr(Ops);
1447 // Skip over the add expression until we get to a multiply.
1448 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1451 // Check to see if there are any folding opportunities present with
1452 // operands multiplied by constant values.
1453 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1454 uint64_t BitWidth = getTypeSizeInBits(Ty);
1455 DenseMap<const SCEV *, APInt> M;
1456 SmallVector<const SCEV *, 8> NewOps;
1457 APInt AccumulatedConstant(BitWidth, 0);
1458 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1459 Ops.data(), Ops.size(),
1460 APInt(BitWidth, 1), *this)) {
1461 // Some interesting folding opportunity is present, so its worthwhile to
1462 // re-generate the operands list. Group the operands by constant scale,
1463 // to avoid multiplying by the same constant scale multiple times.
1464 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1465 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
1466 E = NewOps.end(); I != E; ++I)
1467 MulOpLists[M.find(*I)->second].push_back(*I);
1468 // Re-generate the operands list.
1470 if (AccumulatedConstant != 0)
1471 Ops.push_back(getConstant(AccumulatedConstant));
1472 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1473 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
1475 Ops.push_back(getMulExpr(getConstant(I->first),
1476 getAddExpr(I->second)));
1478 return getConstant(Ty, 0);
1479 if (Ops.size() == 1)
1481 return getAddExpr(Ops);
1485 // If we are adding something to a multiply expression, make sure the
1486 // something is not already an operand of the multiply. If so, merge it into
1488 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
1489 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
1490 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
1491 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
1492 if (isa<SCEVConstant>(MulOpSCEV))
1494 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
1495 if (MulOpSCEV == Ops[AddOp]) {
1496 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1497 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
1498 if (Mul->getNumOperands() != 2) {
1499 // If the multiply has more than two operands, we must get the
1501 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
1502 MulOps.erase(MulOps.begin()+MulOp);
1503 InnerMul = getMulExpr(MulOps);
1505 const SCEV *One = getConstant(Ty, 1);
1506 const SCEV *AddOne = getAddExpr(One, InnerMul);
1507 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
1508 if (Ops.size() == 2) return OuterMul;
1510 Ops.erase(Ops.begin()+AddOp);
1511 Ops.erase(Ops.begin()+Idx-1);
1513 Ops.erase(Ops.begin()+Idx);
1514 Ops.erase(Ops.begin()+AddOp-1);
1516 Ops.push_back(OuterMul);
1517 return getAddExpr(Ops);
1520 // Check this multiply against other multiplies being added together.
1521 bool AnyFold = false;
1522 for (unsigned OtherMulIdx = Idx+1;
1523 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1525 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
1526 // If MulOp occurs in OtherMul, we can fold the two multiplies
1528 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1529 OMulOp != e; ++OMulOp)
1530 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1531 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1532 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
1533 if (Mul->getNumOperands() != 2) {
1534 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1536 MulOps.erase(MulOps.begin()+MulOp);
1537 InnerMul1 = getMulExpr(MulOps);
1539 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1540 if (OtherMul->getNumOperands() != 2) {
1541 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1542 OtherMul->op_end());
1543 MulOps.erase(MulOps.begin()+OMulOp);
1544 InnerMul2 = getMulExpr(MulOps);
1546 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1547 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
1548 if (Ops.size() == 2) return OuterMul;
1549 Ops[Idx] = OuterMul;
1550 Ops.erase(Ops.begin()+OtherMulIdx);
1556 return getAddExpr(Ops);
1560 // If there are any add recurrences in the operands list, see if any other
1561 // added values are loop invariant. If so, we can fold them into the
1563 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1566 // Scan over all recurrences, trying to fold loop invariants into them.
1567 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1568 // Scan all of the other operands to this add and add them to the vector if
1569 // they are loop invariant w.r.t. the recurrence.
1570 SmallVector<const SCEV *, 8> LIOps;
1571 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1572 const Loop *AddRecLoop = AddRec->getLoop();
1573 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1574 if (Ops[i]->isLoopInvariant(AddRecLoop)) {
1575 LIOps.push_back(Ops[i]);
1576 Ops.erase(Ops.begin()+i);
1580 // If we found some loop invariants, fold them into the recurrence.
1581 if (!LIOps.empty()) {
1582 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
1583 LIOps.push_back(AddRec->getStart());
1585 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
1587 AddRecOps[0] = getAddExpr(LIOps);
1589 // Build the new addrec. Propagate the NUW and NSW flags if both the
1590 // outer add and the inner addrec are guaranteed to have no overflow.
1591 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop,
1592 HasNUW && AddRec->hasNoUnsignedWrap(),
1593 HasNSW && AddRec->hasNoSignedWrap());
1595 // If all of the other operands were loop invariant, we are done.
1596 if (Ops.size() == 1) return NewRec;
1598 // Otherwise, add the folded AddRec by the non-liv parts.
1599 for (unsigned i = 0;; ++i)
1600 if (Ops[i] == AddRec) {
1604 return getAddExpr(Ops);
1607 // Okay, if there weren't any loop invariants to be folded, check to see if
1608 // there are multiple AddRec's with the same loop induction variable being
1609 // added together. If so, we can fold them.
1610 for (unsigned OtherIdx = Idx+1;
1611 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1612 if (OtherIdx != Idx) {
1613 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1614 if (AddRecLoop == OtherAddRec->getLoop()) {
1615 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1616 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1618 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1619 if (i >= NewOps.size()) {
1620 NewOps.append(OtherAddRec->op_begin()+i,
1621 OtherAddRec->op_end());
1624 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
1626 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRecLoop);
1628 if (Ops.size() == 2) return NewAddRec;
1630 Ops.erase(Ops.begin()+Idx);
1631 Ops.erase(Ops.begin()+OtherIdx-1);
1632 Ops.push_back(NewAddRec);
1633 return getAddExpr(Ops);
1637 // Otherwise couldn't fold anything into this recurrence. Move onto the
1641 // Okay, it looks like we really DO need an add expr. Check to see if we
1642 // already have one, otherwise create a new one.
1643 FoldingSetNodeID ID;
1644 ID.AddInteger(scAddExpr);
1645 ID.AddInteger(Ops.size());
1646 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1647 ID.AddPointer(Ops[i]);
1650 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1652 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1653 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
1654 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
1656 UniqueSCEVs.InsertNode(S, IP);
1658 if (HasNUW) S->setHasNoUnsignedWrap(true);
1659 if (HasNSW) S->setHasNoSignedWrap(true);
1663 /// getMulExpr - Get a canonical multiply expression, or something simpler if
1665 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1666 bool HasNUW, bool HasNSW) {
1667 assert(!Ops.empty() && "Cannot get empty mul!");
1668 if (Ops.size() == 1) return Ops[0];
1670 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1671 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1672 getEffectiveSCEVType(Ops[0]->getType()) &&
1673 "SCEVMulExpr operand types don't match!");
1676 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1677 if (!HasNUW && HasNSW) {
1679 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1680 if (!isKnownNonNegative(Ops[i])) {
1684 if (All) HasNUW = true;
1687 // Sort by complexity, this groups all similar expression types together.
1688 GroupByComplexity(Ops, LI);
1690 // If there are any constants, fold them together.
1692 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1694 // C1*(C2+V) -> C1*C2 + C1*V
1695 if (Ops.size() == 2)
1696 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1697 if (Add->getNumOperands() == 2 &&
1698 isa<SCEVConstant>(Add->getOperand(0)))
1699 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1700 getMulExpr(LHSC, Add->getOperand(1)));
1703 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1704 // We found two constants, fold them together!
1705 ConstantInt *Fold = ConstantInt::get(getContext(),
1706 LHSC->getValue()->getValue() *
1707 RHSC->getValue()->getValue());
1708 Ops[0] = getConstant(Fold);
1709 Ops.erase(Ops.begin()+1); // Erase the folded element
1710 if (Ops.size() == 1) return Ops[0];
1711 LHSC = cast<SCEVConstant>(Ops[0]);
1714 // If we are left with a constant one being multiplied, strip it off.
1715 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1716 Ops.erase(Ops.begin());
1718 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1719 // If we have a multiply of zero, it will always be zero.
1721 } else if (Ops[0]->isAllOnesValue()) {
1722 // If we have a mul by -1 of an add, try distributing the -1 among the
1724 if (Ops.size() == 2)
1725 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1726 SmallVector<const SCEV *, 4> NewOps;
1727 bool AnyFolded = false;
1728 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1730 const SCEV *Mul = getMulExpr(Ops[0], *I);
1731 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1732 NewOps.push_back(Mul);
1735 return getAddExpr(NewOps);
1739 if (Ops.size() == 1)
1743 // Skip over the add expression until we get to a multiply.
1744 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1747 // If there are mul operands inline them all into this expression.
1748 if (Idx < Ops.size()) {
1749 bool DeletedMul = false;
1750 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1751 // If we have an mul, expand the mul operands onto the end of the operands
1753 Ops.erase(Ops.begin()+Idx);
1754 Ops.append(Mul->op_begin(), Mul->op_end());
1758 // If we deleted at least one mul, we added operands to the end of the list,
1759 // and they are not necessarily sorted. Recurse to resort and resimplify
1760 // any operands we just acquired.
1762 return getMulExpr(Ops);
1765 // If there are any add recurrences in the operands list, see if any other
1766 // added values are loop invariant. If so, we can fold them into the
1768 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1771 // Scan over all recurrences, trying to fold loop invariants into them.
1772 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1773 // Scan all of the other operands to this mul and add them to the vector if
1774 // they are loop invariant w.r.t. the recurrence.
1775 SmallVector<const SCEV *, 8> LIOps;
1776 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1777 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1778 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1779 LIOps.push_back(Ops[i]);
1780 Ops.erase(Ops.begin()+i);
1784 // If we found some loop invariants, fold them into the recurrence.
1785 if (!LIOps.empty()) {
1786 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
1787 SmallVector<const SCEV *, 4> NewOps;
1788 NewOps.reserve(AddRec->getNumOperands());
1789 const SCEV *Scale = getMulExpr(LIOps);
1790 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1791 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1793 // Build the new addrec. Propagate the NUW and NSW flags if both the
1794 // outer mul and the inner addrec are guaranteed to have no overflow.
1795 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(),
1796 HasNUW && AddRec->hasNoUnsignedWrap(),
1797 HasNSW && AddRec->hasNoSignedWrap());
1799 // If all of the other operands were loop invariant, we are done.
1800 if (Ops.size() == 1) return NewRec;
1802 // Otherwise, multiply the folded AddRec by the non-liv parts.
1803 for (unsigned i = 0;; ++i)
1804 if (Ops[i] == AddRec) {
1808 return getMulExpr(Ops);
1811 // Okay, if there weren't any loop invariants to be folded, check to see if
1812 // there are multiple AddRec's with the same loop induction variable being
1813 // multiplied together. If so, we can fold them.
1814 for (unsigned OtherIdx = Idx+1;
1815 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1816 if (OtherIdx != Idx) {
1817 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1818 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1819 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1820 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1821 const SCEV *NewStart = getMulExpr(F->getStart(),
1823 const SCEV *B = F->getStepRecurrence(*this);
1824 const SCEV *D = G->getStepRecurrence(*this);
1825 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
1828 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
1830 if (Ops.size() == 2) return NewAddRec;
1832 Ops.erase(Ops.begin()+Idx);
1833 Ops.erase(Ops.begin()+OtherIdx-1);
1834 Ops.push_back(NewAddRec);
1835 return getMulExpr(Ops);
1839 // Otherwise couldn't fold anything into this recurrence. Move onto the
1843 // Okay, it looks like we really DO need an mul expr. Check to see if we
1844 // already have one, otherwise create a new one.
1845 FoldingSetNodeID ID;
1846 ID.AddInteger(scMulExpr);
1847 ID.AddInteger(Ops.size());
1848 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1849 ID.AddPointer(Ops[i]);
1852 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1854 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1855 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
1856 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
1858 UniqueSCEVs.InsertNode(S, IP);
1860 if (HasNUW) S->setHasNoUnsignedWrap(true);
1861 if (HasNSW) S->setHasNoSignedWrap(true);
1865 /// getUDivExpr - Get a canonical unsigned division expression, or something
1866 /// simpler if possible.
1867 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1869 assert(getEffectiveSCEVType(LHS->getType()) ==
1870 getEffectiveSCEVType(RHS->getType()) &&
1871 "SCEVUDivExpr operand types don't match!");
1873 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1874 if (RHSC->getValue()->equalsInt(1))
1875 return LHS; // X udiv 1 --> x
1876 // If the denominator is zero, the result of the udiv is undefined. Don't
1877 // try to analyze it, because the resolution chosen here may differ from
1878 // the resolution chosen in other parts of the compiler.
1879 if (!RHSC->getValue()->isZero()) {
1880 // Determine if the division can be folded into the operands of
1882 // TODO: Generalize this to non-constants by using known-bits information.
1883 const Type *Ty = LHS->getType();
1884 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1885 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
1886 // For non-power-of-two values, effectively round the value up to the
1887 // nearest power of two.
1888 if (!RHSC->getValue()->getValue().isPowerOf2())
1890 const IntegerType *ExtTy =
1891 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
1892 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1893 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1894 if (const SCEVConstant *Step =
1895 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1896 if (!Step->getValue()->getValue()
1897 .urem(RHSC->getValue()->getValue()) &&
1898 getZeroExtendExpr(AR, ExtTy) ==
1899 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1900 getZeroExtendExpr(Step, ExtTy),
1902 SmallVector<const SCEV *, 4> Operands;
1903 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1904 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1905 return getAddRecExpr(Operands, AR->getLoop());
1907 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1908 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1909 SmallVector<const SCEV *, 4> Operands;
1910 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1911 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1912 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
1913 // Find an operand that's safely divisible.
1914 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1915 const SCEV *Op = M->getOperand(i);
1916 const SCEV *Div = getUDivExpr(Op, RHSC);
1917 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1918 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
1921 return getMulExpr(Operands);
1925 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
1926 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1927 SmallVector<const SCEV *, 4> Operands;
1928 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1929 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1930 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1932 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1933 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
1934 if (isa<SCEVUDivExpr>(Op) ||
1935 getMulExpr(Op, RHS) != A->getOperand(i))
1937 Operands.push_back(Op);
1939 if (Operands.size() == A->getNumOperands())
1940 return getAddExpr(Operands);
1944 // Fold if both operands are constant.
1945 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1946 Constant *LHSCV = LHSC->getValue();
1947 Constant *RHSCV = RHSC->getValue();
1948 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1954 FoldingSetNodeID ID;
1955 ID.AddInteger(scUDivExpr);
1959 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1960 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
1962 UniqueSCEVs.InsertNode(S, IP);
1967 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1968 /// Simplify the expression as much as possible.
1969 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
1970 const SCEV *Step, const Loop *L,
1971 bool HasNUW, bool HasNSW) {
1972 SmallVector<const SCEV *, 4> Operands;
1973 Operands.push_back(Start);
1974 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1975 if (StepChrec->getLoop() == L) {
1976 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
1977 return getAddRecExpr(Operands, L);
1980 Operands.push_back(Step);
1981 return getAddRecExpr(Operands, L, HasNUW, HasNSW);
1984 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1985 /// Simplify the expression as much as possible.
1987 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
1989 bool HasNUW, bool HasNSW) {
1990 if (Operands.size() == 1) return Operands[0];
1992 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1993 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1994 getEffectiveSCEVType(Operands[0]->getType()) &&
1995 "SCEVAddRecExpr operand types don't match!");
1998 if (Operands.back()->isZero()) {
1999 Operands.pop_back();
2000 return getAddRecExpr(Operands, L, HasNUW, HasNSW); // {X,+,0} --> X
2003 // It's tempting to want to call getMaxBackedgeTakenCount count here and
2004 // use that information to infer NUW and NSW flags. However, computing a
2005 // BE count requires calling getAddRecExpr, so we may not yet have a
2006 // meaningful BE count at this point (and if we don't, we'd be stuck
2007 // with a SCEVCouldNotCompute as the cached BE count).
2009 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
2010 if (!HasNUW && HasNSW) {
2012 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2013 if (!isKnownNonNegative(Operands[i])) {
2017 if (All) HasNUW = true;
2020 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
2021 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
2022 const Loop *NestedLoop = NestedAR->getLoop();
2023 if (L->contains(NestedLoop) ?
2024 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
2025 (!NestedLoop->contains(L) &&
2026 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
2027 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
2028 NestedAR->op_end());
2029 Operands[0] = NestedAR->getStart();
2030 // AddRecs require their operands be loop-invariant with respect to their
2031 // loops. Don't perform this transformation if it would break this
2033 bool AllInvariant = true;
2034 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2035 if (!Operands[i]->isLoopInvariant(L)) {
2036 AllInvariant = false;
2040 NestedOperands[0] = getAddRecExpr(Operands, L);
2041 AllInvariant = true;
2042 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
2043 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
2044 AllInvariant = false;
2048 // Ok, both add recurrences are valid after the transformation.
2049 return getAddRecExpr(NestedOperands, NestedLoop, HasNUW, HasNSW);
2051 // Reset Operands to its original state.
2052 Operands[0] = NestedAR;
2056 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2057 // already have one, otherwise create a new one.
2058 FoldingSetNodeID ID;
2059 ID.AddInteger(scAddRecExpr);
2060 ID.AddInteger(Operands.size());
2061 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2062 ID.AddPointer(Operands[i]);
2066 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2068 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2069 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
2070 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2071 O, Operands.size(), L);
2072 UniqueSCEVs.InsertNode(S, IP);
2074 if (HasNUW) S->setHasNoUnsignedWrap(true);
2075 if (HasNSW) S->setHasNoSignedWrap(true);
2079 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2081 SmallVector<const SCEV *, 2> Ops;
2084 return getSMaxExpr(Ops);
2088 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2089 assert(!Ops.empty() && "Cannot get empty smax!");
2090 if (Ops.size() == 1) return Ops[0];
2092 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2093 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2094 getEffectiveSCEVType(Ops[0]->getType()) &&
2095 "SCEVSMaxExpr operand types don't match!");
2098 // Sort by complexity, this groups all similar expression types together.
2099 GroupByComplexity(Ops, LI);
2101 // If there are any constants, fold them together.
2103 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2105 assert(Idx < Ops.size());
2106 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2107 // We found two constants, fold them together!
2108 ConstantInt *Fold = ConstantInt::get(getContext(),
2109 APIntOps::smax(LHSC->getValue()->getValue(),
2110 RHSC->getValue()->getValue()));
2111 Ops[0] = getConstant(Fold);
2112 Ops.erase(Ops.begin()+1); // Erase the folded element
2113 if (Ops.size() == 1) return Ops[0];
2114 LHSC = cast<SCEVConstant>(Ops[0]);
2117 // If we are left with a constant minimum-int, strip it off.
2118 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2119 Ops.erase(Ops.begin());
2121 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2122 // If we have an smax with a constant maximum-int, it will always be
2127 if (Ops.size() == 1) return Ops[0];
2130 // Find the first SMax
2131 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2134 // Check to see if one of the operands is an SMax. If so, expand its operands
2135 // onto our operand list, and recurse to simplify.
2136 if (Idx < Ops.size()) {
2137 bool DeletedSMax = false;
2138 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
2139 Ops.erase(Ops.begin()+Idx);
2140 Ops.append(SMax->op_begin(), SMax->op_end());
2145 return getSMaxExpr(Ops);
2148 // Okay, check to see if the same value occurs in the operand list twice. If
2149 // so, delete one. Since we sorted the list, these values are required to
2151 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2152 // X smax Y smax Y --> X smax Y
2153 // X smax Y --> X, if X is always greater than Y
2154 if (Ops[i] == Ops[i+1] ||
2155 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
2156 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2158 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
2159 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2163 if (Ops.size() == 1) return Ops[0];
2165 assert(!Ops.empty() && "Reduced smax down to nothing!");
2167 // Okay, it looks like we really DO need an smax expr. Check to see if we
2168 // already have one, otherwise create a new one.
2169 FoldingSetNodeID ID;
2170 ID.AddInteger(scSMaxExpr);
2171 ID.AddInteger(Ops.size());
2172 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2173 ID.AddPointer(Ops[i]);
2175 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2176 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2177 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2178 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
2180 UniqueSCEVs.InsertNode(S, IP);
2184 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2186 SmallVector<const SCEV *, 2> Ops;
2189 return getUMaxExpr(Ops);
2193 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2194 assert(!Ops.empty() && "Cannot get empty umax!");
2195 if (Ops.size() == 1) return Ops[0];
2197 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2198 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2199 getEffectiveSCEVType(Ops[0]->getType()) &&
2200 "SCEVUMaxExpr operand types don't match!");
2203 // Sort by complexity, this groups all similar expression types together.
2204 GroupByComplexity(Ops, LI);
2206 // If there are any constants, fold them together.
2208 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2210 assert(Idx < Ops.size());
2211 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2212 // We found two constants, fold them together!
2213 ConstantInt *Fold = ConstantInt::get(getContext(),
2214 APIntOps::umax(LHSC->getValue()->getValue(),
2215 RHSC->getValue()->getValue()));
2216 Ops[0] = getConstant(Fold);
2217 Ops.erase(Ops.begin()+1); // Erase the folded element
2218 if (Ops.size() == 1) return Ops[0];
2219 LHSC = cast<SCEVConstant>(Ops[0]);
2222 // If we are left with a constant minimum-int, strip it off.
2223 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2224 Ops.erase(Ops.begin());
2226 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2227 // If we have an umax with a constant maximum-int, it will always be
2232 if (Ops.size() == 1) return Ops[0];
2235 // Find the first UMax
2236 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2239 // Check to see if one of the operands is a UMax. If so, expand its operands
2240 // onto our operand list, and recurse to simplify.
2241 if (Idx < Ops.size()) {
2242 bool DeletedUMax = false;
2243 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
2244 Ops.erase(Ops.begin()+Idx);
2245 Ops.append(UMax->op_begin(), UMax->op_end());
2250 return getUMaxExpr(Ops);
2253 // Okay, check to see if the same value occurs in the operand list twice. If
2254 // so, delete one. Since we sorted the list, these values are required to
2256 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2257 // X umax Y umax Y --> X umax Y
2258 // X umax Y --> X, if X is always greater than Y
2259 if (Ops[i] == Ops[i+1] ||
2260 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
2261 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2263 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
2264 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2268 if (Ops.size() == 1) return Ops[0];
2270 assert(!Ops.empty() && "Reduced umax down to nothing!");
2272 // Okay, it looks like we really DO need a umax expr. Check to see if we
2273 // already have one, otherwise create a new one.
2274 FoldingSetNodeID ID;
2275 ID.AddInteger(scUMaxExpr);
2276 ID.AddInteger(Ops.size());
2277 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2278 ID.AddPointer(Ops[i]);
2280 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2281 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2282 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2283 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
2285 UniqueSCEVs.InsertNode(S, IP);
2289 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2291 // ~smax(~x, ~y) == smin(x, y).
2292 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2295 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2297 // ~umax(~x, ~y) == umin(x, y)
2298 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2301 const SCEV *ScalarEvolution::getSizeOfExpr(const Type *AllocTy) {
2302 // If we have TargetData, we can bypass creating a target-independent
2303 // constant expression and then folding it back into a ConstantInt.
2304 // This is just a compile-time optimization.
2306 return getConstant(TD->getIntPtrType(getContext()),
2307 TD->getTypeAllocSize(AllocTy));
2309 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2310 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2311 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2313 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2314 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2317 const SCEV *ScalarEvolution::getAlignOfExpr(const Type *AllocTy) {
2318 Constant *C = ConstantExpr::getAlignOf(AllocTy);
2319 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2320 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2322 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2323 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2326 const SCEV *ScalarEvolution::getOffsetOfExpr(const StructType *STy,
2328 // If we have TargetData, we can bypass creating a target-independent
2329 // constant expression and then folding it back into a ConstantInt.
2330 // This is just a compile-time optimization.
2332 return getConstant(TD->getIntPtrType(getContext()),
2333 TD->getStructLayout(STy)->getElementOffset(FieldNo));
2335 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2336 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2337 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2339 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
2340 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2343 const SCEV *ScalarEvolution::getOffsetOfExpr(const Type *CTy,
2344 Constant *FieldNo) {
2345 Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
2346 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2347 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2349 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
2350 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2353 const SCEV *ScalarEvolution::getUnknown(Value *V) {
2354 // Don't attempt to do anything other than create a SCEVUnknown object
2355 // here. createSCEV only calls getUnknown after checking for all other
2356 // interesting possibilities, and any other code that calls getUnknown
2357 // is doing so in order to hide a value from SCEV canonicalization.
2359 FoldingSetNodeID ID;
2360 ID.AddInteger(scUnknown);
2363 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
2364 assert(cast<SCEVUnknown>(S)->getValue() == V &&
2365 "Stale SCEVUnknown in uniquing map!");
2368 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
2370 FirstUnknown = cast<SCEVUnknown>(S);
2371 UniqueSCEVs.InsertNode(S, IP);
2375 //===----------------------------------------------------------------------===//
2376 // Basic SCEV Analysis and PHI Idiom Recognition Code
2379 /// isSCEVable - Test if values of the given type are analyzable within
2380 /// the SCEV framework. This primarily includes integer types, and it
2381 /// can optionally include pointer types if the ScalarEvolution class
2382 /// has access to target-specific information.
2383 bool ScalarEvolution::isSCEVable(const Type *Ty) const {
2384 // Integers and pointers are always SCEVable.
2385 return Ty->isIntegerTy() || Ty->isPointerTy();
2388 /// getTypeSizeInBits - Return the size in bits of the specified type,
2389 /// for which isSCEVable must return true.
2390 uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
2391 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2393 // If we have a TargetData, use it!
2395 return TD->getTypeSizeInBits(Ty);
2397 // Integer types have fixed sizes.
2398 if (Ty->isIntegerTy())
2399 return Ty->getPrimitiveSizeInBits();
2401 // The only other support type is pointer. Without TargetData, conservatively
2402 // assume pointers are 64-bit.
2403 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
2407 /// getEffectiveSCEVType - Return a type with the same bitwidth as
2408 /// the given type and which represents how SCEV will treat the given
2409 /// type, for which isSCEVable must return true. For pointer types,
2410 /// this is the pointer-sized integer type.
2411 const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
2412 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2414 if (Ty->isIntegerTy())
2417 // The only other support type is pointer.
2418 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
2419 if (TD) return TD->getIntPtrType(getContext());
2421 // Without TargetData, conservatively assume pointers are 64-bit.
2422 return Type::getInt64Ty(getContext());
2425 const SCEV *ScalarEvolution::getCouldNotCompute() {
2426 return &CouldNotCompute;
2429 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2430 /// expression and create a new one.
2431 const SCEV *ScalarEvolution::getSCEV(Value *V) {
2432 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
2434 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
2435 if (I != Scalars.end()) return I->second;
2436 const SCEV *S = createSCEV(V);
2437 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
2441 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2443 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
2444 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2446 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
2448 const Type *Ty = V->getType();
2449 Ty = getEffectiveSCEVType(Ty);
2450 return getMulExpr(V,
2451 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
2454 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
2455 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
2456 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2458 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
2460 const Type *Ty = V->getType();
2461 Ty = getEffectiveSCEVType(Ty);
2462 const SCEV *AllOnes =
2463 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
2464 return getMinusSCEV(AllOnes, V);
2467 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2469 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2471 // Fast path: X - X --> 0.
2473 return getConstant(LHS->getType(), 0);
2476 return getAddExpr(LHS, getNegativeSCEV(RHS));
2479 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2480 /// input value to the specified type. If the type must be extended, it is zero
2483 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
2485 const Type *SrcTy = V->getType();
2486 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2487 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2488 "Cannot truncate or zero extend with non-integer arguments!");
2489 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2490 return V; // No conversion
2491 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2492 return getTruncateExpr(V, Ty);
2493 return getZeroExtendExpr(V, Ty);
2496 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2497 /// input value to the specified type. If the type must be extended, it is sign
2500 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
2502 const Type *SrcTy = V->getType();
2503 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2504 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2505 "Cannot truncate or zero extend with non-integer arguments!");
2506 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2507 return V; // No conversion
2508 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2509 return getTruncateExpr(V, Ty);
2510 return getSignExtendExpr(V, Ty);
2513 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2514 /// input value to the specified type. If the type must be extended, it is zero
2515 /// extended. The conversion must not be narrowing.
2517 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
2518 const Type *SrcTy = V->getType();
2519 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2520 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2521 "Cannot noop or zero extend with non-integer arguments!");
2522 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2523 "getNoopOrZeroExtend cannot truncate!");
2524 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2525 return V; // No conversion
2526 return getZeroExtendExpr(V, Ty);
2529 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2530 /// input value to the specified type. If the type must be extended, it is sign
2531 /// extended. The conversion must not be narrowing.
2533 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
2534 const Type *SrcTy = V->getType();
2535 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2536 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2537 "Cannot noop or sign extend with non-integer arguments!");
2538 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2539 "getNoopOrSignExtend cannot truncate!");
2540 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2541 return V; // No conversion
2542 return getSignExtendExpr(V, Ty);
2545 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2546 /// the input value to the specified type. If the type must be extended,
2547 /// it is extended with unspecified bits. The conversion must not be
2550 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
2551 const Type *SrcTy = V->getType();
2552 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2553 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2554 "Cannot noop or any extend with non-integer arguments!");
2555 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2556 "getNoopOrAnyExtend cannot truncate!");
2557 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2558 return V; // No conversion
2559 return getAnyExtendExpr(V, Ty);
2562 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2563 /// input value to the specified type. The conversion must not be widening.
2565 ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
2566 const Type *SrcTy = V->getType();
2567 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2568 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2569 "Cannot truncate or noop with non-integer arguments!");
2570 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2571 "getTruncateOrNoop cannot extend!");
2572 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2573 return V; // No conversion
2574 return getTruncateExpr(V, Ty);
2577 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2578 /// the types using zero-extension, and then perform a umax operation
2580 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2582 const SCEV *PromotedLHS = LHS;
2583 const SCEV *PromotedRHS = RHS;
2585 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2586 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2588 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2590 return getUMaxExpr(PromotedLHS, PromotedRHS);
2593 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
2594 /// the types using zero-extension, and then perform a umin operation
2596 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2598 const SCEV *PromotedLHS = LHS;
2599 const SCEV *PromotedRHS = RHS;
2601 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2602 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2604 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2606 return getUMinExpr(PromotedLHS, PromotedRHS);
2609 /// PushDefUseChildren - Push users of the given Instruction
2610 /// onto the given Worklist.
2612 PushDefUseChildren(Instruction *I,
2613 SmallVectorImpl<Instruction *> &Worklist) {
2614 // Push the def-use children onto the Worklist stack.
2615 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2617 Worklist.push_back(cast<Instruction>(*UI));
2620 /// ForgetSymbolicValue - This looks up computed SCEV values for all
2621 /// instructions that depend on the given instruction and removes them from
2622 /// the Scalars map if they reference SymName. This is used during PHI
2625 ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
2626 SmallVector<Instruction *, 16> Worklist;
2627 PushDefUseChildren(PN, Worklist);
2629 SmallPtrSet<Instruction *, 8> Visited;
2631 while (!Worklist.empty()) {
2632 Instruction *I = Worklist.pop_back_val();
2633 if (!Visited.insert(I)) continue;
2635 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
2636 Scalars.find(static_cast<Value *>(I));
2637 if (It != Scalars.end()) {
2638 // Short-circuit the def-use traversal if the symbolic name
2639 // ceases to appear in expressions.
2640 if (It->second != SymName && !It->second->hasOperand(SymName))
2643 // SCEVUnknown for a PHI either means that it has an unrecognized
2644 // structure, it's a PHI that's in the progress of being computed
2645 // by createNodeForPHI, or it's a single-value PHI. In the first case,
2646 // additional loop trip count information isn't going to change anything.
2647 // In the second case, createNodeForPHI will perform the necessary
2648 // updates on its own when it gets to that point. In the third, we do
2649 // want to forget the SCEVUnknown.
2650 if (!isa<PHINode>(I) ||
2651 !isa<SCEVUnknown>(It->second) ||
2652 (I != PN && It->second == SymName)) {
2653 ValuesAtScopes.erase(It->second);
2658 PushDefUseChildren(I, Worklist);
2662 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2663 /// a loop header, making it a potential recurrence, or it doesn't.
2665 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
2666 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2667 if (L->getHeader() == PN->getParent()) {
2668 // The loop may have multiple entrances or multiple exits; we can analyze
2669 // this phi as an addrec if it has a unique entry value and a unique
2671 Value *BEValueV = 0, *StartValueV = 0;
2672 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2673 Value *V = PN->getIncomingValue(i);
2674 if (L->contains(PN->getIncomingBlock(i))) {
2677 } else if (BEValueV != V) {
2681 } else if (!StartValueV) {
2683 } else if (StartValueV != V) {
2688 if (BEValueV && StartValueV) {
2689 // While we are analyzing this PHI node, handle its value symbolically.
2690 const SCEV *SymbolicName = getUnknown(PN);
2691 assert(Scalars.find(PN) == Scalars.end() &&
2692 "PHI node already processed?");
2693 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
2695 // Using this symbolic name for the PHI, analyze the value coming around
2697 const SCEV *BEValue = getSCEV(BEValueV);
2699 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2700 // has a special value for the first iteration of the loop.
2702 // If the value coming around the backedge is an add with the symbolic
2703 // value we just inserted, then we found a simple induction variable!
2704 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
2705 // If there is a single occurrence of the symbolic value, replace it
2706 // with a recurrence.
2707 unsigned FoundIndex = Add->getNumOperands();
2708 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2709 if (Add->getOperand(i) == SymbolicName)
2710 if (FoundIndex == e) {
2715 if (FoundIndex != Add->getNumOperands()) {
2716 // Create an add with everything but the specified operand.
2717 SmallVector<const SCEV *, 8> Ops;
2718 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2719 if (i != FoundIndex)
2720 Ops.push_back(Add->getOperand(i));
2721 const SCEV *Accum = getAddExpr(Ops);
2723 // This is not a valid addrec if the step amount is varying each
2724 // loop iteration, but is not itself an addrec in this loop.
2725 if (Accum->isLoopInvariant(L) ||
2726 (isa<SCEVAddRecExpr>(Accum) &&
2727 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
2728 bool HasNUW = false;
2729 bool HasNSW = false;
2731 // If the increment doesn't overflow, then neither the addrec nor
2732 // the post-increment will overflow.
2733 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
2734 if (OBO->hasNoUnsignedWrap())
2736 if (OBO->hasNoSignedWrap())
2740 const SCEV *StartVal = getSCEV(StartValueV);
2741 const SCEV *PHISCEV =
2742 getAddRecExpr(StartVal, Accum, L, HasNUW, HasNSW);
2744 // Since the no-wrap flags are on the increment, they apply to the
2745 // post-incremented value as well.
2746 if (Accum->isLoopInvariant(L))
2747 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
2748 Accum, L, HasNUW, HasNSW);
2750 // Okay, for the entire analysis of this edge we assumed the PHI
2751 // to be symbolic. We now need to go back and purge all of the
2752 // entries for the scalars that use the symbolic expression.
2753 ForgetSymbolicName(PN, SymbolicName);
2754 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
2758 } else if (const SCEVAddRecExpr *AddRec =
2759 dyn_cast<SCEVAddRecExpr>(BEValue)) {
2760 // Otherwise, this could be a loop like this:
2761 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2762 // In this case, j = {1,+,1} and BEValue is j.
2763 // Because the other in-value of i (0) fits the evolution of BEValue
2764 // i really is an addrec evolution.
2765 if (AddRec->getLoop() == L && AddRec->isAffine()) {
2766 const SCEV *StartVal = getSCEV(StartValueV);
2768 // If StartVal = j.start - j.stride, we can use StartVal as the
2769 // initial step of the addrec evolution.
2770 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
2771 AddRec->getOperand(1))) {
2772 const SCEV *PHISCEV =
2773 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
2775 // Okay, for the entire analysis of this edge we assumed the PHI
2776 // to be symbolic. We now need to go back and purge all of the
2777 // entries for the scalars that use the symbolic expression.
2778 ForgetSymbolicName(PN, SymbolicName);
2779 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
2787 // If the PHI has a single incoming value, follow that value, unless the
2788 // PHI's incoming blocks are in a different loop, in which case doing so
2789 // risks breaking LCSSA form. Instcombine would normally zap these, but
2790 // it doesn't have DominatorTree information, so it may miss cases.
2791 if (Value *V = PN->hasConstantValue(DT)) {
2792 bool AllSameLoop = true;
2793 Loop *PNLoop = LI->getLoopFor(PN->getParent());
2794 for (size_t i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2795 if (LI->getLoopFor(PN->getIncomingBlock(i)) != PNLoop) {
2796 AllSameLoop = false;
2803 // If it's not a loop phi, we can't handle it yet.
2804 return getUnknown(PN);
2807 /// createNodeForGEP - Expand GEP instructions into add and multiply
2808 /// operations. This allows them to be analyzed by regular SCEV code.
2810 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
2812 // Don't blindly transfer the inbounds flag from the GEP instruction to the
2813 // Add expression, because the Instruction may be guarded by control flow
2814 // and the no-overflow bits may not be valid for the expression in any
2817 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
2818 Value *Base = GEP->getOperand(0);
2819 // Don't attempt to analyze GEPs over unsized objects.
2820 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2821 return getUnknown(GEP);
2822 const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
2823 gep_type_iterator GTI = gep_type_begin(GEP);
2824 for (GetElementPtrInst::op_iterator I = llvm::next(GEP->op_begin()),
2828 // Compute the (potentially symbolic) offset in bytes for this index.
2829 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2830 // For a struct, add the member offset.
2831 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2832 const SCEV *FieldOffset = getOffsetOfExpr(STy, FieldNo);
2834 // Add the field offset to the running total offset.
2835 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
2837 // For an array, add the element offset, explicitly scaled.
2838 const SCEV *ElementSize = getSizeOfExpr(*GTI);
2839 const SCEV *IndexS = getSCEV(Index);
2840 // Getelementptr indices are signed.
2841 IndexS = getTruncateOrSignExtend(IndexS, IntPtrTy);
2843 // Multiply the index by the element size to compute the element offset.
2844 const SCEV *LocalOffset = getMulExpr(IndexS, ElementSize);
2846 // Add the element offset to the running total offset.
2847 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2851 // Get the SCEV for the GEP base.
2852 const SCEV *BaseS = getSCEV(Base);
2854 // Add the total offset from all the GEP indices to the base.
2855 return getAddExpr(BaseS, TotalOffset);
2858 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2859 /// guaranteed to end in (at every loop iteration). It is, at the same time,
2860 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2861 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
2863 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
2864 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2865 return C->getValue()->getValue().countTrailingZeros();
2867 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
2868 return std::min(GetMinTrailingZeros(T->getOperand()),
2869 (uint32_t)getTypeSizeInBits(T->getType()));
2871 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
2872 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2873 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2874 getTypeSizeInBits(E->getType()) : OpRes;
2877 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
2878 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2879 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2880 getTypeSizeInBits(E->getType()) : OpRes;
2883 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
2884 // The result is the min of all operands results.
2885 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2886 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2887 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2891 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
2892 // The result is the sum of all operands results.
2893 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2894 uint32_t BitWidth = getTypeSizeInBits(M->getType());
2895 for (unsigned i = 1, e = M->getNumOperands();
2896 SumOpRes != BitWidth && i != e; ++i)
2897 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
2902 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
2903 // The result is the min of all operands results.
2904 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2905 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2906 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2910 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
2911 // The result is the min of all operands results.
2912 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2913 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2914 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2918 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
2919 // The result is the min of all operands results.
2920 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2921 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2922 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2926 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2927 // For a SCEVUnknown, ask ValueTracking.
2928 unsigned BitWidth = getTypeSizeInBits(U->getType());
2929 APInt Mask = APInt::getAllOnesValue(BitWidth);
2930 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2931 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2932 return Zeros.countTrailingOnes();
2939 /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2942 ScalarEvolution::getUnsignedRange(const SCEV *S) {
2944 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2945 return ConstantRange(C->getValue()->getValue());
2947 unsigned BitWidth = getTypeSizeInBits(S->getType());
2948 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2950 // If the value has known zeros, the maximum unsigned value will have those
2951 // known zeros as well.
2952 uint32_t TZ = GetMinTrailingZeros(S);
2954 ConservativeResult =
2955 ConstantRange(APInt::getMinValue(BitWidth),
2956 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
2958 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2959 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2960 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2961 X = X.add(getUnsignedRange(Add->getOperand(i)));
2962 return ConservativeResult.intersectWith(X);
2965 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2966 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2967 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2968 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
2969 return ConservativeResult.intersectWith(X);
2972 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2973 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2974 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2975 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
2976 return ConservativeResult.intersectWith(X);
2979 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2980 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2981 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2982 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
2983 return ConservativeResult.intersectWith(X);
2986 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2987 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2988 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
2989 return ConservativeResult.intersectWith(X.udiv(Y));
2992 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2993 ConstantRange X = getUnsignedRange(ZExt->getOperand());
2994 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
2997 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2998 ConstantRange X = getUnsignedRange(SExt->getOperand());
2999 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
3002 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3003 ConstantRange X = getUnsignedRange(Trunc->getOperand());
3004 return ConservativeResult.intersectWith(X.truncate(BitWidth));
3007 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
3008 // If there's no unsigned wrap, the value will never be less than its
3010 if (AddRec->hasNoUnsignedWrap())
3011 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
3012 if (!C->getValue()->isZero())
3013 ConservativeResult =
3014 ConservativeResult.intersectWith(
3015 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0)));
3017 // TODO: non-affine addrec
3018 if (AddRec->isAffine()) {
3019 const Type *Ty = AddRec->getType();
3020 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
3021 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3022 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
3023 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3025 const SCEV *Start = AddRec->getStart();
3026 const SCEV *Step = AddRec->getStepRecurrence(*this);
3028 ConstantRange StartRange = getUnsignedRange(Start);
3029 ConstantRange StepRange = getSignedRange(Step);
3030 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3031 ConstantRange EndRange =
3032 StartRange.add(MaxBECountRange.multiply(StepRange));
3034 // Check for overflow. This must be done with ConstantRange arithmetic
3035 // because we could be called from within the ScalarEvolution overflow
3037 ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
3038 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3039 ConstantRange ExtMaxBECountRange =
3040 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3041 ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
3042 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3044 return ConservativeResult;
3046 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
3047 EndRange.getUnsignedMin());
3048 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
3049 EndRange.getUnsignedMax());
3050 if (Min.isMinValue() && Max.isMaxValue())
3051 return ConservativeResult;
3052 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
3056 return ConservativeResult;
3059 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3060 // For a SCEVUnknown, ask ValueTracking.
3061 APInt Mask = APInt::getAllOnesValue(BitWidth);
3062 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3063 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
3064 if (Ones == ~Zeros + 1)
3065 return ConservativeResult;
3066 return ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
3069 return ConservativeResult;
3072 /// getSignedRange - Determine the signed range for a particular SCEV.
3075 ScalarEvolution::getSignedRange(const SCEV *S) {
3077 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
3078 return ConstantRange(C->getValue()->getValue());
3080 unsigned BitWidth = getTypeSizeInBits(S->getType());
3081 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3083 // If the value has known zeros, the maximum signed value will have those
3084 // known zeros as well.
3085 uint32_t TZ = GetMinTrailingZeros(S);
3087 ConservativeResult =
3088 ConstantRange(APInt::getSignedMinValue(BitWidth),
3089 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
3091 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3092 ConstantRange X = getSignedRange(Add->getOperand(0));
3093 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3094 X = X.add(getSignedRange(Add->getOperand(i)));
3095 return ConservativeResult.intersectWith(X);
3098 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3099 ConstantRange X = getSignedRange(Mul->getOperand(0));
3100 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3101 X = X.multiply(getSignedRange(Mul->getOperand(i)));
3102 return ConservativeResult.intersectWith(X);
3105 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3106 ConstantRange X = getSignedRange(SMax->getOperand(0));
3107 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3108 X = X.smax(getSignedRange(SMax->getOperand(i)));
3109 return ConservativeResult.intersectWith(X);
3112 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3113 ConstantRange X = getSignedRange(UMax->getOperand(0));
3114 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3115 X = X.umax(getSignedRange(UMax->getOperand(i)));
3116 return ConservativeResult.intersectWith(X);
3119 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3120 ConstantRange X = getSignedRange(UDiv->getLHS());
3121 ConstantRange Y = getSignedRange(UDiv->getRHS());
3122 return ConservativeResult.intersectWith(X.udiv(Y));
3125 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3126 ConstantRange X = getSignedRange(ZExt->getOperand());
3127 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
3130 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3131 ConstantRange X = getSignedRange(SExt->getOperand());
3132 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
3135 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3136 ConstantRange X = getSignedRange(Trunc->getOperand());
3137 return ConservativeResult.intersectWith(X.truncate(BitWidth));
3140 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
3141 // If there's no signed wrap, and all the operands have the same sign or
3142 // zero, the value won't ever change sign.
3143 if (AddRec->hasNoSignedWrap()) {
3144 bool AllNonNeg = true;
3145 bool AllNonPos = true;
3146 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3147 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3148 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3151 ConservativeResult = ConservativeResult.intersectWith(
3152 ConstantRange(APInt(BitWidth, 0),
3153 APInt::getSignedMinValue(BitWidth)));
3155 ConservativeResult = ConservativeResult.intersectWith(
3156 ConstantRange(APInt::getSignedMinValue(BitWidth),
3157 APInt(BitWidth, 1)));
3160 // TODO: non-affine addrec
3161 if (AddRec->isAffine()) {
3162 const Type *Ty = AddRec->getType();
3163 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
3164 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3165 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
3166 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3168 const SCEV *Start = AddRec->getStart();
3169 const SCEV *Step = AddRec->getStepRecurrence(*this);
3171 ConstantRange StartRange = getSignedRange(Start);
3172 ConstantRange StepRange = getSignedRange(Step);
3173 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3174 ConstantRange EndRange =
3175 StartRange.add(MaxBECountRange.multiply(StepRange));
3177 // Check for overflow. This must be done with ConstantRange arithmetic
3178 // because we could be called from within the ScalarEvolution overflow
3180 ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
3181 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3182 ConstantRange ExtMaxBECountRange =
3183 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3184 ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
3185 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3187 return ConservativeResult;
3189 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3190 EndRange.getSignedMin());
3191 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3192 EndRange.getSignedMax());
3193 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
3194 return ConservativeResult;
3195 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
3199 return ConservativeResult;
3202 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3203 // For a SCEVUnknown, ask ValueTracking.
3204 if (!U->getValue()->getType()->isIntegerTy() && !TD)
3205 return ConservativeResult;
3206 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3208 return ConservativeResult;
3209 return ConservativeResult.intersectWith(
3210 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
3211 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1));
3214 return ConservativeResult;
3217 /// createSCEV - We know that there is no SCEV for the specified value.
3218 /// Analyze the expression.
3220 const SCEV *ScalarEvolution::createSCEV(Value *V) {
3221 if (!isSCEVable(V->getType()))
3222 return getUnknown(V);
3224 unsigned Opcode = Instruction::UserOp1;
3225 if (Instruction *I = dyn_cast<Instruction>(V)) {
3226 Opcode = I->getOpcode();
3228 // Don't attempt to analyze instructions in blocks that aren't
3229 // reachable. Such instructions don't matter, and they aren't required
3230 // to obey basic rules for definitions dominating uses which this
3231 // analysis depends on.
3232 if (!DT->isReachableFromEntry(I->getParent()))
3233 return getUnknown(V);
3234 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
3235 Opcode = CE->getOpcode();
3236 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3237 return getConstant(CI);
3238 else if (isa<ConstantPointerNull>(V))
3239 return getConstant(V->getType(), 0);
3240 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3241 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
3243 return getUnknown(V);
3245 Operator *U = cast<Operator>(V);
3247 case Instruction::Add:
3248 return getAddExpr(getSCEV(U->getOperand(0)),
3249 getSCEV(U->getOperand(1)));
3250 case Instruction::Mul:
3251 return getMulExpr(getSCEV(U->getOperand(0)),
3252 getSCEV(U->getOperand(1)));
3253 case Instruction::UDiv:
3254 return getUDivExpr(getSCEV(U->getOperand(0)),
3255 getSCEV(U->getOperand(1)));
3256 case Instruction::Sub:
3257 return getMinusSCEV(getSCEV(U->getOperand(0)),
3258 getSCEV(U->getOperand(1)));
3259 case Instruction::And:
3260 // For an expression like x&255 that merely masks off the high bits,
3261 // use zext(trunc(x)) as the SCEV expression.
3262 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3263 if (CI->isNullValue())
3264 return getSCEV(U->getOperand(1));
3265 if (CI->isAllOnesValue())
3266 return getSCEV(U->getOperand(0));
3267 const APInt &A = CI->getValue();
3269 // Instcombine's ShrinkDemandedConstant may strip bits out of
3270 // constants, obscuring what would otherwise be a low-bits mask.
3271 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3272 // knew about to reconstruct a low-bits mask value.
3273 unsigned LZ = A.countLeadingZeros();
3274 unsigned BitWidth = A.getBitWidth();
3275 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3276 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3277 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3279 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3281 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
3283 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
3284 IntegerType::get(getContext(), BitWidth - LZ)),
3289 case Instruction::Or:
3290 // If the RHS of the Or is a constant, we may have something like:
3291 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3292 // optimizations will transparently handle this case.
3294 // In order for this transformation to be safe, the LHS must be of the
3295 // form X*(2^n) and the Or constant must be less than 2^n.
3296 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3297 const SCEV *LHS = getSCEV(U->getOperand(0));
3298 const APInt &CIVal = CI->getValue();
3299 if (GetMinTrailingZeros(LHS) >=
3300 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3301 // Build a plain add SCEV.
3302 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3303 // If the LHS of the add was an addrec and it has no-wrap flags,
3304 // transfer the no-wrap flags, since an or won't introduce a wrap.
3305 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3306 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
3307 if (OldAR->hasNoUnsignedWrap())
3308 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoUnsignedWrap(true);
3309 if (OldAR->hasNoSignedWrap())
3310 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoSignedWrap(true);
3316 case Instruction::Xor:
3317 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3318 // If the RHS of the xor is a signbit, then this is just an add.
3319 // Instcombine turns add of signbit into xor as a strength reduction step.
3320 if (CI->getValue().isSignBit())
3321 return getAddExpr(getSCEV(U->getOperand(0)),
3322 getSCEV(U->getOperand(1)));
3324 // If the RHS of xor is -1, then this is a not operation.
3325 if (CI->isAllOnesValue())
3326 return getNotSCEV(getSCEV(U->getOperand(0)));
3328 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3329 // This is a variant of the check for xor with -1, and it handles
3330 // the case where instcombine has trimmed non-demanded bits out
3331 // of an xor with -1.
3332 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3333 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3334 if (BO->getOpcode() == Instruction::And &&
3335 LCI->getValue() == CI->getValue())
3336 if (const SCEVZeroExtendExpr *Z =
3337 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
3338 const Type *UTy = U->getType();
3339 const SCEV *Z0 = Z->getOperand();
3340 const Type *Z0Ty = Z0->getType();
3341 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3343 // If C is a low-bits mask, the zero extend is serving to
3344 // mask off the high bits. Complement the operand and
3345 // re-apply the zext.
3346 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3347 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3349 // If C is a single bit, it may be in the sign-bit position
3350 // before the zero-extend. In this case, represent the xor
3351 // using an add, which is equivalent, and re-apply the zext.
3352 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
3353 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3355 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3361 case Instruction::Shl:
3362 // Turn shift left of a constant amount into a multiply.
3363 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3364 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
3366 // If the shift count is not less than the bitwidth, the result of
3367 // the shift is undefined. Don't try to analyze it, because the
3368 // resolution chosen here may differ from the resolution chosen in
3369 // other parts of the compiler.
3370 if (SA->getValue().uge(BitWidth))
3373 Constant *X = ConstantInt::get(getContext(),
3374 APInt(BitWidth, 1).shl(SA->getZExtValue()));
3375 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3379 case Instruction::LShr:
3380 // Turn logical shift right of a constant into a unsigned divide.
3381 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3382 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
3384 // If the shift count is not less than the bitwidth, the result of
3385 // the shift is undefined. Don't try to analyze it, because the
3386 // resolution chosen here may differ from the resolution chosen in
3387 // other parts of the compiler.
3388 if (SA->getValue().uge(BitWidth))
3391 Constant *X = ConstantInt::get(getContext(),
3392 APInt(BitWidth, 1).shl(SA->getZExtValue()));
3393 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3397 case Instruction::AShr:
3398 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3399 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
3400 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
3401 if (L->getOpcode() == Instruction::Shl &&
3402 L->getOperand(1) == U->getOperand(1)) {
3403 uint64_t BitWidth = getTypeSizeInBits(U->getType());
3405 // If the shift count is not less than the bitwidth, the result of
3406 // the shift is undefined. Don't try to analyze it, because the
3407 // resolution chosen here may differ from the resolution chosen in
3408 // other parts of the compiler.
3409 if (CI->getValue().uge(BitWidth))
3412 uint64_t Amt = BitWidth - CI->getZExtValue();
3413 if (Amt == BitWidth)
3414 return getSCEV(L->getOperand(0)); // shift by zero --> noop
3416 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
3417 IntegerType::get(getContext(),
3423 case Instruction::Trunc:
3424 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
3426 case Instruction::ZExt:
3427 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3429 case Instruction::SExt:
3430 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3432 case Instruction::BitCast:
3433 // BitCasts are no-op casts so we just eliminate the cast.
3434 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
3435 return getSCEV(U->getOperand(0));
3438 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3439 // lead to pointer expressions which cannot safely be expanded to GEPs,
3440 // because ScalarEvolution doesn't respect the GEP aliasing rules when
3441 // simplifying integer expressions.
3443 case Instruction::GetElementPtr:
3444 return createNodeForGEP(cast<GEPOperator>(U));
3446 case Instruction::PHI:
3447 return createNodeForPHI(cast<PHINode>(U));
3449 case Instruction::Select:
3450 // This could be a smax or umax that was lowered earlier.
3451 // Try to recover it.
3452 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3453 Value *LHS = ICI->getOperand(0);
3454 Value *RHS = ICI->getOperand(1);
3455 switch (ICI->getPredicate()) {
3456 case ICmpInst::ICMP_SLT:
3457 case ICmpInst::ICMP_SLE:
3458 std::swap(LHS, RHS);
3460 case ICmpInst::ICMP_SGT:
3461 case ICmpInst::ICMP_SGE:
3462 // a >s b ? a+x : b+x -> smax(a, b)+x
3463 // a >s b ? b+x : a+x -> smin(a, b)+x
3464 if (LHS->getType() == U->getType()) {
3465 const SCEV *LS = getSCEV(LHS);
3466 const SCEV *RS = getSCEV(RHS);
3467 const SCEV *LA = getSCEV(U->getOperand(1));
3468 const SCEV *RA = getSCEV(U->getOperand(2));
3469 const SCEV *LDiff = getMinusSCEV(LA, LS);
3470 const SCEV *RDiff = getMinusSCEV(RA, RS);
3472 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
3473 LDiff = getMinusSCEV(LA, RS);
3474 RDiff = getMinusSCEV(RA, LS);
3476 return getAddExpr(getSMinExpr(LS, RS), LDiff);
3479 case ICmpInst::ICMP_ULT:
3480 case ICmpInst::ICMP_ULE:
3481 std::swap(LHS, RHS);
3483 case ICmpInst::ICMP_UGT:
3484 case ICmpInst::ICMP_UGE:
3485 // a >u b ? a+x : b+x -> umax(a, b)+x
3486 // a >u b ? b+x : a+x -> umin(a, b)+x
3487 if (LHS->getType() == U->getType()) {
3488 const SCEV *LS = getSCEV(LHS);
3489 const SCEV *RS = getSCEV(RHS);
3490 const SCEV *LA = getSCEV(U->getOperand(1));
3491 const SCEV *RA = getSCEV(U->getOperand(2));
3492 const SCEV *LDiff = getMinusSCEV(LA, LS);
3493 const SCEV *RDiff = getMinusSCEV(RA, RS);
3495 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
3496 LDiff = getMinusSCEV(LA, RS);
3497 RDiff = getMinusSCEV(RA, LS);
3499 return getAddExpr(getUMinExpr(LS, RS), LDiff);
3502 case ICmpInst::ICMP_NE:
3503 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
3504 if (LHS->getType() == U->getType() &&
3505 isa<ConstantInt>(RHS) &&
3506 cast<ConstantInt>(RHS)->isZero()) {
3507 const SCEV *One = getConstant(LHS->getType(), 1);
3508 const SCEV *LS = getSCEV(LHS);
3509 const SCEV *LA = getSCEV(U->getOperand(1));
3510 const SCEV *RA = getSCEV(U->getOperand(2));
3511 const SCEV *LDiff = getMinusSCEV(LA, LS);
3512 const SCEV *RDiff = getMinusSCEV(RA, One);
3514 return getAddExpr(getUMaxExpr(One, LS), LDiff);
3517 case ICmpInst::ICMP_EQ:
3518 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
3519 if (LHS->getType() == U->getType() &&
3520 isa<ConstantInt>(RHS) &&
3521 cast<ConstantInt>(RHS)->isZero()) {
3522 const SCEV *One = getConstant(LHS->getType(), 1);
3523 const SCEV *LS = getSCEV(LHS);
3524 const SCEV *LA = getSCEV(U->getOperand(1));
3525 const SCEV *RA = getSCEV(U->getOperand(2));
3526 const SCEV *LDiff = getMinusSCEV(LA, One);
3527 const SCEV *RDiff = getMinusSCEV(RA, LS);
3529 return getAddExpr(getUMaxExpr(One, LS), LDiff);
3537 default: // We cannot analyze this expression.
3541 return getUnknown(V);
3546 //===----------------------------------------------------------------------===//
3547 // Iteration Count Computation Code
3550 /// getBackedgeTakenCount - If the specified loop has a predictable
3551 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3552 /// object. The backedge-taken count is the number of times the loop header
3553 /// will be branched to from within the loop. This is one less than the
3554 /// trip count of the loop, since it doesn't count the first iteration,
3555 /// when the header is branched to from outside the loop.
3557 /// Note that it is not valid to call this method on a loop without a
3558 /// loop-invariant backedge-taken count (see
3559 /// hasLoopInvariantBackedgeTakenCount).
3561 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
3562 return getBackedgeTakenInfo(L).Exact;
3565 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3566 /// return the least SCEV value that is known never to be less than the
3567 /// actual backedge taken count.
3568 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
3569 return getBackedgeTakenInfo(L).Max;
3572 /// PushLoopPHIs - Push PHI nodes in the header of the given loop
3573 /// onto the given Worklist.
3575 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3576 BasicBlock *Header = L->getHeader();
3578 // Push all Loop-header PHIs onto the Worklist stack.
3579 for (BasicBlock::iterator I = Header->begin();
3580 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3581 Worklist.push_back(PN);
3584 const ScalarEvolution::BackedgeTakenInfo &
3585 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
3586 // Initially insert a CouldNotCompute for this loop. If the insertion
3587 // succeeds, proceed to actually compute a backedge-taken count and
3588 // update the value. The temporary CouldNotCompute value tells SCEV
3589 // code elsewhere that it shouldn't attempt to request a new
3590 // backedge-taken count, which could result in infinite recursion.
3591 std::pair<std::map<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
3592 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3594 BackedgeTakenInfo BECount = ComputeBackedgeTakenCount(L);
3595 if (BECount.Exact != getCouldNotCompute()) {
3596 assert(BECount.Exact->isLoopInvariant(L) &&
3597 BECount.Max->isLoopInvariant(L) &&
3598 "Computed backedge-taken count isn't loop invariant for loop!");
3599 ++NumTripCountsComputed;
3601 // Update the value in the map.
3602 Pair.first->second = BECount;
3604 if (BECount.Max != getCouldNotCompute())
3605 // Update the value in the map.
3606 Pair.first->second = BECount;
3607 if (isa<PHINode>(L->getHeader()->begin()))
3608 // Only count loops that have phi nodes as not being computable.
3609 ++NumTripCountsNotComputed;
3612 // Now that we know more about the trip count for this loop, forget any
3613 // existing SCEV values for PHI nodes in this loop since they are only
3614 // conservative estimates made without the benefit of trip count
3615 // information. This is similar to the code in forgetLoop, except that
3616 // it handles SCEVUnknown PHI nodes specially.
3617 if (BECount.hasAnyInfo()) {
3618 SmallVector<Instruction *, 16> Worklist;
3619 PushLoopPHIs(L, Worklist);
3621 SmallPtrSet<Instruction *, 8> Visited;
3622 while (!Worklist.empty()) {
3623 Instruction *I = Worklist.pop_back_val();
3624 if (!Visited.insert(I)) continue;
3626 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3627 Scalars.find(static_cast<Value *>(I));
3628 if (It != Scalars.end()) {
3629 // SCEVUnknown for a PHI either means that it has an unrecognized
3630 // structure, or it's a PHI that's in the progress of being computed
3631 // by createNodeForPHI. In the former case, additional loop trip
3632 // count information isn't going to change anything. In the later
3633 // case, createNodeForPHI will perform the necessary updates on its
3634 // own when it gets to that point.
3635 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
3636 ValuesAtScopes.erase(It->second);
3639 if (PHINode *PN = dyn_cast<PHINode>(I))
3640 ConstantEvolutionLoopExitValue.erase(PN);
3643 PushDefUseChildren(I, Worklist);
3647 return Pair.first->second;
3650 /// forgetLoop - This method should be called by the client when it has
3651 /// changed a loop in a way that may effect ScalarEvolution's ability to
3652 /// compute a trip count, or if the loop is deleted.
3653 void ScalarEvolution::forgetLoop(const Loop *L) {
3654 // Drop any stored trip count value.
3655 BackedgeTakenCounts.erase(L);
3657 // Drop information about expressions based on loop-header PHIs.
3658 SmallVector<Instruction *, 16> Worklist;
3659 PushLoopPHIs(L, Worklist);
3661 SmallPtrSet<Instruction *, 8> Visited;
3662 while (!Worklist.empty()) {
3663 Instruction *I = Worklist.pop_back_val();
3664 if (!Visited.insert(I)) continue;
3666 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3667 Scalars.find(static_cast<Value *>(I));
3668 if (It != Scalars.end()) {
3669 ValuesAtScopes.erase(It->second);
3671 if (PHINode *PN = dyn_cast<PHINode>(I))
3672 ConstantEvolutionLoopExitValue.erase(PN);
3675 PushDefUseChildren(I, Worklist);
3679 /// forgetValue - This method should be called by the client when it has
3680 /// changed a value in a way that may effect its value, or which may
3681 /// disconnect it from a def-use chain linking it to a loop.
3682 void ScalarEvolution::forgetValue(Value *V) {
3683 Instruction *I = dyn_cast<Instruction>(V);
3686 // Drop information about expressions based on loop-header PHIs.
3687 SmallVector<Instruction *, 16> Worklist;
3688 Worklist.push_back(I);
3690 SmallPtrSet<Instruction *, 8> Visited;
3691 while (!Worklist.empty()) {
3692 I = Worklist.pop_back_val();
3693 if (!Visited.insert(I)) continue;
3695 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3696 Scalars.find(static_cast<Value *>(I));
3697 if (It != Scalars.end()) {
3698 ValuesAtScopes.erase(It->second);
3700 if (PHINode *PN = dyn_cast<PHINode>(I))
3701 ConstantEvolutionLoopExitValue.erase(PN);
3704 PushDefUseChildren(I, Worklist);
3708 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
3709 /// of the specified loop will execute.
3710 ScalarEvolution::BackedgeTakenInfo
3711 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
3712 SmallVector<BasicBlock *, 8> ExitingBlocks;
3713 L->getExitingBlocks(ExitingBlocks);
3715 // Examine all exits and pick the most conservative values.
3716 const SCEV *BECount = getCouldNotCompute();
3717 const SCEV *MaxBECount = getCouldNotCompute();
3718 bool CouldNotComputeBECount = false;
3719 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3720 BackedgeTakenInfo NewBTI =
3721 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
3723 if (NewBTI.Exact == getCouldNotCompute()) {
3724 // We couldn't compute an exact value for this exit, so
3725 // we won't be able to compute an exact value for the loop.
3726 CouldNotComputeBECount = true;
3727 BECount = getCouldNotCompute();
3728 } else if (!CouldNotComputeBECount) {
3729 if (BECount == getCouldNotCompute())
3730 BECount = NewBTI.Exact;
3732 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
3734 if (MaxBECount == getCouldNotCompute())
3735 MaxBECount = NewBTI.Max;
3736 else if (NewBTI.Max != getCouldNotCompute())
3737 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
3740 return BackedgeTakenInfo(BECount, MaxBECount);
3743 /// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3744 /// of the specified loop will execute if it exits via the specified block.
3745 ScalarEvolution::BackedgeTakenInfo
3746 ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3747 BasicBlock *ExitingBlock) {
3749 // Okay, we've chosen an exiting block. See what condition causes us to
3750 // exit at this block.
3752 // FIXME: we should be able to handle switch instructions (with a single exit)
3753 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
3754 if (ExitBr == 0) return getCouldNotCompute();
3755 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
3757 // At this point, we know we have a conditional branch that determines whether
3758 // the loop is exited. However, we don't know if the branch is executed each
3759 // time through the loop. If not, then the execution count of the branch will
3760 // not be equal to the trip count of the loop.
3762 // Currently we check for this by checking to see if the Exit branch goes to
3763 // the loop header. If so, we know it will always execute the same number of
3764 // times as the loop. We also handle the case where the exit block *is* the
3765 // loop header. This is common for un-rotated loops.
3767 // If both of those tests fail, walk up the unique predecessor chain to the
3768 // header, stopping if there is an edge that doesn't exit the loop. If the
3769 // header is reached, the execution count of the branch will be equal to the
3770 // trip count of the loop.
3772 // More extensive analysis could be done to handle more cases here.
3774 if (ExitBr->getSuccessor(0) != L->getHeader() &&
3775 ExitBr->getSuccessor(1) != L->getHeader() &&
3776 ExitBr->getParent() != L->getHeader()) {
3777 // The simple checks failed, try climbing the unique predecessor chain
3778 // up to the header.
3780 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3781 BasicBlock *Pred = BB->getUniquePredecessor();
3783 return getCouldNotCompute();
3784 TerminatorInst *PredTerm = Pred->getTerminator();
3785 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3786 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3789 // If the predecessor has a successor that isn't BB and isn't
3790 // outside the loop, assume the worst.
3791 if (L->contains(PredSucc))
3792 return getCouldNotCompute();
3794 if (Pred == L->getHeader()) {
3801 return getCouldNotCompute();
3804 // Proceed to the next level to examine the exit condition expression.
3805 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3806 ExitBr->getSuccessor(0),
3807 ExitBr->getSuccessor(1));
3810 /// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3811 /// backedge of the specified loop will execute if its exit condition
3812 /// were a conditional branch of ExitCond, TBB, and FBB.
3813 ScalarEvolution::BackedgeTakenInfo
3814 ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3818 // Check if the controlling expression for this loop is an And or Or.
3819 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3820 if (BO->getOpcode() == Instruction::And) {
3821 // Recurse on the operands of the and.
3822 BackedgeTakenInfo BTI0 =
3823 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3824 BackedgeTakenInfo BTI1 =
3825 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3826 const SCEV *BECount = getCouldNotCompute();
3827 const SCEV *MaxBECount = getCouldNotCompute();
3828 if (L->contains(TBB)) {
3829 // Both conditions must be true for the loop to continue executing.
3830 // Choose the less conservative count.
3831 if (BTI0.Exact == getCouldNotCompute() ||
3832 BTI1.Exact == getCouldNotCompute())
3833 BECount = getCouldNotCompute();
3835 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3836 if (BTI0.Max == getCouldNotCompute())
3837 MaxBECount = BTI1.Max;
3838 else if (BTI1.Max == getCouldNotCompute())
3839 MaxBECount = BTI0.Max;
3841 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3843 // Both conditions must be true at the same time for the loop to exit.
3844 // For now, be conservative.
3845 assert(L->contains(FBB) && "Loop block has no successor in loop!");
3846 if (BTI0.Max == BTI1.Max)
3847 MaxBECount = BTI0.Max;
3848 if (BTI0.Exact == BTI1.Exact)
3849 BECount = BTI0.Exact;
3852 return BackedgeTakenInfo(BECount, MaxBECount);
3854 if (BO->getOpcode() == Instruction::Or) {
3855 // Recurse on the operands of the or.
3856 BackedgeTakenInfo BTI0 =
3857 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3858 BackedgeTakenInfo BTI1 =
3859 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3860 const SCEV *BECount = getCouldNotCompute();
3861 const SCEV *MaxBECount = getCouldNotCompute();
3862 if (L->contains(FBB)) {
3863 // Both conditions must be false for the loop to continue executing.
3864 // Choose the less conservative count.
3865 if (BTI0.Exact == getCouldNotCompute() ||
3866 BTI1.Exact == getCouldNotCompute())
3867 BECount = getCouldNotCompute();
3869 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3870 if (BTI0.Max == getCouldNotCompute())
3871 MaxBECount = BTI1.Max;
3872 else if (BTI1.Max == getCouldNotCompute())
3873 MaxBECount = BTI0.Max;
3875 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3877 // Both conditions must be false at the same time for the loop to exit.
3878 // For now, be conservative.
3879 assert(L->contains(TBB) && "Loop block has no successor in loop!");
3880 if (BTI0.Max == BTI1.Max)
3881 MaxBECount = BTI0.Max;
3882 if (BTI0.Exact == BTI1.Exact)
3883 BECount = BTI0.Exact;
3886 return BackedgeTakenInfo(BECount, MaxBECount);
3890 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3891 // Proceed to the next level to examine the icmp.
3892 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3893 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
3895 // Check for a constant condition. These are normally stripped out by
3896 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
3897 // preserve the CFG and is temporarily leaving constant conditions
3899 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
3900 if (L->contains(FBB) == !CI->getZExtValue())
3901 // The backedge is always taken.
3902 return getCouldNotCompute();
3904 // The backedge is never taken.
3905 return getConstant(CI->getType(), 0);
3908 // If it's not an integer or pointer comparison then compute it the hard way.
3909 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3912 /// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3913 /// backedge of the specified loop will execute if its exit condition
3914 /// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3915 ScalarEvolution::BackedgeTakenInfo
3916 ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3921 // If the condition was exit on true, convert the condition to exit on false
3922 ICmpInst::Predicate Cond;
3923 if (!L->contains(FBB))
3924 Cond = ExitCond->getPredicate();
3926 Cond = ExitCond->getInversePredicate();
3928 // Handle common loops like: for (X = "string"; *X; ++X)
3929 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3930 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
3931 BackedgeTakenInfo ItCnt =
3932 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
3933 if (ItCnt.hasAnyInfo())
3937 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3938 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
3940 // Try to evaluate any dependencies out of the loop.
3941 LHS = getSCEVAtScope(LHS, L);
3942 RHS = getSCEVAtScope(RHS, L);
3944 // At this point, we would like to compute how many iterations of the
3945 // loop the predicate will return true for these inputs.
3946 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3947 // If there is a loop-invariant, force it into the RHS.
3948 std::swap(LHS, RHS);
3949 Cond = ICmpInst::getSwappedPredicate(Cond);
3952 // Simplify the operands before analyzing them.
3953 (void)SimplifyICmpOperands(Cond, LHS, RHS);
3955 // If we have a comparison of a chrec against a constant, try to use value
3956 // ranges to answer this query.
3957 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3958 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
3959 if (AddRec->getLoop() == L) {
3960 // Form the constant range.
3961 ConstantRange CompRange(
3962 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
3964 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
3965 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
3969 case ICmpInst::ICMP_NE: { // while (X != Y)
3970 // Convert to: while (X-Y != 0)
3971 BackedgeTakenInfo BTI = HowFarToZero(getMinusSCEV(LHS, RHS), L);
3972 if (BTI.hasAnyInfo()) return BTI;
3975 case ICmpInst::ICMP_EQ: { // while (X == Y)
3976 // Convert to: while (X-Y == 0)
3977 BackedgeTakenInfo BTI = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
3978 if (BTI.hasAnyInfo()) return BTI;
3981 case ICmpInst::ICMP_SLT: {
3982 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3983 if (BTI.hasAnyInfo()) return BTI;
3986 case ICmpInst::ICMP_SGT: {
3987 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3988 getNotSCEV(RHS), L, true);
3989 if (BTI.hasAnyInfo()) return BTI;
3992 case ICmpInst::ICMP_ULT: {
3993 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3994 if (BTI.hasAnyInfo()) return BTI;
3997 case ICmpInst::ICMP_UGT: {
3998 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3999 getNotSCEV(RHS), L, false);
4000 if (BTI.hasAnyInfo()) return BTI;
4005 dbgs() << "ComputeBackedgeTakenCount ";
4006 if (ExitCond->getOperand(0)->getType()->isUnsigned())
4007 dbgs() << "[unsigned] ";
4008 dbgs() << *LHS << " "
4009 << Instruction::getOpcodeName(Instruction::ICmp)
4010 << " " << *RHS << "\n";
4015 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
4018 static ConstantInt *
4019 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
4020 ScalarEvolution &SE) {
4021 const SCEV *InVal = SE.getConstant(C);
4022 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
4023 assert(isa<SCEVConstant>(Val) &&
4024 "Evaluation of SCEV at constant didn't fold correctly?");
4025 return cast<SCEVConstant>(Val)->getValue();
4028 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
4029 /// and a GEP expression (missing the pointer index) indexing into it, return
4030 /// the addressed element of the initializer or null if the index expression is
4033 GetAddressedElementFromGlobal(GlobalVariable *GV,
4034 const std::vector<ConstantInt*> &Indices) {
4035 Constant *Init = GV->getInitializer();
4036 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
4037 uint64_t Idx = Indices[i]->getZExtValue();
4038 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
4039 assert(Idx < CS->getNumOperands() && "Bad struct index!");
4040 Init = cast<Constant>(CS->getOperand(Idx));
4041 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
4042 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
4043 Init = cast<Constant>(CA->getOperand(Idx));
4044 } else if (isa<ConstantAggregateZero>(Init)) {
4045 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
4046 assert(Idx < STy->getNumElements() && "Bad struct index!");
4047 Init = Constant::getNullValue(STy->getElementType(Idx));
4048 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
4049 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
4050 Init = Constant::getNullValue(ATy->getElementType());
4052 llvm_unreachable("Unknown constant aggregate type!");
4056 return 0; // Unknown initializer type
4062 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
4063 /// 'icmp op load X, cst', try to see if we can compute the backedge
4064 /// execution count.
4065 ScalarEvolution::BackedgeTakenInfo
4066 ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
4070 ICmpInst::Predicate predicate) {
4071 if (LI->isVolatile()) return getCouldNotCompute();
4073 // Check to see if the loaded pointer is a getelementptr of a global.
4074 // TODO: Use SCEV instead of manually grubbing with GEPs.
4075 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
4076 if (!GEP) return getCouldNotCompute();
4078 // Make sure that it is really a constant global we are gepping, with an
4079 // initializer, and make sure the first IDX is really 0.
4080 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
4081 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
4082 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
4083 !cast<Constant>(GEP->getOperand(1))->isNullValue())
4084 return getCouldNotCompute();
4086 // Okay, we allow one non-constant index into the GEP instruction.
4088 std::vector<ConstantInt*> Indexes;
4089 unsigned VarIdxNum = 0;
4090 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
4091 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4092 Indexes.push_back(CI);
4093 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
4094 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
4095 VarIdx = GEP->getOperand(i);
4097 Indexes.push_back(0);
4100 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
4101 // Check to see if X is a loop variant variable value now.
4102 const SCEV *Idx = getSCEV(VarIdx);
4103 Idx = getSCEVAtScope(Idx, L);
4105 // We can only recognize very limited forms of loop index expressions, in
4106 // particular, only affine AddRec's like {C1,+,C2}.
4107 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
4108 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
4109 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
4110 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
4111 return getCouldNotCompute();
4113 unsigned MaxSteps = MaxBruteForceIterations;
4114 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
4115 ConstantInt *ItCst = ConstantInt::get(
4116 cast<IntegerType>(IdxExpr->getType()), IterationNum);
4117 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
4119 // Form the GEP offset.
4120 Indexes[VarIdxNum] = Val;
4122 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
4123 if (Result == 0) break; // Cannot compute!
4125 // Evaluate the condition for this iteration.
4126 Result = ConstantExpr::getICmp(predicate, Result, RHS);
4127 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
4128 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
4130 dbgs() << "\n***\n*** Computed loop count " << *ItCst
4131 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
4134 ++NumArrayLenItCounts;
4135 return getConstant(ItCst); // Found terminating iteration!
4138 return getCouldNotCompute();
4142 /// CanConstantFold - Return true if we can constant fold an instruction of the
4143 /// specified type, assuming that all operands were constants.
4144 static bool CanConstantFold(const Instruction *I) {
4145 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
4146 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
4149 if (const CallInst *CI = dyn_cast<CallInst>(I))
4150 if (const Function *F = CI->getCalledFunction())
4151 return canConstantFoldCallTo(F);
4155 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
4156 /// in the loop that V is derived from. We allow arbitrary operations along the
4157 /// way, but the operands of an operation must either be constants or a value
4158 /// derived from a constant PHI. If this expression does not fit with these
4159 /// constraints, return null.
4160 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
4161 // If this is not an instruction, or if this is an instruction outside of the
4162 // loop, it can't be derived from a loop PHI.
4163 Instruction *I = dyn_cast<Instruction>(V);
4164 if (I == 0 || !L->contains(I)) return 0;
4166 if (PHINode *PN = dyn_cast<PHINode>(I)) {
4167 if (L->getHeader() == I->getParent())
4170 // We don't currently keep track of the control flow needed to evaluate
4171 // PHIs, so we cannot handle PHIs inside of loops.
4175 // If we won't be able to constant fold this expression even if the operands
4176 // are constants, return early.
4177 if (!CanConstantFold(I)) return 0;
4179 // Otherwise, we can evaluate this instruction if all of its operands are
4180 // constant or derived from a PHI node themselves.
4182 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
4183 if (!isa<Constant>(I->getOperand(Op))) {
4184 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
4185 if (P == 0) return 0; // Not evolving from PHI
4189 return 0; // Evolving from multiple different PHIs.
4192 // This is a expression evolving from a constant PHI!
4196 /// EvaluateExpression - Given an expression that passes the
4197 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
4198 /// in the loop has the value PHIVal. If we can't fold this expression for some
4199 /// reason, return null.
4200 static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
4201 const TargetData *TD) {
4202 if (isa<PHINode>(V)) return PHIVal;
4203 if (Constant *C = dyn_cast<Constant>(V)) return C;
4204 Instruction *I = cast<Instruction>(V);
4206 std::vector<Constant*> Operands(I->getNumOperands());
4208 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4209 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
4210 if (Operands[i] == 0) return 0;
4213 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4214 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
4216 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4217 &Operands[0], Operands.size(), TD);
4220 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
4221 /// in the header of its containing loop, we know the loop executes a
4222 /// constant number of times, and the PHI node is just a recurrence
4223 /// involving constants, fold it.
4225 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
4228 std::map<PHINode*, Constant*>::iterator I =
4229 ConstantEvolutionLoopExitValue.find(PN);
4230 if (I != ConstantEvolutionLoopExitValue.end())
4233 if (BEs.ugt(MaxBruteForceIterations))
4234 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
4236 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
4238 // Since the loop is canonicalized, the PHI node must have two entries. One
4239 // entry must be a constant (coming in from outside of the loop), and the
4240 // second must be derived from the same PHI.
4241 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4242 Constant *StartCST =
4243 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4245 return RetVal = 0; // Must be a constant.
4247 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4248 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4249 !isa<Constant>(BEValue))
4250 return RetVal = 0; // Not derived from same PHI.
4252 // Execute the loop symbolically to determine the exit value.
4253 if (BEs.getActiveBits() >= 32)
4254 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
4256 unsigned NumIterations = BEs.getZExtValue(); // must be in range
4257 unsigned IterationNum = 0;
4258 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
4259 if (IterationNum == NumIterations)
4260 return RetVal = PHIVal; // Got exit value!
4262 // Compute the value of the PHI node for the next iteration.
4263 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
4264 if (NextPHI == PHIVal)
4265 return RetVal = NextPHI; // Stopped evolving!
4267 return 0; // Couldn't evaluate!
4272 /// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
4273 /// constant number of times (the condition evolves only from constants),
4274 /// try to evaluate a few iterations of the loop until we get the exit
4275 /// condition gets a value of ExitWhen (true or false). If we cannot
4276 /// evaluate the trip count of the loop, return getCouldNotCompute().
4278 ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
4281 PHINode *PN = getConstantEvolvingPHI(Cond, L);
4282 if (PN == 0) return getCouldNotCompute();
4284 // If the loop is canonicalized, the PHI will have exactly two entries.
4285 // That's the only form we support here.
4286 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
4288 // One entry must be a constant (coming in from outside of the loop), and the
4289 // second must be derived from the same PHI.
4290 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4291 Constant *StartCST =
4292 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4293 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
4295 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4296 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4297 !isa<Constant>(BEValue))
4298 return getCouldNotCompute(); // Not derived from same PHI.
4300 // Okay, we find a PHI node that defines the trip count of this loop. Execute
4301 // the loop symbolically to determine when the condition gets a value of
4303 unsigned IterationNum = 0;
4304 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
4305 for (Constant *PHIVal = StartCST;
4306 IterationNum != MaxIterations; ++IterationNum) {
4307 ConstantInt *CondVal =
4308 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
4310 // Couldn't symbolically evaluate.
4311 if (!CondVal) return getCouldNotCompute();
4313 if (CondVal->getValue() == uint64_t(ExitWhen)) {
4314 ++NumBruteForceTripCountsComputed;
4315 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
4318 // Compute the value of the PHI node for the next iteration.
4319 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
4320 if (NextPHI == 0 || NextPHI == PHIVal)
4321 return getCouldNotCompute();// Couldn't evaluate or not making progress...
4325 // Too many iterations were needed to evaluate.
4326 return getCouldNotCompute();
4329 /// getSCEVAtScope - Return a SCEV expression for the specified value
4330 /// at the specified scope in the program. The L value specifies a loop
4331 /// nest to evaluate the expression at, where null is the top-level or a
4332 /// specified loop is immediately inside of the loop.
4334 /// This method can be used to compute the exit value for a variable defined
4335 /// in a loop by querying what the value will hold in the parent loop.
4337 /// In the case that a relevant loop exit value cannot be computed, the
4338 /// original value V is returned.
4339 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
4340 // Check to see if we've folded this expression at this loop before.
4341 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4342 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4343 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4345 return Pair.first->second ? Pair.first->second : V;
4347 // Otherwise compute it.
4348 const SCEV *C = computeSCEVAtScope(V, L);
4349 ValuesAtScopes[V][L] = C;
4353 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
4354 if (isa<SCEVConstant>(V)) return V;
4356 // If this instruction is evolved from a constant-evolving PHI, compute the
4357 // exit value from the loop without using SCEVs.
4358 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
4359 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
4360 const Loop *LI = (*this->LI)[I->getParent()];
4361 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
4362 if (PHINode *PN = dyn_cast<PHINode>(I))
4363 if (PN->getParent() == LI->getHeader()) {
4364 // Okay, there is no closed form solution for the PHI node. Check
4365 // to see if the loop that contains it has a known backedge-taken
4366 // count. If so, we may be able to force computation of the exit
4368 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
4369 if (const SCEVConstant *BTCC =
4370 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
4371 // Okay, we know how many times the containing loop executes. If
4372 // this is a constant evolving PHI node, get the final value at
4373 // the specified iteration number.
4374 Constant *RV = getConstantEvolutionLoopExitValue(PN,
4375 BTCC->getValue()->getValue(),
4377 if (RV) return getSCEV(RV);
4381 // Okay, this is an expression that we cannot symbolically evaluate
4382 // into a SCEV. Check to see if it's possible to symbolically evaluate
4383 // the arguments into constants, and if so, try to constant propagate the
4384 // result. This is particularly useful for computing loop exit values.
4385 if (CanConstantFold(I)) {
4386 SmallVector<Constant *, 4> Operands;
4387 bool MadeImprovement = false;
4388 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4389 Value *Op = I->getOperand(i);
4390 if (Constant *C = dyn_cast<Constant>(Op)) {
4391 Operands.push_back(C);
4395 // If any of the operands is non-constant and if they are
4396 // non-integer and non-pointer, don't even try to analyze them
4397 // with scev techniques.
4398 if (!isSCEVable(Op->getType()))
4401 const SCEV *OrigV = getSCEV(Op);
4402 const SCEV *OpV = getSCEVAtScope(OrigV, L);
4403 MadeImprovement |= OrigV != OpV;
4406 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
4408 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV))
4409 C = dyn_cast<Constant>(SU->getValue());
4411 if (C->getType() != Op->getType())
4412 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4416 Operands.push_back(C);
4419 // Check to see if getSCEVAtScope actually made an improvement.
4420 if (MadeImprovement) {
4422 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4423 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
4424 Operands[0], Operands[1], TD);
4426 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4427 &Operands[0], Operands.size(), TD);
4434 // This is some other type of SCEVUnknown, just return it.
4438 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
4439 // Avoid performing the look-up in the common case where the specified
4440 // expression has no loop-variant portions.
4441 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
4442 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
4443 if (OpAtScope != Comm->getOperand(i)) {
4444 // Okay, at least one of these operands is loop variant but might be
4445 // foldable. Build a new instance of the folded commutative expression.
4446 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4447 Comm->op_begin()+i);
4448 NewOps.push_back(OpAtScope);
4450 for (++i; i != e; ++i) {
4451 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
4452 NewOps.push_back(OpAtScope);
4454 if (isa<SCEVAddExpr>(Comm))
4455 return getAddExpr(NewOps);
4456 if (isa<SCEVMulExpr>(Comm))
4457 return getMulExpr(NewOps);
4458 if (isa<SCEVSMaxExpr>(Comm))
4459 return getSMaxExpr(NewOps);
4460 if (isa<SCEVUMaxExpr>(Comm))
4461 return getUMaxExpr(NewOps);
4462 llvm_unreachable("Unknown commutative SCEV type!");
4465 // If we got here, all operands are loop invariant.
4469 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
4470 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4471 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
4472 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4473 return Div; // must be loop invariant
4474 return getUDivExpr(LHS, RHS);
4477 // If this is a loop recurrence for a loop that does not contain L, then we
4478 // are dealing with the final value computed by the loop.
4479 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4480 // First, attempt to evaluate each operand.
4481 // Avoid performing the look-up in the common case where the specified
4482 // expression has no loop-variant portions.
4483 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4484 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
4485 if (OpAtScope == AddRec->getOperand(i))
4488 // Okay, at least one of these operands is loop variant but might be
4489 // foldable. Build a new instance of the folded commutative expression.
4490 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
4491 AddRec->op_begin()+i);
4492 NewOps.push_back(OpAtScope);
4493 for (++i; i != e; ++i)
4494 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
4496 AddRec = cast<SCEVAddRecExpr>(getAddRecExpr(NewOps, AddRec->getLoop()));
4500 // If the scope is outside the addrec's loop, evaluate it by using the
4501 // loop exit value of the addrec.
4502 if (!AddRec->getLoop()->contains(L)) {
4503 // To evaluate this recurrence, we need to know how many times the AddRec
4504 // loop iterates. Compute this now.
4505 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
4506 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
4508 // Then, evaluate the AddRec.
4509 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
4515 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
4516 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4517 if (Op == Cast->getOperand())
4518 return Cast; // must be loop invariant
4519 return getZeroExtendExpr(Op, Cast->getType());
4522 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
4523 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4524 if (Op == Cast->getOperand())
4525 return Cast; // must be loop invariant
4526 return getSignExtendExpr(Op, Cast->getType());
4529 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
4530 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4531 if (Op == Cast->getOperand())
4532 return Cast; // must be loop invariant
4533 return getTruncateExpr(Op, Cast->getType());
4536 llvm_unreachable("Unknown SCEV type!");
4540 /// getSCEVAtScope - This is a convenience function which does
4541 /// getSCEVAtScope(getSCEV(V), L).
4542 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
4543 return getSCEVAtScope(getSCEV(V), L);
4546 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4547 /// following equation:
4549 /// A * X = B (mod N)
4551 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4552 /// A and B isn't important.
4554 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
4555 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
4556 ScalarEvolution &SE) {
4557 uint32_t BW = A.getBitWidth();
4558 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4559 assert(A != 0 && "A must be non-zero.");
4563 // The gcd of A and N may have only one prime factor: 2. The number of
4564 // trailing zeros in A is its multiplicity
4565 uint32_t Mult2 = A.countTrailingZeros();
4568 // 2. Check if B is divisible by D.
4570 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4571 // is not less than multiplicity of this prime factor for D.
4572 if (B.countTrailingZeros() < Mult2)
4573 return SE.getCouldNotCompute();
4575 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4578 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4579 // bit width during computations.
4580 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4581 APInt Mod(BW + 1, 0);
4582 Mod.set(BW - Mult2); // Mod = N / D
4583 APInt I = AD.multiplicativeInverse(Mod);
4585 // 4. Compute the minimum unsigned root of the equation:
4586 // I * (B / D) mod (N / D)
4587 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4589 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4591 return SE.getConstant(Result.trunc(BW));
4594 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4595 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4596 /// might be the same) or two SCEVCouldNotCompute objects.
4598 static std::pair<const SCEV *,const SCEV *>
4599 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
4600 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
4601 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4602 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4603 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
4605 // We currently can only solve this if the coefficients are constants.
4606 if (!LC || !MC || !NC) {
4607 const SCEV *CNC = SE.getCouldNotCompute();
4608 return std::make_pair(CNC, CNC);
4611 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
4612 const APInt &L = LC->getValue()->getValue();
4613 const APInt &M = MC->getValue()->getValue();
4614 const APInt &N = NC->getValue()->getValue();
4615 APInt Two(BitWidth, 2);
4616 APInt Four(BitWidth, 4);
4619 using namespace APIntOps;
4621 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4622 // The B coefficient is M-N/2
4626 // The A coefficient is N/2
4627 APInt A(N.sdiv(Two));
4629 // Compute the B^2-4ac term.
4632 SqrtTerm -= Four * (A * C);
4634 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4635 // integer value or else APInt::sqrt() will assert.
4636 APInt SqrtVal(SqrtTerm.sqrt());
4638 // Compute the two solutions for the quadratic formula.
4639 // The divisions must be performed as signed divisions.
4641 APInt TwoA( A << 1 );
4642 if (TwoA.isMinValue()) {
4643 const SCEV *CNC = SE.getCouldNotCompute();
4644 return std::make_pair(CNC, CNC);
4647 LLVMContext &Context = SE.getContext();
4649 ConstantInt *Solution1 =
4650 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
4651 ConstantInt *Solution2 =
4652 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
4654 return std::make_pair(SE.getConstant(Solution1),
4655 SE.getConstant(Solution2));
4656 } // end APIntOps namespace
4659 /// HowFarToZero - Return the number of times a backedge comparing the specified
4660 /// value to zero will execute. If not computable, return CouldNotCompute.
4661 ScalarEvolution::BackedgeTakenInfo
4662 ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
4663 // If the value is a constant
4664 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
4665 // If the value is already zero, the branch will execute zero times.
4666 if (C->getValue()->isZero()) return C;
4667 return getCouldNotCompute(); // Otherwise it will loop infinitely.
4670 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
4671 if (!AddRec || AddRec->getLoop() != L)
4672 return getCouldNotCompute();
4674 if (AddRec->isAffine()) {
4675 // If this is an affine expression, the execution count of this branch is
4676 // the minimum unsigned root of the following equation:
4678 // Start + Step*N = 0 (mod 2^BW)
4682 // Step*N = -Start (mod 2^BW)
4684 // where BW is the common bit width of Start and Step.
4686 // Get the initial value for the loop.
4687 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4688 L->getParentLoop());
4689 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4690 L->getParentLoop());
4692 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
4693 // For now we handle only constant steps.
4695 // First, handle unitary steps.
4696 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
4697 return getNegativeSCEV(Start); // N = -Start (as unsigned)
4698 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4699 return Start; // N = Start (as unsigned)
4701 // Then, try to solve the above equation provided that Start is constant.
4702 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
4703 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
4704 -StartC->getValue()->getValue(),
4707 } else if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
4708 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4709 // the quadratic equation to solve it.
4710 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
4712 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4713 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
4716 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
4717 << " sol#2: " << *R2 << "\n";
4719 // Pick the smallest positive root value.
4720 if (ConstantInt *CB =
4721 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
4722 R1->getValue(), R2->getValue()))) {
4723 if (CB->getZExtValue() == false)
4724 std::swap(R1, R2); // R1 is the minimum root now.
4726 // We can only use this value if the chrec ends up with an exact zero
4727 // value at this index. When solving for "X*X != 5", for example, we
4728 // should not accept a root of 2.
4729 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
4731 return R1; // We found a quadratic root!
4736 return getCouldNotCompute();
4739 /// HowFarToNonZero - Return the number of times a backedge checking the
4740 /// specified value for nonzero will execute. If not computable, return
4742 ScalarEvolution::BackedgeTakenInfo
4743 ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
4744 // Loops that look like: while (X == 0) are very strange indeed. We don't
4745 // handle them yet except for the trivial case. This could be expanded in the
4746 // future as needed.
4748 // If the value is a constant, check to see if it is known to be non-zero
4749 // already. If so, the backedge will execute zero times.
4750 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
4751 if (!C->getValue()->isNullValue())
4752 return getConstant(C->getType(), 0);
4753 return getCouldNotCompute(); // Otherwise it will loop infinitely.
4756 // We could implement others, but I really doubt anyone writes loops like
4757 // this, and if they did, they would already be constant folded.
4758 return getCouldNotCompute();
4761 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4762 /// (which may not be an immediate predecessor) which has exactly one
4763 /// successor from which BB is reachable, or null if no such block is
4766 std::pair<BasicBlock *, BasicBlock *>
4767 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
4768 // If the block has a unique predecessor, then there is no path from the
4769 // predecessor to the block that does not go through the direct edge
4770 // from the predecessor to the block.
4771 if (BasicBlock *Pred = BB->getSinglePredecessor())
4772 return std::make_pair(Pred, BB);
4774 // A loop's header is defined to be a block that dominates the loop.
4775 // If the header has a unique predecessor outside the loop, it must be
4776 // a block that has exactly one successor that can reach the loop.
4777 if (Loop *L = LI->getLoopFor(BB))
4778 return std::make_pair(L->getLoopPredecessor(), L->getHeader());
4780 return std::pair<BasicBlock *, BasicBlock *>();
4783 /// HasSameValue - SCEV structural equivalence is usually sufficient for
4784 /// testing whether two expressions are equal, however for the purposes of
4785 /// looking for a condition guarding a loop, it can be useful to be a little
4786 /// more general, since a front-end may have replicated the controlling
4789 static bool HasSameValue(const SCEV *A, const SCEV *B) {
4790 // Quick check to see if they are the same SCEV.
4791 if (A == B) return true;
4793 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4794 // two different instructions with the same value. Check for this case.
4795 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4796 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4797 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4798 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
4799 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
4802 // Otherwise assume they may have a different value.
4806 /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
4807 /// predicate Pred. Return true iff any changes were made.
4809 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
4810 const SCEV *&LHS, const SCEV *&RHS) {
4811 bool Changed = false;
4813 // Canonicalize a constant to the right side.
4814 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
4815 // Check for both operands constant.
4816 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
4817 if (ConstantExpr::getICmp(Pred,
4819 RHSC->getValue())->isNullValue())
4820 goto trivially_false;
4822 goto trivially_true;
4824 // Otherwise swap the operands to put the constant on the right.
4825 std::swap(LHS, RHS);
4826 Pred = ICmpInst::getSwappedPredicate(Pred);
4830 // If we're comparing an addrec with a value which is loop-invariant in the
4831 // addrec's loop, put the addrec on the left. Also make a dominance check,
4832 // as both operands could be addrecs loop-invariant in each other's loop.
4833 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
4834 const Loop *L = AR->getLoop();
4835 if (LHS->isLoopInvariant(L) && LHS->properlyDominates(L->getHeader(), DT)) {
4836 std::swap(LHS, RHS);
4837 Pred = ICmpInst::getSwappedPredicate(Pred);
4842 // If there's a constant operand, canonicalize comparisons with boundary
4843 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
4844 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4845 const APInt &RA = RC->getValue()->getValue();
4847 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4848 case ICmpInst::ICMP_EQ:
4849 case ICmpInst::ICMP_NE:
4851 case ICmpInst::ICMP_UGE:
4852 if ((RA - 1).isMinValue()) {
4853 Pred = ICmpInst::ICMP_NE;
4854 RHS = getConstant(RA - 1);
4858 if (RA.isMaxValue()) {
4859 Pred = ICmpInst::ICMP_EQ;
4863 if (RA.isMinValue()) goto trivially_true;
4865 Pred = ICmpInst::ICMP_UGT;
4866 RHS = getConstant(RA - 1);
4869 case ICmpInst::ICMP_ULE:
4870 if ((RA + 1).isMaxValue()) {
4871 Pred = ICmpInst::ICMP_NE;
4872 RHS = getConstant(RA + 1);
4876 if (RA.isMinValue()) {
4877 Pred = ICmpInst::ICMP_EQ;
4881 if (RA.isMaxValue()) goto trivially_true;
4883 Pred = ICmpInst::ICMP_ULT;
4884 RHS = getConstant(RA + 1);
4887 case ICmpInst::ICMP_SGE:
4888 if ((RA - 1).isMinSignedValue()) {
4889 Pred = ICmpInst::ICMP_NE;
4890 RHS = getConstant(RA - 1);
4894 if (RA.isMaxSignedValue()) {
4895 Pred = ICmpInst::ICMP_EQ;
4899 if (RA.isMinSignedValue()) goto trivially_true;
4901 Pred = ICmpInst::ICMP_SGT;
4902 RHS = getConstant(RA - 1);
4905 case ICmpInst::ICMP_SLE:
4906 if ((RA + 1).isMaxSignedValue()) {
4907 Pred = ICmpInst::ICMP_NE;
4908 RHS = getConstant(RA + 1);
4912 if (RA.isMinSignedValue()) {
4913 Pred = ICmpInst::ICMP_EQ;
4917 if (RA.isMaxSignedValue()) goto trivially_true;
4919 Pred = ICmpInst::ICMP_SLT;
4920 RHS = getConstant(RA + 1);
4923 case ICmpInst::ICMP_UGT:
4924 if (RA.isMinValue()) {
4925 Pred = ICmpInst::ICMP_NE;
4929 if ((RA + 1).isMaxValue()) {
4930 Pred = ICmpInst::ICMP_EQ;
4931 RHS = getConstant(RA + 1);
4935 if (RA.isMaxValue()) goto trivially_false;
4937 case ICmpInst::ICMP_ULT:
4938 if (RA.isMaxValue()) {
4939 Pred = ICmpInst::ICMP_NE;
4943 if ((RA - 1).isMinValue()) {
4944 Pred = ICmpInst::ICMP_EQ;
4945 RHS = getConstant(RA - 1);
4949 if (RA.isMinValue()) goto trivially_false;
4951 case ICmpInst::ICMP_SGT:
4952 if (RA.isMinSignedValue()) {
4953 Pred = ICmpInst::ICMP_NE;
4957 if ((RA + 1).isMaxSignedValue()) {
4958 Pred = ICmpInst::ICMP_EQ;
4959 RHS = getConstant(RA + 1);
4963 if (RA.isMaxSignedValue()) goto trivially_false;
4965 case ICmpInst::ICMP_SLT:
4966 if (RA.isMaxSignedValue()) {
4967 Pred = ICmpInst::ICMP_NE;
4971 if ((RA - 1).isMinSignedValue()) {
4972 Pred = ICmpInst::ICMP_EQ;
4973 RHS = getConstant(RA - 1);
4977 if (RA.isMinSignedValue()) goto trivially_false;
4982 // Check for obvious equality.
4983 if (HasSameValue(LHS, RHS)) {
4984 if (ICmpInst::isTrueWhenEqual(Pred))
4985 goto trivially_true;
4986 if (ICmpInst::isFalseWhenEqual(Pred))
4987 goto trivially_false;
4990 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
4991 // adding or subtracting 1 from one of the operands.
4993 case ICmpInst::ICMP_SLE:
4994 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
4995 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
4996 /*HasNUW=*/false, /*HasNSW=*/true);
4997 Pred = ICmpInst::ICMP_SLT;
4999 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
5000 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
5001 /*HasNUW=*/false, /*HasNSW=*/true);
5002 Pred = ICmpInst::ICMP_SLT;
5006 case ICmpInst::ICMP_SGE:
5007 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
5008 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
5009 /*HasNUW=*/false, /*HasNSW=*/true);
5010 Pred = ICmpInst::ICMP_SGT;
5012 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
5013 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
5014 /*HasNUW=*/false, /*HasNSW=*/true);
5015 Pred = ICmpInst::ICMP_SGT;
5019 case ICmpInst::ICMP_ULE:
5020 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
5021 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
5022 /*HasNUW=*/true, /*HasNSW=*/false);
5023 Pred = ICmpInst::ICMP_ULT;
5025 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
5026 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
5027 /*HasNUW=*/true, /*HasNSW=*/false);
5028 Pred = ICmpInst::ICMP_ULT;
5032 case ICmpInst::ICMP_UGE:
5033 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
5034 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
5035 /*HasNUW=*/true, /*HasNSW=*/false);
5036 Pred = ICmpInst::ICMP_UGT;
5038 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
5039 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
5040 /*HasNUW=*/true, /*HasNSW=*/false);
5041 Pred = ICmpInst::ICMP_UGT;
5049 // TODO: More simplifications are possible here.
5055 LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
5056 Pred = ICmpInst::ICMP_EQ;
5061 LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
5062 Pred = ICmpInst::ICMP_NE;
5066 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
5067 return getSignedRange(S).getSignedMax().isNegative();
5070 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
5071 return getSignedRange(S).getSignedMin().isStrictlyPositive();
5074 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
5075 return !getSignedRange(S).getSignedMin().isNegative();
5078 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
5079 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
5082 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
5083 return isKnownNegative(S) || isKnownPositive(S);
5086 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
5087 const SCEV *LHS, const SCEV *RHS) {
5088 // Canonicalize the inputs first.
5089 (void)SimplifyICmpOperands(Pred, LHS, RHS);
5091 // If LHS or RHS is an addrec, check to see if the condition is true in
5092 // every iteration of the loop.
5093 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
5094 if (isLoopEntryGuardedByCond(
5095 AR->getLoop(), Pred, AR->getStart(), RHS) &&
5096 isLoopBackedgeGuardedByCond(
5097 AR->getLoop(), Pred, AR->getPostIncExpr(*this), RHS))
5099 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS))
5100 if (isLoopEntryGuardedByCond(
5101 AR->getLoop(), Pred, LHS, AR->getStart()) &&
5102 isLoopBackedgeGuardedByCond(
5103 AR->getLoop(), Pred, LHS, AR->getPostIncExpr(*this)))
5106 // Otherwise see what can be done with known constant ranges.
5107 return isKnownPredicateWithRanges(Pred, LHS, RHS);
5111 ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
5112 const SCEV *LHS, const SCEV *RHS) {
5113 if (HasSameValue(LHS, RHS))
5114 return ICmpInst::isTrueWhenEqual(Pred);
5116 // This code is split out from isKnownPredicate because it is called from
5117 // within isLoopEntryGuardedByCond.
5120 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5122 case ICmpInst::ICMP_SGT:
5123 Pred = ICmpInst::ICMP_SLT;
5124 std::swap(LHS, RHS);
5125 case ICmpInst::ICMP_SLT: {
5126 ConstantRange LHSRange = getSignedRange(LHS);
5127 ConstantRange RHSRange = getSignedRange(RHS);
5128 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
5130 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
5134 case ICmpInst::ICMP_SGE:
5135 Pred = ICmpInst::ICMP_SLE;
5136 std::swap(LHS, RHS);
5137 case ICmpInst::ICMP_SLE: {
5138 ConstantRange LHSRange = getSignedRange(LHS);
5139 ConstantRange RHSRange = getSignedRange(RHS);
5140 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
5142 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
5146 case ICmpInst::ICMP_UGT:
5147 Pred = ICmpInst::ICMP_ULT;
5148 std::swap(LHS, RHS);
5149 case ICmpInst::ICMP_ULT: {
5150 ConstantRange LHSRange = getUnsignedRange(LHS);
5151 ConstantRange RHSRange = getUnsignedRange(RHS);
5152 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
5154 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
5158 case ICmpInst::ICMP_UGE:
5159 Pred = ICmpInst::ICMP_ULE;
5160 std::swap(LHS, RHS);
5161 case ICmpInst::ICMP_ULE: {
5162 ConstantRange LHSRange = getUnsignedRange(LHS);
5163 ConstantRange RHSRange = getUnsignedRange(RHS);
5164 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
5166 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
5170 case ICmpInst::ICMP_NE: {
5171 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
5173 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
5176 const SCEV *Diff = getMinusSCEV(LHS, RHS);
5177 if (isKnownNonZero(Diff))
5181 case ICmpInst::ICMP_EQ:
5182 // The check at the top of the function catches the case where
5183 // the values are known to be equal.
5189 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
5190 /// protected by a conditional between LHS and RHS. This is used to
5191 /// to eliminate casts.
5193 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
5194 ICmpInst::Predicate Pred,
5195 const SCEV *LHS, const SCEV *RHS) {
5196 // Interpret a null as meaning no loop, where there is obviously no guard
5197 // (interprocedural conditions notwithstanding).
5198 if (!L) return true;
5200 BasicBlock *Latch = L->getLoopLatch();
5204 BranchInst *LoopContinuePredicate =
5205 dyn_cast<BranchInst>(Latch->getTerminator());
5206 if (!LoopContinuePredicate ||
5207 LoopContinuePredicate->isUnconditional())
5210 return isImpliedCond(Pred, LHS, RHS,
5211 LoopContinuePredicate->getCondition(),
5212 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
5215 /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
5216 /// by a conditional between LHS and RHS. This is used to help avoid max
5217 /// expressions in loop trip counts, and to eliminate casts.
5219 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
5220 ICmpInst::Predicate Pred,
5221 const SCEV *LHS, const SCEV *RHS) {
5222 // Interpret a null as meaning no loop, where there is obviously no guard
5223 // (interprocedural conditions notwithstanding).
5224 if (!L) return false;
5226 // Starting at the loop predecessor, climb up the predecessor chain, as long
5227 // as there are predecessors that can be found that have unique successors
5228 // leading to the original header.
5229 for (std::pair<BasicBlock *, BasicBlock *>
5230 Pair(L->getLoopPredecessor(), L->getHeader());
5232 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
5234 BranchInst *LoopEntryPredicate =
5235 dyn_cast<BranchInst>(Pair.first->getTerminator());
5236 if (!LoopEntryPredicate ||
5237 LoopEntryPredicate->isUnconditional())
5240 if (isImpliedCond(Pred, LHS, RHS,
5241 LoopEntryPredicate->getCondition(),
5242 LoopEntryPredicate->getSuccessor(0) != Pair.second))
5249 /// isImpliedCond - Test whether the condition described by Pred, LHS,
5250 /// and RHS is true whenever the given Cond value evaluates to true.
5251 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
5252 const SCEV *LHS, const SCEV *RHS,
5253 Value *FoundCondValue,
5255 // Recursively handle And and Or conditions.
5256 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
5257 if (BO->getOpcode() == Instruction::And) {
5259 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5260 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
5261 } else if (BO->getOpcode() == Instruction::Or) {
5263 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5264 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
5268 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
5269 if (!ICI) return false;
5271 // Bail if the ICmp's operands' types are wider than the needed type
5272 // before attempting to call getSCEV on them. This avoids infinite
5273 // recursion, since the analysis of widening casts can require loop
5274 // exit condition information for overflow checking, which would
5276 if (getTypeSizeInBits(LHS->getType()) <
5277 getTypeSizeInBits(ICI->getOperand(0)->getType()))
5280 // Now that we found a conditional branch that dominates the loop, check to
5281 // see if it is the comparison we are looking for.
5282 ICmpInst::Predicate FoundPred;
5284 FoundPred = ICI->getInversePredicate();
5286 FoundPred = ICI->getPredicate();
5288 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
5289 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
5291 // Balance the types. The case where FoundLHS' type is wider than
5292 // LHS' type is checked for above.
5293 if (getTypeSizeInBits(LHS->getType()) >
5294 getTypeSizeInBits(FoundLHS->getType())) {
5295 if (CmpInst::isSigned(Pred)) {
5296 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
5297 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
5299 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
5300 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
5304 // Canonicalize the query to match the way instcombine will have
5305 // canonicalized the comparison.
5306 if (SimplifyICmpOperands(Pred, LHS, RHS))
5308 return CmpInst::isTrueWhenEqual(Pred);
5309 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
5310 if (FoundLHS == FoundRHS)
5311 return CmpInst::isFalseWhenEqual(Pred);
5313 // Check to see if we can make the LHS or RHS match.
5314 if (LHS == FoundRHS || RHS == FoundLHS) {
5315 if (isa<SCEVConstant>(RHS)) {
5316 std::swap(FoundLHS, FoundRHS);
5317 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
5319 std::swap(LHS, RHS);
5320 Pred = ICmpInst::getSwappedPredicate(Pred);
5324 // Check whether the found predicate is the same as the desired predicate.
5325 if (FoundPred == Pred)
5326 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
5328 // Check whether swapping the found predicate makes it the same as the
5329 // desired predicate.
5330 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
5331 if (isa<SCEVConstant>(RHS))
5332 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
5334 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
5335 RHS, LHS, FoundLHS, FoundRHS);
5338 // Check whether the actual condition is beyond sufficient.
5339 if (FoundPred == ICmpInst::ICMP_EQ)
5340 if (ICmpInst::isTrueWhenEqual(Pred))
5341 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
5343 if (Pred == ICmpInst::ICMP_NE)
5344 if (!ICmpInst::isTrueWhenEqual(FoundPred))
5345 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
5348 // Otherwise assume the worst.
5352 /// isImpliedCondOperands - Test whether the condition described by Pred,
5353 /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
5354 /// and FoundRHS is true.
5355 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
5356 const SCEV *LHS, const SCEV *RHS,
5357 const SCEV *FoundLHS,
5358 const SCEV *FoundRHS) {
5359 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
5360 FoundLHS, FoundRHS) ||
5361 // ~x < ~y --> x > y
5362 isImpliedCondOperandsHelper(Pred, LHS, RHS,
5363 getNotSCEV(FoundRHS),
5364 getNotSCEV(FoundLHS));
5367 /// isImpliedCondOperandsHelper - Test whether the condition described by
5368 /// Pred, LHS, and RHS is true whenever the condition described by Pred,
5369 /// FoundLHS, and FoundRHS is true.
5371 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
5372 const SCEV *LHS, const SCEV *RHS,
5373 const SCEV *FoundLHS,
5374 const SCEV *FoundRHS) {
5376 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5377 case ICmpInst::ICMP_EQ:
5378 case ICmpInst::ICMP_NE:
5379 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
5382 case ICmpInst::ICMP_SLT:
5383 case ICmpInst::ICMP_SLE:
5384 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
5385 isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS))
5388 case ICmpInst::ICMP_SGT:
5389 case ICmpInst::ICMP_SGE:
5390 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
5391 isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS))
5394 case ICmpInst::ICMP_ULT:
5395 case ICmpInst::ICMP_ULE:
5396 if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
5397 isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS))
5400 case ICmpInst::ICMP_UGT:
5401 case ICmpInst::ICMP_UGE:
5402 if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
5403 isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS))
5411 /// getBECount - Subtract the end and start values and divide by the step,
5412 /// rounding up, to get the number of times the backedge is executed. Return
5413 /// CouldNotCompute if an intermediate computation overflows.
5414 const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
5418 assert(!isKnownNegative(Step) &&
5419 "This code doesn't handle negative strides yet!");
5421 const Type *Ty = Start->getType();
5422 const SCEV *NegOne = getConstant(Ty, (uint64_t)-1);
5423 const SCEV *Diff = getMinusSCEV(End, Start);
5424 const SCEV *RoundUp = getAddExpr(Step, NegOne);
5426 // Add an adjustment to the difference between End and Start so that
5427 // the division will effectively round up.
5428 const SCEV *Add = getAddExpr(Diff, RoundUp);
5431 // Check Add for unsigned overflow.
5432 // TODO: More sophisticated things could be done here.
5433 const Type *WideTy = IntegerType::get(getContext(),
5434 getTypeSizeInBits(Ty) + 1);
5435 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
5436 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
5437 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
5438 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
5439 return getCouldNotCompute();
5442 return getUDivExpr(Add, Step);
5445 /// HowManyLessThans - Return the number of times a backedge containing the
5446 /// specified less-than comparison will execute. If not computable, return
5447 /// CouldNotCompute.
5448 ScalarEvolution::BackedgeTakenInfo
5449 ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
5450 const Loop *L, bool isSigned) {
5451 // Only handle: "ADDREC < LoopInvariant".
5452 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
5454 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
5455 if (!AddRec || AddRec->getLoop() != L)
5456 return getCouldNotCompute();
5458 // Check to see if we have a flag which makes analysis easy.
5459 bool NoWrap = isSigned ? AddRec->hasNoSignedWrap() :
5460 AddRec->hasNoUnsignedWrap();
5462 if (AddRec->isAffine()) {
5463 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
5464 const SCEV *Step = AddRec->getStepRecurrence(*this);
5467 return getCouldNotCompute();
5468 if (Step->isOne()) {
5469 // With unit stride, the iteration never steps past the limit value.
5470 } else if (isKnownPositive(Step)) {
5471 // Test whether a positive iteration can step past the limit
5472 // value and past the maximum value for its type in a single step.
5473 // Note that it's not sufficient to check NoWrap here, because even
5474 // though the value after a wrap is undefined, it's not undefined
5475 // behavior, so if wrap does occur, the loop could either terminate or
5476 // loop infinitely, but in either case, the loop is guaranteed to
5477 // iterate at least until the iteration where the wrapping occurs.
5478 const SCEV *One = getConstant(Step->getType(), 1);
5480 APInt Max = APInt::getSignedMaxValue(BitWidth);
5481 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
5482 .slt(getSignedRange(RHS).getSignedMax()))
5483 return getCouldNotCompute();
5485 APInt Max = APInt::getMaxValue(BitWidth);
5486 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
5487 .ult(getUnsignedRange(RHS).getUnsignedMax()))
5488 return getCouldNotCompute();
5491 // TODO: Handle negative strides here and below.
5492 return getCouldNotCompute();
5494 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
5495 // m. So, we count the number of iterations in which {n,+,s} < m is true.
5496 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
5497 // treat m-n as signed nor unsigned due to overflow possibility.
5499 // First, we get the value of the LHS in the first iteration: n
5500 const SCEV *Start = AddRec->getOperand(0);
5502 // Determine the minimum constant start value.
5503 const SCEV *MinStart = getConstant(isSigned ?
5504 getSignedRange(Start).getSignedMin() :
5505 getUnsignedRange(Start).getUnsignedMin());
5507 // If we know that the condition is true in order to enter the loop,
5508 // then we know that it will run exactly (m-n)/s times. Otherwise, we
5509 // only know that it will execute (max(m,n)-n)/s times. In both cases,
5510 // the division must round up.
5511 const SCEV *End = RHS;
5512 if (!isLoopEntryGuardedByCond(L,
5513 isSigned ? ICmpInst::ICMP_SLT :
5515 getMinusSCEV(Start, Step), RHS))
5516 End = isSigned ? getSMaxExpr(RHS, Start)
5517 : getUMaxExpr(RHS, Start);
5519 // Determine the maximum constant end value.
5520 const SCEV *MaxEnd = getConstant(isSigned ?
5521 getSignedRange(End).getSignedMax() :
5522 getUnsignedRange(End).getUnsignedMax());
5524 // If MaxEnd is within a step of the maximum integer value in its type,
5525 // adjust it down to the minimum value which would produce the same effect.
5526 // This allows the subsequent ceiling division of (N+(step-1))/step to
5527 // compute the correct value.
5528 const SCEV *StepMinusOne = getMinusSCEV(Step,
5529 getConstant(Step->getType(), 1));
5532 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
5535 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
5538 // Finally, we subtract these two values and divide, rounding up, to get
5539 // the number of times the backedge is executed.
5540 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
5542 // The maximum backedge count is similar, except using the minimum start
5543 // value and the maximum end value.
5544 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step, NoWrap);
5546 return BackedgeTakenInfo(BECount, MaxBECount);
5549 return getCouldNotCompute();
5552 /// getNumIterationsInRange - Return the number of iterations of this loop that
5553 /// produce values in the specified constant range. Another way of looking at
5554 /// this is that it returns the first iteration number where the value is not in
5555 /// the condition, thus computing the exit count. If the iteration count can't
5556 /// be computed, an instance of SCEVCouldNotCompute is returned.
5557 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
5558 ScalarEvolution &SE) const {
5559 if (Range.isFullSet()) // Infinite loop.
5560 return SE.getCouldNotCompute();
5562 // If the start is a non-zero constant, shift the range to simplify things.
5563 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
5564 if (!SC->getValue()->isZero()) {
5565 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
5566 Operands[0] = SE.getConstant(SC->getType(), 0);
5567 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
5568 if (const SCEVAddRecExpr *ShiftedAddRec =
5569 dyn_cast<SCEVAddRecExpr>(Shifted))
5570 return ShiftedAddRec->getNumIterationsInRange(
5571 Range.subtract(SC->getValue()->getValue()), SE);
5572 // This is strange and shouldn't happen.
5573 return SE.getCouldNotCompute();
5576 // The only time we can solve this is when we have all constant indices.
5577 // Otherwise, we cannot determine the overflow conditions.
5578 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5579 if (!isa<SCEVConstant>(getOperand(i)))
5580 return SE.getCouldNotCompute();
5583 // Okay at this point we know that all elements of the chrec are constants and
5584 // that the start element is zero.
5586 // First check to see if the range contains zero. If not, the first
5588 unsigned BitWidth = SE.getTypeSizeInBits(getType());
5589 if (!Range.contains(APInt(BitWidth, 0)))
5590 return SE.getConstant(getType(), 0);
5593 // If this is an affine expression then we have this situation:
5594 // Solve {0,+,A} in Range === Ax in Range
5596 // We know that zero is in the range. If A is positive then we know that
5597 // the upper value of the range must be the first possible exit value.
5598 // If A is negative then the lower of the range is the last possible loop
5599 // value. Also note that we already checked for a full range.
5600 APInt One(BitWidth,1);
5601 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
5602 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
5604 // The exit value should be (End+A)/A.
5605 APInt ExitVal = (End + A).udiv(A);
5606 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
5608 // Evaluate at the exit value. If we really did fall out of the valid
5609 // range, then we computed our trip count, otherwise wrap around or other
5610 // things must have happened.
5611 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
5612 if (Range.contains(Val->getValue()))
5613 return SE.getCouldNotCompute(); // Something strange happened
5615 // Ensure that the previous value is in the range. This is a sanity check.
5616 assert(Range.contains(
5617 EvaluateConstantChrecAtConstant(this,
5618 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
5619 "Linear scev computation is off in a bad way!");
5620 return SE.getConstant(ExitValue);
5621 } else if (isQuadratic()) {
5622 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5623 // quadratic equation to solve it. To do this, we must frame our problem in
5624 // terms of figuring out when zero is crossed, instead of when
5625 // Range.getUpper() is crossed.
5626 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
5627 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
5628 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
5630 // Next, solve the constructed addrec
5631 std::pair<const SCEV *,const SCEV *> Roots =
5632 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
5633 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5634 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
5636 // Pick the smallest positive root value.
5637 if (ConstantInt *CB =
5638 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
5639 R1->getValue(), R2->getValue()))) {
5640 if (CB->getZExtValue() == false)
5641 std::swap(R1, R2); // R1 is the minimum root now.
5643 // Make sure the root is not off by one. The returned iteration should
5644 // not be in the range, but the previous one should be. When solving
5645 // for "X*X < 5", for example, we should not return a root of 2.
5646 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
5649 if (Range.contains(R1Val->getValue())) {
5650 // The next iteration must be out of the range...
5651 ConstantInt *NextVal =
5652 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
5654 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
5655 if (!Range.contains(R1Val->getValue()))
5656 return SE.getConstant(NextVal);
5657 return SE.getCouldNotCompute(); // Something strange happened
5660 // If R1 was not in the range, then it is a good return value. Make
5661 // sure that R1-1 WAS in the range though, just in case.
5662 ConstantInt *NextVal =
5663 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
5664 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
5665 if (Range.contains(R1Val->getValue()))
5667 return SE.getCouldNotCompute(); // Something strange happened
5672 return SE.getCouldNotCompute();
5677 //===----------------------------------------------------------------------===//
5678 // SCEVCallbackVH Class Implementation
5679 //===----------------------------------------------------------------------===//
5681 void ScalarEvolution::SCEVCallbackVH::deleted() {
5682 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
5683 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5684 SE->ConstantEvolutionLoopExitValue.erase(PN);
5685 SE->Scalars.erase(getValPtr());
5686 // this now dangles!
5689 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
5690 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
5692 // Forget all the expressions associated with users of the old value,
5693 // so that future queries will recompute the expressions using the new
5695 Value *Old = getValPtr();
5696 SmallVector<User *, 16> Worklist;
5697 SmallPtrSet<User *, 8> Visited;
5698 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5700 Worklist.push_back(*UI);
5701 while (!Worklist.empty()) {
5702 User *U = Worklist.pop_back_val();
5703 // Deleting the Old value will cause this to dangle. Postpone
5704 // that until everything else is done.
5707 if (!Visited.insert(U))
5709 if (PHINode *PN = dyn_cast<PHINode>(U))
5710 SE->ConstantEvolutionLoopExitValue.erase(PN);
5711 SE->Scalars.erase(U);
5712 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5714 Worklist.push_back(*UI);
5716 // Delete the Old value.
5717 if (PHINode *PN = dyn_cast<PHINode>(Old))
5718 SE->ConstantEvolutionLoopExitValue.erase(PN);
5719 SE->Scalars.erase(Old);
5720 // this now dangles!
5723 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
5724 : CallbackVH(V), SE(se) {}
5726 //===----------------------------------------------------------------------===//
5727 // ScalarEvolution Class Implementation
5728 //===----------------------------------------------------------------------===//
5730 ScalarEvolution::ScalarEvolution()
5731 : FunctionPass(ID), FirstUnknown(0) {
5734 bool ScalarEvolution::runOnFunction(Function &F) {
5736 LI = &getAnalysis<LoopInfo>();
5737 TD = getAnalysisIfAvailable<TargetData>();
5738 DT = &getAnalysis<DominatorTree>();
5742 void ScalarEvolution::releaseMemory() {
5743 // Iterate through all the SCEVUnknown instances and call their
5744 // destructors, so that they release their references to their values.
5745 for (SCEVUnknown *U = FirstUnknown; U; U = U->Next)
5750 BackedgeTakenCounts.clear();
5751 ConstantEvolutionLoopExitValue.clear();
5752 ValuesAtScopes.clear();
5753 UniqueSCEVs.clear();
5754 SCEVAllocator.Reset();
5757 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5758 AU.setPreservesAll();
5759 AU.addRequiredTransitive<LoopInfo>();
5760 AU.addRequiredTransitive<DominatorTree>();
5763 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
5764 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
5767 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
5769 // Print all inner loops first
5770 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5771 PrintLoopInfo(OS, SE, *I);
5774 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5777 SmallVector<BasicBlock *, 8> ExitBlocks;
5778 L->getExitBlocks(ExitBlocks);
5779 if (ExitBlocks.size() != 1)
5780 OS << "<multiple exits> ";
5782 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5783 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
5785 OS << "Unpredictable backedge-taken count. ";
5790 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5793 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5794 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5796 OS << "Unpredictable max backedge-taken count. ";
5802 void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
5803 // ScalarEvolution's implementation of the print method is to print
5804 // out SCEV values of all instructions that are interesting. Doing
5805 // this potentially causes it to create new SCEV objects though,
5806 // which technically conflicts with the const qualifier. This isn't
5807 // observable from outside the class though, so casting away the
5808 // const isn't dangerous.
5809 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
5811 OS << "Classifying expressions for: ";
5812 WriteAsOperand(OS, F, /*PrintType=*/false);
5814 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
5815 if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) {
5818 const SCEV *SV = SE.getSCEV(&*I);
5821 const Loop *L = LI->getLoopFor((*I).getParent());
5823 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
5830 OS << "\t\t" "Exits: ";
5831 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
5832 if (!ExitValue->isLoopInvariant(L)) {
5833 OS << "<<Unknown>>";
5842 OS << "Determining loop execution counts for: ";
5843 WriteAsOperand(OS, F, /*PrintType=*/false);
5845 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5846 PrintLoopInfo(OS, &SE, *I);