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 (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
262 if (!(*I)->dominates(BB, DT))
267 bool SCEVNAryExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
268 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
269 if (!(*I)->properlyDominates(BB, DT))
274 bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
275 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
278 bool SCEVUDivExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
279 return LHS->properlyDominates(BB, DT) && RHS->properlyDominates(BB, DT);
282 void SCEVUDivExpr::print(raw_ostream &OS) const {
283 OS << "(" << *LHS << " /u " << *RHS << ")";
286 const Type *SCEVUDivExpr::getType() const {
287 // In most cases the types of LHS and RHS will be the same, but in some
288 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
289 // depend on the type for correctness, but handling types carefully can
290 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
291 // a pointer type than the RHS, so use the RHS' type here.
292 return RHS->getType();
295 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
296 // Add recurrences are never invariant in the function-body (null loop).
300 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
301 if (QueryLoop->contains(L))
304 // This recurrence is invariant w.r.t. QueryLoop if L contains QueryLoop.
305 if (L->contains(QueryLoop))
308 // This recurrence is variant w.r.t. QueryLoop if any of its operands
310 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
311 if (!getOperand(i)->isLoopInvariant(QueryLoop))
314 // Otherwise it's loop-invariant.
319 SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
320 return DT->dominates(L->getHeader(), BB) &&
321 SCEVNAryExpr::dominates(BB, DT);
325 SCEVAddRecExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
326 // This uses a "dominates" query instead of "properly dominates" query because
327 // the instruction which produces the addrec's value is a PHI, and a PHI
328 // effectively properly dominates its entire containing block.
329 return DT->dominates(L->getHeader(), BB) &&
330 SCEVNAryExpr::properlyDominates(BB, DT);
333 void SCEVAddRecExpr::print(raw_ostream &OS) const {
334 OS << "{" << *Operands[0];
335 for (unsigned i = 1, e = NumOperands; i != e; ++i)
336 OS << ",+," << *Operands[i];
338 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
342 void SCEVUnknown::deleted() {
343 // Clear this SCEVUnknown from ValuesAtScopes.
344 SE->ValuesAtScopes.erase(this);
346 // Remove this SCEVUnknown from the uniquing map.
347 SE->UniqueSCEVs.RemoveNode(this);
349 // Release the value.
353 void SCEVUnknown::allUsesReplacedWith(Value *New) {
354 // Clear this SCEVUnknown from ValuesAtScopes.
355 SE->ValuesAtScopes.erase(this);
357 // Remove this SCEVUnknown from the uniquing map.
358 SE->UniqueSCEVs.RemoveNode(this);
360 // Update this SCEVUnknown to point to the new value. This is needed
361 // because there may still be outstanding SCEVs which still point to
366 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
367 // All non-instruction values are loop invariant. All instructions are loop
368 // invariant if they are not contained in the specified loop.
369 // Instructions are never considered invariant in the function body
370 // (null loop) because they are defined within the "loop".
371 if (Instruction *I = dyn_cast<Instruction>(getValue()))
372 return L && !L->contains(I);
376 bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
377 if (Instruction *I = dyn_cast<Instruction>(getValue()))
378 return DT->dominates(I->getParent(), BB);
382 bool SCEVUnknown::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
383 if (Instruction *I = dyn_cast<Instruction>(getValue()))
384 return DT->properlyDominates(I->getParent(), BB);
388 const Type *SCEVUnknown::getType() const {
389 return getValue()->getType();
392 bool SCEVUnknown::isSizeOf(const Type *&AllocTy) const {
393 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
394 if (VCE->getOpcode() == Instruction::PtrToInt)
395 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
396 if (CE->getOpcode() == Instruction::GetElementPtr &&
397 CE->getOperand(0)->isNullValue() &&
398 CE->getNumOperands() == 2)
399 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
401 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
409 bool SCEVUnknown::isAlignOf(const Type *&AllocTy) const {
410 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
411 if (VCE->getOpcode() == Instruction::PtrToInt)
412 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
413 if (CE->getOpcode() == Instruction::GetElementPtr &&
414 CE->getOperand(0)->isNullValue()) {
416 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
417 if (const StructType *STy = dyn_cast<StructType>(Ty))
418 if (!STy->isPacked() &&
419 CE->getNumOperands() == 3 &&
420 CE->getOperand(1)->isNullValue()) {
421 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
423 STy->getNumElements() == 2 &&
424 STy->getElementType(0)->isIntegerTy(1)) {
425 AllocTy = STy->getElementType(1);
434 bool SCEVUnknown::isOffsetOf(const Type *&CTy, Constant *&FieldNo) const {
435 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
436 if (VCE->getOpcode() == Instruction::PtrToInt)
437 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
438 if (CE->getOpcode() == Instruction::GetElementPtr &&
439 CE->getNumOperands() == 3 &&
440 CE->getOperand(0)->isNullValue() &&
441 CE->getOperand(1)->isNullValue()) {
443 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
444 // Ignore vector types here so that ScalarEvolutionExpander doesn't
445 // emit getelementptrs that index into vectors.
446 if (Ty->isStructTy() || Ty->isArrayTy()) {
448 FieldNo = CE->getOperand(2);
456 void SCEVUnknown::print(raw_ostream &OS) const {
458 if (isSizeOf(AllocTy)) {
459 OS << "sizeof(" << *AllocTy << ")";
462 if (isAlignOf(AllocTy)) {
463 OS << "alignof(" << *AllocTy << ")";
469 if (isOffsetOf(CTy, FieldNo)) {
470 OS << "offsetof(" << *CTy << ", ";
471 WriteAsOperand(OS, FieldNo, false);
476 // Otherwise just print it normally.
477 WriteAsOperand(OS, getValue(), false);
480 //===----------------------------------------------------------------------===//
482 //===----------------------------------------------------------------------===//
485 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
486 /// than the complexity of the RHS. This comparator is used to canonicalize
488 class SCEVComplexityCompare {
489 const LoopInfo *const LI;
491 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
493 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
494 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
498 // Primarily, sort the SCEVs by their getSCEVType().
499 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
501 return LType < RType;
503 // Aside from the getSCEVType() ordering, the particular ordering
504 // isn't very important except that it's beneficial to be consistent,
505 // so that (a + b) and (b + a) don't end up as different expressions.
507 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
508 // not as complete as it could be.
509 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
510 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
511 const Value *LV = LU->getValue(), *RV = RU->getValue();
513 // Order pointer values after integer values. This helps SCEVExpander
515 bool LIsPointer = LV->getType()->isPointerTy(),
516 RIsPointer = RV->getType()->isPointerTy();
517 if (LIsPointer != RIsPointer)
520 // Compare getValueID values.
521 unsigned LID = LV->getValueID(),
522 RID = RV->getValueID();
526 // Sort arguments by their position.
527 if (const Argument *LA = dyn_cast<Argument>(LV)) {
528 const Argument *RA = cast<Argument>(RV);
529 return LA->getArgNo() < RA->getArgNo();
532 // For instructions, compare their loop depth, and their opcode.
533 // This is pretty loose.
534 if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
535 const Instruction *RInst = cast<Instruction>(RV);
537 // Compare loop depths.
538 const BasicBlock *LParent = LInst->getParent(),
539 *RParent = RInst->getParent();
540 if (LParent != RParent) {
541 unsigned LDepth = LI->getLoopDepth(LParent),
542 RDepth = LI->getLoopDepth(RParent);
543 if (LDepth != RDepth)
544 return LDepth < RDepth;
547 // Compare the number of operands.
548 unsigned LNumOps = LInst->getNumOperands(),
549 RNumOps = RInst->getNumOperands();
550 if (LNumOps != RNumOps)
551 return LNumOps < RNumOps;
557 // Compare constant values.
558 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
559 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
560 const ConstantInt *LCC = LC->getValue();
561 const ConstantInt *RCC = RC->getValue();
562 unsigned LBitWidth = LCC->getBitWidth(), RBitWidth = RCC->getBitWidth();
563 if (LBitWidth != RBitWidth)
564 return LBitWidth < RBitWidth;
565 return LCC->getValue().ult(RCC->getValue());
568 // Compare addrec loop depths.
569 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
570 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
571 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
572 if (LLoop != RLoop) {
573 unsigned LDepth = LLoop->getLoopDepth(),
574 RDepth = RLoop->getLoopDepth();
575 if (LDepth != RDepth)
576 return LDepth < RDepth;
580 // Lexicographically compare n-ary expressions.
581 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
582 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
583 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
584 for (unsigned i = 0; i != LNumOps; ++i) {
587 const SCEV *LOp = LC->getOperand(i), *ROp = RC->getOperand(i);
588 if (operator()(LOp, ROp))
590 if (operator()(ROp, LOp))
593 return LNumOps < RNumOps;
596 // Lexicographically compare udiv expressions.
597 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
598 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
599 const SCEV *LL = LC->getLHS(), *LR = LC->getRHS(),
600 *RL = RC->getLHS(), *RR = RC->getRHS();
601 if (operator()(LL, RL))
603 if (operator()(RL, LL))
605 if (operator()(LR, RR))
607 if (operator()(RR, LR))
612 // Compare cast expressions by operand.
613 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
614 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
615 return operator()(LC->getOperand(), RC->getOperand());
618 llvm_unreachable("Unknown SCEV kind!");
624 /// GroupByComplexity - Given a list of SCEV objects, order them by their
625 /// complexity, and group objects of the same complexity together by value.
626 /// When this routine is finished, we know that any duplicates in the vector are
627 /// consecutive and that complexity is monotonically increasing.
629 /// Note that we go take special precautions to ensure that we get deterministic
630 /// results from this routine. In other words, we don't want the results of
631 /// this to depend on where the addresses of various SCEV objects happened to
634 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
636 if (Ops.size() < 2) return; // Noop
637 if (Ops.size() == 2) {
638 // This is the common case, which also happens to be trivially simple.
640 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
641 std::swap(Ops[0], Ops[1]);
645 // Do the rough sort by complexity.
646 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
648 // Now that we are sorted by complexity, group elements of the same
649 // complexity. Note that this is, at worst, N^2, but the vector is likely to
650 // be extremely short in practice. Note that we take this approach because we
651 // do not want to depend on the addresses of the objects we are grouping.
652 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
653 const SCEV *S = Ops[i];
654 unsigned Complexity = S->getSCEVType();
656 // If there are any objects of the same complexity and same value as this
658 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
659 if (Ops[j] == S) { // Found a duplicate.
660 // Move it to immediately after i'th element.
661 std::swap(Ops[i+1], Ops[j]);
662 ++i; // no need to rescan it.
663 if (i == e-2) return; // Done!
671 //===----------------------------------------------------------------------===//
672 // Simple SCEV method implementations
673 //===----------------------------------------------------------------------===//
675 /// BinomialCoefficient - Compute BC(It, K). The result has width W.
677 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
679 const Type* ResultTy) {
680 // Handle the simplest case efficiently.
682 return SE.getTruncateOrZeroExtend(It, ResultTy);
684 // We are using the following formula for BC(It, K):
686 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
688 // Suppose, W is the bitwidth of the return value. We must be prepared for
689 // overflow. Hence, we must assure that the result of our computation is
690 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
691 // safe in modular arithmetic.
693 // However, this code doesn't use exactly that formula; the formula it uses
694 // is something like the following, where T is the number of factors of 2 in
695 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
698 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
700 // This formula is trivially equivalent to the previous formula. However,
701 // this formula can be implemented much more efficiently. The trick is that
702 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
703 // arithmetic. To do exact division in modular arithmetic, all we have
704 // to do is multiply by the inverse. Therefore, this step can be done at
707 // The next issue is how to safely do the division by 2^T. The way this
708 // is done is by doing the multiplication step at a width of at least W + T
709 // bits. This way, the bottom W+T bits of the product are accurate. Then,
710 // when we perform the division by 2^T (which is equivalent to a right shift
711 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
712 // truncated out after the division by 2^T.
714 // In comparison to just directly using the first formula, this technique
715 // is much more efficient; using the first formula requires W * K bits,
716 // but this formula less than W + K bits. Also, the first formula requires
717 // a division step, whereas this formula only requires multiplies and shifts.
719 // It doesn't matter whether the subtraction step is done in the calculation
720 // width or the input iteration count's width; if the subtraction overflows,
721 // the result must be zero anyway. We prefer here to do it in the width of
722 // the induction variable because it helps a lot for certain cases; CodeGen
723 // isn't smart enough to ignore the overflow, which leads to much less
724 // efficient code if the width of the subtraction is wider than the native
727 // (It's possible to not widen at all by pulling out factors of 2 before
728 // the multiplication; for example, K=2 can be calculated as
729 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
730 // extra arithmetic, so it's not an obvious win, and it gets
731 // much more complicated for K > 3.)
733 // Protection from insane SCEVs; this bound is conservative,
734 // but it probably doesn't matter.
736 return SE.getCouldNotCompute();
738 unsigned W = SE.getTypeSizeInBits(ResultTy);
740 // Calculate K! / 2^T and T; we divide out the factors of two before
741 // multiplying for calculating K! / 2^T to avoid overflow.
742 // Other overflow doesn't matter because we only care about the bottom
743 // W bits of the result.
744 APInt OddFactorial(W, 1);
746 for (unsigned i = 3; i <= K; ++i) {
748 unsigned TwoFactors = Mult.countTrailingZeros();
750 Mult = Mult.lshr(TwoFactors);
751 OddFactorial *= Mult;
754 // We need at least W + T bits for the multiplication step
755 unsigned CalculationBits = W + T;
757 // Calculate 2^T, at width T+W.
758 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
760 // Calculate the multiplicative inverse of K! / 2^T;
761 // this multiplication factor will perform the exact division by
763 APInt Mod = APInt::getSignedMinValue(W+1);
764 APInt MultiplyFactor = OddFactorial.zext(W+1);
765 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
766 MultiplyFactor = MultiplyFactor.trunc(W);
768 // Calculate the product, at width T+W
769 const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
771 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
772 for (unsigned i = 1; i != K; ++i) {
773 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
774 Dividend = SE.getMulExpr(Dividend,
775 SE.getTruncateOrZeroExtend(S, CalculationTy));
779 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
781 // Truncate the result, and divide by K! / 2^T.
783 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
784 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
787 /// evaluateAtIteration - Return the value of this chain of recurrences at
788 /// the specified iteration number. We can evaluate this recurrence by
789 /// multiplying each element in the chain by the binomial coefficient
790 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
792 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
794 /// where BC(It, k) stands for binomial coefficient.
796 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
797 ScalarEvolution &SE) const {
798 const SCEV *Result = getStart();
799 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
800 // The computation is correct in the face of overflow provided that the
801 // multiplication is performed _after_ the evaluation of the binomial
803 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
804 if (isa<SCEVCouldNotCompute>(Coeff))
807 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
812 //===----------------------------------------------------------------------===//
813 // SCEV Expression folder implementations
814 //===----------------------------------------------------------------------===//
816 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
818 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
819 "This is not a truncating conversion!");
820 assert(isSCEVable(Ty) &&
821 "This is not a conversion to a SCEVable type!");
822 Ty = getEffectiveSCEVType(Ty);
825 ID.AddInteger(scTruncate);
829 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
831 // Fold if the operand is constant.
832 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
834 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(),
835 getEffectiveSCEVType(Ty))));
837 // trunc(trunc(x)) --> trunc(x)
838 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
839 return getTruncateExpr(ST->getOperand(), Ty);
841 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
842 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
843 return getTruncateOrSignExtend(SS->getOperand(), Ty);
845 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
846 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
847 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
849 // If the input value is a chrec scev, truncate the chrec's operands.
850 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
851 SmallVector<const SCEV *, 4> Operands;
852 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
853 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
854 return getAddRecExpr(Operands, AddRec->getLoop());
857 // As a special case, fold trunc(undef) to undef. We don't want to
858 // know too much about SCEVUnknowns, but this special case is handy
860 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
861 if (isa<UndefValue>(U->getValue()))
862 return getSCEV(UndefValue::get(Ty));
864 // The cast wasn't folded; create an explicit cast node. We can reuse
865 // the existing insert position since if we get here, we won't have
866 // made any changes which would invalidate it.
867 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
869 UniqueSCEVs.InsertNode(S, IP);
873 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
875 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
876 "This is not an extending conversion!");
877 assert(isSCEVable(Ty) &&
878 "This is not a conversion to a SCEVable type!");
879 Ty = getEffectiveSCEVType(Ty);
881 // Fold if the operand is constant.
882 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
884 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(),
885 getEffectiveSCEVType(Ty))));
887 // zext(zext(x)) --> zext(x)
888 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
889 return getZeroExtendExpr(SZ->getOperand(), Ty);
891 // Before doing any expensive analysis, check to see if we've already
892 // computed a SCEV for this Op and Ty.
894 ID.AddInteger(scZeroExtend);
898 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
900 // If the input value is a chrec scev, and we can prove that the value
901 // did not overflow the old, smaller, value, we can zero extend all of the
902 // operands (often constants). This allows analysis of something like
903 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
904 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
905 if (AR->isAffine()) {
906 const SCEV *Start = AR->getStart();
907 const SCEV *Step = AR->getStepRecurrence(*this);
908 unsigned BitWidth = getTypeSizeInBits(AR->getType());
909 const Loop *L = AR->getLoop();
911 // If we have special knowledge that this addrec won't overflow,
912 // we don't need to do any further analysis.
913 if (AR->hasNoUnsignedWrap())
914 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
915 getZeroExtendExpr(Step, Ty),
918 // Check whether the backedge-taken count is SCEVCouldNotCompute.
919 // Note that this serves two purposes: It filters out loops that are
920 // simply not analyzable, and it covers the case where this code is
921 // being called from within backedge-taken count analysis, such that
922 // attempting to ask for the backedge-taken count would likely result
923 // in infinite recursion. In the later case, the analysis code will
924 // cope with a conservative value, and it will take care to purge
925 // that value once it has finished.
926 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
927 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
928 // Manually compute the final value for AR, checking for
931 // Check whether the backedge-taken count can be losslessly casted to
932 // the addrec's type. The count is always unsigned.
933 const SCEV *CastedMaxBECount =
934 getTruncateOrZeroExtend(MaxBECount, Start->getType());
935 const SCEV *RecastedMaxBECount =
936 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
937 if (MaxBECount == RecastedMaxBECount) {
938 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
939 // Check whether Start+Step*MaxBECount has no unsigned overflow.
940 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
941 const SCEV *Add = getAddExpr(Start, ZMul);
942 const SCEV *OperandExtendedAdd =
943 getAddExpr(getZeroExtendExpr(Start, WideTy),
944 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
945 getZeroExtendExpr(Step, WideTy)));
946 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
947 // Return the expression with the addrec on the outside.
948 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
949 getZeroExtendExpr(Step, Ty),
952 // Similar to above, only this time treat the step value as signed.
953 // This covers loops that count down.
954 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
955 Add = getAddExpr(Start, SMul);
957 getAddExpr(getZeroExtendExpr(Start, WideTy),
958 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
959 getSignExtendExpr(Step, WideTy)));
960 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
961 // Return the expression with the addrec on the outside.
962 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
963 getSignExtendExpr(Step, Ty),
967 // If the backedge is guarded by a comparison with the pre-inc value
968 // the addrec is safe. Also, if the entry is guarded by a comparison
969 // with the start value and the backedge is guarded by a comparison
970 // with the post-inc value, the addrec is safe.
971 if (isKnownPositive(Step)) {
972 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
973 getUnsignedRange(Step).getUnsignedMax());
974 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
975 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
976 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
977 AR->getPostIncExpr(*this), N)))
978 // Return the expression with the addrec on the outside.
979 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
980 getZeroExtendExpr(Step, Ty),
982 } else if (isKnownNegative(Step)) {
983 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
984 getSignedRange(Step).getSignedMin());
985 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
986 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
987 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
988 AR->getPostIncExpr(*this), N)))
989 // Return the expression with the addrec on the outside.
990 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
991 getSignExtendExpr(Step, Ty),
997 // The cast wasn't folded; create an explicit cast node.
998 // Recompute the insert position, as it may have been invalidated.
999 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1000 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1002 UniqueSCEVs.InsertNode(S, IP);
1006 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
1008 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1009 "This is not an extending conversion!");
1010 assert(isSCEVable(Ty) &&
1011 "This is not a conversion to a SCEVable type!");
1012 Ty = getEffectiveSCEVType(Ty);
1014 // Fold if the operand is constant.
1015 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1017 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(),
1018 getEffectiveSCEVType(Ty))));
1020 // sext(sext(x)) --> sext(x)
1021 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1022 return getSignExtendExpr(SS->getOperand(), Ty);
1024 // Before doing any expensive analysis, check to see if we've already
1025 // computed a SCEV for this Op and Ty.
1026 FoldingSetNodeID ID;
1027 ID.AddInteger(scSignExtend);
1031 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1033 // If the input value is a chrec scev, and we can prove that the value
1034 // did not overflow the old, smaller, value, we can sign extend all of the
1035 // operands (often constants). This allows analysis of something like
1036 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1037 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1038 if (AR->isAffine()) {
1039 const SCEV *Start = AR->getStart();
1040 const SCEV *Step = AR->getStepRecurrence(*this);
1041 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1042 const Loop *L = AR->getLoop();
1044 // If we have special knowledge that this addrec won't overflow,
1045 // we don't need to do any further analysis.
1046 if (AR->hasNoSignedWrap())
1047 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1048 getSignExtendExpr(Step, Ty),
1051 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1052 // Note that this serves two purposes: It filters out loops that are
1053 // simply not analyzable, and it covers the case where this code is
1054 // being called from within backedge-taken count analysis, such that
1055 // attempting to ask for the backedge-taken count would likely result
1056 // in infinite recursion. In the later case, the analysis code will
1057 // cope with a conservative value, and it will take care to purge
1058 // that value once it has finished.
1059 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1060 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1061 // Manually compute the final value for AR, checking for
1064 // Check whether the backedge-taken count can be losslessly casted to
1065 // the addrec's type. The count is always unsigned.
1066 const SCEV *CastedMaxBECount =
1067 getTruncateOrZeroExtend(MaxBECount, Start->getType());
1068 const SCEV *RecastedMaxBECount =
1069 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1070 if (MaxBECount == RecastedMaxBECount) {
1071 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1072 // Check whether Start+Step*MaxBECount has no signed overflow.
1073 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
1074 const SCEV *Add = getAddExpr(Start, SMul);
1075 const SCEV *OperandExtendedAdd =
1076 getAddExpr(getSignExtendExpr(Start, WideTy),
1077 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1078 getSignExtendExpr(Step, WideTy)));
1079 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
1080 // Return the expression with the addrec on the outside.
1081 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1082 getSignExtendExpr(Step, Ty),
1085 // Similar to above, only this time treat the step value as unsigned.
1086 // This covers loops that count up with an unsigned step.
1087 const SCEV *UMul = getMulExpr(CastedMaxBECount, Step);
1088 Add = getAddExpr(Start, UMul);
1089 OperandExtendedAdd =
1090 getAddExpr(getSignExtendExpr(Start, WideTy),
1091 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1092 getZeroExtendExpr(Step, WideTy)));
1093 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
1094 // Return the expression with the addrec on the outside.
1095 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1096 getZeroExtendExpr(Step, Ty),
1100 // If the backedge is guarded by a comparison with the pre-inc value
1101 // the addrec is safe. Also, if the entry is guarded by a comparison
1102 // with the start value and the backedge is guarded by a comparison
1103 // with the post-inc value, the addrec is safe.
1104 if (isKnownPositive(Step)) {
1105 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
1106 getSignedRange(Step).getSignedMax());
1107 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
1108 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
1109 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
1110 AR->getPostIncExpr(*this), N)))
1111 // Return the expression with the addrec on the outside.
1112 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1113 getSignExtendExpr(Step, Ty),
1115 } else if (isKnownNegative(Step)) {
1116 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1117 getSignedRange(Step).getSignedMin());
1118 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
1119 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
1120 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1121 AR->getPostIncExpr(*this), N)))
1122 // Return the expression with the addrec on the outside.
1123 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1124 getSignExtendExpr(Step, Ty),
1130 // The cast wasn't folded; create an explicit cast node.
1131 // Recompute the insert position, as it may have been invalidated.
1132 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1133 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1135 UniqueSCEVs.InsertNode(S, IP);
1139 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1140 /// unspecified bits out to the given type.
1142 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1144 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1145 "This is not an extending conversion!");
1146 assert(isSCEVable(Ty) &&
1147 "This is not a conversion to a SCEVable type!");
1148 Ty = getEffectiveSCEVType(Ty);
1150 // Sign-extend negative constants.
1151 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1152 if (SC->getValue()->getValue().isNegative())
1153 return getSignExtendExpr(Op, Ty);
1155 // Peel off a truncate cast.
1156 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
1157 const SCEV *NewOp = T->getOperand();
1158 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1159 return getAnyExtendExpr(NewOp, Ty);
1160 return getTruncateOrNoop(NewOp, Ty);
1163 // Next try a zext cast. If the cast is folded, use it.
1164 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
1165 if (!isa<SCEVZeroExtendExpr>(ZExt))
1168 // Next try a sext cast. If the cast is folded, use it.
1169 const SCEV *SExt = getSignExtendExpr(Op, Ty);
1170 if (!isa<SCEVSignExtendExpr>(SExt))
1173 // Force the cast to be folded into the operands of an addrec.
1174 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1175 SmallVector<const SCEV *, 4> Ops;
1176 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
1178 Ops.push_back(getAnyExtendExpr(*I, Ty));
1179 return getAddRecExpr(Ops, AR->getLoop());
1182 // As a special case, fold anyext(undef) to undef. We don't want to
1183 // know too much about SCEVUnknowns, but this special case is handy
1185 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
1186 if (isa<UndefValue>(U->getValue()))
1187 return getSCEV(UndefValue::get(Ty));
1189 // If the expression is obviously signed, use the sext cast value.
1190 if (isa<SCEVSMaxExpr>(Op))
1193 // Absent any other information, use the zext cast value.
1197 /// CollectAddOperandsWithScales - Process the given Ops list, which is
1198 /// a list of operands to be added under the given scale, update the given
1199 /// map. This is a helper function for getAddRecExpr. As an example of
1200 /// what it does, given a sequence of operands that would form an add
1201 /// expression like this:
1203 /// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1205 /// where A and B are constants, update the map with these values:
1207 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1209 /// and add 13 + A*B*29 to AccumulatedConstant.
1210 /// This will allow getAddRecExpr to produce this:
1212 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1214 /// This form often exposes folding opportunities that are hidden in
1215 /// the original operand list.
1217 /// Return true iff it appears that any interesting folding opportunities
1218 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
1219 /// the common case where no interesting opportunities are present, and
1220 /// is also used as a check to avoid infinite recursion.
1223 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1224 SmallVector<const SCEV *, 8> &NewOps,
1225 APInt &AccumulatedConstant,
1226 const SCEV *const *Ops, size_t NumOperands,
1228 ScalarEvolution &SE) {
1229 bool Interesting = false;
1231 // Iterate over the add operands. They are sorted, with constants first.
1233 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1235 // Pull a buried constant out to the outside.
1236 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1238 AccumulatedConstant += Scale * C->getValue()->getValue();
1241 // Next comes everything else. We're especially interested in multiplies
1242 // here, but they're in the middle, so just visit the rest with one loop.
1243 for (; i != NumOperands; ++i) {
1244 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1245 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1247 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1248 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1249 // A multiplication of a constant with another add; recurse.
1250 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
1252 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1253 Add->op_begin(), Add->getNumOperands(),
1256 // A multiplication of a constant with some other value. Update
1258 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1259 const SCEV *Key = SE.getMulExpr(MulOps);
1260 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1261 M.insert(std::make_pair(Key, NewScale));
1263 NewOps.push_back(Pair.first->first);
1265 Pair.first->second += NewScale;
1266 // The map already had an entry for this value, which may indicate
1267 // a folding opportunity.
1272 // An ordinary operand. Update the map.
1273 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1274 M.insert(std::make_pair(Ops[i], Scale));
1276 NewOps.push_back(Pair.first->first);
1278 Pair.first->second += Scale;
1279 // The map already had an entry for this value, which may indicate
1280 // a folding opportunity.
1290 struct APIntCompare {
1291 bool operator()(const APInt &LHS, const APInt &RHS) const {
1292 return LHS.ult(RHS);
1297 /// getAddExpr - Get a canonical add expression, or something simpler if
1299 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1300 bool HasNUW, bool HasNSW) {
1301 assert(!Ops.empty() && "Cannot get empty add!");
1302 if (Ops.size() == 1) return Ops[0];
1304 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
1305 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1306 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
1307 "SCEVAddExpr operand types don't match!");
1310 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1311 if (!HasNUW && HasNSW) {
1313 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1314 if (!isKnownNonNegative(Ops[i])) {
1318 if (All) HasNUW = true;
1321 // Sort by complexity, this groups all similar expression types together.
1322 GroupByComplexity(Ops, LI);
1324 // If there are any constants, fold them together.
1326 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1328 assert(Idx < Ops.size());
1329 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1330 // We found two constants, fold them together!
1331 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1332 RHSC->getValue()->getValue());
1333 if (Ops.size() == 2) return Ops[0];
1334 Ops.erase(Ops.begin()+1); // Erase the folded element
1335 LHSC = cast<SCEVConstant>(Ops[0]);
1338 // If we are left with a constant zero being added, strip it off.
1339 if (LHSC->getValue()->isZero()) {
1340 Ops.erase(Ops.begin());
1344 if (Ops.size() == 1) return Ops[0];
1347 // Okay, check to see if the same value occurs in the operand list twice. If
1348 // so, merge them together into an multiply expression. Since we sorted the
1349 // list, these values are required to be adjacent.
1350 const Type *Ty = Ops[0]->getType();
1351 bool FoundMatch = false;
1352 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1353 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1354 // Found a match, merge the two values into a multiply, and add any
1355 // remaining values to the result.
1356 const SCEV *Two = getConstant(Ty, 2);
1357 const SCEV *Mul = getMulExpr(Two, Ops[i]);
1358 if (Ops.size() == 2)
1361 Ops.erase(Ops.begin()+i+1);
1366 return getAddExpr(Ops, HasNUW, HasNSW);
1368 // Check for truncates. If all the operands are truncated from the same
1369 // type, see if factoring out the truncate would permit the result to be
1370 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1371 // if the contents of the resulting outer trunc fold to something simple.
1372 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1373 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1374 const Type *DstType = Trunc->getType();
1375 const Type *SrcType = Trunc->getOperand()->getType();
1376 SmallVector<const SCEV *, 8> LargeOps;
1378 // Check all the operands to see if they can be represented in the
1379 // source type of the truncate.
1380 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1381 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1382 if (T->getOperand()->getType() != SrcType) {
1386 LargeOps.push_back(T->getOperand());
1387 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1388 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
1389 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
1390 SmallVector<const SCEV *, 8> LargeMulOps;
1391 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1392 if (const SCEVTruncateExpr *T =
1393 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1394 if (T->getOperand()->getType() != SrcType) {
1398 LargeMulOps.push_back(T->getOperand());
1399 } else if (const SCEVConstant *C =
1400 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1401 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
1408 LargeOps.push_back(getMulExpr(LargeMulOps));
1415 // Evaluate the expression in the larger type.
1416 const SCEV *Fold = getAddExpr(LargeOps, HasNUW, HasNSW);
1417 // If it folds to something simple, use it. Otherwise, don't.
1418 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1419 return getTruncateExpr(Fold, DstType);
1423 // Skip past any other cast SCEVs.
1424 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1427 // If there are add operands they would be next.
1428 if (Idx < Ops.size()) {
1429 bool DeletedAdd = false;
1430 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
1431 // If we have an add, expand the add operands onto the end of the operands
1433 Ops.erase(Ops.begin()+Idx);
1434 Ops.append(Add->op_begin(), Add->op_end());
1438 // If we deleted at least one add, we added operands to the end of the list,
1439 // and they are not necessarily sorted. Recurse to resort and resimplify
1440 // any operands we just acquired.
1442 return getAddExpr(Ops);
1445 // Skip over the add expression until we get to a multiply.
1446 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1449 // Check to see if there are any folding opportunities present with
1450 // operands multiplied by constant values.
1451 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1452 uint64_t BitWidth = getTypeSizeInBits(Ty);
1453 DenseMap<const SCEV *, APInt> M;
1454 SmallVector<const SCEV *, 8> NewOps;
1455 APInt AccumulatedConstant(BitWidth, 0);
1456 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1457 Ops.data(), Ops.size(),
1458 APInt(BitWidth, 1), *this)) {
1459 // Some interesting folding opportunity is present, so its worthwhile to
1460 // re-generate the operands list. Group the operands by constant scale,
1461 // to avoid multiplying by the same constant scale multiple times.
1462 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1463 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
1464 E = NewOps.end(); I != E; ++I)
1465 MulOpLists[M.find(*I)->second].push_back(*I);
1466 // Re-generate the operands list.
1468 if (AccumulatedConstant != 0)
1469 Ops.push_back(getConstant(AccumulatedConstant));
1470 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1471 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
1473 Ops.push_back(getMulExpr(getConstant(I->first),
1474 getAddExpr(I->second)));
1476 return getConstant(Ty, 0);
1477 if (Ops.size() == 1)
1479 return getAddExpr(Ops);
1483 // If we are adding something to a multiply expression, make sure the
1484 // something is not already an operand of the multiply. If so, merge it into
1486 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
1487 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
1488 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
1489 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
1490 if (isa<SCEVConstant>(MulOpSCEV))
1492 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
1493 if (MulOpSCEV == Ops[AddOp]) {
1494 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1495 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
1496 if (Mul->getNumOperands() != 2) {
1497 // If the multiply has more than two operands, we must get the
1499 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
1500 MulOps.erase(MulOps.begin()+MulOp);
1501 InnerMul = getMulExpr(MulOps);
1503 const SCEV *One = getConstant(Ty, 1);
1504 const SCEV *AddOne = getAddExpr(One, InnerMul);
1505 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
1506 if (Ops.size() == 2) return OuterMul;
1508 Ops.erase(Ops.begin()+AddOp);
1509 Ops.erase(Ops.begin()+Idx-1);
1511 Ops.erase(Ops.begin()+Idx);
1512 Ops.erase(Ops.begin()+AddOp-1);
1514 Ops.push_back(OuterMul);
1515 return getAddExpr(Ops);
1518 // Check this multiply against other multiplies being added together.
1519 bool AnyFold = false;
1520 for (unsigned OtherMulIdx = Idx+1;
1521 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1523 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
1524 // If MulOp occurs in OtherMul, we can fold the two multiplies
1526 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1527 OMulOp != e; ++OMulOp)
1528 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1529 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1530 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
1531 if (Mul->getNumOperands() != 2) {
1532 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1534 MulOps.erase(MulOps.begin()+MulOp);
1535 InnerMul1 = getMulExpr(MulOps);
1537 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1538 if (OtherMul->getNumOperands() != 2) {
1539 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1540 OtherMul->op_end());
1541 MulOps.erase(MulOps.begin()+OMulOp);
1542 InnerMul2 = getMulExpr(MulOps);
1544 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1545 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
1546 if (Ops.size() == 2) return OuterMul;
1547 Ops[Idx] = OuterMul;
1548 Ops.erase(Ops.begin()+OtherMulIdx);
1554 return getAddExpr(Ops);
1558 // If there are any add recurrences in the operands list, see if any other
1559 // added values are loop invariant. If so, we can fold them into the
1561 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1564 // Scan over all recurrences, trying to fold loop invariants into them.
1565 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1566 // Scan all of the other operands to this add and add them to the vector if
1567 // they are loop invariant w.r.t. the recurrence.
1568 SmallVector<const SCEV *, 8> LIOps;
1569 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1570 const Loop *AddRecLoop = AddRec->getLoop();
1571 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1572 if (Ops[i]->isLoopInvariant(AddRecLoop)) {
1573 LIOps.push_back(Ops[i]);
1574 Ops.erase(Ops.begin()+i);
1578 // If we found some loop invariants, fold them into the recurrence.
1579 if (!LIOps.empty()) {
1580 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
1581 LIOps.push_back(AddRec->getStart());
1583 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
1585 AddRecOps[0] = getAddExpr(LIOps);
1587 // Build the new addrec. Propagate the NUW and NSW flags if both the
1588 // outer add and the inner addrec are guaranteed to have no overflow.
1589 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop,
1590 HasNUW && AddRec->hasNoUnsignedWrap(),
1591 HasNSW && AddRec->hasNoSignedWrap());
1593 // If all of the other operands were loop invariant, we are done.
1594 if (Ops.size() == 1) return NewRec;
1596 // Otherwise, add the folded AddRec by the non-liv parts.
1597 for (unsigned i = 0;; ++i)
1598 if (Ops[i] == AddRec) {
1602 return getAddExpr(Ops);
1605 // Okay, if there weren't any loop invariants to be folded, check to see if
1606 // there are multiple AddRec's with the same loop induction variable being
1607 // added together. If so, we can fold them.
1608 for (unsigned OtherIdx = Idx+1;
1609 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1610 if (OtherIdx != Idx) {
1611 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1612 if (AddRecLoop == OtherAddRec->getLoop()) {
1613 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1614 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1616 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1617 if (i >= NewOps.size()) {
1618 NewOps.append(OtherAddRec->op_begin()+i,
1619 OtherAddRec->op_end());
1622 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
1624 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRecLoop);
1626 if (Ops.size() == 2) return NewAddRec;
1628 Ops.erase(Ops.begin()+Idx);
1629 Ops.erase(Ops.begin()+OtherIdx-1);
1630 Ops.push_back(NewAddRec);
1631 return getAddExpr(Ops);
1635 // Otherwise couldn't fold anything into this recurrence. Move onto the
1639 // Okay, it looks like we really DO need an add expr. Check to see if we
1640 // already have one, otherwise create a new one.
1641 FoldingSetNodeID ID;
1642 ID.AddInteger(scAddExpr);
1643 ID.AddInteger(Ops.size());
1644 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1645 ID.AddPointer(Ops[i]);
1648 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1650 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1651 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
1652 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
1654 UniqueSCEVs.InsertNode(S, IP);
1656 if (HasNUW) S->setHasNoUnsignedWrap(true);
1657 if (HasNSW) S->setHasNoSignedWrap(true);
1661 /// getMulExpr - Get a canonical multiply expression, or something simpler if
1663 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1664 bool HasNUW, bool HasNSW) {
1665 assert(!Ops.empty() && "Cannot get empty mul!");
1666 if (Ops.size() == 1) return Ops[0];
1668 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
1669 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1670 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
1671 "SCEVMulExpr operand types don't match!");
1674 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1675 if (!HasNUW && HasNSW) {
1677 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1678 if (!isKnownNonNegative(Ops[i])) {
1682 if (All) HasNUW = true;
1685 // Sort by complexity, this groups all similar expression types together.
1686 GroupByComplexity(Ops, LI);
1688 // If there are any constants, fold them together.
1690 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1692 // C1*(C2+V) -> C1*C2 + C1*V
1693 if (Ops.size() == 2)
1694 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1695 if (Add->getNumOperands() == 2 &&
1696 isa<SCEVConstant>(Add->getOperand(0)))
1697 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1698 getMulExpr(LHSC, Add->getOperand(1)));
1701 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1702 // We found two constants, fold them together!
1703 ConstantInt *Fold = ConstantInt::get(getContext(),
1704 LHSC->getValue()->getValue() *
1705 RHSC->getValue()->getValue());
1706 Ops[0] = getConstant(Fold);
1707 Ops.erase(Ops.begin()+1); // Erase the folded element
1708 if (Ops.size() == 1) return Ops[0];
1709 LHSC = cast<SCEVConstant>(Ops[0]);
1712 // If we are left with a constant one being multiplied, strip it off.
1713 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1714 Ops.erase(Ops.begin());
1716 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1717 // If we have a multiply of zero, it will always be zero.
1719 } else if (Ops[0]->isAllOnesValue()) {
1720 // If we have a mul by -1 of an add, try distributing the -1 among the
1722 if (Ops.size() == 2)
1723 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1724 SmallVector<const SCEV *, 4> NewOps;
1725 bool AnyFolded = false;
1726 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1728 const SCEV *Mul = getMulExpr(Ops[0], *I);
1729 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1730 NewOps.push_back(Mul);
1733 return getAddExpr(NewOps);
1737 if (Ops.size() == 1)
1741 // Skip over the add expression until we get to a multiply.
1742 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1745 // If there are mul operands inline them all into this expression.
1746 if (Idx < Ops.size()) {
1747 bool DeletedMul = false;
1748 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1749 // If we have an mul, expand the mul operands onto the end of the operands
1751 Ops.erase(Ops.begin()+Idx);
1752 Ops.append(Mul->op_begin(), Mul->op_end());
1756 // If we deleted at least one mul, we added operands to the end of the list,
1757 // and they are not necessarily sorted. Recurse to resort and resimplify
1758 // any operands we just acquired.
1760 return getMulExpr(Ops);
1763 // If there are any add recurrences in the operands list, see if any other
1764 // added values are loop invariant. If so, we can fold them into the
1766 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1769 // Scan over all recurrences, trying to fold loop invariants into them.
1770 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1771 // Scan all of the other operands to this mul and add them to the vector if
1772 // they are loop invariant w.r.t. the recurrence.
1773 SmallVector<const SCEV *, 8> LIOps;
1774 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1775 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1776 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1777 LIOps.push_back(Ops[i]);
1778 Ops.erase(Ops.begin()+i);
1782 // If we found some loop invariants, fold them into the recurrence.
1783 if (!LIOps.empty()) {
1784 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
1785 SmallVector<const SCEV *, 4> NewOps;
1786 NewOps.reserve(AddRec->getNumOperands());
1787 const SCEV *Scale = getMulExpr(LIOps);
1788 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1789 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1791 // Build the new addrec. Propagate the NUW and NSW flags if both the
1792 // outer mul and the inner addrec are guaranteed to have no overflow.
1793 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(),
1794 HasNUW && AddRec->hasNoUnsignedWrap(),
1795 HasNSW && AddRec->hasNoSignedWrap());
1797 // If all of the other operands were loop invariant, we are done.
1798 if (Ops.size() == 1) return NewRec;
1800 // Otherwise, multiply the folded AddRec by the non-liv parts.
1801 for (unsigned i = 0;; ++i)
1802 if (Ops[i] == AddRec) {
1806 return getMulExpr(Ops);
1809 // Okay, if there weren't any loop invariants to be folded, check to see if
1810 // there are multiple AddRec's with the same loop induction variable being
1811 // multiplied together. If so, we can fold them.
1812 for (unsigned OtherIdx = Idx+1;
1813 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1814 if (OtherIdx != Idx) {
1815 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1816 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1817 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1818 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1819 const SCEV *NewStart = getMulExpr(F->getStart(),
1821 const SCEV *B = F->getStepRecurrence(*this);
1822 const SCEV *D = G->getStepRecurrence(*this);
1823 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
1826 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
1828 if (Ops.size() == 2) return NewAddRec;
1830 Ops.erase(Ops.begin()+Idx);
1831 Ops.erase(Ops.begin()+OtherIdx-1);
1832 Ops.push_back(NewAddRec);
1833 return getMulExpr(Ops);
1837 // Otherwise couldn't fold anything into this recurrence. Move onto the
1841 // Okay, it looks like we really DO need an mul expr. Check to see if we
1842 // already have one, otherwise create a new one.
1843 FoldingSetNodeID ID;
1844 ID.AddInteger(scMulExpr);
1845 ID.AddInteger(Ops.size());
1846 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1847 ID.AddPointer(Ops[i]);
1850 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1852 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1853 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
1854 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
1856 UniqueSCEVs.InsertNode(S, IP);
1858 if (HasNUW) S->setHasNoUnsignedWrap(true);
1859 if (HasNSW) S->setHasNoSignedWrap(true);
1863 /// getUDivExpr - Get a canonical unsigned division expression, or something
1864 /// simpler if possible.
1865 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1867 assert(getEffectiveSCEVType(LHS->getType()) ==
1868 getEffectiveSCEVType(RHS->getType()) &&
1869 "SCEVUDivExpr operand types don't match!");
1871 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1872 if (RHSC->getValue()->equalsInt(1))
1873 return LHS; // X udiv 1 --> x
1874 // If the denominator is zero, the result of the udiv is undefined. Don't
1875 // try to analyze it, because the resolution chosen here may differ from
1876 // the resolution chosen in other parts of the compiler.
1877 if (!RHSC->getValue()->isZero()) {
1878 // Determine if the division can be folded into the operands of
1880 // TODO: Generalize this to non-constants by using known-bits information.
1881 const Type *Ty = LHS->getType();
1882 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1883 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
1884 // For non-power-of-two values, effectively round the value up to the
1885 // nearest power of two.
1886 if (!RHSC->getValue()->getValue().isPowerOf2())
1888 const IntegerType *ExtTy =
1889 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
1890 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1891 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1892 if (const SCEVConstant *Step =
1893 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1894 if (!Step->getValue()->getValue()
1895 .urem(RHSC->getValue()->getValue()) &&
1896 getZeroExtendExpr(AR, ExtTy) ==
1897 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1898 getZeroExtendExpr(Step, ExtTy),
1900 SmallVector<const SCEV *, 4> Operands;
1901 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1902 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1903 return getAddRecExpr(Operands, AR->getLoop());
1905 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1906 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1907 SmallVector<const SCEV *, 4> Operands;
1908 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1909 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1910 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
1911 // Find an operand that's safely divisible.
1912 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1913 const SCEV *Op = M->getOperand(i);
1914 const SCEV *Div = getUDivExpr(Op, RHSC);
1915 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1916 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
1919 return getMulExpr(Operands);
1923 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
1924 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1925 SmallVector<const SCEV *, 4> Operands;
1926 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1927 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1928 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1930 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1931 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
1932 if (isa<SCEVUDivExpr>(Op) ||
1933 getMulExpr(Op, RHS) != A->getOperand(i))
1935 Operands.push_back(Op);
1937 if (Operands.size() == A->getNumOperands())
1938 return getAddExpr(Operands);
1942 // Fold if both operands are constant.
1943 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1944 Constant *LHSCV = LHSC->getValue();
1945 Constant *RHSCV = RHSC->getValue();
1946 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1952 FoldingSetNodeID ID;
1953 ID.AddInteger(scUDivExpr);
1957 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1958 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
1960 UniqueSCEVs.InsertNode(S, IP);
1965 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1966 /// Simplify the expression as much as possible.
1967 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
1968 const SCEV *Step, const Loop *L,
1969 bool HasNUW, bool HasNSW) {
1970 SmallVector<const SCEV *, 4> Operands;
1971 Operands.push_back(Start);
1972 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1973 if (StepChrec->getLoop() == L) {
1974 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
1975 return getAddRecExpr(Operands, L);
1978 Operands.push_back(Step);
1979 return getAddRecExpr(Operands, L, HasNUW, HasNSW);
1982 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1983 /// Simplify the expression as much as possible.
1985 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
1987 bool HasNUW, bool HasNSW) {
1988 if (Operands.size() == 1) return Operands[0];
1990 const Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
1991 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1992 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
1993 "SCEVAddRecExpr operand types don't match!");
1996 if (Operands.back()->isZero()) {
1997 Operands.pop_back();
1998 return getAddRecExpr(Operands, L, HasNUW, HasNSW); // {X,+,0} --> X
2001 // It's tempting to want to call getMaxBackedgeTakenCount count here and
2002 // use that information to infer NUW and NSW flags. However, computing a
2003 // BE count requires calling getAddRecExpr, so we may not yet have a
2004 // meaningful BE count at this point (and if we don't, we'd be stuck
2005 // with a SCEVCouldNotCompute as the cached BE count).
2007 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
2008 if (!HasNUW && HasNSW) {
2010 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2011 if (!isKnownNonNegative(Operands[i])) {
2015 if (All) HasNUW = true;
2018 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
2019 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
2020 const Loop *NestedLoop = NestedAR->getLoop();
2021 if (L->contains(NestedLoop) ?
2022 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
2023 (!NestedLoop->contains(L) &&
2024 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
2025 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
2026 NestedAR->op_end());
2027 Operands[0] = NestedAR->getStart();
2028 // AddRecs require their operands be loop-invariant with respect to their
2029 // loops. Don't perform this transformation if it would break this
2031 bool AllInvariant = true;
2032 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2033 if (!Operands[i]->isLoopInvariant(L)) {
2034 AllInvariant = false;
2038 NestedOperands[0] = getAddRecExpr(Operands, L);
2039 AllInvariant = true;
2040 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
2041 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
2042 AllInvariant = false;
2046 // Ok, both add recurrences are valid after the transformation.
2047 return getAddRecExpr(NestedOperands, NestedLoop, HasNUW, HasNSW);
2049 // Reset Operands to its original state.
2050 Operands[0] = NestedAR;
2054 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2055 // already have one, otherwise create a new one.
2056 FoldingSetNodeID ID;
2057 ID.AddInteger(scAddRecExpr);
2058 ID.AddInteger(Operands.size());
2059 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2060 ID.AddPointer(Operands[i]);
2064 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2066 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2067 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
2068 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2069 O, Operands.size(), L);
2070 UniqueSCEVs.InsertNode(S, IP);
2072 if (HasNUW) S->setHasNoUnsignedWrap(true);
2073 if (HasNSW) S->setHasNoSignedWrap(true);
2077 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2079 SmallVector<const SCEV *, 2> Ops;
2082 return getSMaxExpr(Ops);
2086 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2087 assert(!Ops.empty() && "Cannot get empty smax!");
2088 if (Ops.size() == 1) return Ops[0];
2090 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2091 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2092 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2093 "SCEVSMaxExpr operand types don't match!");
2096 // Sort by complexity, this groups all similar expression types together.
2097 GroupByComplexity(Ops, LI);
2099 // If there are any constants, fold them together.
2101 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2103 assert(Idx < Ops.size());
2104 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2105 // We found two constants, fold them together!
2106 ConstantInt *Fold = ConstantInt::get(getContext(),
2107 APIntOps::smax(LHSC->getValue()->getValue(),
2108 RHSC->getValue()->getValue()));
2109 Ops[0] = getConstant(Fold);
2110 Ops.erase(Ops.begin()+1); // Erase the folded element
2111 if (Ops.size() == 1) return Ops[0];
2112 LHSC = cast<SCEVConstant>(Ops[0]);
2115 // If we are left with a constant minimum-int, strip it off.
2116 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2117 Ops.erase(Ops.begin());
2119 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2120 // If we have an smax with a constant maximum-int, it will always be
2125 if (Ops.size() == 1) return Ops[0];
2128 // Find the first SMax
2129 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2132 // Check to see if one of the operands is an SMax. If so, expand its operands
2133 // onto our operand list, and recurse to simplify.
2134 if (Idx < Ops.size()) {
2135 bool DeletedSMax = false;
2136 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
2137 Ops.erase(Ops.begin()+Idx);
2138 Ops.append(SMax->op_begin(), SMax->op_end());
2143 return getSMaxExpr(Ops);
2146 // Okay, check to see if the same value occurs in the operand list twice. If
2147 // so, delete one. Since we sorted the list, these values are required to
2149 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2150 // X smax Y smax Y --> X smax Y
2151 // X smax Y --> X, if X is always greater than Y
2152 if (Ops[i] == Ops[i+1] ||
2153 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
2154 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2156 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
2157 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2161 if (Ops.size() == 1) return Ops[0];
2163 assert(!Ops.empty() && "Reduced smax down to nothing!");
2165 // Okay, it looks like we really DO need an smax expr. Check to see if we
2166 // already have one, otherwise create a new one.
2167 FoldingSetNodeID ID;
2168 ID.AddInteger(scSMaxExpr);
2169 ID.AddInteger(Ops.size());
2170 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2171 ID.AddPointer(Ops[i]);
2173 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2174 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2175 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2176 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
2178 UniqueSCEVs.InsertNode(S, IP);
2182 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2184 SmallVector<const SCEV *, 2> Ops;
2187 return getUMaxExpr(Ops);
2191 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2192 assert(!Ops.empty() && "Cannot get empty umax!");
2193 if (Ops.size() == 1) return Ops[0];
2195 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2196 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2197 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2198 "SCEVUMaxExpr operand types don't match!");
2201 // Sort by complexity, this groups all similar expression types together.
2202 GroupByComplexity(Ops, LI);
2204 // If there are any constants, fold them together.
2206 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2208 assert(Idx < Ops.size());
2209 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2210 // We found two constants, fold them together!
2211 ConstantInt *Fold = ConstantInt::get(getContext(),
2212 APIntOps::umax(LHSC->getValue()->getValue(),
2213 RHSC->getValue()->getValue()));
2214 Ops[0] = getConstant(Fold);
2215 Ops.erase(Ops.begin()+1); // Erase the folded element
2216 if (Ops.size() == 1) return Ops[0];
2217 LHSC = cast<SCEVConstant>(Ops[0]);
2220 // If we are left with a constant minimum-int, strip it off.
2221 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2222 Ops.erase(Ops.begin());
2224 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2225 // If we have an umax with a constant maximum-int, it will always be
2230 if (Ops.size() == 1) return Ops[0];
2233 // Find the first UMax
2234 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2237 // Check to see if one of the operands is a UMax. If so, expand its operands
2238 // onto our operand list, and recurse to simplify.
2239 if (Idx < Ops.size()) {
2240 bool DeletedUMax = false;
2241 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
2242 Ops.erase(Ops.begin()+Idx);
2243 Ops.append(UMax->op_begin(), UMax->op_end());
2248 return getUMaxExpr(Ops);
2251 // Okay, check to see if the same value occurs in the operand list twice. If
2252 // so, delete one. Since we sorted the list, these values are required to
2254 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2255 // X umax Y umax Y --> X umax Y
2256 // X umax Y --> X, if X is always greater than Y
2257 if (Ops[i] == Ops[i+1] ||
2258 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
2259 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2261 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
2262 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2266 if (Ops.size() == 1) return Ops[0];
2268 assert(!Ops.empty() && "Reduced umax down to nothing!");
2270 // Okay, it looks like we really DO need a umax expr. Check to see if we
2271 // already have one, otherwise create a new one.
2272 FoldingSetNodeID ID;
2273 ID.AddInteger(scUMaxExpr);
2274 ID.AddInteger(Ops.size());
2275 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2276 ID.AddPointer(Ops[i]);
2278 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2279 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2280 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2281 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
2283 UniqueSCEVs.InsertNode(S, IP);
2287 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2289 // ~smax(~x, ~y) == smin(x, y).
2290 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2293 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2295 // ~umax(~x, ~y) == umin(x, y)
2296 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2299 const SCEV *ScalarEvolution::getSizeOfExpr(const Type *AllocTy) {
2300 // If we have TargetData, we can bypass creating a target-independent
2301 // constant expression and then folding it back into a ConstantInt.
2302 // This is just a compile-time optimization.
2304 return getConstant(TD->getIntPtrType(getContext()),
2305 TD->getTypeAllocSize(AllocTy));
2307 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2308 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2309 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2311 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2312 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2315 const SCEV *ScalarEvolution::getAlignOfExpr(const Type *AllocTy) {
2316 Constant *C = ConstantExpr::getAlignOf(AllocTy);
2317 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2318 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2320 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2321 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2324 const SCEV *ScalarEvolution::getOffsetOfExpr(const StructType *STy,
2326 // If we have TargetData, we can bypass creating a target-independent
2327 // constant expression and then folding it back into a ConstantInt.
2328 // This is just a compile-time optimization.
2330 return getConstant(TD->getIntPtrType(getContext()),
2331 TD->getStructLayout(STy)->getElementOffset(FieldNo));
2333 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2334 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2335 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2337 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
2338 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2341 const SCEV *ScalarEvolution::getOffsetOfExpr(const Type *CTy,
2342 Constant *FieldNo) {
2343 Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
2344 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2345 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2347 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
2348 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2351 const SCEV *ScalarEvolution::getUnknown(Value *V) {
2352 // Don't attempt to do anything other than create a SCEVUnknown object
2353 // here. createSCEV only calls getUnknown after checking for all other
2354 // interesting possibilities, and any other code that calls getUnknown
2355 // is doing so in order to hide a value from SCEV canonicalization.
2357 FoldingSetNodeID ID;
2358 ID.AddInteger(scUnknown);
2361 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
2362 assert(cast<SCEVUnknown>(S)->getValue() == V &&
2363 "Stale SCEVUnknown in uniquing map!");
2366 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
2368 FirstUnknown = cast<SCEVUnknown>(S);
2369 UniqueSCEVs.InsertNode(S, IP);
2373 //===----------------------------------------------------------------------===//
2374 // Basic SCEV Analysis and PHI Idiom Recognition Code
2377 /// isSCEVable - Test if values of the given type are analyzable within
2378 /// the SCEV framework. This primarily includes integer types, and it
2379 /// can optionally include pointer types if the ScalarEvolution class
2380 /// has access to target-specific information.
2381 bool ScalarEvolution::isSCEVable(const Type *Ty) const {
2382 // Integers and pointers are always SCEVable.
2383 return Ty->isIntegerTy() || Ty->isPointerTy();
2386 /// getTypeSizeInBits - Return the size in bits of the specified type,
2387 /// for which isSCEVable must return true.
2388 uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
2389 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2391 // If we have a TargetData, use it!
2393 return TD->getTypeSizeInBits(Ty);
2395 // Integer types have fixed sizes.
2396 if (Ty->isIntegerTy())
2397 return Ty->getPrimitiveSizeInBits();
2399 // The only other support type is pointer. Without TargetData, conservatively
2400 // assume pointers are 64-bit.
2401 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
2405 /// getEffectiveSCEVType - Return a type with the same bitwidth as
2406 /// the given type and which represents how SCEV will treat the given
2407 /// type, for which isSCEVable must return true. For pointer types,
2408 /// this is the pointer-sized integer type.
2409 const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
2410 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2412 if (Ty->isIntegerTy())
2415 // The only other support type is pointer.
2416 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
2417 if (TD) return TD->getIntPtrType(getContext());
2419 // Without TargetData, conservatively assume pointers are 64-bit.
2420 return Type::getInt64Ty(getContext());
2423 const SCEV *ScalarEvolution::getCouldNotCompute() {
2424 return &CouldNotCompute;
2427 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2428 /// expression and create a new one.
2429 const SCEV *ScalarEvolution::getSCEV(Value *V) {
2430 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
2432 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
2433 if (I != Scalars.end()) return I->second;
2434 const SCEV *S = createSCEV(V);
2435 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
2439 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2441 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
2442 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2444 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
2446 const Type *Ty = V->getType();
2447 Ty = getEffectiveSCEVType(Ty);
2448 return getMulExpr(V,
2449 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
2452 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
2453 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
2454 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2456 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
2458 const Type *Ty = V->getType();
2459 Ty = getEffectiveSCEVType(Ty);
2460 const SCEV *AllOnes =
2461 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
2462 return getMinusSCEV(AllOnes, V);
2465 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2467 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2469 // Fast path: X - X --> 0.
2471 return getConstant(LHS->getType(), 0);
2474 return getAddExpr(LHS, getNegativeSCEV(RHS));
2477 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2478 /// input value to the specified type. If the type must be extended, it is zero
2481 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
2483 const Type *SrcTy = V->getType();
2484 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2485 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2486 "Cannot truncate or zero extend with non-integer arguments!");
2487 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2488 return V; // No conversion
2489 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2490 return getTruncateExpr(V, Ty);
2491 return getZeroExtendExpr(V, Ty);
2494 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2495 /// input value to the specified type. If the type must be extended, it is sign
2498 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
2500 const Type *SrcTy = V->getType();
2501 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2502 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2503 "Cannot truncate or zero extend with non-integer arguments!");
2504 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2505 return V; // No conversion
2506 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2507 return getTruncateExpr(V, Ty);
2508 return getSignExtendExpr(V, Ty);
2511 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2512 /// input value to the specified type. If the type must be extended, it is zero
2513 /// extended. The conversion must not be narrowing.
2515 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
2516 const Type *SrcTy = V->getType();
2517 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2518 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2519 "Cannot noop or zero extend with non-integer arguments!");
2520 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2521 "getNoopOrZeroExtend cannot truncate!");
2522 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2523 return V; // No conversion
2524 return getZeroExtendExpr(V, Ty);
2527 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2528 /// input value to the specified type. If the type must be extended, it is sign
2529 /// extended. The conversion must not be narrowing.
2531 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
2532 const Type *SrcTy = V->getType();
2533 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2534 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2535 "Cannot noop or sign extend with non-integer arguments!");
2536 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2537 "getNoopOrSignExtend cannot truncate!");
2538 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2539 return V; // No conversion
2540 return getSignExtendExpr(V, Ty);
2543 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2544 /// the input value to the specified type. If the type must be extended,
2545 /// it is extended with unspecified bits. The conversion must not be
2548 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
2549 const Type *SrcTy = V->getType();
2550 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2551 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2552 "Cannot noop or any extend with non-integer arguments!");
2553 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2554 "getNoopOrAnyExtend cannot truncate!");
2555 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2556 return V; // No conversion
2557 return getAnyExtendExpr(V, Ty);
2560 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2561 /// input value to the specified type. The conversion must not be widening.
2563 ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
2564 const Type *SrcTy = V->getType();
2565 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2566 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2567 "Cannot truncate or noop with non-integer arguments!");
2568 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2569 "getTruncateOrNoop cannot extend!");
2570 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2571 return V; // No conversion
2572 return getTruncateExpr(V, Ty);
2575 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2576 /// the types using zero-extension, and then perform a umax operation
2578 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2580 const SCEV *PromotedLHS = LHS;
2581 const SCEV *PromotedRHS = RHS;
2583 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2584 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2586 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2588 return getUMaxExpr(PromotedLHS, PromotedRHS);
2591 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
2592 /// the types using zero-extension, and then perform a umin operation
2594 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2596 const SCEV *PromotedLHS = LHS;
2597 const SCEV *PromotedRHS = RHS;
2599 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2600 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2602 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2604 return getUMinExpr(PromotedLHS, PromotedRHS);
2607 /// PushDefUseChildren - Push users of the given Instruction
2608 /// onto the given Worklist.
2610 PushDefUseChildren(Instruction *I,
2611 SmallVectorImpl<Instruction *> &Worklist) {
2612 // Push the def-use children onto the Worklist stack.
2613 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2615 Worklist.push_back(cast<Instruction>(*UI));
2618 /// ForgetSymbolicValue - This looks up computed SCEV values for all
2619 /// instructions that depend on the given instruction and removes them from
2620 /// the Scalars map if they reference SymName. This is used during PHI
2623 ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
2624 SmallVector<Instruction *, 16> Worklist;
2625 PushDefUseChildren(PN, Worklist);
2627 SmallPtrSet<Instruction *, 8> Visited;
2629 while (!Worklist.empty()) {
2630 Instruction *I = Worklist.pop_back_val();
2631 if (!Visited.insert(I)) continue;
2633 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
2634 Scalars.find(static_cast<Value *>(I));
2635 if (It != Scalars.end()) {
2636 // Short-circuit the def-use traversal if the symbolic name
2637 // ceases to appear in expressions.
2638 if (It->second != SymName && !It->second->hasOperand(SymName))
2641 // SCEVUnknown for a PHI either means that it has an unrecognized
2642 // structure, it's a PHI that's in the progress of being computed
2643 // by createNodeForPHI, or it's a single-value PHI. In the first case,
2644 // additional loop trip count information isn't going to change anything.
2645 // In the second case, createNodeForPHI will perform the necessary
2646 // updates on its own when it gets to that point. In the third, we do
2647 // want to forget the SCEVUnknown.
2648 if (!isa<PHINode>(I) ||
2649 !isa<SCEVUnknown>(It->second) ||
2650 (I != PN && It->second == SymName)) {
2651 ValuesAtScopes.erase(It->second);
2656 PushDefUseChildren(I, Worklist);
2660 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2661 /// a loop header, making it a potential recurrence, or it doesn't.
2663 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
2664 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2665 if (L->getHeader() == PN->getParent()) {
2666 // The loop may have multiple entrances or multiple exits; we can analyze
2667 // this phi as an addrec if it has a unique entry value and a unique
2669 Value *BEValueV = 0, *StartValueV = 0;
2670 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2671 Value *V = PN->getIncomingValue(i);
2672 if (L->contains(PN->getIncomingBlock(i))) {
2675 } else if (BEValueV != V) {
2679 } else if (!StartValueV) {
2681 } else if (StartValueV != V) {
2686 if (BEValueV && StartValueV) {
2687 // While we are analyzing this PHI node, handle its value symbolically.
2688 const SCEV *SymbolicName = getUnknown(PN);
2689 assert(Scalars.find(PN) == Scalars.end() &&
2690 "PHI node already processed?");
2691 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
2693 // Using this symbolic name for the PHI, analyze the value coming around
2695 const SCEV *BEValue = getSCEV(BEValueV);
2697 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2698 // has a special value for the first iteration of the loop.
2700 // If the value coming around the backedge is an add with the symbolic
2701 // value we just inserted, then we found a simple induction variable!
2702 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
2703 // If there is a single occurrence of the symbolic value, replace it
2704 // with a recurrence.
2705 unsigned FoundIndex = Add->getNumOperands();
2706 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2707 if (Add->getOperand(i) == SymbolicName)
2708 if (FoundIndex == e) {
2713 if (FoundIndex != Add->getNumOperands()) {
2714 // Create an add with everything but the specified operand.
2715 SmallVector<const SCEV *, 8> Ops;
2716 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2717 if (i != FoundIndex)
2718 Ops.push_back(Add->getOperand(i));
2719 const SCEV *Accum = getAddExpr(Ops);
2721 // This is not a valid addrec if the step amount is varying each
2722 // loop iteration, but is not itself an addrec in this loop.
2723 if (Accum->isLoopInvariant(L) ||
2724 (isa<SCEVAddRecExpr>(Accum) &&
2725 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
2726 bool HasNUW = false;
2727 bool HasNSW = false;
2729 // If the increment doesn't overflow, then neither the addrec nor
2730 // the post-increment will overflow.
2731 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
2732 if (OBO->hasNoUnsignedWrap())
2734 if (OBO->hasNoSignedWrap())
2738 const SCEV *StartVal = getSCEV(StartValueV);
2739 const SCEV *PHISCEV =
2740 getAddRecExpr(StartVal, Accum, L, HasNUW, HasNSW);
2742 // Since the no-wrap flags are on the increment, they apply to the
2743 // post-incremented value as well.
2744 if (Accum->isLoopInvariant(L))
2745 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
2746 Accum, L, HasNUW, HasNSW);
2748 // Okay, for the entire analysis of this edge we assumed the PHI
2749 // to be symbolic. We now need to go back and purge all of the
2750 // entries for the scalars that use the symbolic expression.
2751 ForgetSymbolicName(PN, SymbolicName);
2752 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
2756 } else if (const SCEVAddRecExpr *AddRec =
2757 dyn_cast<SCEVAddRecExpr>(BEValue)) {
2758 // Otherwise, this could be a loop like this:
2759 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2760 // In this case, j = {1,+,1} and BEValue is j.
2761 // Because the other in-value of i (0) fits the evolution of BEValue
2762 // i really is an addrec evolution.
2763 if (AddRec->getLoop() == L && AddRec->isAffine()) {
2764 const SCEV *StartVal = getSCEV(StartValueV);
2766 // If StartVal = j.start - j.stride, we can use StartVal as the
2767 // initial step of the addrec evolution.
2768 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
2769 AddRec->getOperand(1))) {
2770 const SCEV *PHISCEV =
2771 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
2773 // Okay, for the entire analysis of this edge we assumed the PHI
2774 // to be symbolic. We now need to go back and purge all of the
2775 // entries for the scalars that use the symbolic expression.
2776 ForgetSymbolicName(PN, SymbolicName);
2777 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
2785 // If the PHI has a single incoming value, follow that value, unless the
2786 // PHI's incoming blocks are in a different loop, in which case doing so
2787 // risks breaking LCSSA form. Instcombine would normally zap these, but
2788 // it doesn't have DominatorTree information, so it may miss cases.
2789 if (Value *V = PN->hasConstantValue(DT)) {
2790 bool AllSameLoop = true;
2791 Loop *PNLoop = LI->getLoopFor(PN->getParent());
2792 for (size_t i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2793 if (LI->getLoopFor(PN->getIncomingBlock(i)) != PNLoop) {
2794 AllSameLoop = false;
2801 // If it's not a loop phi, we can't handle it yet.
2802 return getUnknown(PN);
2805 /// createNodeForGEP - Expand GEP instructions into add and multiply
2806 /// operations. This allows them to be analyzed by regular SCEV code.
2808 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
2810 // Don't blindly transfer the inbounds flag from the GEP instruction to the
2811 // Add expression, because the Instruction may be guarded by control flow
2812 // and the no-overflow bits may not be valid for the expression in any
2815 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
2816 Value *Base = GEP->getOperand(0);
2817 // Don't attempt to analyze GEPs over unsized objects.
2818 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2819 return getUnknown(GEP);
2820 const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
2821 gep_type_iterator GTI = gep_type_begin(GEP);
2822 for (GetElementPtrInst::op_iterator I = llvm::next(GEP->op_begin()),
2826 // Compute the (potentially symbolic) offset in bytes for this index.
2827 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2828 // For a struct, add the member offset.
2829 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2830 const SCEV *FieldOffset = getOffsetOfExpr(STy, FieldNo);
2832 // Add the field offset to the running total offset.
2833 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
2835 // For an array, add the element offset, explicitly scaled.
2836 const SCEV *ElementSize = getSizeOfExpr(*GTI);
2837 const SCEV *IndexS = getSCEV(Index);
2838 // Getelementptr indices are signed.
2839 IndexS = getTruncateOrSignExtend(IndexS, IntPtrTy);
2841 // Multiply the index by the element size to compute the element offset.
2842 const SCEV *LocalOffset = getMulExpr(IndexS, ElementSize);
2844 // Add the element offset to the running total offset.
2845 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2849 // Get the SCEV for the GEP base.
2850 const SCEV *BaseS = getSCEV(Base);
2852 // Add the total offset from all the GEP indices to the base.
2853 return getAddExpr(BaseS, TotalOffset);
2856 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2857 /// guaranteed to end in (at every loop iteration). It is, at the same time,
2858 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2859 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
2861 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
2862 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2863 return C->getValue()->getValue().countTrailingZeros();
2865 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
2866 return std::min(GetMinTrailingZeros(T->getOperand()),
2867 (uint32_t)getTypeSizeInBits(T->getType()));
2869 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
2870 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2871 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2872 getTypeSizeInBits(E->getType()) : OpRes;
2875 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
2876 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2877 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2878 getTypeSizeInBits(E->getType()) : OpRes;
2881 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
2882 // The result is the min of all operands results.
2883 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2884 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2885 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2889 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
2890 // The result is the sum of all operands results.
2891 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2892 uint32_t BitWidth = getTypeSizeInBits(M->getType());
2893 for (unsigned i = 1, e = M->getNumOperands();
2894 SumOpRes != BitWidth && i != e; ++i)
2895 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
2900 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
2901 // The result is the min of all operands results.
2902 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2903 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2904 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2908 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
2909 // The result is the min of all operands results.
2910 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2911 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2912 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2916 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
2917 // The result is the min of all operands results.
2918 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2919 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2920 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2924 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2925 // For a SCEVUnknown, ask ValueTracking.
2926 unsigned BitWidth = getTypeSizeInBits(U->getType());
2927 APInt Mask = APInt::getAllOnesValue(BitWidth);
2928 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2929 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2930 return Zeros.countTrailingOnes();
2937 /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2940 ScalarEvolution::getUnsignedRange(const SCEV *S) {
2942 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2943 return ConstantRange(C->getValue()->getValue());
2945 unsigned BitWidth = getTypeSizeInBits(S->getType());
2946 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2948 // If the value has known zeros, the maximum unsigned value will have those
2949 // known zeros as well.
2950 uint32_t TZ = GetMinTrailingZeros(S);
2952 ConservativeResult =
2953 ConstantRange(APInt::getMinValue(BitWidth),
2954 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
2956 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2957 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2958 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2959 X = X.add(getUnsignedRange(Add->getOperand(i)));
2960 return ConservativeResult.intersectWith(X);
2963 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2964 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2965 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2966 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
2967 return ConservativeResult.intersectWith(X);
2970 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2971 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2972 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2973 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
2974 return ConservativeResult.intersectWith(X);
2977 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2978 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2979 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2980 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
2981 return ConservativeResult.intersectWith(X);
2984 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2985 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2986 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
2987 return ConservativeResult.intersectWith(X.udiv(Y));
2990 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2991 ConstantRange X = getUnsignedRange(ZExt->getOperand());
2992 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
2995 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2996 ConstantRange X = getUnsignedRange(SExt->getOperand());
2997 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
3000 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3001 ConstantRange X = getUnsignedRange(Trunc->getOperand());
3002 return ConservativeResult.intersectWith(X.truncate(BitWidth));
3005 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
3006 // If there's no unsigned wrap, the value will never be less than its
3008 if (AddRec->hasNoUnsignedWrap())
3009 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
3010 if (!C->getValue()->isZero())
3011 ConservativeResult =
3012 ConservativeResult.intersectWith(
3013 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0)));
3015 // TODO: non-affine addrec
3016 if (AddRec->isAffine()) {
3017 const Type *Ty = AddRec->getType();
3018 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
3019 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3020 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
3021 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3023 const SCEV *Start = AddRec->getStart();
3024 const SCEV *Step = AddRec->getStepRecurrence(*this);
3026 ConstantRange StartRange = getUnsignedRange(Start);
3027 ConstantRange StepRange = getSignedRange(Step);
3028 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3029 ConstantRange EndRange =
3030 StartRange.add(MaxBECountRange.multiply(StepRange));
3032 // Check for overflow. This must be done with ConstantRange arithmetic
3033 // because we could be called from within the ScalarEvolution overflow
3035 ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
3036 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3037 ConstantRange ExtMaxBECountRange =
3038 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3039 ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
3040 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3042 return ConservativeResult;
3044 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
3045 EndRange.getUnsignedMin());
3046 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
3047 EndRange.getUnsignedMax());
3048 if (Min.isMinValue() && Max.isMaxValue())
3049 return ConservativeResult;
3050 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
3054 return ConservativeResult;
3057 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3058 // For a SCEVUnknown, ask ValueTracking.
3059 APInt Mask = APInt::getAllOnesValue(BitWidth);
3060 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3061 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
3062 if (Ones == ~Zeros + 1)
3063 return ConservativeResult;
3064 return ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
3067 return ConservativeResult;
3070 /// getSignedRange - Determine the signed range for a particular SCEV.
3073 ScalarEvolution::getSignedRange(const SCEV *S) {
3075 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
3076 return ConstantRange(C->getValue()->getValue());
3078 unsigned BitWidth = getTypeSizeInBits(S->getType());
3079 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3081 // If the value has known zeros, the maximum signed value will have those
3082 // known zeros as well.
3083 uint32_t TZ = GetMinTrailingZeros(S);
3085 ConservativeResult =
3086 ConstantRange(APInt::getSignedMinValue(BitWidth),
3087 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
3089 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3090 ConstantRange X = getSignedRange(Add->getOperand(0));
3091 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3092 X = X.add(getSignedRange(Add->getOperand(i)));
3093 return ConservativeResult.intersectWith(X);
3096 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3097 ConstantRange X = getSignedRange(Mul->getOperand(0));
3098 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3099 X = X.multiply(getSignedRange(Mul->getOperand(i)));
3100 return ConservativeResult.intersectWith(X);
3103 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3104 ConstantRange X = getSignedRange(SMax->getOperand(0));
3105 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3106 X = X.smax(getSignedRange(SMax->getOperand(i)));
3107 return ConservativeResult.intersectWith(X);
3110 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3111 ConstantRange X = getSignedRange(UMax->getOperand(0));
3112 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3113 X = X.umax(getSignedRange(UMax->getOperand(i)));
3114 return ConservativeResult.intersectWith(X);
3117 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3118 ConstantRange X = getSignedRange(UDiv->getLHS());
3119 ConstantRange Y = getSignedRange(UDiv->getRHS());
3120 return ConservativeResult.intersectWith(X.udiv(Y));
3123 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3124 ConstantRange X = getSignedRange(ZExt->getOperand());
3125 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
3128 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3129 ConstantRange X = getSignedRange(SExt->getOperand());
3130 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
3133 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3134 ConstantRange X = getSignedRange(Trunc->getOperand());
3135 return ConservativeResult.intersectWith(X.truncate(BitWidth));
3138 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
3139 // If there's no signed wrap, and all the operands have the same sign or
3140 // zero, the value won't ever change sign.
3141 if (AddRec->hasNoSignedWrap()) {
3142 bool AllNonNeg = true;
3143 bool AllNonPos = true;
3144 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3145 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3146 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3149 ConservativeResult = ConservativeResult.intersectWith(
3150 ConstantRange(APInt(BitWidth, 0),
3151 APInt::getSignedMinValue(BitWidth)));
3153 ConservativeResult = ConservativeResult.intersectWith(
3154 ConstantRange(APInt::getSignedMinValue(BitWidth),
3155 APInt(BitWidth, 1)));
3158 // TODO: non-affine addrec
3159 if (AddRec->isAffine()) {
3160 const Type *Ty = AddRec->getType();
3161 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
3162 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3163 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
3164 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3166 const SCEV *Start = AddRec->getStart();
3167 const SCEV *Step = AddRec->getStepRecurrence(*this);
3169 ConstantRange StartRange = getSignedRange(Start);
3170 ConstantRange StepRange = getSignedRange(Step);
3171 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3172 ConstantRange EndRange =
3173 StartRange.add(MaxBECountRange.multiply(StepRange));
3175 // Check for overflow. This must be done with ConstantRange arithmetic
3176 // because we could be called from within the ScalarEvolution overflow
3178 ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
3179 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3180 ConstantRange ExtMaxBECountRange =
3181 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3182 ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
3183 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3185 return ConservativeResult;
3187 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3188 EndRange.getSignedMin());
3189 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3190 EndRange.getSignedMax());
3191 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
3192 return ConservativeResult;
3193 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
3197 return ConservativeResult;
3200 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3201 // For a SCEVUnknown, ask ValueTracking.
3202 if (!U->getValue()->getType()->isIntegerTy() && !TD)
3203 return ConservativeResult;
3204 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3206 return ConservativeResult;
3207 return ConservativeResult.intersectWith(
3208 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
3209 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1));
3212 return ConservativeResult;
3215 /// createSCEV - We know that there is no SCEV for the specified value.
3216 /// Analyze the expression.
3218 const SCEV *ScalarEvolution::createSCEV(Value *V) {
3219 if (!isSCEVable(V->getType()))
3220 return getUnknown(V);
3222 unsigned Opcode = Instruction::UserOp1;
3223 if (Instruction *I = dyn_cast<Instruction>(V)) {
3224 Opcode = I->getOpcode();
3226 // Don't attempt to analyze instructions in blocks that aren't
3227 // reachable. Such instructions don't matter, and they aren't required
3228 // to obey basic rules for definitions dominating uses which this
3229 // analysis depends on.
3230 if (!DT->isReachableFromEntry(I->getParent()))
3231 return getUnknown(V);
3232 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
3233 Opcode = CE->getOpcode();
3234 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3235 return getConstant(CI);
3236 else if (isa<ConstantPointerNull>(V))
3237 return getConstant(V->getType(), 0);
3238 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3239 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
3241 return getUnknown(V);
3243 Operator *U = cast<Operator>(V);
3245 case Instruction::Add: {
3246 // The simple thing to do would be to just call getSCEV on both operands
3247 // and call getAddExpr with the result. However if we're looking at a
3248 // bunch of things all added together, this can be quite inefficient,
3249 // because it leads to N-1 getAddExpr calls for N ultimate operands.
3250 // Instead, gather up all the operands and make a single getAddExpr call.
3251 // LLVM IR canonical form means we need only traverse the left operands.
3252 SmallVector<const SCEV *, 4> AddOps;
3253 AddOps.push_back(getSCEV(U->getOperand(1)));
3254 for (Value *Op = U->getOperand(0);
3255 Op->getValueID() == Instruction::Add + Value::InstructionVal;
3256 Op = U->getOperand(0)) {
3257 U = cast<Operator>(Op);
3258 AddOps.push_back(getSCEV(U->getOperand(1)));
3260 AddOps.push_back(getSCEV(U->getOperand(0)));
3261 return getAddExpr(AddOps);
3263 case Instruction::Mul: {
3264 // See the Add code above.
3265 SmallVector<const SCEV *, 4> MulOps;
3266 MulOps.push_back(getSCEV(U->getOperand(1)));
3267 for (Value *Op = U->getOperand(0);
3268 Op->getValueID() == Instruction::Mul + Value::InstructionVal;
3269 Op = U->getOperand(0)) {
3270 U = cast<Operator>(Op);
3271 MulOps.push_back(getSCEV(U->getOperand(1)));
3273 MulOps.push_back(getSCEV(U->getOperand(0)));
3274 return getMulExpr(MulOps);
3276 case Instruction::UDiv:
3277 return getUDivExpr(getSCEV(U->getOperand(0)),
3278 getSCEV(U->getOperand(1)));
3279 case Instruction::Sub:
3280 return getMinusSCEV(getSCEV(U->getOperand(0)),
3281 getSCEV(U->getOperand(1)));
3282 case Instruction::And:
3283 // For an expression like x&255 that merely masks off the high bits,
3284 // use zext(trunc(x)) as the SCEV expression.
3285 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3286 if (CI->isNullValue())
3287 return getSCEV(U->getOperand(1));
3288 if (CI->isAllOnesValue())
3289 return getSCEV(U->getOperand(0));
3290 const APInt &A = CI->getValue();
3292 // Instcombine's ShrinkDemandedConstant may strip bits out of
3293 // constants, obscuring what would otherwise be a low-bits mask.
3294 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3295 // knew about to reconstruct a low-bits mask value.
3296 unsigned LZ = A.countLeadingZeros();
3297 unsigned BitWidth = A.getBitWidth();
3298 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3299 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3300 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3302 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3304 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
3306 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
3307 IntegerType::get(getContext(), BitWidth - LZ)),
3312 case Instruction::Or:
3313 // If the RHS of the Or is a constant, we may have something like:
3314 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3315 // optimizations will transparently handle this case.
3317 // In order for this transformation to be safe, the LHS must be of the
3318 // form X*(2^n) and the Or constant must be less than 2^n.
3319 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3320 const SCEV *LHS = getSCEV(U->getOperand(0));
3321 const APInt &CIVal = CI->getValue();
3322 if (GetMinTrailingZeros(LHS) >=
3323 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3324 // Build a plain add SCEV.
3325 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3326 // If the LHS of the add was an addrec and it has no-wrap flags,
3327 // transfer the no-wrap flags, since an or won't introduce a wrap.
3328 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3329 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
3330 if (OldAR->hasNoUnsignedWrap())
3331 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoUnsignedWrap(true);
3332 if (OldAR->hasNoSignedWrap())
3333 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoSignedWrap(true);
3339 case Instruction::Xor:
3340 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3341 // If the RHS of the xor is a signbit, then this is just an add.
3342 // Instcombine turns add of signbit into xor as a strength reduction step.
3343 if (CI->getValue().isSignBit())
3344 return getAddExpr(getSCEV(U->getOperand(0)),
3345 getSCEV(U->getOperand(1)));
3347 // If the RHS of xor is -1, then this is a not operation.
3348 if (CI->isAllOnesValue())
3349 return getNotSCEV(getSCEV(U->getOperand(0)));
3351 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3352 // This is a variant of the check for xor with -1, and it handles
3353 // the case where instcombine has trimmed non-demanded bits out
3354 // of an xor with -1.
3355 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3356 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3357 if (BO->getOpcode() == Instruction::And &&
3358 LCI->getValue() == CI->getValue())
3359 if (const SCEVZeroExtendExpr *Z =
3360 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
3361 const Type *UTy = U->getType();
3362 const SCEV *Z0 = Z->getOperand();
3363 const Type *Z0Ty = Z0->getType();
3364 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3366 // If C is a low-bits mask, the zero extend is serving to
3367 // mask off the high bits. Complement the operand and
3368 // re-apply the zext.
3369 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3370 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3372 // If C is a single bit, it may be in the sign-bit position
3373 // before the zero-extend. In this case, represent the xor
3374 // using an add, which is equivalent, and re-apply the zext.
3375 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
3376 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3378 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3384 case Instruction::Shl:
3385 // Turn shift left of a constant amount into a multiply.
3386 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3387 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
3389 // If the shift count is not less than the bitwidth, the result of
3390 // the shift is undefined. Don't try to analyze it, because the
3391 // resolution chosen here may differ from the resolution chosen in
3392 // other parts of the compiler.
3393 if (SA->getValue().uge(BitWidth))
3396 Constant *X = ConstantInt::get(getContext(),
3397 APInt(BitWidth, 1).shl(SA->getZExtValue()));
3398 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3402 case Instruction::LShr:
3403 // Turn logical shift right of a constant into a unsigned divide.
3404 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3405 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
3407 // If the shift count is not less than the bitwidth, the result of
3408 // the shift is undefined. Don't try to analyze it, because the
3409 // resolution chosen here may differ from the resolution chosen in
3410 // other parts of the compiler.
3411 if (SA->getValue().uge(BitWidth))
3414 Constant *X = ConstantInt::get(getContext(),
3415 APInt(BitWidth, 1).shl(SA->getZExtValue()));
3416 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3420 case Instruction::AShr:
3421 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3422 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
3423 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
3424 if (L->getOpcode() == Instruction::Shl &&
3425 L->getOperand(1) == U->getOperand(1)) {
3426 uint64_t BitWidth = getTypeSizeInBits(U->getType());
3428 // If the shift count is not less than the bitwidth, the result of
3429 // the shift is undefined. Don't try to analyze it, because the
3430 // resolution chosen here may differ from the resolution chosen in
3431 // other parts of the compiler.
3432 if (CI->getValue().uge(BitWidth))
3435 uint64_t Amt = BitWidth - CI->getZExtValue();
3436 if (Amt == BitWidth)
3437 return getSCEV(L->getOperand(0)); // shift by zero --> noop
3439 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
3440 IntegerType::get(getContext(),
3446 case Instruction::Trunc:
3447 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
3449 case Instruction::ZExt:
3450 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3452 case Instruction::SExt:
3453 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3455 case Instruction::BitCast:
3456 // BitCasts are no-op casts so we just eliminate the cast.
3457 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
3458 return getSCEV(U->getOperand(0));
3461 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3462 // lead to pointer expressions which cannot safely be expanded to GEPs,
3463 // because ScalarEvolution doesn't respect the GEP aliasing rules when
3464 // simplifying integer expressions.
3466 case Instruction::GetElementPtr:
3467 return createNodeForGEP(cast<GEPOperator>(U));
3469 case Instruction::PHI:
3470 return createNodeForPHI(cast<PHINode>(U));
3472 case Instruction::Select:
3473 // This could be a smax or umax that was lowered earlier.
3474 // Try to recover it.
3475 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3476 Value *LHS = ICI->getOperand(0);
3477 Value *RHS = ICI->getOperand(1);
3478 switch (ICI->getPredicate()) {
3479 case ICmpInst::ICMP_SLT:
3480 case ICmpInst::ICMP_SLE:
3481 std::swap(LHS, RHS);
3483 case ICmpInst::ICMP_SGT:
3484 case ICmpInst::ICMP_SGE:
3485 // a >s b ? a+x : b+x -> smax(a, b)+x
3486 // a >s b ? b+x : a+x -> smin(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(getSMaxExpr(LS, RS), LDiff);
3496 LDiff = getMinusSCEV(LA, RS);
3497 RDiff = getMinusSCEV(RA, LS);
3499 return getAddExpr(getSMinExpr(LS, RS), LDiff);
3502 case ICmpInst::ICMP_ULT:
3503 case ICmpInst::ICMP_ULE:
3504 std::swap(LHS, RHS);
3506 case ICmpInst::ICMP_UGT:
3507 case ICmpInst::ICMP_UGE:
3508 // a >u b ? a+x : b+x -> umax(a, b)+x
3509 // a >u b ? b+x : a+x -> umin(a, b)+x
3510 if (LHS->getType() == U->getType()) {
3511 const SCEV *LS = getSCEV(LHS);
3512 const SCEV *RS = getSCEV(RHS);
3513 const SCEV *LA = getSCEV(U->getOperand(1));
3514 const SCEV *RA = getSCEV(U->getOperand(2));
3515 const SCEV *LDiff = getMinusSCEV(LA, LS);
3516 const SCEV *RDiff = getMinusSCEV(RA, RS);
3518 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
3519 LDiff = getMinusSCEV(LA, RS);
3520 RDiff = getMinusSCEV(RA, LS);
3522 return getAddExpr(getUMinExpr(LS, RS), LDiff);
3525 case ICmpInst::ICMP_NE:
3526 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
3527 if (LHS->getType() == U->getType() &&
3528 isa<ConstantInt>(RHS) &&
3529 cast<ConstantInt>(RHS)->isZero()) {
3530 const SCEV *One = getConstant(LHS->getType(), 1);
3531 const SCEV *LS = getSCEV(LHS);
3532 const SCEV *LA = getSCEV(U->getOperand(1));
3533 const SCEV *RA = getSCEV(U->getOperand(2));
3534 const SCEV *LDiff = getMinusSCEV(LA, LS);
3535 const SCEV *RDiff = getMinusSCEV(RA, One);
3537 return getAddExpr(getUMaxExpr(One, LS), LDiff);
3540 case ICmpInst::ICMP_EQ:
3541 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
3542 if (LHS->getType() == U->getType() &&
3543 isa<ConstantInt>(RHS) &&
3544 cast<ConstantInt>(RHS)->isZero()) {
3545 const SCEV *One = getConstant(LHS->getType(), 1);
3546 const SCEV *LS = getSCEV(LHS);
3547 const SCEV *LA = getSCEV(U->getOperand(1));
3548 const SCEV *RA = getSCEV(U->getOperand(2));
3549 const SCEV *LDiff = getMinusSCEV(LA, One);
3550 const SCEV *RDiff = getMinusSCEV(RA, LS);
3552 return getAddExpr(getUMaxExpr(One, LS), LDiff);
3560 default: // We cannot analyze this expression.
3564 return getUnknown(V);
3569 //===----------------------------------------------------------------------===//
3570 // Iteration Count Computation Code
3573 /// getBackedgeTakenCount - If the specified loop has a predictable
3574 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3575 /// object. The backedge-taken count is the number of times the loop header
3576 /// will be branched to from within the loop. This is one less than the
3577 /// trip count of the loop, since it doesn't count the first iteration,
3578 /// when the header is branched to from outside the loop.
3580 /// Note that it is not valid to call this method on a loop without a
3581 /// loop-invariant backedge-taken count (see
3582 /// hasLoopInvariantBackedgeTakenCount).
3584 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
3585 return getBackedgeTakenInfo(L).Exact;
3588 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3589 /// return the least SCEV value that is known never to be less than the
3590 /// actual backedge taken count.
3591 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
3592 return getBackedgeTakenInfo(L).Max;
3595 /// PushLoopPHIs - Push PHI nodes in the header of the given loop
3596 /// onto the given Worklist.
3598 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3599 BasicBlock *Header = L->getHeader();
3601 // Push all Loop-header PHIs onto the Worklist stack.
3602 for (BasicBlock::iterator I = Header->begin();
3603 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3604 Worklist.push_back(PN);
3607 const ScalarEvolution::BackedgeTakenInfo &
3608 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
3609 // Initially insert a CouldNotCompute for this loop. If the insertion
3610 // succeeds, proceed to actually compute a backedge-taken count and
3611 // update the value. The temporary CouldNotCompute value tells SCEV
3612 // code elsewhere that it shouldn't attempt to request a new
3613 // backedge-taken count, which could result in infinite recursion.
3614 std::pair<std::map<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
3615 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3617 BackedgeTakenInfo BECount = ComputeBackedgeTakenCount(L);
3618 if (BECount.Exact != getCouldNotCompute()) {
3619 assert(BECount.Exact->isLoopInvariant(L) &&
3620 BECount.Max->isLoopInvariant(L) &&
3621 "Computed backedge-taken count isn't loop invariant for loop!");
3622 ++NumTripCountsComputed;
3624 // Update the value in the map.
3625 Pair.first->second = BECount;
3627 if (BECount.Max != getCouldNotCompute())
3628 // Update the value in the map.
3629 Pair.first->second = BECount;
3630 if (isa<PHINode>(L->getHeader()->begin()))
3631 // Only count loops that have phi nodes as not being computable.
3632 ++NumTripCountsNotComputed;
3635 // Now that we know more about the trip count for this loop, forget any
3636 // existing SCEV values for PHI nodes in this loop since they are only
3637 // conservative estimates made without the benefit of trip count
3638 // information. This is similar to the code in forgetLoop, except that
3639 // it handles SCEVUnknown PHI nodes specially.
3640 if (BECount.hasAnyInfo()) {
3641 SmallVector<Instruction *, 16> Worklist;
3642 PushLoopPHIs(L, Worklist);
3644 SmallPtrSet<Instruction *, 8> Visited;
3645 while (!Worklist.empty()) {
3646 Instruction *I = Worklist.pop_back_val();
3647 if (!Visited.insert(I)) continue;
3649 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3650 Scalars.find(static_cast<Value *>(I));
3651 if (It != Scalars.end()) {
3652 // SCEVUnknown for a PHI either means that it has an unrecognized
3653 // structure, or it's a PHI that's in the progress of being computed
3654 // by createNodeForPHI. In the former case, additional loop trip
3655 // count information isn't going to change anything. In the later
3656 // case, createNodeForPHI will perform the necessary updates on its
3657 // own when it gets to that point.
3658 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
3659 ValuesAtScopes.erase(It->second);
3662 if (PHINode *PN = dyn_cast<PHINode>(I))
3663 ConstantEvolutionLoopExitValue.erase(PN);
3666 PushDefUseChildren(I, Worklist);
3670 return Pair.first->second;
3673 /// forgetLoop - This method should be called by the client when it has
3674 /// changed a loop in a way that may effect ScalarEvolution's ability to
3675 /// compute a trip count, or if the loop is deleted.
3676 void ScalarEvolution::forgetLoop(const Loop *L) {
3677 // Drop any stored trip count value.
3678 BackedgeTakenCounts.erase(L);
3680 // Drop information about expressions based on loop-header PHIs.
3681 SmallVector<Instruction *, 16> Worklist;
3682 PushLoopPHIs(L, Worklist);
3684 SmallPtrSet<Instruction *, 8> Visited;
3685 while (!Worklist.empty()) {
3686 Instruction *I = Worklist.pop_back_val();
3687 if (!Visited.insert(I)) continue;
3689 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3690 Scalars.find(static_cast<Value *>(I));
3691 if (It != Scalars.end()) {
3692 ValuesAtScopes.erase(It->second);
3694 if (PHINode *PN = dyn_cast<PHINode>(I))
3695 ConstantEvolutionLoopExitValue.erase(PN);
3698 PushDefUseChildren(I, Worklist);
3702 /// forgetValue - This method should be called by the client when it has
3703 /// changed a value in a way that may effect its value, or which may
3704 /// disconnect it from a def-use chain linking it to a loop.
3705 void ScalarEvolution::forgetValue(Value *V) {
3706 Instruction *I = dyn_cast<Instruction>(V);
3709 // Drop information about expressions based on loop-header PHIs.
3710 SmallVector<Instruction *, 16> Worklist;
3711 Worklist.push_back(I);
3713 SmallPtrSet<Instruction *, 8> Visited;
3714 while (!Worklist.empty()) {
3715 I = Worklist.pop_back_val();
3716 if (!Visited.insert(I)) continue;
3718 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3719 Scalars.find(static_cast<Value *>(I));
3720 if (It != Scalars.end()) {
3721 ValuesAtScopes.erase(It->second);
3723 if (PHINode *PN = dyn_cast<PHINode>(I))
3724 ConstantEvolutionLoopExitValue.erase(PN);
3727 PushDefUseChildren(I, Worklist);
3731 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
3732 /// of the specified loop will execute.
3733 ScalarEvolution::BackedgeTakenInfo
3734 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
3735 SmallVector<BasicBlock *, 8> ExitingBlocks;
3736 L->getExitingBlocks(ExitingBlocks);
3738 // Examine all exits and pick the most conservative values.
3739 const SCEV *BECount = getCouldNotCompute();
3740 const SCEV *MaxBECount = getCouldNotCompute();
3741 bool CouldNotComputeBECount = false;
3742 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3743 BackedgeTakenInfo NewBTI =
3744 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
3746 if (NewBTI.Exact == getCouldNotCompute()) {
3747 // We couldn't compute an exact value for this exit, so
3748 // we won't be able to compute an exact value for the loop.
3749 CouldNotComputeBECount = true;
3750 BECount = getCouldNotCompute();
3751 } else if (!CouldNotComputeBECount) {
3752 if (BECount == getCouldNotCompute())
3753 BECount = NewBTI.Exact;
3755 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
3757 if (MaxBECount == getCouldNotCompute())
3758 MaxBECount = NewBTI.Max;
3759 else if (NewBTI.Max != getCouldNotCompute())
3760 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
3763 return BackedgeTakenInfo(BECount, MaxBECount);
3766 /// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3767 /// of the specified loop will execute if it exits via the specified block.
3768 ScalarEvolution::BackedgeTakenInfo
3769 ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3770 BasicBlock *ExitingBlock) {
3772 // Okay, we've chosen an exiting block. See what condition causes us to
3773 // exit at this block.
3775 // FIXME: we should be able to handle switch instructions (with a single exit)
3776 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
3777 if (ExitBr == 0) return getCouldNotCompute();
3778 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
3780 // At this point, we know we have a conditional branch that determines whether
3781 // the loop is exited. However, we don't know if the branch is executed each
3782 // time through the loop. If not, then the execution count of the branch will
3783 // not be equal to the trip count of the loop.
3785 // Currently we check for this by checking to see if the Exit branch goes to
3786 // the loop header. If so, we know it will always execute the same number of
3787 // times as the loop. We also handle the case where the exit block *is* the
3788 // loop header. This is common for un-rotated loops.
3790 // If both of those tests fail, walk up the unique predecessor chain to the
3791 // header, stopping if there is an edge that doesn't exit the loop. If the
3792 // header is reached, the execution count of the branch will be equal to the
3793 // trip count of the loop.
3795 // More extensive analysis could be done to handle more cases here.
3797 if (ExitBr->getSuccessor(0) != L->getHeader() &&
3798 ExitBr->getSuccessor(1) != L->getHeader() &&
3799 ExitBr->getParent() != L->getHeader()) {
3800 // The simple checks failed, try climbing the unique predecessor chain
3801 // up to the header.
3803 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3804 BasicBlock *Pred = BB->getUniquePredecessor();
3806 return getCouldNotCompute();
3807 TerminatorInst *PredTerm = Pred->getTerminator();
3808 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3809 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3812 // If the predecessor has a successor that isn't BB and isn't
3813 // outside the loop, assume the worst.
3814 if (L->contains(PredSucc))
3815 return getCouldNotCompute();
3817 if (Pred == L->getHeader()) {
3824 return getCouldNotCompute();
3827 // Proceed to the next level to examine the exit condition expression.
3828 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3829 ExitBr->getSuccessor(0),
3830 ExitBr->getSuccessor(1));
3833 /// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3834 /// backedge of the specified loop will execute if its exit condition
3835 /// were a conditional branch of ExitCond, TBB, and FBB.
3836 ScalarEvolution::BackedgeTakenInfo
3837 ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3841 // Check if the controlling expression for this loop is an And or Or.
3842 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3843 if (BO->getOpcode() == Instruction::And) {
3844 // Recurse on the operands of the and.
3845 BackedgeTakenInfo BTI0 =
3846 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3847 BackedgeTakenInfo BTI1 =
3848 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3849 const SCEV *BECount = getCouldNotCompute();
3850 const SCEV *MaxBECount = getCouldNotCompute();
3851 if (L->contains(TBB)) {
3852 // Both conditions must be true for the loop to continue executing.
3853 // Choose the less conservative count.
3854 if (BTI0.Exact == getCouldNotCompute() ||
3855 BTI1.Exact == getCouldNotCompute())
3856 BECount = getCouldNotCompute();
3858 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3859 if (BTI0.Max == getCouldNotCompute())
3860 MaxBECount = BTI1.Max;
3861 else if (BTI1.Max == getCouldNotCompute())
3862 MaxBECount = BTI0.Max;
3864 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3866 // Both conditions must be true at the same time for the loop to exit.
3867 // For now, be conservative.
3868 assert(L->contains(FBB) && "Loop block has no successor in loop!");
3869 if (BTI0.Max == BTI1.Max)
3870 MaxBECount = BTI0.Max;
3871 if (BTI0.Exact == BTI1.Exact)
3872 BECount = BTI0.Exact;
3875 return BackedgeTakenInfo(BECount, MaxBECount);
3877 if (BO->getOpcode() == Instruction::Or) {
3878 // Recurse on the operands of the or.
3879 BackedgeTakenInfo BTI0 =
3880 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3881 BackedgeTakenInfo BTI1 =
3882 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3883 const SCEV *BECount = getCouldNotCompute();
3884 const SCEV *MaxBECount = getCouldNotCompute();
3885 if (L->contains(FBB)) {
3886 // Both conditions must be false for the loop to continue executing.
3887 // Choose the less conservative count.
3888 if (BTI0.Exact == getCouldNotCompute() ||
3889 BTI1.Exact == getCouldNotCompute())
3890 BECount = getCouldNotCompute();
3892 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3893 if (BTI0.Max == getCouldNotCompute())
3894 MaxBECount = BTI1.Max;
3895 else if (BTI1.Max == getCouldNotCompute())
3896 MaxBECount = BTI0.Max;
3898 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3900 // Both conditions must be false at the same time for the loop to exit.
3901 // For now, be conservative.
3902 assert(L->contains(TBB) && "Loop block has no successor in loop!");
3903 if (BTI0.Max == BTI1.Max)
3904 MaxBECount = BTI0.Max;
3905 if (BTI0.Exact == BTI1.Exact)
3906 BECount = BTI0.Exact;
3909 return BackedgeTakenInfo(BECount, MaxBECount);
3913 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3914 // Proceed to the next level to examine the icmp.
3915 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3916 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
3918 // Check for a constant condition. These are normally stripped out by
3919 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
3920 // preserve the CFG and is temporarily leaving constant conditions
3922 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
3923 if (L->contains(FBB) == !CI->getZExtValue())
3924 // The backedge is always taken.
3925 return getCouldNotCompute();
3927 // The backedge is never taken.
3928 return getConstant(CI->getType(), 0);
3931 // If it's not an integer or pointer comparison then compute it the hard way.
3932 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3935 /// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3936 /// backedge of the specified loop will execute if its exit condition
3937 /// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3938 ScalarEvolution::BackedgeTakenInfo
3939 ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3944 // If the condition was exit on true, convert the condition to exit on false
3945 ICmpInst::Predicate Cond;
3946 if (!L->contains(FBB))
3947 Cond = ExitCond->getPredicate();
3949 Cond = ExitCond->getInversePredicate();
3951 // Handle common loops like: for (X = "string"; *X; ++X)
3952 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3953 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
3954 BackedgeTakenInfo ItCnt =
3955 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
3956 if (ItCnt.hasAnyInfo())
3960 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3961 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
3963 // Try to evaluate any dependencies out of the loop.
3964 LHS = getSCEVAtScope(LHS, L);
3965 RHS = getSCEVAtScope(RHS, L);
3967 // At this point, we would like to compute how many iterations of the
3968 // loop the predicate will return true for these inputs.
3969 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3970 // If there is a loop-invariant, force it into the RHS.
3971 std::swap(LHS, RHS);
3972 Cond = ICmpInst::getSwappedPredicate(Cond);
3975 // Simplify the operands before analyzing them.
3976 (void)SimplifyICmpOperands(Cond, LHS, RHS);
3978 // If we have a comparison of a chrec against a constant, try to use value
3979 // ranges to answer this query.
3980 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3981 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
3982 if (AddRec->getLoop() == L) {
3983 // Form the constant range.
3984 ConstantRange CompRange(
3985 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
3987 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
3988 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
3992 case ICmpInst::ICMP_NE: { // while (X != Y)
3993 // Convert to: while (X-Y != 0)
3994 BackedgeTakenInfo BTI = HowFarToZero(getMinusSCEV(LHS, RHS), L);
3995 if (BTI.hasAnyInfo()) return BTI;
3998 case ICmpInst::ICMP_EQ: { // while (X == Y)
3999 // Convert to: while (X-Y == 0)
4000 BackedgeTakenInfo BTI = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
4001 if (BTI.hasAnyInfo()) return BTI;
4004 case ICmpInst::ICMP_SLT: {
4005 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
4006 if (BTI.hasAnyInfo()) return BTI;
4009 case ICmpInst::ICMP_SGT: {
4010 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
4011 getNotSCEV(RHS), L, true);
4012 if (BTI.hasAnyInfo()) return BTI;
4015 case ICmpInst::ICMP_ULT: {
4016 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
4017 if (BTI.hasAnyInfo()) return BTI;
4020 case ICmpInst::ICMP_UGT: {
4021 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
4022 getNotSCEV(RHS), L, false);
4023 if (BTI.hasAnyInfo()) return BTI;
4028 dbgs() << "ComputeBackedgeTakenCount ";
4029 if (ExitCond->getOperand(0)->getType()->isUnsigned())
4030 dbgs() << "[unsigned] ";
4031 dbgs() << *LHS << " "
4032 << Instruction::getOpcodeName(Instruction::ICmp)
4033 << " " << *RHS << "\n";
4038 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
4041 static ConstantInt *
4042 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
4043 ScalarEvolution &SE) {
4044 const SCEV *InVal = SE.getConstant(C);
4045 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
4046 assert(isa<SCEVConstant>(Val) &&
4047 "Evaluation of SCEV at constant didn't fold correctly?");
4048 return cast<SCEVConstant>(Val)->getValue();
4051 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
4052 /// and a GEP expression (missing the pointer index) indexing into it, return
4053 /// the addressed element of the initializer or null if the index expression is
4056 GetAddressedElementFromGlobal(GlobalVariable *GV,
4057 const std::vector<ConstantInt*> &Indices) {
4058 Constant *Init = GV->getInitializer();
4059 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
4060 uint64_t Idx = Indices[i]->getZExtValue();
4061 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
4062 assert(Idx < CS->getNumOperands() && "Bad struct index!");
4063 Init = cast<Constant>(CS->getOperand(Idx));
4064 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
4065 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
4066 Init = cast<Constant>(CA->getOperand(Idx));
4067 } else if (isa<ConstantAggregateZero>(Init)) {
4068 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
4069 assert(Idx < STy->getNumElements() && "Bad struct index!");
4070 Init = Constant::getNullValue(STy->getElementType(Idx));
4071 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
4072 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
4073 Init = Constant::getNullValue(ATy->getElementType());
4075 llvm_unreachable("Unknown constant aggregate type!");
4079 return 0; // Unknown initializer type
4085 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
4086 /// 'icmp op load X, cst', try to see if we can compute the backedge
4087 /// execution count.
4088 ScalarEvolution::BackedgeTakenInfo
4089 ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
4093 ICmpInst::Predicate predicate) {
4094 if (LI->isVolatile()) return getCouldNotCompute();
4096 // Check to see if the loaded pointer is a getelementptr of a global.
4097 // TODO: Use SCEV instead of manually grubbing with GEPs.
4098 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
4099 if (!GEP) return getCouldNotCompute();
4101 // Make sure that it is really a constant global we are gepping, with an
4102 // initializer, and make sure the first IDX is really 0.
4103 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
4104 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
4105 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
4106 !cast<Constant>(GEP->getOperand(1))->isNullValue())
4107 return getCouldNotCompute();
4109 // Okay, we allow one non-constant index into the GEP instruction.
4111 std::vector<ConstantInt*> Indexes;
4112 unsigned VarIdxNum = 0;
4113 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
4114 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4115 Indexes.push_back(CI);
4116 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
4117 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
4118 VarIdx = GEP->getOperand(i);
4120 Indexes.push_back(0);
4123 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
4124 // Check to see if X is a loop variant variable value now.
4125 const SCEV *Idx = getSCEV(VarIdx);
4126 Idx = getSCEVAtScope(Idx, L);
4128 // We can only recognize very limited forms of loop index expressions, in
4129 // particular, only affine AddRec's like {C1,+,C2}.
4130 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
4131 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
4132 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
4133 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
4134 return getCouldNotCompute();
4136 unsigned MaxSteps = MaxBruteForceIterations;
4137 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
4138 ConstantInt *ItCst = ConstantInt::get(
4139 cast<IntegerType>(IdxExpr->getType()), IterationNum);
4140 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
4142 // Form the GEP offset.
4143 Indexes[VarIdxNum] = Val;
4145 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
4146 if (Result == 0) break; // Cannot compute!
4148 // Evaluate the condition for this iteration.
4149 Result = ConstantExpr::getICmp(predicate, Result, RHS);
4150 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
4151 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
4153 dbgs() << "\n***\n*** Computed loop count " << *ItCst
4154 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
4157 ++NumArrayLenItCounts;
4158 return getConstant(ItCst); // Found terminating iteration!
4161 return getCouldNotCompute();
4165 /// CanConstantFold - Return true if we can constant fold an instruction of the
4166 /// specified type, assuming that all operands were constants.
4167 static bool CanConstantFold(const Instruction *I) {
4168 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
4169 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
4172 if (const CallInst *CI = dyn_cast<CallInst>(I))
4173 if (const Function *F = CI->getCalledFunction())
4174 return canConstantFoldCallTo(F);
4178 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
4179 /// in the loop that V is derived from. We allow arbitrary operations along the
4180 /// way, but the operands of an operation must either be constants or a value
4181 /// derived from a constant PHI. If this expression does not fit with these
4182 /// constraints, return null.
4183 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
4184 // If this is not an instruction, or if this is an instruction outside of the
4185 // loop, it can't be derived from a loop PHI.
4186 Instruction *I = dyn_cast<Instruction>(V);
4187 if (I == 0 || !L->contains(I)) return 0;
4189 if (PHINode *PN = dyn_cast<PHINode>(I)) {
4190 if (L->getHeader() == I->getParent())
4193 // We don't currently keep track of the control flow needed to evaluate
4194 // PHIs, so we cannot handle PHIs inside of loops.
4198 // If we won't be able to constant fold this expression even if the operands
4199 // are constants, return early.
4200 if (!CanConstantFold(I)) return 0;
4202 // Otherwise, we can evaluate this instruction if all of its operands are
4203 // constant or derived from a PHI node themselves.
4205 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
4206 if (!isa<Constant>(I->getOperand(Op))) {
4207 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
4208 if (P == 0) return 0; // Not evolving from PHI
4212 return 0; // Evolving from multiple different PHIs.
4215 // This is a expression evolving from a constant PHI!
4219 /// EvaluateExpression - Given an expression that passes the
4220 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
4221 /// in the loop has the value PHIVal. If we can't fold this expression for some
4222 /// reason, return null.
4223 static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
4224 const TargetData *TD) {
4225 if (isa<PHINode>(V)) return PHIVal;
4226 if (Constant *C = dyn_cast<Constant>(V)) return C;
4227 Instruction *I = cast<Instruction>(V);
4229 std::vector<Constant*> Operands(I->getNumOperands());
4231 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4232 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
4233 if (Operands[i] == 0) return 0;
4236 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4237 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
4239 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4240 &Operands[0], Operands.size(), TD);
4243 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
4244 /// in the header of its containing loop, we know the loop executes a
4245 /// constant number of times, and the PHI node is just a recurrence
4246 /// involving constants, fold it.
4248 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
4251 std::map<PHINode*, Constant*>::iterator I =
4252 ConstantEvolutionLoopExitValue.find(PN);
4253 if (I != ConstantEvolutionLoopExitValue.end())
4256 if (BEs.ugt(MaxBruteForceIterations))
4257 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
4259 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
4261 // Since the loop is canonicalized, the PHI node must have two entries. One
4262 // entry must be a constant (coming in from outside of the loop), and the
4263 // second must be derived from the same PHI.
4264 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4265 Constant *StartCST =
4266 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4268 return RetVal = 0; // Must be a constant.
4270 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4271 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4272 !isa<Constant>(BEValue))
4273 return RetVal = 0; // Not derived from same PHI.
4275 // Execute the loop symbolically to determine the exit value.
4276 if (BEs.getActiveBits() >= 32)
4277 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
4279 unsigned NumIterations = BEs.getZExtValue(); // must be in range
4280 unsigned IterationNum = 0;
4281 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
4282 if (IterationNum == NumIterations)
4283 return RetVal = PHIVal; // Got exit value!
4285 // Compute the value of the PHI node for the next iteration.
4286 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
4287 if (NextPHI == PHIVal)
4288 return RetVal = NextPHI; // Stopped evolving!
4290 return 0; // Couldn't evaluate!
4295 /// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
4296 /// constant number of times (the condition evolves only from constants),
4297 /// try to evaluate a few iterations of the loop until we get the exit
4298 /// condition gets a value of ExitWhen (true or false). If we cannot
4299 /// evaluate the trip count of the loop, return getCouldNotCompute().
4301 ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
4304 PHINode *PN = getConstantEvolvingPHI(Cond, L);
4305 if (PN == 0) return getCouldNotCompute();
4307 // If the loop is canonicalized, the PHI will have exactly two entries.
4308 // That's the only form we support here.
4309 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
4311 // One entry must be a constant (coming in from outside of the loop), and the
4312 // second must be derived from the same PHI.
4313 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4314 Constant *StartCST =
4315 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4316 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
4318 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4319 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4320 !isa<Constant>(BEValue))
4321 return getCouldNotCompute(); // Not derived from same PHI.
4323 // Okay, we find a PHI node that defines the trip count of this loop. Execute
4324 // the loop symbolically to determine when the condition gets a value of
4326 unsigned IterationNum = 0;
4327 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
4328 for (Constant *PHIVal = StartCST;
4329 IterationNum != MaxIterations; ++IterationNum) {
4330 ConstantInt *CondVal =
4331 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
4333 // Couldn't symbolically evaluate.
4334 if (!CondVal) return getCouldNotCompute();
4336 if (CondVal->getValue() == uint64_t(ExitWhen)) {
4337 ++NumBruteForceTripCountsComputed;
4338 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
4341 // Compute the value of the PHI node for the next iteration.
4342 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
4343 if (NextPHI == 0 || NextPHI == PHIVal)
4344 return getCouldNotCompute();// Couldn't evaluate or not making progress...
4348 // Too many iterations were needed to evaluate.
4349 return getCouldNotCompute();
4352 /// getSCEVAtScope - Return a SCEV expression for the specified value
4353 /// at the specified scope in the program. The L value specifies a loop
4354 /// nest to evaluate the expression at, where null is the top-level or a
4355 /// specified loop is immediately inside of the loop.
4357 /// This method can be used to compute the exit value for a variable defined
4358 /// in a loop by querying what the value will hold in the parent loop.
4360 /// In the case that a relevant loop exit value cannot be computed, the
4361 /// original value V is returned.
4362 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
4363 // Check to see if we've folded this expression at this loop before.
4364 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4365 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4366 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4368 return Pair.first->second ? Pair.first->second : V;
4370 // Otherwise compute it.
4371 const SCEV *C = computeSCEVAtScope(V, L);
4372 ValuesAtScopes[V][L] = C;
4376 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
4377 if (isa<SCEVConstant>(V)) return V;
4379 // If this instruction is evolved from a constant-evolving PHI, compute the
4380 // exit value from the loop without using SCEVs.
4381 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
4382 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
4383 const Loop *LI = (*this->LI)[I->getParent()];
4384 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
4385 if (PHINode *PN = dyn_cast<PHINode>(I))
4386 if (PN->getParent() == LI->getHeader()) {
4387 // Okay, there is no closed form solution for the PHI node. Check
4388 // to see if the loop that contains it has a known backedge-taken
4389 // count. If so, we may be able to force computation of the exit
4391 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
4392 if (const SCEVConstant *BTCC =
4393 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
4394 // Okay, we know how many times the containing loop executes. If
4395 // this is a constant evolving PHI node, get the final value at
4396 // the specified iteration number.
4397 Constant *RV = getConstantEvolutionLoopExitValue(PN,
4398 BTCC->getValue()->getValue(),
4400 if (RV) return getSCEV(RV);
4404 // Okay, this is an expression that we cannot symbolically evaluate
4405 // into a SCEV. Check to see if it's possible to symbolically evaluate
4406 // the arguments into constants, and if so, try to constant propagate the
4407 // result. This is particularly useful for computing loop exit values.
4408 if (CanConstantFold(I)) {
4409 SmallVector<Constant *, 4> Operands;
4410 bool MadeImprovement = false;
4411 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4412 Value *Op = I->getOperand(i);
4413 if (Constant *C = dyn_cast<Constant>(Op)) {
4414 Operands.push_back(C);
4418 // If any of the operands is non-constant and if they are
4419 // non-integer and non-pointer, don't even try to analyze them
4420 // with scev techniques.
4421 if (!isSCEVable(Op->getType()))
4424 const SCEV *OrigV = getSCEV(Op);
4425 const SCEV *OpV = getSCEVAtScope(OrigV, L);
4426 MadeImprovement |= OrigV != OpV;
4429 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
4431 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV))
4432 C = dyn_cast<Constant>(SU->getValue());
4434 if (C->getType() != Op->getType())
4435 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4439 Operands.push_back(C);
4442 // Check to see if getSCEVAtScope actually made an improvement.
4443 if (MadeImprovement) {
4445 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4446 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
4447 Operands[0], Operands[1], TD);
4449 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4450 &Operands[0], Operands.size(), TD);
4457 // This is some other type of SCEVUnknown, just return it.
4461 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
4462 // Avoid performing the look-up in the common case where the specified
4463 // expression has no loop-variant portions.
4464 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
4465 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
4466 if (OpAtScope != Comm->getOperand(i)) {
4467 // Okay, at least one of these operands is loop variant but might be
4468 // foldable. Build a new instance of the folded commutative expression.
4469 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4470 Comm->op_begin()+i);
4471 NewOps.push_back(OpAtScope);
4473 for (++i; i != e; ++i) {
4474 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
4475 NewOps.push_back(OpAtScope);
4477 if (isa<SCEVAddExpr>(Comm))
4478 return getAddExpr(NewOps);
4479 if (isa<SCEVMulExpr>(Comm))
4480 return getMulExpr(NewOps);
4481 if (isa<SCEVSMaxExpr>(Comm))
4482 return getSMaxExpr(NewOps);
4483 if (isa<SCEVUMaxExpr>(Comm))
4484 return getUMaxExpr(NewOps);
4485 llvm_unreachable("Unknown commutative SCEV type!");
4488 // If we got here, all operands are loop invariant.
4492 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
4493 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4494 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
4495 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4496 return Div; // must be loop invariant
4497 return getUDivExpr(LHS, RHS);
4500 // If this is a loop recurrence for a loop that does not contain L, then we
4501 // are dealing with the final value computed by the loop.
4502 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4503 // First, attempt to evaluate each operand.
4504 // Avoid performing the look-up in the common case where the specified
4505 // expression has no loop-variant portions.
4506 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4507 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
4508 if (OpAtScope == AddRec->getOperand(i))
4511 // Okay, at least one of these operands is loop variant but might be
4512 // foldable. Build a new instance of the folded commutative expression.
4513 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
4514 AddRec->op_begin()+i);
4515 NewOps.push_back(OpAtScope);
4516 for (++i; i != e; ++i)
4517 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
4519 AddRec = cast<SCEVAddRecExpr>(getAddRecExpr(NewOps, AddRec->getLoop()));
4523 // If the scope is outside the addrec's loop, evaluate it by using the
4524 // loop exit value of the addrec.
4525 if (!AddRec->getLoop()->contains(L)) {
4526 // To evaluate this recurrence, we need to know how many times the AddRec
4527 // loop iterates. Compute this now.
4528 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
4529 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
4531 // Then, evaluate the AddRec.
4532 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
4538 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
4539 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4540 if (Op == Cast->getOperand())
4541 return Cast; // must be loop invariant
4542 return getZeroExtendExpr(Op, Cast->getType());
4545 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
4546 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4547 if (Op == Cast->getOperand())
4548 return Cast; // must be loop invariant
4549 return getSignExtendExpr(Op, Cast->getType());
4552 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
4553 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4554 if (Op == Cast->getOperand())
4555 return Cast; // must be loop invariant
4556 return getTruncateExpr(Op, Cast->getType());
4559 llvm_unreachable("Unknown SCEV type!");
4563 /// getSCEVAtScope - This is a convenience function which does
4564 /// getSCEVAtScope(getSCEV(V), L).
4565 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
4566 return getSCEVAtScope(getSCEV(V), L);
4569 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4570 /// following equation:
4572 /// A * X = B (mod N)
4574 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4575 /// A and B isn't important.
4577 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
4578 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
4579 ScalarEvolution &SE) {
4580 uint32_t BW = A.getBitWidth();
4581 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4582 assert(A != 0 && "A must be non-zero.");
4586 // The gcd of A and N may have only one prime factor: 2. The number of
4587 // trailing zeros in A is its multiplicity
4588 uint32_t Mult2 = A.countTrailingZeros();
4591 // 2. Check if B is divisible by D.
4593 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4594 // is not less than multiplicity of this prime factor for D.
4595 if (B.countTrailingZeros() < Mult2)
4596 return SE.getCouldNotCompute();
4598 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4601 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4602 // bit width during computations.
4603 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4604 APInt Mod(BW + 1, 0);
4605 Mod.set(BW - Mult2); // Mod = N / D
4606 APInt I = AD.multiplicativeInverse(Mod);
4608 // 4. Compute the minimum unsigned root of the equation:
4609 // I * (B / D) mod (N / D)
4610 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4612 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4614 return SE.getConstant(Result.trunc(BW));
4617 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4618 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4619 /// might be the same) or two SCEVCouldNotCompute objects.
4621 static std::pair<const SCEV *,const SCEV *>
4622 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
4623 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
4624 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4625 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4626 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
4628 // We currently can only solve this if the coefficients are constants.
4629 if (!LC || !MC || !NC) {
4630 const SCEV *CNC = SE.getCouldNotCompute();
4631 return std::make_pair(CNC, CNC);
4634 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
4635 const APInt &L = LC->getValue()->getValue();
4636 const APInt &M = MC->getValue()->getValue();
4637 const APInt &N = NC->getValue()->getValue();
4638 APInt Two(BitWidth, 2);
4639 APInt Four(BitWidth, 4);
4642 using namespace APIntOps;
4644 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4645 // The B coefficient is M-N/2
4649 // The A coefficient is N/2
4650 APInt A(N.sdiv(Two));
4652 // Compute the B^2-4ac term.
4655 SqrtTerm -= Four * (A * C);
4657 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4658 // integer value or else APInt::sqrt() will assert.
4659 APInt SqrtVal(SqrtTerm.sqrt());
4661 // Compute the two solutions for the quadratic formula.
4662 // The divisions must be performed as signed divisions.
4664 APInt TwoA( A << 1 );
4665 if (TwoA.isMinValue()) {
4666 const SCEV *CNC = SE.getCouldNotCompute();
4667 return std::make_pair(CNC, CNC);
4670 LLVMContext &Context = SE.getContext();
4672 ConstantInt *Solution1 =
4673 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
4674 ConstantInt *Solution2 =
4675 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
4677 return std::make_pair(SE.getConstant(Solution1),
4678 SE.getConstant(Solution2));
4679 } // end APIntOps namespace
4682 /// HowFarToZero - Return the number of times a backedge comparing the specified
4683 /// value to zero will execute. If not computable, return CouldNotCompute.
4684 ScalarEvolution::BackedgeTakenInfo
4685 ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
4686 // If the value is a constant
4687 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
4688 // If the value is already zero, the branch will execute zero times.
4689 if (C->getValue()->isZero()) return C;
4690 return getCouldNotCompute(); // Otherwise it will loop infinitely.
4693 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
4694 if (!AddRec || AddRec->getLoop() != L)
4695 return getCouldNotCompute();
4697 if (AddRec->isAffine()) {
4698 // If this is an affine expression, the execution count of this branch is
4699 // the minimum unsigned root of the following equation:
4701 // Start + Step*N = 0 (mod 2^BW)
4705 // Step*N = -Start (mod 2^BW)
4707 // where BW is the common bit width of Start and Step.
4709 // Get the initial value for the loop.
4710 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4711 L->getParentLoop());
4712 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4713 L->getParentLoop());
4715 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
4716 // For now we handle only constant steps.
4718 // First, handle unitary steps.
4719 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
4720 return getNegativeSCEV(Start); // N = -Start (as unsigned)
4721 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4722 return Start; // N = Start (as unsigned)
4724 // Then, try to solve the above equation provided that Start is constant.
4725 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
4726 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
4727 -StartC->getValue()->getValue(),
4730 } else if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
4731 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4732 // the quadratic equation to solve it.
4733 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
4735 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4736 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
4739 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
4740 << " sol#2: " << *R2 << "\n";
4742 // Pick the smallest positive root value.
4743 if (ConstantInt *CB =
4744 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
4745 R1->getValue(), R2->getValue()))) {
4746 if (CB->getZExtValue() == false)
4747 std::swap(R1, R2); // R1 is the minimum root now.
4749 // We can only use this value if the chrec ends up with an exact zero
4750 // value at this index. When solving for "X*X != 5", for example, we
4751 // should not accept a root of 2.
4752 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
4754 return R1; // We found a quadratic root!
4759 return getCouldNotCompute();
4762 /// HowFarToNonZero - Return the number of times a backedge checking the
4763 /// specified value for nonzero will execute. If not computable, return
4765 ScalarEvolution::BackedgeTakenInfo
4766 ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
4767 // Loops that look like: while (X == 0) are very strange indeed. We don't
4768 // handle them yet except for the trivial case. This could be expanded in the
4769 // future as needed.
4771 // If the value is a constant, check to see if it is known to be non-zero
4772 // already. If so, the backedge will execute zero times.
4773 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
4774 if (!C->getValue()->isNullValue())
4775 return getConstant(C->getType(), 0);
4776 return getCouldNotCompute(); // Otherwise it will loop infinitely.
4779 // We could implement others, but I really doubt anyone writes loops like
4780 // this, and if they did, they would already be constant folded.
4781 return getCouldNotCompute();
4784 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4785 /// (which may not be an immediate predecessor) which has exactly one
4786 /// successor from which BB is reachable, or null if no such block is
4789 std::pair<BasicBlock *, BasicBlock *>
4790 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
4791 // If the block has a unique predecessor, then there is no path from the
4792 // predecessor to the block that does not go through the direct edge
4793 // from the predecessor to the block.
4794 if (BasicBlock *Pred = BB->getSinglePredecessor())
4795 return std::make_pair(Pred, BB);
4797 // A loop's header is defined to be a block that dominates the loop.
4798 // If the header has a unique predecessor outside the loop, it must be
4799 // a block that has exactly one successor that can reach the loop.
4800 if (Loop *L = LI->getLoopFor(BB))
4801 return std::make_pair(L->getLoopPredecessor(), L->getHeader());
4803 return std::pair<BasicBlock *, BasicBlock *>();
4806 /// HasSameValue - SCEV structural equivalence is usually sufficient for
4807 /// testing whether two expressions are equal, however for the purposes of
4808 /// looking for a condition guarding a loop, it can be useful to be a little
4809 /// more general, since a front-end may have replicated the controlling
4812 static bool HasSameValue(const SCEV *A, const SCEV *B) {
4813 // Quick check to see if they are the same SCEV.
4814 if (A == B) return true;
4816 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4817 // two different instructions with the same value. Check for this case.
4818 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4819 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4820 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4821 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
4822 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
4825 // Otherwise assume they may have a different value.
4829 /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
4830 /// predicate Pred. Return true iff any changes were made.
4832 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
4833 const SCEV *&LHS, const SCEV *&RHS) {
4834 bool Changed = false;
4836 // Canonicalize a constant to the right side.
4837 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
4838 // Check for both operands constant.
4839 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
4840 if (ConstantExpr::getICmp(Pred,
4842 RHSC->getValue())->isNullValue())
4843 goto trivially_false;
4845 goto trivially_true;
4847 // Otherwise swap the operands to put the constant on the right.
4848 std::swap(LHS, RHS);
4849 Pred = ICmpInst::getSwappedPredicate(Pred);
4853 // If we're comparing an addrec with a value which is loop-invariant in the
4854 // addrec's loop, put the addrec on the left. Also make a dominance check,
4855 // as both operands could be addrecs loop-invariant in each other's loop.
4856 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
4857 const Loop *L = AR->getLoop();
4858 if (LHS->isLoopInvariant(L) && LHS->properlyDominates(L->getHeader(), DT)) {
4859 std::swap(LHS, RHS);
4860 Pred = ICmpInst::getSwappedPredicate(Pred);
4865 // If there's a constant operand, canonicalize comparisons with boundary
4866 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
4867 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4868 const APInt &RA = RC->getValue()->getValue();
4870 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4871 case ICmpInst::ICMP_EQ:
4872 case ICmpInst::ICMP_NE:
4874 case ICmpInst::ICMP_UGE:
4875 if ((RA - 1).isMinValue()) {
4876 Pred = ICmpInst::ICMP_NE;
4877 RHS = getConstant(RA - 1);
4881 if (RA.isMaxValue()) {
4882 Pred = ICmpInst::ICMP_EQ;
4886 if (RA.isMinValue()) goto trivially_true;
4888 Pred = ICmpInst::ICMP_UGT;
4889 RHS = getConstant(RA - 1);
4892 case ICmpInst::ICMP_ULE:
4893 if ((RA + 1).isMaxValue()) {
4894 Pred = ICmpInst::ICMP_NE;
4895 RHS = getConstant(RA + 1);
4899 if (RA.isMinValue()) {
4900 Pred = ICmpInst::ICMP_EQ;
4904 if (RA.isMaxValue()) goto trivially_true;
4906 Pred = ICmpInst::ICMP_ULT;
4907 RHS = getConstant(RA + 1);
4910 case ICmpInst::ICMP_SGE:
4911 if ((RA - 1).isMinSignedValue()) {
4912 Pred = ICmpInst::ICMP_NE;
4913 RHS = getConstant(RA - 1);
4917 if (RA.isMaxSignedValue()) {
4918 Pred = ICmpInst::ICMP_EQ;
4922 if (RA.isMinSignedValue()) goto trivially_true;
4924 Pred = ICmpInst::ICMP_SGT;
4925 RHS = getConstant(RA - 1);
4928 case ICmpInst::ICMP_SLE:
4929 if ((RA + 1).isMaxSignedValue()) {
4930 Pred = ICmpInst::ICMP_NE;
4931 RHS = getConstant(RA + 1);
4935 if (RA.isMinSignedValue()) {
4936 Pred = ICmpInst::ICMP_EQ;
4940 if (RA.isMaxSignedValue()) goto trivially_true;
4942 Pred = ICmpInst::ICMP_SLT;
4943 RHS = getConstant(RA + 1);
4946 case ICmpInst::ICMP_UGT:
4947 if (RA.isMinValue()) {
4948 Pred = ICmpInst::ICMP_NE;
4952 if ((RA + 1).isMaxValue()) {
4953 Pred = ICmpInst::ICMP_EQ;
4954 RHS = getConstant(RA + 1);
4958 if (RA.isMaxValue()) goto trivially_false;
4960 case ICmpInst::ICMP_ULT:
4961 if (RA.isMaxValue()) {
4962 Pred = ICmpInst::ICMP_NE;
4966 if ((RA - 1).isMinValue()) {
4967 Pred = ICmpInst::ICMP_EQ;
4968 RHS = getConstant(RA - 1);
4972 if (RA.isMinValue()) goto trivially_false;
4974 case ICmpInst::ICMP_SGT:
4975 if (RA.isMinSignedValue()) {
4976 Pred = ICmpInst::ICMP_NE;
4980 if ((RA + 1).isMaxSignedValue()) {
4981 Pred = ICmpInst::ICMP_EQ;
4982 RHS = getConstant(RA + 1);
4986 if (RA.isMaxSignedValue()) goto trivially_false;
4988 case ICmpInst::ICMP_SLT:
4989 if (RA.isMaxSignedValue()) {
4990 Pred = ICmpInst::ICMP_NE;
4994 if ((RA - 1).isMinSignedValue()) {
4995 Pred = ICmpInst::ICMP_EQ;
4996 RHS = getConstant(RA - 1);
5000 if (RA.isMinSignedValue()) goto trivially_false;
5005 // Check for obvious equality.
5006 if (HasSameValue(LHS, RHS)) {
5007 if (ICmpInst::isTrueWhenEqual(Pred))
5008 goto trivially_true;
5009 if (ICmpInst::isFalseWhenEqual(Pred))
5010 goto trivially_false;
5013 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
5014 // adding or subtracting 1 from one of the operands.
5016 case ICmpInst::ICMP_SLE:
5017 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
5018 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
5019 /*HasNUW=*/false, /*HasNSW=*/true);
5020 Pred = ICmpInst::ICMP_SLT;
5022 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
5023 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
5024 /*HasNUW=*/false, /*HasNSW=*/true);
5025 Pred = ICmpInst::ICMP_SLT;
5029 case ICmpInst::ICMP_SGE:
5030 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
5031 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
5032 /*HasNUW=*/false, /*HasNSW=*/true);
5033 Pred = ICmpInst::ICMP_SGT;
5035 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
5036 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
5037 /*HasNUW=*/false, /*HasNSW=*/true);
5038 Pred = ICmpInst::ICMP_SGT;
5042 case ICmpInst::ICMP_ULE:
5043 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
5044 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
5045 /*HasNUW=*/true, /*HasNSW=*/false);
5046 Pred = ICmpInst::ICMP_ULT;
5048 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
5049 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
5050 /*HasNUW=*/true, /*HasNSW=*/false);
5051 Pred = ICmpInst::ICMP_ULT;
5055 case ICmpInst::ICMP_UGE:
5056 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
5057 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
5058 /*HasNUW=*/true, /*HasNSW=*/false);
5059 Pred = ICmpInst::ICMP_UGT;
5061 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
5062 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
5063 /*HasNUW=*/true, /*HasNSW=*/false);
5064 Pred = ICmpInst::ICMP_UGT;
5072 // TODO: More simplifications are possible here.
5078 LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
5079 Pred = ICmpInst::ICMP_EQ;
5084 LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
5085 Pred = ICmpInst::ICMP_NE;
5089 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
5090 return getSignedRange(S).getSignedMax().isNegative();
5093 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
5094 return getSignedRange(S).getSignedMin().isStrictlyPositive();
5097 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
5098 return !getSignedRange(S).getSignedMin().isNegative();
5101 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
5102 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
5105 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
5106 return isKnownNegative(S) || isKnownPositive(S);
5109 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
5110 const SCEV *LHS, const SCEV *RHS) {
5111 // Canonicalize the inputs first.
5112 (void)SimplifyICmpOperands(Pred, LHS, RHS);
5114 // If LHS or RHS is an addrec, check to see if the condition is true in
5115 // every iteration of the loop.
5116 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
5117 if (isLoopEntryGuardedByCond(
5118 AR->getLoop(), Pred, AR->getStart(), RHS) &&
5119 isLoopBackedgeGuardedByCond(
5120 AR->getLoop(), Pred, AR->getPostIncExpr(*this), RHS))
5122 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS))
5123 if (isLoopEntryGuardedByCond(
5124 AR->getLoop(), Pred, LHS, AR->getStart()) &&
5125 isLoopBackedgeGuardedByCond(
5126 AR->getLoop(), Pred, LHS, AR->getPostIncExpr(*this)))
5129 // Otherwise see what can be done with known constant ranges.
5130 return isKnownPredicateWithRanges(Pred, LHS, RHS);
5134 ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
5135 const SCEV *LHS, const SCEV *RHS) {
5136 if (HasSameValue(LHS, RHS))
5137 return ICmpInst::isTrueWhenEqual(Pred);
5139 // This code is split out from isKnownPredicate because it is called from
5140 // within isLoopEntryGuardedByCond.
5143 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5145 case ICmpInst::ICMP_SGT:
5146 Pred = ICmpInst::ICMP_SLT;
5147 std::swap(LHS, RHS);
5148 case ICmpInst::ICMP_SLT: {
5149 ConstantRange LHSRange = getSignedRange(LHS);
5150 ConstantRange RHSRange = getSignedRange(RHS);
5151 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
5153 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
5157 case ICmpInst::ICMP_SGE:
5158 Pred = ICmpInst::ICMP_SLE;
5159 std::swap(LHS, RHS);
5160 case ICmpInst::ICMP_SLE: {
5161 ConstantRange LHSRange = getSignedRange(LHS);
5162 ConstantRange RHSRange = getSignedRange(RHS);
5163 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
5165 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
5169 case ICmpInst::ICMP_UGT:
5170 Pred = ICmpInst::ICMP_ULT;
5171 std::swap(LHS, RHS);
5172 case ICmpInst::ICMP_ULT: {
5173 ConstantRange LHSRange = getUnsignedRange(LHS);
5174 ConstantRange RHSRange = getUnsignedRange(RHS);
5175 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
5177 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
5181 case ICmpInst::ICMP_UGE:
5182 Pred = ICmpInst::ICMP_ULE;
5183 std::swap(LHS, RHS);
5184 case ICmpInst::ICMP_ULE: {
5185 ConstantRange LHSRange = getUnsignedRange(LHS);
5186 ConstantRange RHSRange = getUnsignedRange(RHS);
5187 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
5189 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
5193 case ICmpInst::ICMP_NE: {
5194 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
5196 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
5199 const SCEV *Diff = getMinusSCEV(LHS, RHS);
5200 if (isKnownNonZero(Diff))
5204 case ICmpInst::ICMP_EQ:
5205 // The check at the top of the function catches the case where
5206 // the values are known to be equal.
5212 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
5213 /// protected by a conditional between LHS and RHS. This is used to
5214 /// to eliminate casts.
5216 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
5217 ICmpInst::Predicate Pred,
5218 const SCEV *LHS, const SCEV *RHS) {
5219 // Interpret a null as meaning no loop, where there is obviously no guard
5220 // (interprocedural conditions notwithstanding).
5221 if (!L) return true;
5223 BasicBlock *Latch = L->getLoopLatch();
5227 BranchInst *LoopContinuePredicate =
5228 dyn_cast<BranchInst>(Latch->getTerminator());
5229 if (!LoopContinuePredicate ||
5230 LoopContinuePredicate->isUnconditional())
5233 return isImpliedCond(Pred, LHS, RHS,
5234 LoopContinuePredicate->getCondition(),
5235 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
5238 /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
5239 /// by a conditional between LHS and RHS. This is used to help avoid max
5240 /// expressions in loop trip counts, and to eliminate casts.
5242 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
5243 ICmpInst::Predicate Pred,
5244 const SCEV *LHS, const SCEV *RHS) {
5245 // Interpret a null as meaning no loop, where there is obviously no guard
5246 // (interprocedural conditions notwithstanding).
5247 if (!L) return false;
5249 // Starting at the loop predecessor, climb up the predecessor chain, as long
5250 // as there are predecessors that can be found that have unique successors
5251 // leading to the original header.
5252 for (std::pair<BasicBlock *, BasicBlock *>
5253 Pair(L->getLoopPredecessor(), L->getHeader());
5255 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
5257 BranchInst *LoopEntryPredicate =
5258 dyn_cast<BranchInst>(Pair.first->getTerminator());
5259 if (!LoopEntryPredicate ||
5260 LoopEntryPredicate->isUnconditional())
5263 if (isImpliedCond(Pred, LHS, RHS,
5264 LoopEntryPredicate->getCondition(),
5265 LoopEntryPredicate->getSuccessor(0) != Pair.second))
5272 /// isImpliedCond - Test whether the condition described by Pred, LHS,
5273 /// and RHS is true whenever the given Cond value evaluates to true.
5274 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
5275 const SCEV *LHS, const SCEV *RHS,
5276 Value *FoundCondValue,
5278 // Recursively handle And and Or conditions.
5279 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
5280 if (BO->getOpcode() == Instruction::And) {
5282 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5283 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
5284 } else if (BO->getOpcode() == Instruction::Or) {
5286 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5287 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
5291 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
5292 if (!ICI) return false;
5294 // Bail if the ICmp's operands' types are wider than the needed type
5295 // before attempting to call getSCEV on them. This avoids infinite
5296 // recursion, since the analysis of widening casts can require loop
5297 // exit condition information for overflow checking, which would
5299 if (getTypeSizeInBits(LHS->getType()) <
5300 getTypeSizeInBits(ICI->getOperand(0)->getType()))
5303 // Now that we found a conditional branch that dominates the loop, check to
5304 // see if it is the comparison we are looking for.
5305 ICmpInst::Predicate FoundPred;
5307 FoundPred = ICI->getInversePredicate();
5309 FoundPred = ICI->getPredicate();
5311 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
5312 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
5314 // Balance the types. The case where FoundLHS' type is wider than
5315 // LHS' type is checked for above.
5316 if (getTypeSizeInBits(LHS->getType()) >
5317 getTypeSizeInBits(FoundLHS->getType())) {
5318 if (CmpInst::isSigned(Pred)) {
5319 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
5320 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
5322 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
5323 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
5327 // Canonicalize the query to match the way instcombine will have
5328 // canonicalized the comparison.
5329 if (SimplifyICmpOperands(Pred, LHS, RHS))
5331 return CmpInst::isTrueWhenEqual(Pred);
5332 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
5333 if (FoundLHS == FoundRHS)
5334 return CmpInst::isFalseWhenEqual(Pred);
5336 // Check to see if we can make the LHS or RHS match.
5337 if (LHS == FoundRHS || RHS == FoundLHS) {
5338 if (isa<SCEVConstant>(RHS)) {
5339 std::swap(FoundLHS, FoundRHS);
5340 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
5342 std::swap(LHS, RHS);
5343 Pred = ICmpInst::getSwappedPredicate(Pred);
5347 // Check whether the found predicate is the same as the desired predicate.
5348 if (FoundPred == Pred)
5349 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
5351 // Check whether swapping the found predicate makes it the same as the
5352 // desired predicate.
5353 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
5354 if (isa<SCEVConstant>(RHS))
5355 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
5357 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
5358 RHS, LHS, FoundLHS, FoundRHS);
5361 // Check whether the actual condition is beyond sufficient.
5362 if (FoundPred == ICmpInst::ICMP_EQ)
5363 if (ICmpInst::isTrueWhenEqual(Pred))
5364 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
5366 if (Pred == ICmpInst::ICMP_NE)
5367 if (!ICmpInst::isTrueWhenEqual(FoundPred))
5368 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
5371 // Otherwise assume the worst.
5375 /// isImpliedCondOperands - Test whether the condition described by Pred,
5376 /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
5377 /// and FoundRHS is true.
5378 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
5379 const SCEV *LHS, const SCEV *RHS,
5380 const SCEV *FoundLHS,
5381 const SCEV *FoundRHS) {
5382 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
5383 FoundLHS, FoundRHS) ||
5384 // ~x < ~y --> x > y
5385 isImpliedCondOperandsHelper(Pred, LHS, RHS,
5386 getNotSCEV(FoundRHS),
5387 getNotSCEV(FoundLHS));
5390 /// isImpliedCondOperandsHelper - Test whether the condition described by
5391 /// Pred, LHS, and RHS is true whenever the condition described by Pred,
5392 /// FoundLHS, and FoundRHS is true.
5394 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
5395 const SCEV *LHS, const SCEV *RHS,
5396 const SCEV *FoundLHS,
5397 const SCEV *FoundRHS) {
5399 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5400 case ICmpInst::ICMP_EQ:
5401 case ICmpInst::ICMP_NE:
5402 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
5405 case ICmpInst::ICMP_SLT:
5406 case ICmpInst::ICMP_SLE:
5407 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
5408 isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS))
5411 case ICmpInst::ICMP_SGT:
5412 case ICmpInst::ICMP_SGE:
5413 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
5414 isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS))
5417 case ICmpInst::ICMP_ULT:
5418 case ICmpInst::ICMP_ULE:
5419 if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
5420 isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS))
5423 case ICmpInst::ICMP_UGT:
5424 case ICmpInst::ICMP_UGE:
5425 if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
5426 isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS))
5434 /// getBECount - Subtract the end and start values and divide by the step,
5435 /// rounding up, to get the number of times the backedge is executed. Return
5436 /// CouldNotCompute if an intermediate computation overflows.
5437 const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
5441 assert(!isKnownNegative(Step) &&
5442 "This code doesn't handle negative strides yet!");
5444 const Type *Ty = Start->getType();
5445 const SCEV *NegOne = getConstant(Ty, (uint64_t)-1);
5446 const SCEV *Diff = getMinusSCEV(End, Start);
5447 const SCEV *RoundUp = getAddExpr(Step, NegOne);
5449 // Add an adjustment to the difference between End and Start so that
5450 // the division will effectively round up.
5451 const SCEV *Add = getAddExpr(Diff, RoundUp);
5454 // Check Add for unsigned overflow.
5455 // TODO: More sophisticated things could be done here.
5456 const Type *WideTy = IntegerType::get(getContext(),
5457 getTypeSizeInBits(Ty) + 1);
5458 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
5459 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
5460 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
5461 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
5462 return getCouldNotCompute();
5465 return getUDivExpr(Add, Step);
5468 /// HowManyLessThans - Return the number of times a backedge containing the
5469 /// specified less-than comparison will execute. If not computable, return
5470 /// CouldNotCompute.
5471 ScalarEvolution::BackedgeTakenInfo
5472 ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
5473 const Loop *L, bool isSigned) {
5474 // Only handle: "ADDREC < LoopInvariant".
5475 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
5477 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
5478 if (!AddRec || AddRec->getLoop() != L)
5479 return getCouldNotCompute();
5481 // Check to see if we have a flag which makes analysis easy.
5482 bool NoWrap = isSigned ? AddRec->hasNoSignedWrap() :
5483 AddRec->hasNoUnsignedWrap();
5485 if (AddRec->isAffine()) {
5486 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
5487 const SCEV *Step = AddRec->getStepRecurrence(*this);
5490 return getCouldNotCompute();
5491 if (Step->isOne()) {
5492 // With unit stride, the iteration never steps past the limit value.
5493 } else if (isKnownPositive(Step)) {
5494 // Test whether a positive iteration can step past the limit
5495 // value and past the maximum value for its type in a single step.
5496 // Note that it's not sufficient to check NoWrap here, because even
5497 // though the value after a wrap is undefined, it's not undefined
5498 // behavior, so if wrap does occur, the loop could either terminate or
5499 // loop infinitely, but in either case, the loop is guaranteed to
5500 // iterate at least until the iteration where the wrapping occurs.
5501 const SCEV *One = getConstant(Step->getType(), 1);
5503 APInt Max = APInt::getSignedMaxValue(BitWidth);
5504 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
5505 .slt(getSignedRange(RHS).getSignedMax()))
5506 return getCouldNotCompute();
5508 APInt Max = APInt::getMaxValue(BitWidth);
5509 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
5510 .ult(getUnsignedRange(RHS).getUnsignedMax()))
5511 return getCouldNotCompute();
5514 // TODO: Handle negative strides here and below.
5515 return getCouldNotCompute();
5517 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
5518 // m. So, we count the number of iterations in which {n,+,s} < m is true.
5519 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
5520 // treat m-n as signed nor unsigned due to overflow possibility.
5522 // First, we get the value of the LHS in the first iteration: n
5523 const SCEV *Start = AddRec->getOperand(0);
5525 // Determine the minimum constant start value.
5526 const SCEV *MinStart = getConstant(isSigned ?
5527 getSignedRange(Start).getSignedMin() :
5528 getUnsignedRange(Start).getUnsignedMin());
5530 // If we know that the condition is true in order to enter the loop,
5531 // then we know that it will run exactly (m-n)/s times. Otherwise, we
5532 // only know that it will execute (max(m,n)-n)/s times. In both cases,
5533 // the division must round up.
5534 const SCEV *End = RHS;
5535 if (!isLoopEntryGuardedByCond(L,
5536 isSigned ? ICmpInst::ICMP_SLT :
5538 getMinusSCEV(Start, Step), RHS))
5539 End = isSigned ? getSMaxExpr(RHS, Start)
5540 : getUMaxExpr(RHS, Start);
5542 // Determine the maximum constant end value.
5543 const SCEV *MaxEnd = getConstant(isSigned ?
5544 getSignedRange(End).getSignedMax() :
5545 getUnsignedRange(End).getUnsignedMax());
5547 // If MaxEnd is within a step of the maximum integer value in its type,
5548 // adjust it down to the minimum value which would produce the same effect.
5549 // This allows the subsequent ceiling division of (N+(step-1))/step to
5550 // compute the correct value.
5551 const SCEV *StepMinusOne = getMinusSCEV(Step,
5552 getConstant(Step->getType(), 1));
5555 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
5558 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
5561 // Finally, we subtract these two values and divide, rounding up, to get
5562 // the number of times the backedge is executed.
5563 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
5565 // The maximum backedge count is similar, except using the minimum start
5566 // value and the maximum end value.
5567 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step, NoWrap);
5569 return BackedgeTakenInfo(BECount, MaxBECount);
5572 return getCouldNotCompute();
5575 /// getNumIterationsInRange - Return the number of iterations of this loop that
5576 /// produce values in the specified constant range. Another way of looking at
5577 /// this is that it returns the first iteration number where the value is not in
5578 /// the condition, thus computing the exit count. If the iteration count can't
5579 /// be computed, an instance of SCEVCouldNotCompute is returned.
5580 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
5581 ScalarEvolution &SE) const {
5582 if (Range.isFullSet()) // Infinite loop.
5583 return SE.getCouldNotCompute();
5585 // If the start is a non-zero constant, shift the range to simplify things.
5586 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
5587 if (!SC->getValue()->isZero()) {
5588 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
5589 Operands[0] = SE.getConstant(SC->getType(), 0);
5590 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
5591 if (const SCEVAddRecExpr *ShiftedAddRec =
5592 dyn_cast<SCEVAddRecExpr>(Shifted))
5593 return ShiftedAddRec->getNumIterationsInRange(
5594 Range.subtract(SC->getValue()->getValue()), SE);
5595 // This is strange and shouldn't happen.
5596 return SE.getCouldNotCompute();
5599 // The only time we can solve this is when we have all constant indices.
5600 // Otherwise, we cannot determine the overflow conditions.
5601 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5602 if (!isa<SCEVConstant>(getOperand(i)))
5603 return SE.getCouldNotCompute();
5606 // Okay at this point we know that all elements of the chrec are constants and
5607 // that the start element is zero.
5609 // First check to see if the range contains zero. If not, the first
5611 unsigned BitWidth = SE.getTypeSizeInBits(getType());
5612 if (!Range.contains(APInt(BitWidth, 0)))
5613 return SE.getConstant(getType(), 0);
5616 // If this is an affine expression then we have this situation:
5617 // Solve {0,+,A} in Range === Ax in Range
5619 // We know that zero is in the range. If A is positive then we know that
5620 // the upper value of the range must be the first possible exit value.
5621 // If A is negative then the lower of the range is the last possible loop
5622 // value. Also note that we already checked for a full range.
5623 APInt One(BitWidth,1);
5624 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
5625 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
5627 // The exit value should be (End+A)/A.
5628 APInt ExitVal = (End + A).udiv(A);
5629 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
5631 // Evaluate at the exit value. If we really did fall out of the valid
5632 // range, then we computed our trip count, otherwise wrap around or other
5633 // things must have happened.
5634 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
5635 if (Range.contains(Val->getValue()))
5636 return SE.getCouldNotCompute(); // Something strange happened
5638 // Ensure that the previous value is in the range. This is a sanity check.
5639 assert(Range.contains(
5640 EvaluateConstantChrecAtConstant(this,
5641 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
5642 "Linear scev computation is off in a bad way!");
5643 return SE.getConstant(ExitValue);
5644 } else if (isQuadratic()) {
5645 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5646 // quadratic equation to solve it. To do this, we must frame our problem in
5647 // terms of figuring out when zero is crossed, instead of when
5648 // Range.getUpper() is crossed.
5649 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
5650 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
5651 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
5653 // Next, solve the constructed addrec
5654 std::pair<const SCEV *,const SCEV *> Roots =
5655 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
5656 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5657 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
5659 // Pick the smallest positive root value.
5660 if (ConstantInt *CB =
5661 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
5662 R1->getValue(), R2->getValue()))) {
5663 if (CB->getZExtValue() == false)
5664 std::swap(R1, R2); // R1 is the minimum root now.
5666 // Make sure the root is not off by one. The returned iteration should
5667 // not be in the range, but the previous one should be. When solving
5668 // for "X*X < 5", for example, we should not return a root of 2.
5669 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
5672 if (Range.contains(R1Val->getValue())) {
5673 // The next iteration must be out of the range...
5674 ConstantInt *NextVal =
5675 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
5677 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
5678 if (!Range.contains(R1Val->getValue()))
5679 return SE.getConstant(NextVal);
5680 return SE.getCouldNotCompute(); // Something strange happened
5683 // If R1 was not in the range, then it is a good return value. Make
5684 // sure that R1-1 WAS in the range though, just in case.
5685 ConstantInt *NextVal =
5686 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
5687 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
5688 if (Range.contains(R1Val->getValue()))
5690 return SE.getCouldNotCompute(); // Something strange happened
5695 return SE.getCouldNotCompute();
5700 //===----------------------------------------------------------------------===//
5701 // SCEVCallbackVH Class Implementation
5702 //===----------------------------------------------------------------------===//
5704 void ScalarEvolution::SCEVCallbackVH::deleted() {
5705 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
5706 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5707 SE->ConstantEvolutionLoopExitValue.erase(PN);
5708 SE->Scalars.erase(getValPtr());
5709 // this now dangles!
5712 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
5713 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
5715 // Forget all the expressions associated with users of the old value,
5716 // so that future queries will recompute the expressions using the new
5718 Value *Old = getValPtr();
5719 SmallVector<User *, 16> Worklist;
5720 SmallPtrSet<User *, 8> Visited;
5721 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5723 Worklist.push_back(*UI);
5724 while (!Worklist.empty()) {
5725 User *U = Worklist.pop_back_val();
5726 // Deleting the Old value will cause this to dangle. Postpone
5727 // that until everything else is done.
5730 if (!Visited.insert(U))
5732 if (PHINode *PN = dyn_cast<PHINode>(U))
5733 SE->ConstantEvolutionLoopExitValue.erase(PN);
5734 SE->Scalars.erase(U);
5735 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5737 Worklist.push_back(*UI);
5739 // Delete the Old value.
5740 if (PHINode *PN = dyn_cast<PHINode>(Old))
5741 SE->ConstantEvolutionLoopExitValue.erase(PN);
5742 SE->Scalars.erase(Old);
5743 // this now dangles!
5746 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
5747 : CallbackVH(V), SE(se) {}
5749 //===----------------------------------------------------------------------===//
5750 // ScalarEvolution Class Implementation
5751 //===----------------------------------------------------------------------===//
5753 ScalarEvolution::ScalarEvolution()
5754 : FunctionPass(ID), FirstUnknown(0) {
5757 bool ScalarEvolution::runOnFunction(Function &F) {
5759 LI = &getAnalysis<LoopInfo>();
5760 TD = getAnalysisIfAvailable<TargetData>();
5761 DT = &getAnalysis<DominatorTree>();
5765 void ScalarEvolution::releaseMemory() {
5766 // Iterate through all the SCEVUnknown instances and call their
5767 // destructors, so that they release their references to their values.
5768 for (SCEVUnknown *U = FirstUnknown; U; U = U->Next)
5773 BackedgeTakenCounts.clear();
5774 ConstantEvolutionLoopExitValue.clear();
5775 ValuesAtScopes.clear();
5776 UniqueSCEVs.clear();
5777 SCEVAllocator.Reset();
5780 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5781 AU.setPreservesAll();
5782 AU.addRequiredTransitive<LoopInfo>();
5783 AU.addRequiredTransitive<DominatorTree>();
5786 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
5787 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
5790 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
5792 // Print all inner loops first
5793 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5794 PrintLoopInfo(OS, SE, *I);
5797 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5800 SmallVector<BasicBlock *, 8> ExitBlocks;
5801 L->getExitBlocks(ExitBlocks);
5802 if (ExitBlocks.size() != 1)
5803 OS << "<multiple exits> ";
5805 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5806 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
5808 OS << "Unpredictable backedge-taken count. ";
5813 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5816 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5817 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5819 OS << "Unpredictable max backedge-taken count. ";
5825 void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
5826 // ScalarEvolution's implementation of the print method is to print
5827 // out SCEV values of all instructions that are interesting. Doing
5828 // this potentially causes it to create new SCEV objects though,
5829 // which technically conflicts with the const qualifier. This isn't
5830 // observable from outside the class though, so casting away the
5831 // const isn't dangerous.
5832 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
5834 OS << "Classifying expressions for: ";
5835 WriteAsOperand(OS, F, /*PrintType=*/false);
5837 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
5838 if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) {
5841 const SCEV *SV = SE.getSCEV(&*I);
5844 const Loop *L = LI->getLoopFor((*I).getParent());
5846 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
5853 OS << "\t\t" "Exits: ";
5854 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
5855 if (!ExitValue->isLoopInvariant(L)) {
5856 OS << "<<Unknown>>";
5865 OS << "Determining loop execution counts for: ";
5866 WriteAsOperand(OS, F, /*PrintType=*/false);
5868 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5869 PrintLoopInfo(OS, &SE, *I);