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 SCEVNAryExpr::isLoopInvariant(const Loop *L) const {
275 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
276 if (!(*I)->isLoopInvariant(L))
281 // hasComputableLoopEvolution - N-ary expressions have computable loop
282 // evolutions iff they have at least one operand that varies with the loop,
283 // but that all varying operands are computable.
284 bool SCEVNAryExpr::hasComputableLoopEvolution(const Loop *L) const {
285 bool HasVarying = false;
286 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I) {
288 if (!S->isLoopInvariant(L)) {
289 if (S->hasComputableLoopEvolution(L))
298 bool SCEVNAryExpr::hasOperand(const SCEV *O) const {
299 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I) {
301 if (O == S || S->hasOperand(O))
307 bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
308 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
311 bool SCEVUDivExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
312 return LHS->properlyDominates(BB, DT) && RHS->properlyDominates(BB, DT);
315 void SCEVUDivExpr::print(raw_ostream &OS) const {
316 OS << "(" << *LHS << " /u " << *RHS << ")";
319 const Type *SCEVUDivExpr::getType() const {
320 // In most cases the types of LHS and RHS will be the same, but in some
321 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
322 // depend on the type for correctness, but handling types carefully can
323 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
324 // a pointer type than the RHS, so use the RHS' type here.
325 return RHS->getType();
328 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
329 // Add recurrences are never invariant in the function-body (null loop).
333 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
334 if (QueryLoop->contains(L))
337 // This recurrence is invariant w.r.t. QueryLoop if L contains QueryLoop.
338 if (L->contains(QueryLoop))
341 // This recurrence is variant w.r.t. QueryLoop if any of its operands
343 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
344 if (!getOperand(i)->isLoopInvariant(QueryLoop))
347 // Otherwise it's loop-invariant.
352 SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
353 return DT->dominates(L->getHeader(), BB) &&
354 SCEVNAryExpr::dominates(BB, DT);
358 SCEVAddRecExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
359 // This uses a "dominates" query instead of "properly dominates" query because
360 // the instruction which produces the addrec's value is a PHI, and a PHI
361 // effectively properly dominates its entire containing block.
362 return DT->dominates(L->getHeader(), BB) &&
363 SCEVNAryExpr::properlyDominates(BB, DT);
366 void SCEVAddRecExpr::print(raw_ostream &OS) const {
367 OS << "{" << *Operands[0];
368 for (unsigned i = 1, e = NumOperands; i != e; ++i)
369 OS << ",+," << *Operands[i];
371 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
375 void SCEVUnknown::deleted() {
376 // Clear this SCEVUnknown from ValuesAtScopes.
377 SE->ValuesAtScopes.erase(this);
379 // Remove this SCEVUnknown from the uniquing map.
380 SE->UniqueSCEVs.RemoveNode(this);
382 // Release the value.
386 void SCEVUnknown::allUsesReplacedWith(Value *New) {
387 // Clear this SCEVUnknown from ValuesAtScopes.
388 SE->ValuesAtScopes.erase(this);
390 // Remove this SCEVUnknown from the uniquing map.
391 SE->UniqueSCEVs.RemoveNode(this);
393 // Update this SCEVUnknown to point to the new value. This is needed
394 // because there may still be outstanding SCEVs which still point to
399 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
400 // All non-instruction values are loop invariant. All instructions are loop
401 // invariant if they are not contained in the specified loop.
402 // Instructions are never considered invariant in the function body
403 // (null loop) because they are defined within the "loop".
404 if (Instruction *I = dyn_cast<Instruction>(getValue()))
405 return L && !L->contains(I);
409 bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
410 if (Instruction *I = dyn_cast<Instruction>(getValue()))
411 return DT->dominates(I->getParent(), BB);
415 bool SCEVUnknown::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
416 if (Instruction *I = dyn_cast<Instruction>(getValue()))
417 return DT->properlyDominates(I->getParent(), BB);
421 const Type *SCEVUnknown::getType() const {
422 return getValue()->getType();
425 bool SCEVUnknown::isSizeOf(const Type *&AllocTy) const {
426 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
427 if (VCE->getOpcode() == Instruction::PtrToInt)
428 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
429 if (CE->getOpcode() == Instruction::GetElementPtr &&
430 CE->getOperand(0)->isNullValue() &&
431 CE->getNumOperands() == 2)
432 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
434 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
442 bool SCEVUnknown::isAlignOf(const Type *&AllocTy) const {
443 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
444 if (VCE->getOpcode() == Instruction::PtrToInt)
445 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
446 if (CE->getOpcode() == Instruction::GetElementPtr &&
447 CE->getOperand(0)->isNullValue()) {
449 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
450 if (const StructType *STy = dyn_cast<StructType>(Ty))
451 if (!STy->isPacked() &&
452 CE->getNumOperands() == 3 &&
453 CE->getOperand(1)->isNullValue()) {
454 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
456 STy->getNumElements() == 2 &&
457 STy->getElementType(0)->isIntegerTy(1)) {
458 AllocTy = STy->getElementType(1);
467 bool SCEVUnknown::isOffsetOf(const Type *&CTy, Constant *&FieldNo) const {
468 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
469 if (VCE->getOpcode() == Instruction::PtrToInt)
470 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
471 if (CE->getOpcode() == Instruction::GetElementPtr &&
472 CE->getNumOperands() == 3 &&
473 CE->getOperand(0)->isNullValue() &&
474 CE->getOperand(1)->isNullValue()) {
476 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
477 // Ignore vector types here so that ScalarEvolutionExpander doesn't
478 // emit getelementptrs that index into vectors.
479 if (Ty->isStructTy() || Ty->isArrayTy()) {
481 FieldNo = CE->getOperand(2);
489 void SCEVUnknown::print(raw_ostream &OS) const {
491 if (isSizeOf(AllocTy)) {
492 OS << "sizeof(" << *AllocTy << ")";
495 if (isAlignOf(AllocTy)) {
496 OS << "alignof(" << *AllocTy << ")";
502 if (isOffsetOf(CTy, FieldNo)) {
503 OS << "offsetof(" << *CTy << ", ";
504 WriteAsOperand(OS, FieldNo, false);
509 // Otherwise just print it normally.
510 WriteAsOperand(OS, getValue(), false);
513 //===----------------------------------------------------------------------===//
515 //===----------------------------------------------------------------------===//
518 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
519 /// than the complexity of the RHS. This comparator is used to canonicalize
521 class SCEVComplexityCompare {
522 const LoopInfo *const LI;
524 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
526 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
527 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
531 // Primarily, sort the SCEVs by their getSCEVType().
532 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
534 return LType < RType;
536 // Aside from the getSCEVType() ordering, the particular ordering
537 // isn't very important except that it's beneficial to be consistent,
538 // so that (a + b) and (b + a) don't end up as different expressions.
540 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
541 // not as complete as it could be.
542 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
543 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
544 const Value *LV = LU->getValue(), *RV = RU->getValue();
546 // Order pointer values after integer values. This helps SCEVExpander
548 bool LIsPointer = LV->getType()->isPointerTy(),
549 RIsPointer = RV->getType()->isPointerTy();
550 if (LIsPointer != RIsPointer)
553 // Compare getValueID values.
554 unsigned LID = LV->getValueID(),
555 RID = RV->getValueID();
559 // Sort arguments by their position.
560 if (const Argument *LA = dyn_cast<Argument>(LV)) {
561 const Argument *RA = cast<Argument>(RV);
562 return LA->getArgNo() < RA->getArgNo();
565 // For instructions, compare their loop depth, and their opcode.
566 // This is pretty loose.
567 if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
568 const Instruction *RInst = cast<Instruction>(RV);
570 // Compare loop depths.
571 const BasicBlock *LParent = LInst->getParent(),
572 *RParent = RInst->getParent();
573 if (LParent != RParent) {
574 unsigned LDepth = LI->getLoopDepth(LParent),
575 RDepth = LI->getLoopDepth(RParent);
576 if (LDepth != RDepth)
577 return LDepth < RDepth;
580 // Compare the number of operands.
581 unsigned LNumOps = LInst->getNumOperands(),
582 RNumOps = RInst->getNumOperands();
583 if (LNumOps != RNumOps)
584 return LNumOps < RNumOps;
590 // Compare constant values.
591 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
592 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
593 const APInt &LA = LC->getValue()->getValue();
594 const APInt &RA = RC->getValue()->getValue();
595 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
596 if (LBitWidth != RBitWidth)
597 return LBitWidth < RBitWidth;
601 // Compare addrec loop depths.
602 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
603 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
604 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
605 if (LLoop != RLoop) {
606 unsigned LDepth = LLoop->getLoopDepth(),
607 RDepth = RLoop->getLoopDepth();
608 if (LDepth != RDepth)
609 return LDepth < RDepth;
613 // Lexicographically compare n-ary expressions.
614 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
615 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
616 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
617 for (unsigned i = 0; i != LNumOps; ++i) {
620 const SCEV *LOp = LC->getOperand(i), *ROp = RC->getOperand(i);
621 if (operator()(LOp, ROp))
623 if (operator()(ROp, LOp))
626 return LNumOps < RNumOps;
629 // Lexicographically compare udiv expressions.
630 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
631 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
632 const SCEV *LL = LC->getLHS(), *LR = LC->getRHS(),
633 *RL = RC->getLHS(), *RR = RC->getRHS();
634 if (operator()(LL, RL))
636 if (operator()(RL, LL))
638 if (operator()(LR, RR))
640 if (operator()(RR, LR))
645 // Compare cast expressions by operand.
646 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
647 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
648 return operator()(LC->getOperand(), RC->getOperand());
651 llvm_unreachable("Unknown SCEV kind!");
657 /// GroupByComplexity - Given a list of SCEV objects, order them by their
658 /// complexity, and group objects of the same complexity together by value.
659 /// When this routine is finished, we know that any duplicates in the vector are
660 /// consecutive and that complexity is monotonically increasing.
662 /// Note that we go take special precautions to ensure that we get deterministic
663 /// results from this routine. In other words, we don't want the results of
664 /// this to depend on where the addresses of various SCEV objects happened to
667 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
669 if (Ops.size() < 2) return; // Noop
670 if (Ops.size() == 2) {
671 // This is the common case, which also happens to be trivially simple.
673 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
674 std::swap(Ops[0], Ops[1]);
678 // Do the rough sort by complexity.
679 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
681 // Now that we are sorted by complexity, group elements of the same
682 // complexity. Note that this is, at worst, N^2, but the vector is likely to
683 // be extremely short in practice. Note that we take this approach because we
684 // do not want to depend on the addresses of the objects we are grouping.
685 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
686 const SCEV *S = Ops[i];
687 unsigned Complexity = S->getSCEVType();
689 // If there are any objects of the same complexity and same value as this
691 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
692 if (Ops[j] == S) { // Found a duplicate.
693 // Move it to immediately after i'th element.
694 std::swap(Ops[i+1], Ops[j]);
695 ++i; // no need to rescan it.
696 if (i == e-2) return; // Done!
704 //===----------------------------------------------------------------------===//
705 // Simple SCEV method implementations
706 //===----------------------------------------------------------------------===//
708 /// BinomialCoefficient - Compute BC(It, K). The result has width W.
710 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
712 const Type* ResultTy) {
713 // Handle the simplest case efficiently.
715 return SE.getTruncateOrZeroExtend(It, ResultTy);
717 // We are using the following formula for BC(It, K):
719 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
721 // Suppose, W is the bitwidth of the return value. We must be prepared for
722 // overflow. Hence, we must assure that the result of our computation is
723 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
724 // safe in modular arithmetic.
726 // However, this code doesn't use exactly that formula; the formula it uses
727 // is something like the following, where T is the number of factors of 2 in
728 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
731 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
733 // This formula is trivially equivalent to the previous formula. However,
734 // this formula can be implemented much more efficiently. The trick is that
735 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
736 // arithmetic. To do exact division in modular arithmetic, all we have
737 // to do is multiply by the inverse. Therefore, this step can be done at
740 // The next issue is how to safely do the division by 2^T. The way this
741 // is done is by doing the multiplication step at a width of at least W + T
742 // bits. This way, the bottom W+T bits of the product are accurate. Then,
743 // when we perform the division by 2^T (which is equivalent to a right shift
744 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
745 // truncated out after the division by 2^T.
747 // In comparison to just directly using the first formula, this technique
748 // is much more efficient; using the first formula requires W * K bits,
749 // but this formula less than W + K bits. Also, the first formula requires
750 // a division step, whereas this formula only requires multiplies and shifts.
752 // It doesn't matter whether the subtraction step is done in the calculation
753 // width or the input iteration count's width; if the subtraction overflows,
754 // the result must be zero anyway. We prefer here to do it in the width of
755 // the induction variable because it helps a lot for certain cases; CodeGen
756 // isn't smart enough to ignore the overflow, which leads to much less
757 // efficient code if the width of the subtraction is wider than the native
760 // (It's possible to not widen at all by pulling out factors of 2 before
761 // the multiplication; for example, K=2 can be calculated as
762 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
763 // extra arithmetic, so it's not an obvious win, and it gets
764 // much more complicated for K > 3.)
766 // Protection from insane SCEVs; this bound is conservative,
767 // but it probably doesn't matter.
769 return SE.getCouldNotCompute();
771 unsigned W = SE.getTypeSizeInBits(ResultTy);
773 // Calculate K! / 2^T and T; we divide out the factors of two before
774 // multiplying for calculating K! / 2^T to avoid overflow.
775 // Other overflow doesn't matter because we only care about the bottom
776 // W bits of the result.
777 APInt OddFactorial(W, 1);
779 for (unsigned i = 3; i <= K; ++i) {
781 unsigned TwoFactors = Mult.countTrailingZeros();
783 Mult = Mult.lshr(TwoFactors);
784 OddFactorial *= Mult;
787 // We need at least W + T bits for the multiplication step
788 unsigned CalculationBits = W + T;
790 // Calculate 2^T, at width T+W.
791 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
793 // Calculate the multiplicative inverse of K! / 2^T;
794 // this multiplication factor will perform the exact division by
796 APInt Mod = APInt::getSignedMinValue(W+1);
797 APInt MultiplyFactor = OddFactorial.zext(W+1);
798 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
799 MultiplyFactor = MultiplyFactor.trunc(W);
801 // Calculate the product, at width T+W
802 const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
804 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
805 for (unsigned i = 1; i != K; ++i) {
806 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
807 Dividend = SE.getMulExpr(Dividend,
808 SE.getTruncateOrZeroExtend(S, CalculationTy));
812 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
814 // Truncate the result, and divide by K! / 2^T.
816 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
817 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
820 /// evaluateAtIteration - Return the value of this chain of recurrences at
821 /// the specified iteration number. We can evaluate this recurrence by
822 /// multiplying each element in the chain by the binomial coefficient
823 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
825 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
827 /// where BC(It, k) stands for binomial coefficient.
829 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
830 ScalarEvolution &SE) const {
831 const SCEV *Result = getStart();
832 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
833 // The computation is correct in the face of overflow provided that the
834 // multiplication is performed _after_ the evaluation of the binomial
836 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
837 if (isa<SCEVCouldNotCompute>(Coeff))
840 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
845 //===----------------------------------------------------------------------===//
846 // SCEV Expression folder implementations
847 //===----------------------------------------------------------------------===//
849 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
851 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
852 "This is not a truncating conversion!");
853 assert(isSCEVable(Ty) &&
854 "This is not a conversion to a SCEVable type!");
855 Ty = getEffectiveSCEVType(Ty);
858 ID.AddInteger(scTruncate);
862 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
864 // Fold if the operand is constant.
865 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
867 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(),
868 getEffectiveSCEVType(Ty))));
870 // trunc(trunc(x)) --> trunc(x)
871 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
872 return getTruncateExpr(ST->getOperand(), Ty);
874 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
875 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
876 return getTruncateOrSignExtend(SS->getOperand(), Ty);
878 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
879 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
880 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
882 // If the input value is a chrec scev, truncate the chrec's operands.
883 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
884 SmallVector<const SCEV *, 4> Operands;
885 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
886 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
887 return getAddRecExpr(Operands, AddRec->getLoop());
890 // As a special case, fold trunc(undef) to undef. We don't want to
891 // know too much about SCEVUnknowns, but this special case is handy
893 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
894 if (isa<UndefValue>(U->getValue()))
895 return getSCEV(UndefValue::get(Ty));
897 // The cast wasn't folded; create an explicit cast node. We can reuse
898 // the existing insert position since if we get here, we won't have
899 // made any changes which would invalidate it.
900 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
902 UniqueSCEVs.InsertNode(S, IP);
906 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
908 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
909 "This is not an extending conversion!");
910 assert(isSCEVable(Ty) &&
911 "This is not a conversion to a SCEVable type!");
912 Ty = getEffectiveSCEVType(Ty);
914 // Fold if the operand is constant.
915 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
917 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(),
918 getEffectiveSCEVType(Ty))));
920 // zext(zext(x)) --> zext(x)
921 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
922 return getZeroExtendExpr(SZ->getOperand(), Ty);
924 // Before doing any expensive analysis, check to see if we've already
925 // computed a SCEV for this Op and Ty.
927 ID.AddInteger(scZeroExtend);
931 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
933 // If the input value is a chrec scev, and we can prove that the value
934 // did not overflow the old, smaller, value, we can zero extend all of the
935 // operands (often constants). This allows analysis of something like
936 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
937 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
938 if (AR->isAffine()) {
939 const SCEV *Start = AR->getStart();
940 const SCEV *Step = AR->getStepRecurrence(*this);
941 unsigned BitWidth = getTypeSizeInBits(AR->getType());
942 const Loop *L = AR->getLoop();
944 // If we have special knowledge that this addrec won't overflow,
945 // we don't need to do any further analysis.
946 if (AR->hasNoUnsignedWrap())
947 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
948 getZeroExtendExpr(Step, Ty),
951 // Check whether the backedge-taken count is SCEVCouldNotCompute.
952 // Note that this serves two purposes: It filters out loops that are
953 // simply not analyzable, and it covers the case where this code is
954 // being called from within backedge-taken count analysis, such that
955 // attempting to ask for the backedge-taken count would likely result
956 // in infinite recursion. In the later case, the analysis code will
957 // cope with a conservative value, and it will take care to purge
958 // that value once it has finished.
959 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
960 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
961 // Manually compute the final value for AR, checking for
964 // Check whether the backedge-taken count can be losslessly casted to
965 // the addrec's type. The count is always unsigned.
966 const SCEV *CastedMaxBECount =
967 getTruncateOrZeroExtend(MaxBECount, Start->getType());
968 const SCEV *RecastedMaxBECount =
969 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
970 if (MaxBECount == RecastedMaxBECount) {
971 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
972 // Check whether Start+Step*MaxBECount has no unsigned overflow.
973 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
974 const SCEV *Add = getAddExpr(Start, ZMul);
975 const SCEV *OperandExtendedAdd =
976 getAddExpr(getZeroExtendExpr(Start, WideTy),
977 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
978 getZeroExtendExpr(Step, WideTy)));
979 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
980 // Return the expression with the addrec on the outside.
981 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
982 getZeroExtendExpr(Step, Ty),
985 // Similar to above, only this time treat the step value as signed.
986 // This covers loops that count down.
987 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
988 Add = getAddExpr(Start, SMul);
990 getAddExpr(getZeroExtendExpr(Start, WideTy),
991 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
992 getSignExtendExpr(Step, WideTy)));
993 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
994 // Return the expression with the addrec on the outside.
995 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
996 getSignExtendExpr(Step, Ty),
1000 // If the backedge is guarded by a comparison with the pre-inc value
1001 // the addrec is safe. Also, if the entry is guarded by a comparison
1002 // with the start value and the backedge is guarded by a comparison
1003 // with the post-inc value, the addrec is safe.
1004 if (isKnownPositive(Step)) {
1005 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1006 getUnsignedRange(Step).getUnsignedMax());
1007 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1008 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
1009 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
1010 AR->getPostIncExpr(*this), N)))
1011 // Return the expression with the addrec on the outside.
1012 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1013 getZeroExtendExpr(Step, Ty),
1015 } else if (isKnownNegative(Step)) {
1016 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1017 getSignedRange(Step).getSignedMin());
1018 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1019 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
1020 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1021 AR->getPostIncExpr(*this), N)))
1022 // Return the expression with the addrec on the outside.
1023 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1024 getSignExtendExpr(Step, Ty),
1030 // The cast wasn't folded; create an explicit cast node.
1031 // Recompute the insert position, as it may have been invalidated.
1032 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1033 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1035 UniqueSCEVs.InsertNode(S, IP);
1039 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
1041 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1042 "This is not an extending conversion!");
1043 assert(isSCEVable(Ty) &&
1044 "This is not a conversion to a SCEVable type!");
1045 Ty = getEffectiveSCEVType(Ty);
1047 // Fold if the operand is constant.
1048 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1050 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(),
1051 getEffectiveSCEVType(Ty))));
1053 // sext(sext(x)) --> sext(x)
1054 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1055 return getSignExtendExpr(SS->getOperand(), Ty);
1057 // Before doing any expensive analysis, check to see if we've already
1058 // computed a SCEV for this Op and Ty.
1059 FoldingSetNodeID ID;
1060 ID.AddInteger(scSignExtend);
1064 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1066 // If the input value is a chrec scev, and we can prove that the value
1067 // did not overflow the old, smaller, value, we can sign extend all of the
1068 // operands (often constants). This allows analysis of something like
1069 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1070 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1071 if (AR->isAffine()) {
1072 const SCEV *Start = AR->getStart();
1073 const SCEV *Step = AR->getStepRecurrence(*this);
1074 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1075 const Loop *L = AR->getLoop();
1077 // If we have special knowledge that this addrec won't overflow,
1078 // we don't need to do any further analysis.
1079 if (AR->hasNoSignedWrap())
1080 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1081 getSignExtendExpr(Step, Ty),
1084 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1085 // Note that this serves two purposes: It filters out loops that are
1086 // simply not analyzable, and it covers the case where this code is
1087 // being called from within backedge-taken count analysis, such that
1088 // attempting to ask for the backedge-taken count would likely result
1089 // in infinite recursion. In the later case, the analysis code will
1090 // cope with a conservative value, and it will take care to purge
1091 // that value once it has finished.
1092 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1093 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1094 // Manually compute the final value for AR, checking for
1097 // Check whether the backedge-taken count can be losslessly casted to
1098 // the addrec's type. The count is always unsigned.
1099 const SCEV *CastedMaxBECount =
1100 getTruncateOrZeroExtend(MaxBECount, Start->getType());
1101 const SCEV *RecastedMaxBECount =
1102 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1103 if (MaxBECount == RecastedMaxBECount) {
1104 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1105 // Check whether Start+Step*MaxBECount has no signed overflow.
1106 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
1107 const SCEV *Add = getAddExpr(Start, SMul);
1108 const SCEV *OperandExtendedAdd =
1109 getAddExpr(getSignExtendExpr(Start, WideTy),
1110 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1111 getSignExtendExpr(Step, WideTy)));
1112 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
1113 // Return the expression with the addrec on the outside.
1114 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1115 getSignExtendExpr(Step, Ty),
1118 // Similar to above, only this time treat the step value as unsigned.
1119 // This covers loops that count up with an unsigned step.
1120 const SCEV *UMul = getMulExpr(CastedMaxBECount, Step);
1121 Add = getAddExpr(Start, UMul);
1122 OperandExtendedAdd =
1123 getAddExpr(getSignExtendExpr(Start, WideTy),
1124 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1125 getZeroExtendExpr(Step, WideTy)));
1126 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
1127 // Return the expression with the addrec on the outside.
1128 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1129 getZeroExtendExpr(Step, Ty),
1133 // If the backedge is guarded by a comparison with the pre-inc value
1134 // the addrec is safe. Also, if the entry is guarded by a comparison
1135 // with the start value and the backedge is guarded by a comparison
1136 // with the post-inc value, the addrec is safe.
1137 if (isKnownPositive(Step)) {
1138 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
1139 getSignedRange(Step).getSignedMax());
1140 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
1141 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
1142 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
1143 AR->getPostIncExpr(*this), N)))
1144 // Return the expression with the addrec on the outside.
1145 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1146 getSignExtendExpr(Step, Ty),
1148 } else if (isKnownNegative(Step)) {
1149 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1150 getSignedRange(Step).getSignedMin());
1151 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
1152 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
1153 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1154 AR->getPostIncExpr(*this), N)))
1155 // Return the expression with the addrec on the outside.
1156 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1157 getSignExtendExpr(Step, Ty),
1163 // The cast wasn't folded; create an explicit cast node.
1164 // Recompute the insert position, as it may have been invalidated.
1165 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1166 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1168 UniqueSCEVs.InsertNode(S, IP);
1172 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1173 /// unspecified bits out to the given type.
1175 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1177 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1178 "This is not an extending conversion!");
1179 assert(isSCEVable(Ty) &&
1180 "This is not a conversion to a SCEVable type!");
1181 Ty = getEffectiveSCEVType(Ty);
1183 // Sign-extend negative constants.
1184 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1185 if (SC->getValue()->getValue().isNegative())
1186 return getSignExtendExpr(Op, Ty);
1188 // Peel off a truncate cast.
1189 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
1190 const SCEV *NewOp = T->getOperand();
1191 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1192 return getAnyExtendExpr(NewOp, Ty);
1193 return getTruncateOrNoop(NewOp, Ty);
1196 // Next try a zext cast. If the cast is folded, use it.
1197 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
1198 if (!isa<SCEVZeroExtendExpr>(ZExt))
1201 // Next try a sext cast. If the cast is folded, use it.
1202 const SCEV *SExt = getSignExtendExpr(Op, Ty);
1203 if (!isa<SCEVSignExtendExpr>(SExt))
1206 // Force the cast to be folded into the operands of an addrec.
1207 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1208 SmallVector<const SCEV *, 4> Ops;
1209 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
1211 Ops.push_back(getAnyExtendExpr(*I, Ty));
1212 return getAddRecExpr(Ops, AR->getLoop());
1215 // As a special case, fold anyext(undef) to undef. We don't want to
1216 // know too much about SCEVUnknowns, but this special case is handy
1218 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
1219 if (isa<UndefValue>(U->getValue()))
1220 return getSCEV(UndefValue::get(Ty));
1222 // If the expression is obviously signed, use the sext cast value.
1223 if (isa<SCEVSMaxExpr>(Op))
1226 // Absent any other information, use the zext cast value.
1230 /// CollectAddOperandsWithScales - Process the given Ops list, which is
1231 /// a list of operands to be added under the given scale, update the given
1232 /// map. This is a helper function for getAddRecExpr. As an example of
1233 /// what it does, given a sequence of operands that would form an add
1234 /// expression like this:
1236 /// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1238 /// where A and B are constants, update the map with these values:
1240 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1242 /// and add 13 + A*B*29 to AccumulatedConstant.
1243 /// This will allow getAddRecExpr to produce this:
1245 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1247 /// This form often exposes folding opportunities that are hidden in
1248 /// the original operand list.
1250 /// Return true iff it appears that any interesting folding opportunities
1251 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
1252 /// the common case where no interesting opportunities are present, and
1253 /// is also used as a check to avoid infinite recursion.
1256 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1257 SmallVector<const SCEV *, 8> &NewOps,
1258 APInt &AccumulatedConstant,
1259 const SCEV *const *Ops, size_t NumOperands,
1261 ScalarEvolution &SE) {
1262 bool Interesting = false;
1264 // Iterate over the add operands. They are sorted, with constants first.
1266 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1268 // Pull a buried constant out to the outside.
1269 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1271 AccumulatedConstant += Scale * C->getValue()->getValue();
1274 // Next comes everything else. We're especially interested in multiplies
1275 // here, but they're in the middle, so just visit the rest with one loop.
1276 for (; i != NumOperands; ++i) {
1277 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1278 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1280 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1281 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1282 // A multiplication of a constant with another add; recurse.
1283 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
1285 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1286 Add->op_begin(), Add->getNumOperands(),
1289 // A multiplication of a constant with some other value. Update
1291 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1292 const SCEV *Key = SE.getMulExpr(MulOps);
1293 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1294 M.insert(std::make_pair(Key, NewScale));
1296 NewOps.push_back(Pair.first->first);
1298 Pair.first->second += NewScale;
1299 // The map already had an entry for this value, which may indicate
1300 // a folding opportunity.
1305 // An ordinary operand. Update the map.
1306 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1307 M.insert(std::make_pair(Ops[i], Scale));
1309 NewOps.push_back(Pair.first->first);
1311 Pair.first->second += Scale;
1312 // The map already had an entry for this value, which may indicate
1313 // a folding opportunity.
1323 struct APIntCompare {
1324 bool operator()(const APInt &LHS, const APInt &RHS) const {
1325 return LHS.ult(RHS);
1330 /// getAddExpr - Get a canonical add expression, or something simpler if
1332 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1333 bool HasNUW, bool HasNSW) {
1334 assert(!Ops.empty() && "Cannot get empty add!");
1335 if (Ops.size() == 1) return Ops[0];
1337 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
1338 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1339 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
1340 "SCEVAddExpr operand types don't match!");
1343 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1344 if (!HasNUW && HasNSW) {
1346 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
1347 E = Ops.end(); I != E; ++I)
1348 if (!isKnownNonNegative(*I)) {
1352 if (All) HasNUW = true;
1355 // Sort by complexity, this groups all similar expression types together.
1356 GroupByComplexity(Ops, LI);
1358 // If there are any constants, fold them together.
1360 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1362 assert(Idx < Ops.size());
1363 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1364 // We found two constants, fold them together!
1365 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1366 RHSC->getValue()->getValue());
1367 if (Ops.size() == 2) return Ops[0];
1368 Ops.erase(Ops.begin()+1); // Erase the folded element
1369 LHSC = cast<SCEVConstant>(Ops[0]);
1372 // If we are left with a constant zero being added, strip it off.
1373 if (LHSC->getValue()->isZero()) {
1374 Ops.erase(Ops.begin());
1378 if (Ops.size() == 1) return Ops[0];
1381 // Okay, check to see if the same value occurs in the operand list twice. If
1382 // so, merge them together into an multiply expression. Since we sorted the
1383 // list, these values are required to be adjacent.
1384 const Type *Ty = Ops[0]->getType();
1385 bool FoundMatch = false;
1386 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1387 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1388 // Found a match, merge the two values into a multiply, and add any
1389 // remaining values to the result.
1390 const SCEV *Two = getConstant(Ty, 2);
1391 const SCEV *Mul = getMulExpr(Two, Ops[i]);
1392 if (Ops.size() == 2)
1395 Ops.erase(Ops.begin()+i+1);
1400 return getAddExpr(Ops, HasNUW, HasNSW);
1402 // Check for truncates. If all the operands are truncated from the same
1403 // type, see if factoring out the truncate would permit the result to be
1404 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1405 // if the contents of the resulting outer trunc fold to something simple.
1406 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1407 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1408 const Type *DstType = Trunc->getType();
1409 const Type *SrcType = Trunc->getOperand()->getType();
1410 SmallVector<const SCEV *, 8> LargeOps;
1412 // Check all the operands to see if they can be represented in the
1413 // source type of the truncate.
1414 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1415 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1416 if (T->getOperand()->getType() != SrcType) {
1420 LargeOps.push_back(T->getOperand());
1421 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1422 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
1423 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
1424 SmallVector<const SCEV *, 8> LargeMulOps;
1425 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1426 if (const SCEVTruncateExpr *T =
1427 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1428 if (T->getOperand()->getType() != SrcType) {
1432 LargeMulOps.push_back(T->getOperand());
1433 } else if (const SCEVConstant *C =
1434 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1435 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
1442 LargeOps.push_back(getMulExpr(LargeMulOps));
1449 // Evaluate the expression in the larger type.
1450 const SCEV *Fold = getAddExpr(LargeOps, HasNUW, HasNSW);
1451 // If it folds to something simple, use it. Otherwise, don't.
1452 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1453 return getTruncateExpr(Fold, DstType);
1457 // Skip past any other cast SCEVs.
1458 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1461 // If there are add operands they would be next.
1462 if (Idx < Ops.size()) {
1463 bool DeletedAdd = false;
1464 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
1465 // If we have an add, expand the add operands onto the end of the operands
1467 Ops.erase(Ops.begin()+Idx);
1468 Ops.append(Add->op_begin(), Add->op_end());
1472 // If we deleted at least one add, we added operands to the end of the list,
1473 // and they are not necessarily sorted. Recurse to resort and resimplify
1474 // any operands we just acquired.
1476 return getAddExpr(Ops);
1479 // Skip over the add expression until we get to a multiply.
1480 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1483 // Check to see if there are any folding opportunities present with
1484 // operands multiplied by constant values.
1485 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1486 uint64_t BitWidth = getTypeSizeInBits(Ty);
1487 DenseMap<const SCEV *, APInt> M;
1488 SmallVector<const SCEV *, 8> NewOps;
1489 APInt AccumulatedConstant(BitWidth, 0);
1490 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1491 Ops.data(), Ops.size(),
1492 APInt(BitWidth, 1), *this)) {
1493 // Some interesting folding opportunity is present, so its worthwhile to
1494 // re-generate the operands list. Group the operands by constant scale,
1495 // to avoid multiplying by the same constant scale multiple times.
1496 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1497 for (SmallVector<const SCEV *, 8>::const_iterator I = NewOps.begin(),
1498 E = NewOps.end(); I != E; ++I)
1499 MulOpLists[M.find(*I)->second].push_back(*I);
1500 // Re-generate the operands list.
1502 if (AccumulatedConstant != 0)
1503 Ops.push_back(getConstant(AccumulatedConstant));
1504 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1505 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
1507 Ops.push_back(getMulExpr(getConstant(I->first),
1508 getAddExpr(I->second)));
1510 return getConstant(Ty, 0);
1511 if (Ops.size() == 1)
1513 return getAddExpr(Ops);
1517 // If we are adding something to a multiply expression, make sure the
1518 // something is not already an operand of the multiply. If so, merge it into
1520 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
1521 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
1522 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
1523 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
1524 if (isa<SCEVConstant>(MulOpSCEV))
1526 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
1527 if (MulOpSCEV == Ops[AddOp]) {
1528 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1529 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
1530 if (Mul->getNumOperands() != 2) {
1531 // If the multiply has more than two operands, we must get the
1533 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
1534 MulOps.erase(MulOps.begin()+MulOp);
1535 InnerMul = getMulExpr(MulOps);
1537 const SCEV *One = getConstant(Ty, 1);
1538 const SCEV *AddOne = getAddExpr(One, InnerMul);
1539 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
1540 if (Ops.size() == 2) return OuterMul;
1542 Ops.erase(Ops.begin()+AddOp);
1543 Ops.erase(Ops.begin()+Idx-1);
1545 Ops.erase(Ops.begin()+Idx);
1546 Ops.erase(Ops.begin()+AddOp-1);
1548 Ops.push_back(OuterMul);
1549 return getAddExpr(Ops);
1552 // Check this multiply against other multiplies being added together.
1553 bool AnyFold = false;
1554 for (unsigned OtherMulIdx = Idx+1;
1555 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1557 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
1558 // If MulOp occurs in OtherMul, we can fold the two multiplies
1560 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1561 OMulOp != e; ++OMulOp)
1562 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1563 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1564 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
1565 if (Mul->getNumOperands() != 2) {
1566 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1568 MulOps.erase(MulOps.begin()+MulOp);
1569 InnerMul1 = getMulExpr(MulOps);
1571 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1572 if (OtherMul->getNumOperands() != 2) {
1573 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1574 OtherMul->op_end());
1575 MulOps.erase(MulOps.begin()+OMulOp);
1576 InnerMul2 = getMulExpr(MulOps);
1578 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1579 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
1580 if (Ops.size() == 2) return OuterMul;
1581 Ops[Idx] = OuterMul;
1582 Ops.erase(Ops.begin()+OtherMulIdx);
1588 return getAddExpr(Ops);
1592 // If there are any add recurrences in the operands list, see if any other
1593 // added values are loop invariant. If so, we can fold them into the
1595 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1598 // Scan over all recurrences, trying to fold loop invariants into them.
1599 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1600 // Scan all of the other operands to this add and add them to the vector if
1601 // they are loop invariant w.r.t. the recurrence.
1602 SmallVector<const SCEV *, 8> LIOps;
1603 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1604 const Loop *AddRecLoop = AddRec->getLoop();
1605 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1606 if (Ops[i]->isLoopInvariant(AddRecLoop)) {
1607 LIOps.push_back(Ops[i]);
1608 Ops.erase(Ops.begin()+i);
1612 // If we found some loop invariants, fold them into the recurrence.
1613 if (!LIOps.empty()) {
1614 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
1615 LIOps.push_back(AddRec->getStart());
1617 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
1619 AddRecOps[0] = getAddExpr(LIOps);
1621 // Build the new addrec. Propagate the NUW and NSW flags if both the
1622 // outer add and the inner addrec are guaranteed to have no overflow.
1623 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop,
1624 HasNUW && AddRec->hasNoUnsignedWrap(),
1625 HasNSW && AddRec->hasNoSignedWrap());
1627 // If all of the other operands were loop invariant, we are done.
1628 if (Ops.size() == 1) return NewRec;
1630 // Otherwise, add the folded AddRec by the non-liv parts.
1631 for (unsigned i = 0;; ++i)
1632 if (Ops[i] == AddRec) {
1636 return getAddExpr(Ops);
1639 // Okay, if there weren't any loop invariants to be folded, check to see if
1640 // there are multiple AddRec's with the same loop induction variable being
1641 // added together. If so, we can fold them.
1642 for (unsigned OtherIdx = Idx+1;
1643 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1644 if (OtherIdx != Idx) {
1645 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1646 if (AddRecLoop == OtherAddRec->getLoop()) {
1647 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1648 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1650 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1651 if (i >= NewOps.size()) {
1652 NewOps.append(OtherAddRec->op_begin()+i,
1653 OtherAddRec->op_end());
1656 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
1658 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRecLoop);
1660 if (Ops.size() == 2) return NewAddRec;
1662 Ops.erase(Ops.begin()+Idx);
1663 Ops.erase(Ops.begin()+OtherIdx-1);
1664 Ops.push_back(NewAddRec);
1665 return getAddExpr(Ops);
1669 // Otherwise couldn't fold anything into this recurrence. Move onto the
1673 // Okay, it looks like we really DO need an add expr. Check to see if we
1674 // already have one, otherwise create a new one.
1675 FoldingSetNodeID ID;
1676 ID.AddInteger(scAddExpr);
1677 ID.AddInteger(Ops.size());
1678 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1679 ID.AddPointer(Ops[i]);
1682 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1684 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1685 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
1686 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
1688 UniqueSCEVs.InsertNode(S, IP);
1690 if (HasNUW) S->setHasNoUnsignedWrap(true);
1691 if (HasNSW) S->setHasNoSignedWrap(true);
1695 /// getMulExpr - Get a canonical multiply expression, or something simpler if
1697 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1698 bool HasNUW, bool HasNSW) {
1699 assert(!Ops.empty() && "Cannot get empty mul!");
1700 if (Ops.size() == 1) return Ops[0];
1702 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
1703 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1704 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
1705 "SCEVMulExpr operand types don't match!");
1708 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1709 if (!HasNUW && HasNSW) {
1711 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
1712 E = Ops.end(); I != E; ++I)
1713 if (!isKnownNonNegative(*I)) {
1717 if (All) HasNUW = true;
1720 // Sort by complexity, this groups all similar expression types together.
1721 GroupByComplexity(Ops, LI);
1723 // If there are any constants, fold them together.
1725 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1727 // C1*(C2+V) -> C1*C2 + C1*V
1728 if (Ops.size() == 2)
1729 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1730 if (Add->getNumOperands() == 2 &&
1731 isa<SCEVConstant>(Add->getOperand(0)))
1732 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1733 getMulExpr(LHSC, Add->getOperand(1)));
1736 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1737 // We found two constants, fold them together!
1738 ConstantInt *Fold = ConstantInt::get(getContext(),
1739 LHSC->getValue()->getValue() *
1740 RHSC->getValue()->getValue());
1741 Ops[0] = getConstant(Fold);
1742 Ops.erase(Ops.begin()+1); // Erase the folded element
1743 if (Ops.size() == 1) return Ops[0];
1744 LHSC = cast<SCEVConstant>(Ops[0]);
1747 // If we are left with a constant one being multiplied, strip it off.
1748 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1749 Ops.erase(Ops.begin());
1751 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1752 // If we have a multiply of zero, it will always be zero.
1754 } else if (Ops[0]->isAllOnesValue()) {
1755 // If we have a mul by -1 of an add, try distributing the -1 among the
1757 if (Ops.size() == 2)
1758 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1759 SmallVector<const SCEV *, 4> NewOps;
1760 bool AnyFolded = false;
1761 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1763 const SCEV *Mul = getMulExpr(Ops[0], *I);
1764 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1765 NewOps.push_back(Mul);
1768 return getAddExpr(NewOps);
1772 if (Ops.size() == 1)
1776 // Skip over the add expression until we get to a multiply.
1777 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1780 // If there are mul operands inline them all into this expression.
1781 if (Idx < Ops.size()) {
1782 bool DeletedMul = false;
1783 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1784 // If we have an mul, expand the mul operands onto the end of the operands
1786 Ops.erase(Ops.begin()+Idx);
1787 Ops.append(Mul->op_begin(), Mul->op_end());
1791 // If we deleted at least one mul, we added operands to the end of the list,
1792 // and they are not necessarily sorted. Recurse to resort and resimplify
1793 // any operands we just acquired.
1795 return getMulExpr(Ops);
1798 // If there are any add recurrences in the operands list, see if any other
1799 // added values are loop invariant. If so, we can fold them into the
1801 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1804 // Scan over all recurrences, trying to fold loop invariants into them.
1805 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1806 // Scan all of the other operands to this mul and add them to the vector if
1807 // they are loop invariant w.r.t. the recurrence.
1808 SmallVector<const SCEV *, 8> LIOps;
1809 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1810 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1811 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1812 LIOps.push_back(Ops[i]);
1813 Ops.erase(Ops.begin()+i);
1817 // If we found some loop invariants, fold them into the recurrence.
1818 if (!LIOps.empty()) {
1819 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
1820 SmallVector<const SCEV *, 4> NewOps;
1821 NewOps.reserve(AddRec->getNumOperands());
1822 const SCEV *Scale = getMulExpr(LIOps);
1823 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1824 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1826 // Build the new addrec. Propagate the NUW and NSW flags if both the
1827 // outer mul and the inner addrec are guaranteed to have no overflow.
1828 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(),
1829 HasNUW && AddRec->hasNoUnsignedWrap(),
1830 HasNSW && AddRec->hasNoSignedWrap());
1832 // If all of the other operands were loop invariant, we are done.
1833 if (Ops.size() == 1) return NewRec;
1835 // Otherwise, multiply the folded AddRec by the non-liv parts.
1836 for (unsigned i = 0;; ++i)
1837 if (Ops[i] == AddRec) {
1841 return getMulExpr(Ops);
1844 // Okay, if there weren't any loop invariants to be folded, check to see if
1845 // there are multiple AddRec's with the same loop induction variable being
1846 // multiplied together. If so, we can fold them.
1847 for (unsigned OtherIdx = Idx+1;
1848 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1849 if (OtherIdx != Idx) {
1850 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1851 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1852 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1853 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1854 const SCEV *NewStart = getMulExpr(F->getStart(), G->getStart());
1855 const SCEV *B = F->getStepRecurrence(*this);
1856 const SCEV *D = G->getStepRecurrence(*this);
1857 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
1860 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
1862 if (Ops.size() == 2) return NewAddRec;
1864 Ops.erase(Ops.begin()+Idx);
1865 Ops.erase(Ops.begin()+OtherIdx-1);
1866 Ops.push_back(NewAddRec);
1867 return getMulExpr(Ops);
1871 // Otherwise couldn't fold anything into this recurrence. Move onto the
1875 // Okay, it looks like we really DO need an mul expr. Check to see if we
1876 // already have one, otherwise create a new one.
1877 FoldingSetNodeID ID;
1878 ID.AddInteger(scMulExpr);
1879 ID.AddInteger(Ops.size());
1880 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1881 ID.AddPointer(Ops[i]);
1884 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1886 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1887 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
1888 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
1890 UniqueSCEVs.InsertNode(S, IP);
1892 if (HasNUW) S->setHasNoUnsignedWrap(true);
1893 if (HasNSW) S->setHasNoSignedWrap(true);
1897 /// getUDivExpr - Get a canonical unsigned division expression, or something
1898 /// simpler if possible.
1899 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1901 assert(getEffectiveSCEVType(LHS->getType()) ==
1902 getEffectiveSCEVType(RHS->getType()) &&
1903 "SCEVUDivExpr operand types don't match!");
1905 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1906 if (RHSC->getValue()->equalsInt(1))
1907 return LHS; // X udiv 1 --> x
1908 // If the denominator is zero, the result of the udiv is undefined. Don't
1909 // try to analyze it, because the resolution chosen here may differ from
1910 // the resolution chosen in other parts of the compiler.
1911 if (!RHSC->getValue()->isZero()) {
1912 // Determine if the division can be folded into the operands of
1914 // TODO: Generalize this to non-constants by using known-bits information.
1915 const Type *Ty = LHS->getType();
1916 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1917 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
1918 // For non-power-of-two values, effectively round the value up to the
1919 // nearest power of two.
1920 if (!RHSC->getValue()->getValue().isPowerOf2())
1922 const IntegerType *ExtTy =
1923 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
1924 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1925 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1926 if (const SCEVConstant *Step =
1927 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1928 if (!Step->getValue()->getValue()
1929 .urem(RHSC->getValue()->getValue()) &&
1930 getZeroExtendExpr(AR, ExtTy) ==
1931 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1932 getZeroExtendExpr(Step, ExtTy),
1934 SmallVector<const SCEV *, 4> Operands;
1935 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1936 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1937 return getAddRecExpr(Operands, AR->getLoop());
1939 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1940 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1941 SmallVector<const SCEV *, 4> Operands;
1942 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1943 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1944 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
1945 // Find an operand that's safely divisible.
1946 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1947 const SCEV *Op = M->getOperand(i);
1948 const SCEV *Div = getUDivExpr(Op, RHSC);
1949 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1950 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
1953 return getMulExpr(Operands);
1957 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
1958 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1959 SmallVector<const SCEV *, 4> Operands;
1960 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1961 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1962 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1964 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1965 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
1966 if (isa<SCEVUDivExpr>(Op) ||
1967 getMulExpr(Op, RHS) != A->getOperand(i))
1969 Operands.push_back(Op);
1971 if (Operands.size() == A->getNumOperands())
1972 return getAddExpr(Operands);
1976 // Fold if both operands are constant.
1977 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1978 Constant *LHSCV = LHSC->getValue();
1979 Constant *RHSCV = RHSC->getValue();
1980 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1986 FoldingSetNodeID ID;
1987 ID.AddInteger(scUDivExpr);
1991 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1992 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
1994 UniqueSCEVs.InsertNode(S, IP);
1999 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
2000 /// Simplify the expression as much as possible.
2001 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
2002 const SCEV *Step, const Loop *L,
2003 bool HasNUW, bool HasNSW) {
2004 SmallVector<const SCEV *, 4> Operands;
2005 Operands.push_back(Start);
2006 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
2007 if (StepChrec->getLoop() == L) {
2008 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
2009 return getAddRecExpr(Operands, L);
2012 Operands.push_back(Step);
2013 return getAddRecExpr(Operands, L, HasNUW, HasNSW);
2016 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
2017 /// Simplify the expression as much as possible.
2019 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
2021 bool HasNUW, bool HasNSW) {
2022 if (Operands.size() == 1) return Operands[0];
2024 const Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
2025 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
2026 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
2027 "SCEVAddRecExpr operand types don't match!");
2030 if (Operands.back()->isZero()) {
2031 Operands.pop_back();
2032 return getAddRecExpr(Operands, L, HasNUW, HasNSW); // {X,+,0} --> X
2035 // It's tempting to want to call getMaxBackedgeTakenCount count here and
2036 // use that information to infer NUW and NSW flags. However, computing a
2037 // BE count requires calling getAddRecExpr, so we may not yet have a
2038 // meaningful BE count at this point (and if we don't, we'd be stuck
2039 // with a SCEVCouldNotCompute as the cached BE count).
2041 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
2042 if (!HasNUW && HasNSW) {
2044 for (SmallVectorImpl<const SCEV *>::const_iterator I = Operands.begin(),
2045 E = Operands.end(); I != E; ++I)
2046 if (!isKnownNonNegative(*I)) {
2050 if (All) HasNUW = true;
2053 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
2054 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
2055 const Loop *NestedLoop = NestedAR->getLoop();
2056 if (L->contains(NestedLoop) ?
2057 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
2058 (!NestedLoop->contains(L) &&
2059 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
2060 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
2061 NestedAR->op_end());
2062 Operands[0] = NestedAR->getStart();
2063 // AddRecs require their operands be loop-invariant with respect to their
2064 // loops. Don't perform this transformation if it would break this
2066 bool AllInvariant = true;
2067 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2068 if (!Operands[i]->isLoopInvariant(L)) {
2069 AllInvariant = false;
2073 NestedOperands[0] = getAddRecExpr(Operands, L);
2074 AllInvariant = true;
2075 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
2076 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
2077 AllInvariant = false;
2081 // Ok, both add recurrences are valid after the transformation.
2082 return getAddRecExpr(NestedOperands, NestedLoop, HasNUW, HasNSW);
2084 // Reset Operands to its original state.
2085 Operands[0] = NestedAR;
2089 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2090 // already have one, otherwise create a new one.
2091 FoldingSetNodeID ID;
2092 ID.AddInteger(scAddRecExpr);
2093 ID.AddInteger(Operands.size());
2094 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2095 ID.AddPointer(Operands[i]);
2099 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2101 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2102 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
2103 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2104 O, Operands.size(), L);
2105 UniqueSCEVs.InsertNode(S, IP);
2107 if (HasNUW) S->setHasNoUnsignedWrap(true);
2108 if (HasNSW) S->setHasNoSignedWrap(true);
2112 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2114 SmallVector<const SCEV *, 2> Ops;
2117 return getSMaxExpr(Ops);
2121 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2122 assert(!Ops.empty() && "Cannot get empty smax!");
2123 if (Ops.size() == 1) return Ops[0];
2125 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2126 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2127 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2128 "SCEVSMaxExpr operand types don't match!");
2131 // Sort by complexity, this groups all similar expression types together.
2132 GroupByComplexity(Ops, LI);
2134 // If there are any constants, fold them together.
2136 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2138 assert(Idx < Ops.size());
2139 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2140 // We found two constants, fold them together!
2141 ConstantInt *Fold = ConstantInt::get(getContext(),
2142 APIntOps::smax(LHSC->getValue()->getValue(),
2143 RHSC->getValue()->getValue()));
2144 Ops[0] = getConstant(Fold);
2145 Ops.erase(Ops.begin()+1); // Erase the folded element
2146 if (Ops.size() == 1) return Ops[0];
2147 LHSC = cast<SCEVConstant>(Ops[0]);
2150 // If we are left with a constant minimum-int, strip it off.
2151 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2152 Ops.erase(Ops.begin());
2154 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2155 // If we have an smax with a constant maximum-int, it will always be
2160 if (Ops.size() == 1) return Ops[0];
2163 // Find the first SMax
2164 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2167 // Check to see if one of the operands is an SMax. If so, expand its operands
2168 // onto our operand list, and recurse to simplify.
2169 if (Idx < Ops.size()) {
2170 bool DeletedSMax = false;
2171 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
2172 Ops.erase(Ops.begin()+Idx);
2173 Ops.append(SMax->op_begin(), SMax->op_end());
2178 return getSMaxExpr(Ops);
2181 // Okay, check to see if the same value occurs in the operand list twice. If
2182 // so, delete one. Since we sorted the list, these values are required to
2184 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2185 // X smax Y smax Y --> X smax Y
2186 // X smax Y --> X, if X is always greater than Y
2187 if (Ops[i] == Ops[i+1] ||
2188 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
2189 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2191 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
2192 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2196 if (Ops.size() == 1) return Ops[0];
2198 assert(!Ops.empty() && "Reduced smax down to nothing!");
2200 // Okay, it looks like we really DO need an smax expr. Check to see if we
2201 // already have one, otherwise create a new one.
2202 FoldingSetNodeID ID;
2203 ID.AddInteger(scSMaxExpr);
2204 ID.AddInteger(Ops.size());
2205 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2206 ID.AddPointer(Ops[i]);
2208 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2209 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2210 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2211 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
2213 UniqueSCEVs.InsertNode(S, IP);
2217 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2219 SmallVector<const SCEV *, 2> Ops;
2222 return getUMaxExpr(Ops);
2226 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2227 assert(!Ops.empty() && "Cannot get empty umax!");
2228 if (Ops.size() == 1) return Ops[0];
2230 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2231 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2232 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2233 "SCEVUMaxExpr operand types don't match!");
2236 // Sort by complexity, this groups all similar expression types together.
2237 GroupByComplexity(Ops, LI);
2239 // If there are any constants, fold them together.
2241 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2243 assert(Idx < Ops.size());
2244 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2245 // We found two constants, fold them together!
2246 ConstantInt *Fold = ConstantInt::get(getContext(),
2247 APIntOps::umax(LHSC->getValue()->getValue(),
2248 RHSC->getValue()->getValue()));
2249 Ops[0] = getConstant(Fold);
2250 Ops.erase(Ops.begin()+1); // Erase the folded element
2251 if (Ops.size() == 1) return Ops[0];
2252 LHSC = cast<SCEVConstant>(Ops[0]);
2255 // If we are left with a constant minimum-int, strip it off.
2256 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2257 Ops.erase(Ops.begin());
2259 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2260 // If we have an umax with a constant maximum-int, it will always be
2265 if (Ops.size() == 1) return Ops[0];
2268 // Find the first UMax
2269 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2272 // Check to see if one of the operands is a UMax. If so, expand its operands
2273 // onto our operand list, and recurse to simplify.
2274 if (Idx < Ops.size()) {
2275 bool DeletedUMax = false;
2276 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
2277 Ops.erase(Ops.begin()+Idx);
2278 Ops.append(UMax->op_begin(), UMax->op_end());
2283 return getUMaxExpr(Ops);
2286 // Okay, check to see if the same value occurs in the operand list twice. If
2287 // so, delete one. Since we sorted the list, these values are required to
2289 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2290 // X umax Y umax Y --> X umax Y
2291 // X umax Y --> X, if X is always greater than Y
2292 if (Ops[i] == Ops[i+1] ||
2293 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
2294 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2296 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
2297 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2301 if (Ops.size() == 1) return Ops[0];
2303 assert(!Ops.empty() && "Reduced umax down to nothing!");
2305 // Okay, it looks like we really DO need a umax expr. Check to see if we
2306 // already have one, otherwise create a new one.
2307 FoldingSetNodeID ID;
2308 ID.AddInteger(scUMaxExpr);
2309 ID.AddInteger(Ops.size());
2310 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2311 ID.AddPointer(Ops[i]);
2313 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2314 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2315 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2316 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
2318 UniqueSCEVs.InsertNode(S, IP);
2322 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2324 // ~smax(~x, ~y) == smin(x, y).
2325 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2328 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2330 // ~umax(~x, ~y) == umin(x, y)
2331 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2334 const SCEV *ScalarEvolution::getSizeOfExpr(const Type *AllocTy) {
2335 // If we have TargetData, we can bypass creating a target-independent
2336 // constant expression and then folding it back into a ConstantInt.
2337 // This is just a compile-time optimization.
2339 return getConstant(TD->getIntPtrType(getContext()),
2340 TD->getTypeAllocSize(AllocTy));
2342 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2343 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2344 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2346 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2347 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2350 const SCEV *ScalarEvolution::getAlignOfExpr(const Type *AllocTy) {
2351 Constant *C = ConstantExpr::getAlignOf(AllocTy);
2352 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2353 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2355 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2356 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2359 const SCEV *ScalarEvolution::getOffsetOfExpr(const StructType *STy,
2361 // If we have TargetData, we can bypass creating a target-independent
2362 // constant expression and then folding it back into a ConstantInt.
2363 // This is just a compile-time optimization.
2365 return getConstant(TD->getIntPtrType(getContext()),
2366 TD->getStructLayout(STy)->getElementOffset(FieldNo));
2368 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2369 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2370 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2372 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
2373 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2376 const SCEV *ScalarEvolution::getOffsetOfExpr(const Type *CTy,
2377 Constant *FieldNo) {
2378 Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
2379 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2380 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2382 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
2383 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2386 const SCEV *ScalarEvolution::getUnknown(Value *V) {
2387 // Don't attempt to do anything other than create a SCEVUnknown object
2388 // here. createSCEV only calls getUnknown after checking for all other
2389 // interesting possibilities, and any other code that calls getUnknown
2390 // is doing so in order to hide a value from SCEV canonicalization.
2392 FoldingSetNodeID ID;
2393 ID.AddInteger(scUnknown);
2396 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
2397 assert(cast<SCEVUnknown>(S)->getValue() == V &&
2398 "Stale SCEVUnknown in uniquing map!");
2401 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
2403 FirstUnknown = cast<SCEVUnknown>(S);
2404 UniqueSCEVs.InsertNode(S, IP);
2408 //===----------------------------------------------------------------------===//
2409 // Basic SCEV Analysis and PHI Idiom Recognition Code
2412 /// isSCEVable - Test if values of the given type are analyzable within
2413 /// the SCEV framework. This primarily includes integer types, and it
2414 /// can optionally include pointer types if the ScalarEvolution class
2415 /// has access to target-specific information.
2416 bool ScalarEvolution::isSCEVable(const Type *Ty) const {
2417 // Integers and pointers are always SCEVable.
2418 return Ty->isIntegerTy() || Ty->isPointerTy();
2421 /// getTypeSizeInBits - Return the size in bits of the specified type,
2422 /// for which isSCEVable must return true.
2423 uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
2424 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2426 // If we have a TargetData, use it!
2428 return TD->getTypeSizeInBits(Ty);
2430 // Integer types have fixed sizes.
2431 if (Ty->isIntegerTy())
2432 return Ty->getPrimitiveSizeInBits();
2434 // The only other support type is pointer. Without TargetData, conservatively
2435 // assume pointers are 64-bit.
2436 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
2440 /// getEffectiveSCEVType - Return a type with the same bitwidth as
2441 /// the given type and which represents how SCEV will treat the given
2442 /// type, for which isSCEVable must return true. For pointer types,
2443 /// this is the pointer-sized integer type.
2444 const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
2445 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2447 if (Ty->isIntegerTy())
2450 // The only other support type is pointer.
2451 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
2452 if (TD) return TD->getIntPtrType(getContext());
2454 // Without TargetData, conservatively assume pointers are 64-bit.
2455 return Type::getInt64Ty(getContext());
2458 const SCEV *ScalarEvolution::getCouldNotCompute() {
2459 return &CouldNotCompute;
2462 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2463 /// expression and create a new one.
2464 const SCEV *ScalarEvolution::getSCEV(Value *V) {
2465 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
2467 std::map<SCEVCallbackVH, const SCEV *>::const_iterator I = Scalars.find(V);
2468 if (I != Scalars.end()) return I->second;
2469 const SCEV *S = createSCEV(V);
2471 // The process of creating a SCEV for V may have caused other SCEVs
2472 // to have been created, so it's necessary to insert the new entry
2473 // from scratch, rather than trying to remember the insert position
2475 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
2479 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2481 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
2482 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2484 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
2486 const Type *Ty = V->getType();
2487 Ty = getEffectiveSCEVType(Ty);
2488 return getMulExpr(V,
2489 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
2492 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
2493 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
2494 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2496 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
2498 const Type *Ty = V->getType();
2499 Ty = getEffectiveSCEVType(Ty);
2500 const SCEV *AllOnes =
2501 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
2502 return getMinusSCEV(AllOnes, V);
2505 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2507 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2509 // Fast path: X - X --> 0.
2511 return getConstant(LHS->getType(), 0);
2514 return getAddExpr(LHS, getNegativeSCEV(RHS));
2517 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2518 /// input value to the specified type. If the type must be extended, it is zero
2521 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
2523 const Type *SrcTy = V->getType();
2524 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2525 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2526 "Cannot truncate or zero extend with non-integer arguments!");
2527 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2528 return V; // No conversion
2529 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2530 return getTruncateExpr(V, Ty);
2531 return getZeroExtendExpr(V, Ty);
2534 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2535 /// input value to the specified type. If the type must be extended, it is sign
2538 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
2540 const Type *SrcTy = V->getType();
2541 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2542 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2543 "Cannot truncate or zero extend with non-integer arguments!");
2544 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2545 return V; // No conversion
2546 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2547 return getTruncateExpr(V, Ty);
2548 return getSignExtendExpr(V, Ty);
2551 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2552 /// input value to the specified type. If the type must be extended, it is zero
2553 /// extended. The conversion must not be narrowing.
2555 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
2556 const Type *SrcTy = V->getType();
2557 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2558 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2559 "Cannot noop or zero extend with non-integer arguments!");
2560 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2561 "getNoopOrZeroExtend cannot truncate!");
2562 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2563 return V; // No conversion
2564 return getZeroExtendExpr(V, Ty);
2567 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2568 /// input value to the specified type. If the type must be extended, it is sign
2569 /// extended. The conversion must not be narrowing.
2571 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
2572 const Type *SrcTy = V->getType();
2573 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2574 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2575 "Cannot noop or sign extend with non-integer arguments!");
2576 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2577 "getNoopOrSignExtend cannot truncate!");
2578 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2579 return V; // No conversion
2580 return getSignExtendExpr(V, Ty);
2583 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2584 /// the input value to the specified type. If the type must be extended,
2585 /// it is extended with unspecified bits. The conversion must not be
2588 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
2589 const Type *SrcTy = V->getType();
2590 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2591 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2592 "Cannot noop or any extend with non-integer arguments!");
2593 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2594 "getNoopOrAnyExtend cannot truncate!");
2595 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2596 return V; // No conversion
2597 return getAnyExtendExpr(V, Ty);
2600 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2601 /// input value to the specified type. The conversion must not be widening.
2603 ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
2604 const Type *SrcTy = V->getType();
2605 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2606 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2607 "Cannot truncate or noop with non-integer arguments!");
2608 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2609 "getTruncateOrNoop cannot extend!");
2610 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2611 return V; // No conversion
2612 return getTruncateExpr(V, Ty);
2615 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2616 /// the types using zero-extension, and then perform a umax operation
2618 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2620 const SCEV *PromotedLHS = LHS;
2621 const SCEV *PromotedRHS = RHS;
2623 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2624 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2626 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2628 return getUMaxExpr(PromotedLHS, PromotedRHS);
2631 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
2632 /// the types using zero-extension, and then perform a umin operation
2634 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2636 const SCEV *PromotedLHS = LHS;
2637 const SCEV *PromotedRHS = RHS;
2639 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2640 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2642 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2644 return getUMinExpr(PromotedLHS, PromotedRHS);
2647 /// PushDefUseChildren - Push users of the given Instruction
2648 /// onto the given Worklist.
2650 PushDefUseChildren(Instruction *I,
2651 SmallVectorImpl<Instruction *> &Worklist) {
2652 // Push the def-use children onto the Worklist stack.
2653 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2655 Worklist.push_back(cast<Instruction>(*UI));
2658 /// ForgetSymbolicValue - This looks up computed SCEV values for all
2659 /// instructions that depend on the given instruction and removes them from
2660 /// the Scalars map if they reference SymName. This is used during PHI
2663 ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
2664 SmallVector<Instruction *, 16> Worklist;
2665 PushDefUseChildren(PN, Worklist);
2667 SmallPtrSet<Instruction *, 8> Visited;
2669 while (!Worklist.empty()) {
2670 Instruction *I = Worklist.pop_back_val();
2671 if (!Visited.insert(I)) continue;
2673 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
2674 Scalars.find(static_cast<Value *>(I));
2675 if (It != Scalars.end()) {
2676 // Short-circuit the def-use traversal if the symbolic name
2677 // ceases to appear in expressions.
2678 if (It->second != SymName && !It->second->hasOperand(SymName))
2681 // SCEVUnknown for a PHI either means that it has an unrecognized
2682 // structure, it's a PHI that's in the progress of being computed
2683 // by createNodeForPHI, or it's a single-value PHI. In the first case,
2684 // additional loop trip count information isn't going to change anything.
2685 // In the second case, createNodeForPHI will perform the necessary
2686 // updates on its own when it gets to that point. In the third, we do
2687 // want to forget the SCEVUnknown.
2688 if (!isa<PHINode>(I) ||
2689 !isa<SCEVUnknown>(It->second) ||
2690 (I != PN && It->second == SymName)) {
2691 ValuesAtScopes.erase(It->second);
2696 PushDefUseChildren(I, Worklist);
2700 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2701 /// a loop header, making it a potential recurrence, or it doesn't.
2703 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
2704 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2705 if (L->getHeader() == PN->getParent()) {
2706 // The loop may have multiple entrances or multiple exits; we can analyze
2707 // this phi as an addrec if it has a unique entry value and a unique
2709 Value *BEValueV = 0, *StartValueV = 0;
2710 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2711 Value *V = PN->getIncomingValue(i);
2712 if (L->contains(PN->getIncomingBlock(i))) {
2715 } else if (BEValueV != V) {
2719 } else if (!StartValueV) {
2721 } else if (StartValueV != V) {
2726 if (BEValueV && StartValueV) {
2727 // While we are analyzing this PHI node, handle its value symbolically.
2728 const SCEV *SymbolicName = getUnknown(PN);
2729 assert(Scalars.find(PN) == Scalars.end() &&
2730 "PHI node already processed?");
2731 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
2733 // Using this symbolic name for the PHI, analyze the value coming around
2735 const SCEV *BEValue = getSCEV(BEValueV);
2737 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2738 // has a special value for the first iteration of the loop.
2740 // If the value coming around the backedge is an add with the symbolic
2741 // value we just inserted, then we found a simple induction variable!
2742 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
2743 // If there is a single occurrence of the symbolic value, replace it
2744 // with a recurrence.
2745 unsigned FoundIndex = Add->getNumOperands();
2746 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2747 if (Add->getOperand(i) == SymbolicName)
2748 if (FoundIndex == e) {
2753 if (FoundIndex != Add->getNumOperands()) {
2754 // Create an add with everything but the specified operand.
2755 SmallVector<const SCEV *, 8> Ops;
2756 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2757 if (i != FoundIndex)
2758 Ops.push_back(Add->getOperand(i));
2759 const SCEV *Accum = getAddExpr(Ops);
2761 // This is not a valid addrec if the step amount is varying each
2762 // loop iteration, but is not itself an addrec in this loop.
2763 if (Accum->isLoopInvariant(L) ||
2764 (isa<SCEVAddRecExpr>(Accum) &&
2765 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
2766 bool HasNUW = false;
2767 bool HasNSW = false;
2769 // If the increment doesn't overflow, then neither the addrec nor
2770 // the post-increment will overflow.
2771 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
2772 if (OBO->hasNoUnsignedWrap())
2774 if (OBO->hasNoSignedWrap())
2778 const SCEV *StartVal = getSCEV(StartValueV);
2779 const SCEV *PHISCEV =
2780 getAddRecExpr(StartVal, Accum, L, HasNUW, HasNSW);
2782 // Since the no-wrap flags are on the increment, they apply to the
2783 // post-incremented value as well.
2784 if (Accum->isLoopInvariant(L))
2785 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
2786 Accum, L, HasNUW, HasNSW);
2788 // Okay, for the entire analysis of this edge we assumed the PHI
2789 // to be symbolic. We now need to go back and purge all of the
2790 // entries for the scalars that use the symbolic expression.
2791 ForgetSymbolicName(PN, SymbolicName);
2792 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
2796 } else if (const SCEVAddRecExpr *AddRec =
2797 dyn_cast<SCEVAddRecExpr>(BEValue)) {
2798 // Otherwise, this could be a loop like this:
2799 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2800 // In this case, j = {1,+,1} and BEValue is j.
2801 // Because the other in-value of i (0) fits the evolution of BEValue
2802 // i really is an addrec evolution.
2803 if (AddRec->getLoop() == L && AddRec->isAffine()) {
2804 const SCEV *StartVal = getSCEV(StartValueV);
2806 // If StartVal = j.start - j.stride, we can use StartVal as the
2807 // initial step of the addrec evolution.
2808 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
2809 AddRec->getOperand(1))) {
2810 const SCEV *PHISCEV =
2811 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
2813 // Okay, for the entire analysis of this edge we assumed the PHI
2814 // to be symbolic. We now need to go back and purge all of the
2815 // entries for the scalars that use the symbolic expression.
2816 ForgetSymbolicName(PN, SymbolicName);
2817 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
2825 // If the PHI has a single incoming value, follow that value, unless the
2826 // PHI's incoming blocks are in a different loop, in which case doing so
2827 // risks breaking LCSSA form. Instcombine would normally zap these, but
2828 // it doesn't have DominatorTree information, so it may miss cases.
2829 if (Value *V = PN->hasConstantValue(DT)) {
2830 bool AllSameLoop = true;
2831 Loop *PNLoop = LI->getLoopFor(PN->getParent());
2832 for (size_t i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2833 if (LI->getLoopFor(PN->getIncomingBlock(i)) != PNLoop) {
2834 AllSameLoop = false;
2841 // If it's not a loop phi, we can't handle it yet.
2842 return getUnknown(PN);
2845 /// createNodeForGEP - Expand GEP instructions into add and multiply
2846 /// operations. This allows them to be analyzed by regular SCEV code.
2848 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
2850 // Don't blindly transfer the inbounds flag from the GEP instruction to the
2851 // Add expression, because the Instruction may be guarded by control flow
2852 // and the no-overflow bits may not be valid for the expression in any
2855 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
2856 Value *Base = GEP->getOperand(0);
2857 // Don't attempt to analyze GEPs over unsized objects.
2858 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2859 return getUnknown(GEP);
2860 const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
2861 gep_type_iterator GTI = gep_type_begin(GEP);
2862 for (GetElementPtrInst::op_iterator I = llvm::next(GEP->op_begin()),
2866 // Compute the (potentially symbolic) offset in bytes for this index.
2867 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2868 // For a struct, add the member offset.
2869 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2870 const SCEV *FieldOffset = getOffsetOfExpr(STy, FieldNo);
2872 // Add the field offset to the running total offset.
2873 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
2875 // For an array, add the element offset, explicitly scaled.
2876 const SCEV *ElementSize = getSizeOfExpr(*GTI);
2877 const SCEV *IndexS = getSCEV(Index);
2878 // Getelementptr indices are signed.
2879 IndexS = getTruncateOrSignExtend(IndexS, IntPtrTy);
2881 // Multiply the index by the element size to compute the element offset.
2882 const SCEV *LocalOffset = getMulExpr(IndexS, ElementSize);
2884 // Add the element offset to the running total offset.
2885 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2889 // Get the SCEV for the GEP base.
2890 const SCEV *BaseS = getSCEV(Base);
2892 // Add the total offset from all the GEP indices to the base.
2893 return getAddExpr(BaseS, TotalOffset);
2896 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2897 /// guaranteed to end in (at every loop iteration). It is, at the same time,
2898 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2899 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
2901 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
2902 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2903 return C->getValue()->getValue().countTrailingZeros();
2905 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
2906 return std::min(GetMinTrailingZeros(T->getOperand()),
2907 (uint32_t)getTypeSizeInBits(T->getType()));
2909 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
2910 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2911 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2912 getTypeSizeInBits(E->getType()) : OpRes;
2915 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
2916 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2917 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2918 getTypeSizeInBits(E->getType()) : OpRes;
2921 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
2922 // The result is the min of all operands results.
2923 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2924 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2925 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2929 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
2930 // The result is the sum of all operands results.
2931 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2932 uint32_t BitWidth = getTypeSizeInBits(M->getType());
2933 for (unsigned i = 1, e = M->getNumOperands();
2934 SumOpRes != BitWidth && i != e; ++i)
2935 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
2940 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
2941 // The result is the min of all operands results.
2942 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2943 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2944 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2948 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
2949 // The result is the min of all operands results.
2950 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2951 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2952 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2956 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
2957 // The result is the min of all operands results.
2958 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2959 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2960 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2964 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2965 // For a SCEVUnknown, ask ValueTracking.
2966 unsigned BitWidth = getTypeSizeInBits(U->getType());
2967 APInt Mask = APInt::getAllOnesValue(BitWidth);
2968 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2969 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2970 return Zeros.countTrailingOnes();
2977 /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2980 ScalarEvolution::getUnsignedRange(const SCEV *S) {
2982 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2983 return ConstantRange(C->getValue()->getValue());
2985 unsigned BitWidth = getTypeSizeInBits(S->getType());
2986 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2988 // If the value has known zeros, the maximum unsigned value will have those
2989 // known zeros as well.
2990 uint32_t TZ = GetMinTrailingZeros(S);
2992 ConservativeResult =
2993 ConstantRange(APInt::getMinValue(BitWidth),
2994 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
2996 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2997 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2998 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2999 X = X.add(getUnsignedRange(Add->getOperand(i)));
3000 return ConservativeResult.intersectWith(X);
3003 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3004 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
3005 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3006 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
3007 return ConservativeResult.intersectWith(X);
3010 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3011 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
3012 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3013 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
3014 return ConservativeResult.intersectWith(X);
3017 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3018 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
3019 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3020 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
3021 return ConservativeResult.intersectWith(X);
3024 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3025 ConstantRange X = getUnsignedRange(UDiv->getLHS());
3026 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
3027 return ConservativeResult.intersectWith(X.udiv(Y));
3030 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3031 ConstantRange X = getUnsignedRange(ZExt->getOperand());
3032 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
3035 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3036 ConstantRange X = getUnsignedRange(SExt->getOperand());
3037 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
3040 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3041 ConstantRange X = getUnsignedRange(Trunc->getOperand());
3042 return ConservativeResult.intersectWith(X.truncate(BitWidth));
3045 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
3046 // If there's no unsigned wrap, the value will never be less than its
3048 if (AddRec->hasNoUnsignedWrap())
3049 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
3050 if (!C->getValue()->isZero())
3051 ConservativeResult =
3052 ConservativeResult.intersectWith(
3053 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0)));
3055 // TODO: non-affine addrec
3056 if (AddRec->isAffine()) {
3057 const Type *Ty = AddRec->getType();
3058 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
3059 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3060 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
3061 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3063 const SCEV *Start = AddRec->getStart();
3064 const SCEV *Step = AddRec->getStepRecurrence(*this);
3066 ConstantRange StartRange = getUnsignedRange(Start);
3067 ConstantRange StepRange = getSignedRange(Step);
3068 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3069 ConstantRange EndRange =
3070 StartRange.add(MaxBECountRange.multiply(StepRange));
3072 // Check for overflow. This must be done with ConstantRange arithmetic
3073 // because we could be called from within the ScalarEvolution overflow
3075 ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
3076 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3077 ConstantRange ExtMaxBECountRange =
3078 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3079 ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
3080 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3082 return ConservativeResult;
3084 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
3085 EndRange.getUnsignedMin());
3086 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
3087 EndRange.getUnsignedMax());
3088 if (Min.isMinValue() && Max.isMaxValue())
3089 return ConservativeResult;
3090 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
3094 return ConservativeResult;
3097 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3098 // For a SCEVUnknown, ask ValueTracking.
3099 APInt Mask = APInt::getAllOnesValue(BitWidth);
3100 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3101 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
3102 if (Ones == ~Zeros + 1)
3103 return ConservativeResult;
3104 return ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
3107 return ConservativeResult;
3110 /// getSignedRange - Determine the signed range for a particular SCEV.
3113 ScalarEvolution::getSignedRange(const SCEV *S) {
3115 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
3116 return ConstantRange(C->getValue()->getValue());
3118 unsigned BitWidth = getTypeSizeInBits(S->getType());
3119 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3121 // If the value has known zeros, the maximum signed value will have those
3122 // known zeros as well.
3123 uint32_t TZ = GetMinTrailingZeros(S);
3125 ConservativeResult =
3126 ConstantRange(APInt::getSignedMinValue(BitWidth),
3127 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
3129 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3130 ConstantRange X = getSignedRange(Add->getOperand(0));
3131 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3132 X = X.add(getSignedRange(Add->getOperand(i)));
3133 return ConservativeResult.intersectWith(X);
3136 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3137 ConstantRange X = getSignedRange(Mul->getOperand(0));
3138 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3139 X = X.multiply(getSignedRange(Mul->getOperand(i)));
3140 return ConservativeResult.intersectWith(X);
3143 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3144 ConstantRange X = getSignedRange(SMax->getOperand(0));
3145 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3146 X = X.smax(getSignedRange(SMax->getOperand(i)));
3147 return ConservativeResult.intersectWith(X);
3150 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3151 ConstantRange X = getSignedRange(UMax->getOperand(0));
3152 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3153 X = X.umax(getSignedRange(UMax->getOperand(i)));
3154 return ConservativeResult.intersectWith(X);
3157 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3158 ConstantRange X = getSignedRange(UDiv->getLHS());
3159 ConstantRange Y = getSignedRange(UDiv->getRHS());
3160 return ConservativeResult.intersectWith(X.udiv(Y));
3163 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3164 ConstantRange X = getSignedRange(ZExt->getOperand());
3165 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
3168 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3169 ConstantRange X = getSignedRange(SExt->getOperand());
3170 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
3173 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3174 ConstantRange X = getSignedRange(Trunc->getOperand());
3175 return ConservativeResult.intersectWith(X.truncate(BitWidth));
3178 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
3179 // If there's no signed wrap, and all the operands have the same sign or
3180 // zero, the value won't ever change sign.
3181 if (AddRec->hasNoSignedWrap()) {
3182 bool AllNonNeg = true;
3183 bool AllNonPos = true;
3184 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3185 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3186 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3189 ConservativeResult = ConservativeResult.intersectWith(
3190 ConstantRange(APInt(BitWidth, 0),
3191 APInt::getSignedMinValue(BitWidth)));
3193 ConservativeResult = ConservativeResult.intersectWith(
3194 ConstantRange(APInt::getSignedMinValue(BitWidth),
3195 APInt(BitWidth, 1)));
3198 // TODO: non-affine addrec
3199 if (AddRec->isAffine()) {
3200 const Type *Ty = AddRec->getType();
3201 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
3202 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3203 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
3204 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3206 const SCEV *Start = AddRec->getStart();
3207 const SCEV *Step = AddRec->getStepRecurrence(*this);
3209 ConstantRange StartRange = getSignedRange(Start);
3210 ConstantRange StepRange = getSignedRange(Step);
3211 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3212 ConstantRange EndRange =
3213 StartRange.add(MaxBECountRange.multiply(StepRange));
3215 // Check for overflow. This must be done with ConstantRange arithmetic
3216 // because we could be called from within the ScalarEvolution overflow
3218 ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
3219 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3220 ConstantRange ExtMaxBECountRange =
3221 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3222 ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
3223 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3225 return ConservativeResult;
3227 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3228 EndRange.getSignedMin());
3229 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3230 EndRange.getSignedMax());
3231 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
3232 return ConservativeResult;
3233 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
3237 return ConservativeResult;
3240 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3241 // For a SCEVUnknown, ask ValueTracking.
3242 if (!U->getValue()->getType()->isIntegerTy() && !TD)
3243 return ConservativeResult;
3244 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3246 return ConservativeResult;
3247 return ConservativeResult.intersectWith(
3248 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
3249 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1));
3252 return ConservativeResult;
3255 /// createSCEV - We know that there is no SCEV for the specified value.
3256 /// Analyze the expression.
3258 const SCEV *ScalarEvolution::createSCEV(Value *V) {
3259 if (!isSCEVable(V->getType()))
3260 return getUnknown(V);
3262 unsigned Opcode = Instruction::UserOp1;
3263 if (Instruction *I = dyn_cast<Instruction>(V)) {
3264 Opcode = I->getOpcode();
3266 // Don't attempt to analyze instructions in blocks that aren't
3267 // reachable. Such instructions don't matter, and they aren't required
3268 // to obey basic rules for definitions dominating uses which this
3269 // analysis depends on.
3270 if (!DT->isReachableFromEntry(I->getParent()))
3271 return getUnknown(V);
3272 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
3273 Opcode = CE->getOpcode();
3274 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3275 return getConstant(CI);
3276 else if (isa<ConstantPointerNull>(V))
3277 return getConstant(V->getType(), 0);
3278 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3279 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
3281 return getUnknown(V);
3283 Operator *U = cast<Operator>(V);
3285 case Instruction::Add: {
3286 // The simple thing to do would be to just call getSCEV on both operands
3287 // and call getAddExpr with the result. However if we're looking at a
3288 // bunch of things all added together, this can be quite inefficient,
3289 // because it leads to N-1 getAddExpr calls for N ultimate operands.
3290 // Instead, gather up all the operands and make a single getAddExpr call.
3291 // LLVM IR canonical form means we need only traverse the left operands.
3292 SmallVector<const SCEV *, 4> AddOps;
3293 AddOps.push_back(getSCEV(U->getOperand(1)));
3294 for (Value *Op = U->getOperand(0);
3295 Op->getValueID() == Instruction::Add + Value::InstructionVal;
3296 Op = U->getOperand(0)) {
3297 U = cast<Operator>(Op);
3298 AddOps.push_back(getSCEV(U->getOperand(1)));
3300 AddOps.push_back(getSCEV(U->getOperand(0)));
3301 return getAddExpr(AddOps);
3303 case Instruction::Mul: {
3304 // See the Add code above.
3305 SmallVector<const SCEV *, 4> MulOps;
3306 MulOps.push_back(getSCEV(U->getOperand(1)));
3307 for (Value *Op = U->getOperand(0);
3308 Op->getValueID() == Instruction::Mul + Value::InstructionVal;
3309 Op = U->getOperand(0)) {
3310 U = cast<Operator>(Op);
3311 MulOps.push_back(getSCEV(U->getOperand(1)));
3313 MulOps.push_back(getSCEV(U->getOperand(0)));
3314 return getMulExpr(MulOps);
3316 case Instruction::UDiv:
3317 return getUDivExpr(getSCEV(U->getOperand(0)),
3318 getSCEV(U->getOperand(1)));
3319 case Instruction::Sub:
3320 return getMinusSCEV(getSCEV(U->getOperand(0)),
3321 getSCEV(U->getOperand(1)));
3322 case Instruction::And:
3323 // For an expression like x&255 that merely masks off the high bits,
3324 // use zext(trunc(x)) as the SCEV expression.
3325 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3326 if (CI->isNullValue())
3327 return getSCEV(U->getOperand(1));
3328 if (CI->isAllOnesValue())
3329 return getSCEV(U->getOperand(0));
3330 const APInt &A = CI->getValue();
3332 // Instcombine's ShrinkDemandedConstant may strip bits out of
3333 // constants, obscuring what would otherwise be a low-bits mask.
3334 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3335 // knew about to reconstruct a low-bits mask value.
3336 unsigned LZ = A.countLeadingZeros();
3337 unsigned BitWidth = A.getBitWidth();
3338 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3339 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3340 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3342 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3344 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
3346 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
3347 IntegerType::get(getContext(), BitWidth - LZ)),
3352 case Instruction::Or:
3353 // If the RHS of the Or is a constant, we may have something like:
3354 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3355 // optimizations will transparently handle this case.
3357 // In order for this transformation to be safe, the LHS must be of the
3358 // form X*(2^n) and the Or constant must be less than 2^n.
3359 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3360 const SCEV *LHS = getSCEV(U->getOperand(0));
3361 const APInt &CIVal = CI->getValue();
3362 if (GetMinTrailingZeros(LHS) >=
3363 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3364 // Build a plain add SCEV.
3365 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3366 // If the LHS of the add was an addrec and it has no-wrap flags,
3367 // transfer the no-wrap flags, since an or won't introduce a wrap.
3368 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3369 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
3370 if (OldAR->hasNoUnsignedWrap())
3371 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoUnsignedWrap(true);
3372 if (OldAR->hasNoSignedWrap())
3373 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoSignedWrap(true);
3379 case Instruction::Xor:
3380 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3381 // If the RHS of the xor is a signbit, then this is just an add.
3382 // Instcombine turns add of signbit into xor as a strength reduction step.
3383 if (CI->getValue().isSignBit())
3384 return getAddExpr(getSCEV(U->getOperand(0)),
3385 getSCEV(U->getOperand(1)));
3387 // If the RHS of xor is -1, then this is a not operation.
3388 if (CI->isAllOnesValue())
3389 return getNotSCEV(getSCEV(U->getOperand(0)));
3391 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3392 // This is a variant of the check for xor with -1, and it handles
3393 // the case where instcombine has trimmed non-demanded bits out
3394 // of an xor with -1.
3395 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3396 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3397 if (BO->getOpcode() == Instruction::And &&
3398 LCI->getValue() == CI->getValue())
3399 if (const SCEVZeroExtendExpr *Z =
3400 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
3401 const Type *UTy = U->getType();
3402 const SCEV *Z0 = Z->getOperand();
3403 const Type *Z0Ty = Z0->getType();
3404 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3406 // If C is a low-bits mask, the zero extend is serving to
3407 // mask off the high bits. Complement the operand and
3408 // re-apply the zext.
3409 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3410 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3412 // If C is a single bit, it may be in the sign-bit position
3413 // before the zero-extend. In this case, represent the xor
3414 // using an add, which is equivalent, and re-apply the zext.
3415 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
3416 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3418 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3424 case Instruction::Shl:
3425 // Turn shift left of a constant amount into a multiply.
3426 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3427 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
3429 // If the shift count is not less than the bitwidth, the result of
3430 // the shift is undefined. Don't try to analyze it, because the
3431 // resolution chosen here may differ from the resolution chosen in
3432 // other parts of the compiler.
3433 if (SA->getValue().uge(BitWidth))
3436 Constant *X = ConstantInt::get(getContext(),
3437 APInt(BitWidth, 1).shl(SA->getZExtValue()));
3438 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3442 case Instruction::LShr:
3443 // Turn logical shift right of a constant into a unsigned divide.
3444 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3445 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
3447 // If the shift count is not less than the bitwidth, the result of
3448 // the shift is undefined. Don't try to analyze it, because the
3449 // resolution chosen here may differ from the resolution chosen in
3450 // other parts of the compiler.
3451 if (SA->getValue().uge(BitWidth))
3454 Constant *X = ConstantInt::get(getContext(),
3455 APInt(BitWidth, 1).shl(SA->getZExtValue()));
3456 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3460 case Instruction::AShr:
3461 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3462 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
3463 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
3464 if (L->getOpcode() == Instruction::Shl &&
3465 L->getOperand(1) == U->getOperand(1)) {
3466 uint64_t BitWidth = getTypeSizeInBits(U->getType());
3468 // If the shift count is not less than the bitwidth, the result of
3469 // the shift is undefined. Don't try to analyze it, because the
3470 // resolution chosen here may differ from the resolution chosen in
3471 // other parts of the compiler.
3472 if (CI->getValue().uge(BitWidth))
3475 uint64_t Amt = BitWidth - CI->getZExtValue();
3476 if (Amt == BitWidth)
3477 return getSCEV(L->getOperand(0)); // shift by zero --> noop
3479 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
3480 IntegerType::get(getContext(),
3486 case Instruction::Trunc:
3487 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
3489 case Instruction::ZExt:
3490 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3492 case Instruction::SExt:
3493 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3495 case Instruction::BitCast:
3496 // BitCasts are no-op casts so we just eliminate the cast.
3497 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
3498 return getSCEV(U->getOperand(0));
3501 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3502 // lead to pointer expressions which cannot safely be expanded to GEPs,
3503 // because ScalarEvolution doesn't respect the GEP aliasing rules when
3504 // simplifying integer expressions.
3506 case Instruction::GetElementPtr:
3507 return createNodeForGEP(cast<GEPOperator>(U));
3509 case Instruction::PHI:
3510 return createNodeForPHI(cast<PHINode>(U));
3512 case Instruction::Select:
3513 // This could be a smax or umax that was lowered earlier.
3514 // Try to recover it.
3515 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3516 Value *LHS = ICI->getOperand(0);
3517 Value *RHS = ICI->getOperand(1);
3518 switch (ICI->getPredicate()) {
3519 case ICmpInst::ICMP_SLT:
3520 case ICmpInst::ICMP_SLE:
3521 std::swap(LHS, RHS);
3523 case ICmpInst::ICMP_SGT:
3524 case ICmpInst::ICMP_SGE:
3525 // a >s b ? a+x : b+x -> smax(a, b)+x
3526 // a >s b ? b+x : a+x -> smin(a, b)+x
3527 if (LHS->getType() == U->getType()) {
3528 const SCEV *LS = getSCEV(LHS);
3529 const SCEV *RS = getSCEV(RHS);
3530 const SCEV *LA = getSCEV(U->getOperand(1));
3531 const SCEV *RA = getSCEV(U->getOperand(2));
3532 const SCEV *LDiff = getMinusSCEV(LA, LS);
3533 const SCEV *RDiff = getMinusSCEV(RA, RS);
3535 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
3536 LDiff = getMinusSCEV(LA, RS);
3537 RDiff = getMinusSCEV(RA, LS);
3539 return getAddExpr(getSMinExpr(LS, RS), LDiff);
3542 case ICmpInst::ICMP_ULT:
3543 case ICmpInst::ICMP_ULE:
3544 std::swap(LHS, RHS);
3546 case ICmpInst::ICMP_UGT:
3547 case ICmpInst::ICMP_UGE:
3548 // a >u b ? a+x : b+x -> umax(a, b)+x
3549 // a >u b ? b+x : a+x -> umin(a, b)+x
3550 if (LHS->getType() == U->getType()) {
3551 const SCEV *LS = getSCEV(LHS);
3552 const SCEV *RS = getSCEV(RHS);
3553 const SCEV *LA = getSCEV(U->getOperand(1));
3554 const SCEV *RA = getSCEV(U->getOperand(2));
3555 const SCEV *LDiff = getMinusSCEV(LA, LS);
3556 const SCEV *RDiff = getMinusSCEV(RA, RS);
3558 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
3559 LDiff = getMinusSCEV(LA, RS);
3560 RDiff = getMinusSCEV(RA, LS);
3562 return getAddExpr(getUMinExpr(LS, RS), LDiff);
3565 case ICmpInst::ICMP_NE:
3566 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
3567 if (LHS->getType() == U->getType() &&
3568 isa<ConstantInt>(RHS) &&
3569 cast<ConstantInt>(RHS)->isZero()) {
3570 const SCEV *One = getConstant(LHS->getType(), 1);
3571 const SCEV *LS = getSCEV(LHS);
3572 const SCEV *LA = getSCEV(U->getOperand(1));
3573 const SCEV *RA = getSCEV(U->getOperand(2));
3574 const SCEV *LDiff = getMinusSCEV(LA, LS);
3575 const SCEV *RDiff = getMinusSCEV(RA, One);
3577 return getAddExpr(getUMaxExpr(One, LS), LDiff);
3580 case ICmpInst::ICMP_EQ:
3581 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
3582 if (LHS->getType() == U->getType() &&
3583 isa<ConstantInt>(RHS) &&
3584 cast<ConstantInt>(RHS)->isZero()) {
3585 const SCEV *One = getConstant(LHS->getType(), 1);
3586 const SCEV *LS = getSCEV(LHS);
3587 const SCEV *LA = getSCEV(U->getOperand(1));
3588 const SCEV *RA = getSCEV(U->getOperand(2));
3589 const SCEV *LDiff = getMinusSCEV(LA, One);
3590 const SCEV *RDiff = getMinusSCEV(RA, LS);
3592 return getAddExpr(getUMaxExpr(One, LS), LDiff);
3600 default: // We cannot analyze this expression.
3604 return getUnknown(V);
3609 //===----------------------------------------------------------------------===//
3610 // Iteration Count Computation Code
3613 /// getBackedgeTakenCount - If the specified loop has a predictable
3614 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3615 /// object. The backedge-taken count is the number of times the loop header
3616 /// will be branched to from within the loop. This is one less than the
3617 /// trip count of the loop, since it doesn't count the first iteration,
3618 /// when the header is branched to from outside the loop.
3620 /// Note that it is not valid to call this method on a loop without a
3621 /// loop-invariant backedge-taken count (see
3622 /// hasLoopInvariantBackedgeTakenCount).
3624 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
3625 return getBackedgeTakenInfo(L).Exact;
3628 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3629 /// return the least SCEV value that is known never to be less than the
3630 /// actual backedge taken count.
3631 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
3632 return getBackedgeTakenInfo(L).Max;
3635 /// PushLoopPHIs - Push PHI nodes in the header of the given loop
3636 /// onto the given Worklist.
3638 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3639 BasicBlock *Header = L->getHeader();
3641 // Push all Loop-header PHIs onto the Worklist stack.
3642 for (BasicBlock::iterator I = Header->begin();
3643 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3644 Worklist.push_back(PN);
3647 const ScalarEvolution::BackedgeTakenInfo &
3648 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
3649 // Initially insert a CouldNotCompute for this loop. If the insertion
3650 // succeeds, proceed to actually compute a backedge-taken count and
3651 // update the value. The temporary CouldNotCompute value tells SCEV
3652 // code elsewhere that it shouldn't attempt to request a new
3653 // backedge-taken count, which could result in infinite recursion.
3654 std::pair<std::map<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
3655 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3657 BackedgeTakenInfo BECount = ComputeBackedgeTakenCount(L);
3658 if (BECount.Exact != getCouldNotCompute()) {
3659 assert(BECount.Exact->isLoopInvariant(L) &&
3660 BECount.Max->isLoopInvariant(L) &&
3661 "Computed backedge-taken count isn't loop invariant for loop!");
3662 ++NumTripCountsComputed;
3664 // Update the value in the map.
3665 Pair.first->second = BECount;
3667 if (BECount.Max != getCouldNotCompute())
3668 // Update the value in the map.
3669 Pair.first->second = BECount;
3670 if (isa<PHINode>(L->getHeader()->begin()))
3671 // Only count loops that have phi nodes as not being computable.
3672 ++NumTripCountsNotComputed;
3675 // Now that we know more about the trip count for this loop, forget any
3676 // existing SCEV values for PHI nodes in this loop since they are only
3677 // conservative estimates made without the benefit of trip count
3678 // information. This is similar to the code in forgetLoop, except that
3679 // it handles SCEVUnknown PHI nodes specially.
3680 if (BECount.hasAnyInfo()) {
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 // SCEVUnknown for a PHI either means that it has an unrecognized
3693 // structure, or it's a PHI that's in the progress of being computed
3694 // by createNodeForPHI. In the former case, additional loop trip
3695 // count information isn't going to change anything. In the later
3696 // case, createNodeForPHI will perform the necessary updates on its
3697 // own when it gets to that point.
3698 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
3699 ValuesAtScopes.erase(It->second);
3702 if (PHINode *PN = dyn_cast<PHINode>(I))
3703 ConstantEvolutionLoopExitValue.erase(PN);
3706 PushDefUseChildren(I, Worklist);
3710 return Pair.first->second;
3713 /// forgetLoop - This method should be called by the client when it has
3714 /// changed a loop in a way that may effect ScalarEvolution's ability to
3715 /// compute a trip count, or if the loop is deleted.
3716 void ScalarEvolution::forgetLoop(const Loop *L) {
3717 // Drop any stored trip count value.
3718 BackedgeTakenCounts.erase(L);
3720 // Drop information about expressions based on loop-header PHIs.
3721 SmallVector<Instruction *, 16> Worklist;
3722 PushLoopPHIs(L, Worklist);
3724 SmallPtrSet<Instruction *, 8> Visited;
3725 while (!Worklist.empty()) {
3726 Instruction *I = Worklist.pop_back_val();
3727 if (!Visited.insert(I)) continue;
3729 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3730 Scalars.find(static_cast<Value *>(I));
3731 if (It != Scalars.end()) {
3732 ValuesAtScopes.erase(It->second);
3734 if (PHINode *PN = dyn_cast<PHINode>(I))
3735 ConstantEvolutionLoopExitValue.erase(PN);
3738 PushDefUseChildren(I, Worklist);
3742 /// forgetValue - This method should be called by the client when it has
3743 /// changed a value in a way that may effect its value, or which may
3744 /// disconnect it from a def-use chain linking it to a loop.
3745 void ScalarEvolution::forgetValue(Value *V) {
3746 Instruction *I = dyn_cast<Instruction>(V);
3749 // Drop information about expressions based on loop-header PHIs.
3750 SmallVector<Instruction *, 16> Worklist;
3751 Worklist.push_back(I);
3753 SmallPtrSet<Instruction *, 8> Visited;
3754 while (!Worklist.empty()) {
3755 I = Worklist.pop_back_val();
3756 if (!Visited.insert(I)) continue;
3758 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3759 Scalars.find(static_cast<Value *>(I));
3760 if (It != Scalars.end()) {
3761 ValuesAtScopes.erase(It->second);
3763 if (PHINode *PN = dyn_cast<PHINode>(I))
3764 ConstantEvolutionLoopExitValue.erase(PN);
3767 PushDefUseChildren(I, Worklist);
3771 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
3772 /// of the specified loop will execute.
3773 ScalarEvolution::BackedgeTakenInfo
3774 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
3775 SmallVector<BasicBlock *, 8> ExitingBlocks;
3776 L->getExitingBlocks(ExitingBlocks);
3778 // Examine all exits and pick the most conservative values.
3779 const SCEV *BECount = getCouldNotCompute();
3780 const SCEV *MaxBECount = getCouldNotCompute();
3781 bool CouldNotComputeBECount = false;
3782 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3783 BackedgeTakenInfo NewBTI =
3784 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
3786 if (NewBTI.Exact == getCouldNotCompute()) {
3787 // We couldn't compute an exact value for this exit, so
3788 // we won't be able to compute an exact value for the loop.
3789 CouldNotComputeBECount = true;
3790 BECount = getCouldNotCompute();
3791 } else if (!CouldNotComputeBECount) {
3792 if (BECount == getCouldNotCompute())
3793 BECount = NewBTI.Exact;
3795 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
3797 if (MaxBECount == getCouldNotCompute())
3798 MaxBECount = NewBTI.Max;
3799 else if (NewBTI.Max != getCouldNotCompute())
3800 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
3803 return BackedgeTakenInfo(BECount, MaxBECount);
3806 /// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3807 /// of the specified loop will execute if it exits via the specified block.
3808 ScalarEvolution::BackedgeTakenInfo
3809 ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3810 BasicBlock *ExitingBlock) {
3812 // Okay, we've chosen an exiting block. See what condition causes us to
3813 // exit at this block.
3815 // FIXME: we should be able to handle switch instructions (with a single exit)
3816 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
3817 if (ExitBr == 0) return getCouldNotCompute();
3818 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
3820 // At this point, we know we have a conditional branch that determines whether
3821 // the loop is exited. However, we don't know if the branch is executed each
3822 // time through the loop. If not, then the execution count of the branch will
3823 // not be equal to the trip count of the loop.
3825 // Currently we check for this by checking to see if the Exit branch goes to
3826 // the loop header. If so, we know it will always execute the same number of
3827 // times as the loop. We also handle the case where the exit block *is* the
3828 // loop header. This is common for un-rotated loops.
3830 // If both of those tests fail, walk up the unique predecessor chain to the
3831 // header, stopping if there is an edge that doesn't exit the loop. If the
3832 // header is reached, the execution count of the branch will be equal to the
3833 // trip count of the loop.
3835 // More extensive analysis could be done to handle more cases here.
3837 if (ExitBr->getSuccessor(0) != L->getHeader() &&
3838 ExitBr->getSuccessor(1) != L->getHeader() &&
3839 ExitBr->getParent() != L->getHeader()) {
3840 // The simple checks failed, try climbing the unique predecessor chain
3841 // up to the header.
3843 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3844 BasicBlock *Pred = BB->getUniquePredecessor();
3846 return getCouldNotCompute();
3847 TerminatorInst *PredTerm = Pred->getTerminator();
3848 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3849 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3852 // If the predecessor has a successor that isn't BB and isn't
3853 // outside the loop, assume the worst.
3854 if (L->contains(PredSucc))
3855 return getCouldNotCompute();
3857 if (Pred == L->getHeader()) {
3864 return getCouldNotCompute();
3867 // Proceed to the next level to examine the exit condition expression.
3868 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3869 ExitBr->getSuccessor(0),
3870 ExitBr->getSuccessor(1));
3873 /// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3874 /// backedge of the specified loop will execute if its exit condition
3875 /// were a conditional branch of ExitCond, TBB, and FBB.
3876 ScalarEvolution::BackedgeTakenInfo
3877 ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3881 // Check if the controlling expression for this loop is an And or Or.
3882 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3883 if (BO->getOpcode() == Instruction::And) {
3884 // Recurse on the operands of the and.
3885 BackedgeTakenInfo BTI0 =
3886 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3887 BackedgeTakenInfo BTI1 =
3888 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3889 const SCEV *BECount = getCouldNotCompute();
3890 const SCEV *MaxBECount = getCouldNotCompute();
3891 if (L->contains(TBB)) {
3892 // Both conditions must be true for the loop to continue executing.
3893 // Choose the less conservative count.
3894 if (BTI0.Exact == getCouldNotCompute() ||
3895 BTI1.Exact == getCouldNotCompute())
3896 BECount = getCouldNotCompute();
3898 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3899 if (BTI0.Max == getCouldNotCompute())
3900 MaxBECount = BTI1.Max;
3901 else if (BTI1.Max == getCouldNotCompute())
3902 MaxBECount = BTI0.Max;
3904 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3906 // Both conditions must be true at the same time for the loop to exit.
3907 // For now, be conservative.
3908 assert(L->contains(FBB) && "Loop block has no successor in loop!");
3909 if (BTI0.Max == BTI1.Max)
3910 MaxBECount = BTI0.Max;
3911 if (BTI0.Exact == BTI1.Exact)
3912 BECount = BTI0.Exact;
3915 return BackedgeTakenInfo(BECount, MaxBECount);
3917 if (BO->getOpcode() == Instruction::Or) {
3918 // Recurse on the operands of the or.
3919 BackedgeTakenInfo BTI0 =
3920 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3921 BackedgeTakenInfo BTI1 =
3922 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3923 const SCEV *BECount = getCouldNotCompute();
3924 const SCEV *MaxBECount = getCouldNotCompute();
3925 if (L->contains(FBB)) {
3926 // Both conditions must be false for the loop to continue executing.
3927 // Choose the less conservative count.
3928 if (BTI0.Exact == getCouldNotCompute() ||
3929 BTI1.Exact == getCouldNotCompute())
3930 BECount = getCouldNotCompute();
3932 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3933 if (BTI0.Max == getCouldNotCompute())
3934 MaxBECount = BTI1.Max;
3935 else if (BTI1.Max == getCouldNotCompute())
3936 MaxBECount = BTI0.Max;
3938 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3940 // Both conditions must be false at the same time for the loop to exit.
3941 // For now, be conservative.
3942 assert(L->contains(TBB) && "Loop block has no successor in loop!");
3943 if (BTI0.Max == BTI1.Max)
3944 MaxBECount = BTI0.Max;
3945 if (BTI0.Exact == BTI1.Exact)
3946 BECount = BTI0.Exact;
3949 return BackedgeTakenInfo(BECount, MaxBECount);
3953 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3954 // Proceed to the next level to examine the icmp.
3955 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3956 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
3958 // Check for a constant condition. These are normally stripped out by
3959 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
3960 // preserve the CFG and is temporarily leaving constant conditions
3962 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
3963 if (L->contains(FBB) == !CI->getZExtValue())
3964 // The backedge is always taken.
3965 return getCouldNotCompute();
3967 // The backedge is never taken.
3968 return getConstant(CI->getType(), 0);
3971 // If it's not an integer or pointer comparison then compute it the hard way.
3972 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3975 /// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3976 /// backedge of the specified loop will execute if its exit condition
3977 /// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3978 ScalarEvolution::BackedgeTakenInfo
3979 ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3984 // If the condition was exit on true, convert the condition to exit on false
3985 ICmpInst::Predicate Cond;
3986 if (!L->contains(FBB))
3987 Cond = ExitCond->getPredicate();
3989 Cond = ExitCond->getInversePredicate();
3991 // Handle common loops like: for (X = "string"; *X; ++X)
3992 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3993 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
3994 BackedgeTakenInfo ItCnt =
3995 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
3996 if (ItCnt.hasAnyInfo())
4000 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
4001 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
4003 // Try to evaluate any dependencies out of the loop.
4004 LHS = getSCEVAtScope(LHS, L);
4005 RHS = getSCEVAtScope(RHS, L);
4007 // At this point, we would like to compute how many iterations of the
4008 // loop the predicate will return true for these inputs.
4009 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
4010 // If there is a loop-invariant, force it into the RHS.
4011 std::swap(LHS, RHS);
4012 Cond = ICmpInst::getSwappedPredicate(Cond);
4015 // Simplify the operands before analyzing them.
4016 (void)SimplifyICmpOperands(Cond, LHS, RHS);
4018 // If we have a comparison of a chrec against a constant, try to use value
4019 // ranges to answer this query.
4020 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
4021 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
4022 if (AddRec->getLoop() == L) {
4023 // Form the constant range.
4024 ConstantRange CompRange(
4025 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
4027 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
4028 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
4032 case ICmpInst::ICMP_NE: { // while (X != Y)
4033 // Convert to: while (X-Y != 0)
4034 BackedgeTakenInfo BTI = HowFarToZero(getMinusSCEV(LHS, RHS), L);
4035 if (BTI.hasAnyInfo()) return BTI;
4038 case ICmpInst::ICMP_EQ: { // while (X == Y)
4039 // Convert to: while (X-Y == 0)
4040 BackedgeTakenInfo BTI = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
4041 if (BTI.hasAnyInfo()) return BTI;
4044 case ICmpInst::ICMP_SLT: {
4045 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
4046 if (BTI.hasAnyInfo()) return BTI;
4049 case ICmpInst::ICMP_SGT: {
4050 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
4051 getNotSCEV(RHS), L, true);
4052 if (BTI.hasAnyInfo()) return BTI;
4055 case ICmpInst::ICMP_ULT: {
4056 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
4057 if (BTI.hasAnyInfo()) return BTI;
4060 case ICmpInst::ICMP_UGT: {
4061 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
4062 getNotSCEV(RHS), L, false);
4063 if (BTI.hasAnyInfo()) return BTI;
4068 dbgs() << "ComputeBackedgeTakenCount ";
4069 if (ExitCond->getOperand(0)->getType()->isUnsigned())
4070 dbgs() << "[unsigned] ";
4071 dbgs() << *LHS << " "
4072 << Instruction::getOpcodeName(Instruction::ICmp)
4073 << " " << *RHS << "\n";
4078 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
4081 static ConstantInt *
4082 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
4083 ScalarEvolution &SE) {
4084 const SCEV *InVal = SE.getConstant(C);
4085 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
4086 assert(isa<SCEVConstant>(Val) &&
4087 "Evaluation of SCEV at constant didn't fold correctly?");
4088 return cast<SCEVConstant>(Val)->getValue();
4091 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
4092 /// and a GEP expression (missing the pointer index) indexing into it, return
4093 /// the addressed element of the initializer or null if the index expression is
4096 GetAddressedElementFromGlobal(GlobalVariable *GV,
4097 const std::vector<ConstantInt*> &Indices) {
4098 Constant *Init = GV->getInitializer();
4099 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
4100 uint64_t Idx = Indices[i]->getZExtValue();
4101 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
4102 assert(Idx < CS->getNumOperands() && "Bad struct index!");
4103 Init = cast<Constant>(CS->getOperand(Idx));
4104 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
4105 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
4106 Init = cast<Constant>(CA->getOperand(Idx));
4107 } else if (isa<ConstantAggregateZero>(Init)) {
4108 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
4109 assert(Idx < STy->getNumElements() && "Bad struct index!");
4110 Init = Constant::getNullValue(STy->getElementType(Idx));
4111 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
4112 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
4113 Init = Constant::getNullValue(ATy->getElementType());
4115 llvm_unreachable("Unknown constant aggregate type!");
4119 return 0; // Unknown initializer type
4125 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
4126 /// 'icmp op load X, cst', try to see if we can compute the backedge
4127 /// execution count.
4128 ScalarEvolution::BackedgeTakenInfo
4129 ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
4133 ICmpInst::Predicate predicate) {
4134 if (LI->isVolatile()) return getCouldNotCompute();
4136 // Check to see if the loaded pointer is a getelementptr of a global.
4137 // TODO: Use SCEV instead of manually grubbing with GEPs.
4138 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
4139 if (!GEP) return getCouldNotCompute();
4141 // Make sure that it is really a constant global we are gepping, with an
4142 // initializer, and make sure the first IDX is really 0.
4143 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
4144 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
4145 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
4146 !cast<Constant>(GEP->getOperand(1))->isNullValue())
4147 return getCouldNotCompute();
4149 // Okay, we allow one non-constant index into the GEP instruction.
4151 std::vector<ConstantInt*> Indexes;
4152 unsigned VarIdxNum = 0;
4153 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
4154 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4155 Indexes.push_back(CI);
4156 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
4157 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
4158 VarIdx = GEP->getOperand(i);
4160 Indexes.push_back(0);
4163 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
4164 // Check to see if X is a loop variant variable value now.
4165 const SCEV *Idx = getSCEV(VarIdx);
4166 Idx = getSCEVAtScope(Idx, L);
4168 // We can only recognize very limited forms of loop index expressions, in
4169 // particular, only affine AddRec's like {C1,+,C2}.
4170 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
4171 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
4172 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
4173 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
4174 return getCouldNotCompute();
4176 unsigned MaxSteps = MaxBruteForceIterations;
4177 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
4178 ConstantInt *ItCst = ConstantInt::get(
4179 cast<IntegerType>(IdxExpr->getType()), IterationNum);
4180 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
4182 // Form the GEP offset.
4183 Indexes[VarIdxNum] = Val;
4185 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
4186 if (Result == 0) break; // Cannot compute!
4188 // Evaluate the condition for this iteration.
4189 Result = ConstantExpr::getICmp(predicate, Result, RHS);
4190 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
4191 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
4193 dbgs() << "\n***\n*** Computed loop count " << *ItCst
4194 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
4197 ++NumArrayLenItCounts;
4198 return getConstant(ItCst); // Found terminating iteration!
4201 return getCouldNotCompute();
4205 /// CanConstantFold - Return true if we can constant fold an instruction of the
4206 /// specified type, assuming that all operands were constants.
4207 static bool CanConstantFold(const Instruction *I) {
4208 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
4209 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
4212 if (const CallInst *CI = dyn_cast<CallInst>(I))
4213 if (const Function *F = CI->getCalledFunction())
4214 return canConstantFoldCallTo(F);
4218 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
4219 /// in the loop that V is derived from. We allow arbitrary operations along the
4220 /// way, but the operands of an operation must either be constants or a value
4221 /// derived from a constant PHI. If this expression does not fit with these
4222 /// constraints, return null.
4223 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
4224 // If this is not an instruction, or if this is an instruction outside of the
4225 // loop, it can't be derived from a loop PHI.
4226 Instruction *I = dyn_cast<Instruction>(V);
4227 if (I == 0 || !L->contains(I)) return 0;
4229 if (PHINode *PN = dyn_cast<PHINode>(I)) {
4230 if (L->getHeader() == I->getParent())
4233 // We don't currently keep track of the control flow needed to evaluate
4234 // PHIs, so we cannot handle PHIs inside of loops.
4238 // If we won't be able to constant fold this expression even if the operands
4239 // are constants, return early.
4240 if (!CanConstantFold(I)) return 0;
4242 // Otherwise, we can evaluate this instruction if all of its operands are
4243 // constant or derived from a PHI node themselves.
4245 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
4246 if (!isa<Constant>(I->getOperand(Op))) {
4247 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
4248 if (P == 0) return 0; // Not evolving from PHI
4252 return 0; // Evolving from multiple different PHIs.
4255 // This is a expression evolving from a constant PHI!
4259 /// EvaluateExpression - Given an expression that passes the
4260 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
4261 /// in the loop has the value PHIVal. If we can't fold this expression for some
4262 /// reason, return null.
4263 static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
4264 const TargetData *TD) {
4265 if (isa<PHINode>(V)) return PHIVal;
4266 if (Constant *C = dyn_cast<Constant>(V)) return C;
4267 Instruction *I = cast<Instruction>(V);
4269 std::vector<Constant*> Operands(I->getNumOperands());
4271 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4272 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
4273 if (Operands[i] == 0) return 0;
4276 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4277 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
4279 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4280 &Operands[0], Operands.size(), TD);
4283 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
4284 /// in the header of its containing loop, we know the loop executes a
4285 /// constant number of times, and the PHI node is just a recurrence
4286 /// involving constants, fold it.
4288 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
4291 std::map<PHINode*, Constant*>::const_iterator I =
4292 ConstantEvolutionLoopExitValue.find(PN);
4293 if (I != ConstantEvolutionLoopExitValue.end())
4296 if (BEs.ugt(MaxBruteForceIterations))
4297 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
4299 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
4301 // Since the loop is canonicalized, the PHI node must have two entries. One
4302 // entry must be a constant (coming in from outside of the loop), and the
4303 // second must be derived from the same PHI.
4304 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4305 Constant *StartCST =
4306 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4308 return RetVal = 0; // Must be a constant.
4310 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4311 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4312 !isa<Constant>(BEValue))
4313 return RetVal = 0; // Not derived from same PHI.
4315 // Execute the loop symbolically to determine the exit value.
4316 if (BEs.getActiveBits() >= 32)
4317 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
4319 unsigned NumIterations = BEs.getZExtValue(); // must be in range
4320 unsigned IterationNum = 0;
4321 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
4322 if (IterationNum == NumIterations)
4323 return RetVal = PHIVal; // Got exit value!
4325 // Compute the value of the PHI node for the next iteration.
4326 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
4327 if (NextPHI == PHIVal)
4328 return RetVal = NextPHI; // Stopped evolving!
4330 return 0; // Couldn't evaluate!
4335 /// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
4336 /// constant number of times (the condition evolves only from constants),
4337 /// try to evaluate a few iterations of the loop until we get the exit
4338 /// condition gets a value of ExitWhen (true or false). If we cannot
4339 /// evaluate the trip count of the loop, return getCouldNotCompute().
4341 ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
4344 PHINode *PN = getConstantEvolvingPHI(Cond, L);
4345 if (PN == 0) return getCouldNotCompute();
4347 // If the loop is canonicalized, the PHI will have exactly two entries.
4348 // That's the only form we support here.
4349 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
4351 // One entry must be a constant (coming in from outside of the loop), and the
4352 // second must be derived from the same PHI.
4353 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4354 Constant *StartCST =
4355 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4356 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
4358 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4359 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4360 !isa<Constant>(BEValue))
4361 return getCouldNotCompute(); // Not derived from same PHI.
4363 // Okay, we find a PHI node that defines the trip count of this loop. Execute
4364 // the loop symbolically to determine when the condition gets a value of
4366 unsigned IterationNum = 0;
4367 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
4368 for (Constant *PHIVal = StartCST;
4369 IterationNum != MaxIterations; ++IterationNum) {
4370 ConstantInt *CondVal =
4371 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
4373 // Couldn't symbolically evaluate.
4374 if (!CondVal) return getCouldNotCompute();
4376 if (CondVal->getValue() == uint64_t(ExitWhen)) {
4377 ++NumBruteForceTripCountsComputed;
4378 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
4381 // Compute the value of the PHI node for the next iteration.
4382 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
4383 if (NextPHI == 0 || NextPHI == PHIVal)
4384 return getCouldNotCompute();// Couldn't evaluate or not making progress...
4388 // Too many iterations were needed to evaluate.
4389 return getCouldNotCompute();
4392 /// getSCEVAtScope - Return a SCEV expression for the specified value
4393 /// at the specified scope in the program. The L value specifies a loop
4394 /// nest to evaluate the expression at, where null is the top-level or a
4395 /// specified loop is immediately inside of the loop.
4397 /// This method can be used to compute the exit value for a variable defined
4398 /// in a loop by querying what the value will hold in the parent loop.
4400 /// In the case that a relevant loop exit value cannot be computed, the
4401 /// original value V is returned.
4402 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
4403 // Check to see if we've folded this expression at this loop before.
4404 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4405 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4406 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4408 return Pair.first->second ? Pair.first->second : V;
4410 // Otherwise compute it.
4411 const SCEV *C = computeSCEVAtScope(V, L);
4412 ValuesAtScopes[V][L] = C;
4416 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
4417 if (isa<SCEVConstant>(V)) return V;
4419 // If this instruction is evolved from a constant-evolving PHI, compute the
4420 // exit value from the loop without using SCEVs.
4421 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
4422 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
4423 const Loop *LI = (*this->LI)[I->getParent()];
4424 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
4425 if (PHINode *PN = dyn_cast<PHINode>(I))
4426 if (PN->getParent() == LI->getHeader()) {
4427 // Okay, there is no closed form solution for the PHI node. Check
4428 // to see if the loop that contains it has a known backedge-taken
4429 // count. If so, we may be able to force computation of the exit
4431 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
4432 if (const SCEVConstant *BTCC =
4433 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
4434 // Okay, we know how many times the containing loop executes. If
4435 // this is a constant evolving PHI node, get the final value at
4436 // the specified iteration number.
4437 Constant *RV = getConstantEvolutionLoopExitValue(PN,
4438 BTCC->getValue()->getValue(),
4440 if (RV) return getSCEV(RV);
4444 // Okay, this is an expression that we cannot symbolically evaluate
4445 // into a SCEV. Check to see if it's possible to symbolically evaluate
4446 // the arguments into constants, and if so, try to constant propagate the
4447 // result. This is particularly useful for computing loop exit values.
4448 if (CanConstantFold(I)) {
4449 SmallVector<Constant *, 4> Operands;
4450 bool MadeImprovement = false;
4451 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4452 Value *Op = I->getOperand(i);
4453 if (Constant *C = dyn_cast<Constant>(Op)) {
4454 Operands.push_back(C);
4458 // If any of the operands is non-constant and if they are
4459 // non-integer and non-pointer, don't even try to analyze them
4460 // with scev techniques.
4461 if (!isSCEVable(Op->getType()))
4464 const SCEV *OrigV = getSCEV(Op);
4465 const SCEV *OpV = getSCEVAtScope(OrigV, L);
4466 MadeImprovement |= OrigV != OpV;
4469 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
4471 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV))
4472 C = dyn_cast<Constant>(SU->getValue());
4474 if (C->getType() != Op->getType())
4475 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4479 Operands.push_back(C);
4482 // Check to see if getSCEVAtScope actually made an improvement.
4483 if (MadeImprovement) {
4485 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4486 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
4487 Operands[0], Operands[1], TD);
4489 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4490 &Operands[0], Operands.size(), TD);
4497 // This is some other type of SCEVUnknown, just return it.
4501 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
4502 // Avoid performing the look-up in the common case where the specified
4503 // expression has no loop-variant portions.
4504 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
4505 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
4506 if (OpAtScope != Comm->getOperand(i)) {
4507 // Okay, at least one of these operands is loop variant but might be
4508 // foldable. Build a new instance of the folded commutative expression.
4509 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4510 Comm->op_begin()+i);
4511 NewOps.push_back(OpAtScope);
4513 for (++i; i != e; ++i) {
4514 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
4515 NewOps.push_back(OpAtScope);
4517 if (isa<SCEVAddExpr>(Comm))
4518 return getAddExpr(NewOps);
4519 if (isa<SCEVMulExpr>(Comm))
4520 return getMulExpr(NewOps);
4521 if (isa<SCEVSMaxExpr>(Comm))
4522 return getSMaxExpr(NewOps);
4523 if (isa<SCEVUMaxExpr>(Comm))
4524 return getUMaxExpr(NewOps);
4525 llvm_unreachable("Unknown commutative SCEV type!");
4528 // If we got here, all operands are loop invariant.
4532 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
4533 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4534 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
4535 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4536 return Div; // must be loop invariant
4537 return getUDivExpr(LHS, RHS);
4540 // If this is a loop recurrence for a loop that does not contain L, then we
4541 // are dealing with the final value computed by the loop.
4542 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4543 // First, attempt to evaluate each operand.
4544 // Avoid performing the look-up in the common case where the specified
4545 // expression has no loop-variant portions.
4546 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4547 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
4548 if (OpAtScope == AddRec->getOperand(i))
4551 // Okay, at least one of these operands is loop variant but might be
4552 // foldable. Build a new instance of the folded commutative expression.
4553 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
4554 AddRec->op_begin()+i);
4555 NewOps.push_back(OpAtScope);
4556 for (++i; i != e; ++i)
4557 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
4559 AddRec = cast<SCEVAddRecExpr>(getAddRecExpr(NewOps, AddRec->getLoop()));
4563 // If the scope is outside the addrec's loop, evaluate it by using the
4564 // loop exit value of the addrec.
4565 if (!AddRec->getLoop()->contains(L)) {
4566 // To evaluate this recurrence, we need to know how many times the AddRec
4567 // loop iterates. Compute this now.
4568 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
4569 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
4571 // Then, evaluate the AddRec.
4572 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
4578 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
4579 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4580 if (Op == Cast->getOperand())
4581 return Cast; // must be loop invariant
4582 return getZeroExtendExpr(Op, Cast->getType());
4585 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
4586 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4587 if (Op == Cast->getOperand())
4588 return Cast; // must be loop invariant
4589 return getSignExtendExpr(Op, Cast->getType());
4592 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
4593 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4594 if (Op == Cast->getOperand())
4595 return Cast; // must be loop invariant
4596 return getTruncateExpr(Op, Cast->getType());
4599 llvm_unreachable("Unknown SCEV type!");
4603 /// getSCEVAtScope - This is a convenience function which does
4604 /// getSCEVAtScope(getSCEV(V), L).
4605 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
4606 return getSCEVAtScope(getSCEV(V), L);
4609 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4610 /// following equation:
4612 /// A * X = B (mod N)
4614 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4615 /// A and B isn't important.
4617 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
4618 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
4619 ScalarEvolution &SE) {
4620 uint32_t BW = A.getBitWidth();
4621 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4622 assert(A != 0 && "A must be non-zero.");
4626 // The gcd of A and N may have only one prime factor: 2. The number of
4627 // trailing zeros in A is its multiplicity
4628 uint32_t Mult2 = A.countTrailingZeros();
4631 // 2. Check if B is divisible by D.
4633 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4634 // is not less than multiplicity of this prime factor for D.
4635 if (B.countTrailingZeros() < Mult2)
4636 return SE.getCouldNotCompute();
4638 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4641 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4642 // bit width during computations.
4643 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4644 APInt Mod(BW + 1, 0);
4645 Mod.set(BW - Mult2); // Mod = N / D
4646 APInt I = AD.multiplicativeInverse(Mod);
4648 // 4. Compute the minimum unsigned root of the equation:
4649 // I * (B / D) mod (N / D)
4650 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4652 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4654 return SE.getConstant(Result.trunc(BW));
4657 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4658 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4659 /// might be the same) or two SCEVCouldNotCompute objects.
4661 static std::pair<const SCEV *,const SCEV *>
4662 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
4663 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
4664 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4665 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4666 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
4668 // We currently can only solve this if the coefficients are constants.
4669 if (!LC || !MC || !NC) {
4670 const SCEV *CNC = SE.getCouldNotCompute();
4671 return std::make_pair(CNC, CNC);
4674 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
4675 const APInt &L = LC->getValue()->getValue();
4676 const APInt &M = MC->getValue()->getValue();
4677 const APInt &N = NC->getValue()->getValue();
4678 APInt Two(BitWidth, 2);
4679 APInt Four(BitWidth, 4);
4682 using namespace APIntOps;
4684 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4685 // The B coefficient is M-N/2
4689 // The A coefficient is N/2
4690 APInt A(N.sdiv(Two));
4692 // Compute the B^2-4ac term.
4695 SqrtTerm -= Four * (A * C);
4697 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4698 // integer value or else APInt::sqrt() will assert.
4699 APInt SqrtVal(SqrtTerm.sqrt());
4701 // Compute the two solutions for the quadratic formula.
4702 // The divisions must be performed as signed divisions.
4704 APInt TwoA( A << 1 );
4705 if (TwoA.isMinValue()) {
4706 const SCEV *CNC = SE.getCouldNotCompute();
4707 return std::make_pair(CNC, CNC);
4710 LLVMContext &Context = SE.getContext();
4712 ConstantInt *Solution1 =
4713 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
4714 ConstantInt *Solution2 =
4715 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
4717 return std::make_pair(SE.getConstant(Solution1),
4718 SE.getConstant(Solution2));
4719 } // end APIntOps namespace
4722 /// HowFarToZero - Return the number of times a backedge comparing the specified
4723 /// value to zero will execute. If not computable, return CouldNotCompute.
4724 ScalarEvolution::BackedgeTakenInfo
4725 ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
4726 // If the value is a constant
4727 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
4728 // If the value is already zero, the branch will execute zero times.
4729 if (C->getValue()->isZero()) return C;
4730 return getCouldNotCompute(); // Otherwise it will loop infinitely.
4733 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
4734 if (!AddRec || AddRec->getLoop() != L)
4735 return getCouldNotCompute();
4737 if (AddRec->isAffine()) {
4738 // If this is an affine expression, the execution count of this branch is
4739 // the minimum unsigned root of the following equation:
4741 // Start + Step*N = 0 (mod 2^BW)
4745 // Step*N = -Start (mod 2^BW)
4747 // where BW is the common bit width of Start and Step.
4749 // Get the initial value for the loop.
4750 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4751 L->getParentLoop());
4752 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4753 L->getParentLoop());
4755 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
4756 // For now we handle only constant steps.
4758 // First, handle unitary steps.
4759 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
4760 return getNegativeSCEV(Start); // N = -Start (as unsigned)
4761 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4762 return Start; // N = Start (as unsigned)
4764 // Then, try to solve the above equation provided that Start is constant.
4765 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
4766 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
4767 -StartC->getValue()->getValue(),
4770 } else if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
4771 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4772 // the quadratic equation to solve it.
4773 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
4775 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4776 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
4779 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
4780 << " sol#2: " << *R2 << "\n";
4782 // Pick the smallest positive root value.
4783 if (ConstantInt *CB =
4784 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
4785 R1->getValue(), R2->getValue()))) {
4786 if (CB->getZExtValue() == false)
4787 std::swap(R1, R2); // R1 is the minimum root now.
4789 // We can only use this value if the chrec ends up with an exact zero
4790 // value at this index. When solving for "X*X != 5", for example, we
4791 // should not accept a root of 2.
4792 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
4794 return R1; // We found a quadratic root!
4799 return getCouldNotCompute();
4802 /// HowFarToNonZero - Return the number of times a backedge checking the
4803 /// specified value for nonzero will execute. If not computable, return
4805 ScalarEvolution::BackedgeTakenInfo
4806 ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
4807 // Loops that look like: while (X == 0) are very strange indeed. We don't
4808 // handle them yet except for the trivial case. This could be expanded in the
4809 // future as needed.
4811 // If the value is a constant, check to see if it is known to be non-zero
4812 // already. If so, the backedge will execute zero times.
4813 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
4814 if (!C->getValue()->isNullValue())
4815 return getConstant(C->getType(), 0);
4816 return getCouldNotCompute(); // Otherwise it will loop infinitely.
4819 // We could implement others, but I really doubt anyone writes loops like
4820 // this, and if they did, they would already be constant folded.
4821 return getCouldNotCompute();
4824 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4825 /// (which may not be an immediate predecessor) which has exactly one
4826 /// successor from which BB is reachable, or null if no such block is
4829 std::pair<BasicBlock *, BasicBlock *>
4830 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
4831 // If the block has a unique predecessor, then there is no path from the
4832 // predecessor to the block that does not go through the direct edge
4833 // from the predecessor to the block.
4834 if (BasicBlock *Pred = BB->getSinglePredecessor())
4835 return std::make_pair(Pred, BB);
4837 // A loop's header is defined to be a block that dominates the loop.
4838 // If the header has a unique predecessor outside the loop, it must be
4839 // a block that has exactly one successor that can reach the loop.
4840 if (Loop *L = LI->getLoopFor(BB))
4841 return std::make_pair(L->getLoopPredecessor(), L->getHeader());
4843 return std::pair<BasicBlock *, BasicBlock *>();
4846 /// HasSameValue - SCEV structural equivalence is usually sufficient for
4847 /// testing whether two expressions are equal, however for the purposes of
4848 /// looking for a condition guarding a loop, it can be useful to be a little
4849 /// more general, since a front-end may have replicated the controlling
4852 static bool HasSameValue(const SCEV *A, const SCEV *B) {
4853 // Quick check to see if they are the same SCEV.
4854 if (A == B) return true;
4856 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4857 // two different instructions with the same value. Check for this case.
4858 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4859 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4860 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4861 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
4862 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
4865 // Otherwise assume they may have a different value.
4869 /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
4870 /// predicate Pred. Return true iff any changes were made.
4872 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
4873 const SCEV *&LHS, const SCEV *&RHS) {
4874 bool Changed = false;
4876 // Canonicalize a constant to the right side.
4877 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
4878 // Check for both operands constant.
4879 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
4880 if (ConstantExpr::getICmp(Pred,
4882 RHSC->getValue())->isNullValue())
4883 goto trivially_false;
4885 goto trivially_true;
4887 // Otherwise swap the operands to put the constant on the right.
4888 std::swap(LHS, RHS);
4889 Pred = ICmpInst::getSwappedPredicate(Pred);
4893 // If we're comparing an addrec with a value which is loop-invariant in the
4894 // addrec's loop, put the addrec on the left. Also make a dominance check,
4895 // as both operands could be addrecs loop-invariant in each other's loop.
4896 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
4897 const Loop *L = AR->getLoop();
4898 if (LHS->isLoopInvariant(L) && LHS->properlyDominates(L->getHeader(), DT)) {
4899 std::swap(LHS, RHS);
4900 Pred = ICmpInst::getSwappedPredicate(Pred);
4905 // If there's a constant operand, canonicalize comparisons with boundary
4906 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
4907 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4908 const APInt &RA = RC->getValue()->getValue();
4910 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4911 case ICmpInst::ICMP_EQ:
4912 case ICmpInst::ICMP_NE:
4914 case ICmpInst::ICMP_UGE:
4915 if ((RA - 1).isMinValue()) {
4916 Pred = ICmpInst::ICMP_NE;
4917 RHS = getConstant(RA - 1);
4921 if (RA.isMaxValue()) {
4922 Pred = ICmpInst::ICMP_EQ;
4926 if (RA.isMinValue()) goto trivially_true;
4928 Pred = ICmpInst::ICMP_UGT;
4929 RHS = getConstant(RA - 1);
4932 case ICmpInst::ICMP_ULE:
4933 if ((RA + 1).isMaxValue()) {
4934 Pred = ICmpInst::ICMP_NE;
4935 RHS = getConstant(RA + 1);
4939 if (RA.isMinValue()) {
4940 Pred = ICmpInst::ICMP_EQ;
4944 if (RA.isMaxValue()) goto trivially_true;
4946 Pred = ICmpInst::ICMP_ULT;
4947 RHS = getConstant(RA + 1);
4950 case ICmpInst::ICMP_SGE:
4951 if ((RA - 1).isMinSignedValue()) {
4952 Pred = ICmpInst::ICMP_NE;
4953 RHS = getConstant(RA - 1);
4957 if (RA.isMaxSignedValue()) {
4958 Pred = ICmpInst::ICMP_EQ;
4962 if (RA.isMinSignedValue()) goto trivially_true;
4964 Pred = ICmpInst::ICMP_SGT;
4965 RHS = getConstant(RA - 1);
4968 case ICmpInst::ICMP_SLE:
4969 if ((RA + 1).isMaxSignedValue()) {
4970 Pred = ICmpInst::ICMP_NE;
4971 RHS = getConstant(RA + 1);
4975 if (RA.isMinSignedValue()) {
4976 Pred = ICmpInst::ICMP_EQ;
4980 if (RA.isMaxSignedValue()) goto trivially_true;
4982 Pred = ICmpInst::ICMP_SLT;
4983 RHS = getConstant(RA + 1);
4986 case ICmpInst::ICMP_UGT:
4987 if (RA.isMinValue()) {
4988 Pred = ICmpInst::ICMP_NE;
4992 if ((RA + 1).isMaxValue()) {
4993 Pred = ICmpInst::ICMP_EQ;
4994 RHS = getConstant(RA + 1);
4998 if (RA.isMaxValue()) goto trivially_false;
5000 case ICmpInst::ICMP_ULT:
5001 if (RA.isMaxValue()) {
5002 Pred = ICmpInst::ICMP_NE;
5006 if ((RA - 1).isMinValue()) {
5007 Pred = ICmpInst::ICMP_EQ;
5008 RHS = getConstant(RA - 1);
5012 if (RA.isMinValue()) goto trivially_false;
5014 case ICmpInst::ICMP_SGT:
5015 if (RA.isMinSignedValue()) {
5016 Pred = ICmpInst::ICMP_NE;
5020 if ((RA + 1).isMaxSignedValue()) {
5021 Pred = ICmpInst::ICMP_EQ;
5022 RHS = getConstant(RA + 1);
5026 if (RA.isMaxSignedValue()) goto trivially_false;
5028 case ICmpInst::ICMP_SLT:
5029 if (RA.isMaxSignedValue()) {
5030 Pred = ICmpInst::ICMP_NE;
5034 if ((RA - 1).isMinSignedValue()) {
5035 Pred = ICmpInst::ICMP_EQ;
5036 RHS = getConstant(RA - 1);
5040 if (RA.isMinSignedValue()) goto trivially_false;
5045 // Check for obvious equality.
5046 if (HasSameValue(LHS, RHS)) {
5047 if (ICmpInst::isTrueWhenEqual(Pred))
5048 goto trivially_true;
5049 if (ICmpInst::isFalseWhenEqual(Pred))
5050 goto trivially_false;
5053 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
5054 // adding or subtracting 1 from one of the operands.
5056 case ICmpInst::ICMP_SLE:
5057 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
5058 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
5059 /*HasNUW=*/false, /*HasNSW=*/true);
5060 Pred = ICmpInst::ICMP_SLT;
5062 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
5063 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
5064 /*HasNUW=*/false, /*HasNSW=*/true);
5065 Pred = ICmpInst::ICMP_SLT;
5069 case ICmpInst::ICMP_SGE:
5070 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
5071 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
5072 /*HasNUW=*/false, /*HasNSW=*/true);
5073 Pred = ICmpInst::ICMP_SGT;
5075 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
5076 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
5077 /*HasNUW=*/false, /*HasNSW=*/true);
5078 Pred = ICmpInst::ICMP_SGT;
5082 case ICmpInst::ICMP_ULE:
5083 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
5084 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
5085 /*HasNUW=*/true, /*HasNSW=*/false);
5086 Pred = ICmpInst::ICMP_ULT;
5088 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
5089 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
5090 /*HasNUW=*/true, /*HasNSW=*/false);
5091 Pred = ICmpInst::ICMP_ULT;
5095 case ICmpInst::ICMP_UGE:
5096 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
5097 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
5098 /*HasNUW=*/true, /*HasNSW=*/false);
5099 Pred = ICmpInst::ICMP_UGT;
5101 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
5102 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
5103 /*HasNUW=*/true, /*HasNSW=*/false);
5104 Pred = ICmpInst::ICMP_UGT;
5112 // TODO: More simplifications are possible here.
5118 LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
5119 Pred = ICmpInst::ICMP_EQ;
5124 LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
5125 Pred = ICmpInst::ICMP_NE;
5129 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
5130 return getSignedRange(S).getSignedMax().isNegative();
5133 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
5134 return getSignedRange(S).getSignedMin().isStrictlyPositive();
5137 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
5138 return !getSignedRange(S).getSignedMin().isNegative();
5141 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
5142 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
5145 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
5146 return isKnownNegative(S) || isKnownPositive(S);
5149 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
5150 const SCEV *LHS, const SCEV *RHS) {
5151 // Canonicalize the inputs first.
5152 (void)SimplifyICmpOperands(Pred, LHS, RHS);
5154 // If LHS or RHS is an addrec, check to see if the condition is true in
5155 // every iteration of the loop.
5156 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
5157 if (isLoopEntryGuardedByCond(
5158 AR->getLoop(), Pred, AR->getStart(), RHS) &&
5159 isLoopBackedgeGuardedByCond(
5160 AR->getLoop(), Pred, AR->getPostIncExpr(*this), RHS))
5162 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS))
5163 if (isLoopEntryGuardedByCond(
5164 AR->getLoop(), Pred, LHS, AR->getStart()) &&
5165 isLoopBackedgeGuardedByCond(
5166 AR->getLoop(), Pred, LHS, AR->getPostIncExpr(*this)))
5169 // Otherwise see what can be done with known constant ranges.
5170 return isKnownPredicateWithRanges(Pred, LHS, RHS);
5174 ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
5175 const SCEV *LHS, const SCEV *RHS) {
5176 if (HasSameValue(LHS, RHS))
5177 return ICmpInst::isTrueWhenEqual(Pred);
5179 // This code is split out from isKnownPredicate because it is called from
5180 // within isLoopEntryGuardedByCond.
5183 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5185 case ICmpInst::ICMP_SGT:
5186 Pred = ICmpInst::ICMP_SLT;
5187 std::swap(LHS, RHS);
5188 case ICmpInst::ICMP_SLT: {
5189 ConstantRange LHSRange = getSignedRange(LHS);
5190 ConstantRange RHSRange = getSignedRange(RHS);
5191 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
5193 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
5197 case ICmpInst::ICMP_SGE:
5198 Pred = ICmpInst::ICMP_SLE;
5199 std::swap(LHS, RHS);
5200 case ICmpInst::ICMP_SLE: {
5201 ConstantRange LHSRange = getSignedRange(LHS);
5202 ConstantRange RHSRange = getSignedRange(RHS);
5203 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
5205 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
5209 case ICmpInst::ICMP_UGT:
5210 Pred = ICmpInst::ICMP_ULT;
5211 std::swap(LHS, RHS);
5212 case ICmpInst::ICMP_ULT: {
5213 ConstantRange LHSRange = getUnsignedRange(LHS);
5214 ConstantRange RHSRange = getUnsignedRange(RHS);
5215 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
5217 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
5221 case ICmpInst::ICMP_UGE:
5222 Pred = ICmpInst::ICMP_ULE;
5223 std::swap(LHS, RHS);
5224 case ICmpInst::ICMP_ULE: {
5225 ConstantRange LHSRange = getUnsignedRange(LHS);
5226 ConstantRange RHSRange = getUnsignedRange(RHS);
5227 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
5229 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
5233 case ICmpInst::ICMP_NE: {
5234 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
5236 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
5239 const SCEV *Diff = getMinusSCEV(LHS, RHS);
5240 if (isKnownNonZero(Diff))
5244 case ICmpInst::ICMP_EQ:
5245 // The check at the top of the function catches the case where
5246 // the values are known to be equal.
5252 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
5253 /// protected by a conditional between LHS and RHS. This is used to
5254 /// to eliminate casts.
5256 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
5257 ICmpInst::Predicate Pred,
5258 const SCEV *LHS, const SCEV *RHS) {
5259 // Interpret a null as meaning no loop, where there is obviously no guard
5260 // (interprocedural conditions notwithstanding).
5261 if (!L) return true;
5263 BasicBlock *Latch = L->getLoopLatch();
5267 BranchInst *LoopContinuePredicate =
5268 dyn_cast<BranchInst>(Latch->getTerminator());
5269 if (!LoopContinuePredicate ||
5270 LoopContinuePredicate->isUnconditional())
5273 return isImpliedCond(Pred, LHS, RHS,
5274 LoopContinuePredicate->getCondition(),
5275 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
5278 /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
5279 /// by a conditional between LHS and RHS. This is used to help avoid max
5280 /// expressions in loop trip counts, and to eliminate casts.
5282 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
5283 ICmpInst::Predicate Pred,
5284 const SCEV *LHS, const SCEV *RHS) {
5285 // Interpret a null as meaning no loop, where there is obviously no guard
5286 // (interprocedural conditions notwithstanding).
5287 if (!L) return false;
5289 // Starting at the loop predecessor, climb up the predecessor chain, as long
5290 // as there are predecessors that can be found that have unique successors
5291 // leading to the original header.
5292 for (std::pair<BasicBlock *, BasicBlock *>
5293 Pair(L->getLoopPredecessor(), L->getHeader());
5295 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
5297 BranchInst *LoopEntryPredicate =
5298 dyn_cast<BranchInst>(Pair.first->getTerminator());
5299 if (!LoopEntryPredicate ||
5300 LoopEntryPredicate->isUnconditional())
5303 if (isImpliedCond(Pred, LHS, RHS,
5304 LoopEntryPredicate->getCondition(),
5305 LoopEntryPredicate->getSuccessor(0) != Pair.second))
5312 /// isImpliedCond - Test whether the condition described by Pred, LHS,
5313 /// and RHS is true whenever the given Cond value evaluates to true.
5314 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
5315 const SCEV *LHS, const SCEV *RHS,
5316 Value *FoundCondValue,
5318 // Recursively handle And and Or conditions.
5319 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
5320 if (BO->getOpcode() == Instruction::And) {
5322 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5323 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
5324 } else if (BO->getOpcode() == Instruction::Or) {
5326 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5327 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
5331 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
5332 if (!ICI) return false;
5334 // Bail if the ICmp's operands' types are wider than the needed type
5335 // before attempting to call getSCEV on them. This avoids infinite
5336 // recursion, since the analysis of widening casts can require loop
5337 // exit condition information for overflow checking, which would
5339 if (getTypeSizeInBits(LHS->getType()) <
5340 getTypeSizeInBits(ICI->getOperand(0)->getType()))
5343 // Now that we found a conditional branch that dominates the loop, check to
5344 // see if it is the comparison we are looking for.
5345 ICmpInst::Predicate FoundPred;
5347 FoundPred = ICI->getInversePredicate();
5349 FoundPred = ICI->getPredicate();
5351 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
5352 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
5354 // Balance the types. The case where FoundLHS' type is wider than
5355 // LHS' type is checked for above.
5356 if (getTypeSizeInBits(LHS->getType()) >
5357 getTypeSizeInBits(FoundLHS->getType())) {
5358 if (CmpInst::isSigned(Pred)) {
5359 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
5360 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
5362 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
5363 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
5367 // Canonicalize the query to match the way instcombine will have
5368 // canonicalized the comparison.
5369 if (SimplifyICmpOperands(Pred, LHS, RHS))
5371 return CmpInst::isTrueWhenEqual(Pred);
5372 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
5373 if (FoundLHS == FoundRHS)
5374 return CmpInst::isFalseWhenEqual(Pred);
5376 // Check to see if we can make the LHS or RHS match.
5377 if (LHS == FoundRHS || RHS == FoundLHS) {
5378 if (isa<SCEVConstant>(RHS)) {
5379 std::swap(FoundLHS, FoundRHS);
5380 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
5382 std::swap(LHS, RHS);
5383 Pred = ICmpInst::getSwappedPredicate(Pred);
5387 // Check whether the found predicate is the same as the desired predicate.
5388 if (FoundPred == Pred)
5389 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
5391 // Check whether swapping the found predicate makes it the same as the
5392 // desired predicate.
5393 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
5394 if (isa<SCEVConstant>(RHS))
5395 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
5397 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
5398 RHS, LHS, FoundLHS, FoundRHS);
5401 // Check whether the actual condition is beyond sufficient.
5402 if (FoundPred == ICmpInst::ICMP_EQ)
5403 if (ICmpInst::isTrueWhenEqual(Pred))
5404 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
5406 if (Pred == ICmpInst::ICMP_NE)
5407 if (!ICmpInst::isTrueWhenEqual(FoundPred))
5408 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
5411 // Otherwise assume the worst.
5415 /// isImpliedCondOperands - Test whether the condition described by Pred,
5416 /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
5417 /// and FoundRHS is true.
5418 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
5419 const SCEV *LHS, const SCEV *RHS,
5420 const SCEV *FoundLHS,
5421 const SCEV *FoundRHS) {
5422 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
5423 FoundLHS, FoundRHS) ||
5424 // ~x < ~y --> x > y
5425 isImpliedCondOperandsHelper(Pred, LHS, RHS,
5426 getNotSCEV(FoundRHS),
5427 getNotSCEV(FoundLHS));
5430 /// isImpliedCondOperandsHelper - Test whether the condition described by
5431 /// Pred, LHS, and RHS is true whenever the condition described by Pred,
5432 /// FoundLHS, and FoundRHS is true.
5434 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
5435 const SCEV *LHS, const SCEV *RHS,
5436 const SCEV *FoundLHS,
5437 const SCEV *FoundRHS) {
5439 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5440 case ICmpInst::ICMP_EQ:
5441 case ICmpInst::ICMP_NE:
5442 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
5445 case ICmpInst::ICMP_SLT:
5446 case ICmpInst::ICMP_SLE:
5447 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
5448 isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS))
5451 case ICmpInst::ICMP_SGT:
5452 case ICmpInst::ICMP_SGE:
5453 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
5454 isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS))
5457 case ICmpInst::ICMP_ULT:
5458 case ICmpInst::ICMP_ULE:
5459 if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
5460 isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS))
5463 case ICmpInst::ICMP_UGT:
5464 case ICmpInst::ICMP_UGE:
5465 if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
5466 isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS))
5474 /// getBECount - Subtract the end and start values and divide by the step,
5475 /// rounding up, to get the number of times the backedge is executed. Return
5476 /// CouldNotCompute if an intermediate computation overflows.
5477 const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
5481 assert(!isKnownNegative(Step) &&
5482 "This code doesn't handle negative strides yet!");
5484 const Type *Ty = Start->getType();
5485 const SCEV *NegOne = getConstant(Ty, (uint64_t)-1);
5486 const SCEV *Diff = getMinusSCEV(End, Start);
5487 const SCEV *RoundUp = getAddExpr(Step, NegOne);
5489 // Add an adjustment to the difference between End and Start so that
5490 // the division will effectively round up.
5491 const SCEV *Add = getAddExpr(Diff, RoundUp);
5494 // Check Add for unsigned overflow.
5495 // TODO: More sophisticated things could be done here.
5496 const Type *WideTy = IntegerType::get(getContext(),
5497 getTypeSizeInBits(Ty) + 1);
5498 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
5499 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
5500 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
5501 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
5502 return getCouldNotCompute();
5505 return getUDivExpr(Add, Step);
5508 /// HowManyLessThans - Return the number of times a backedge containing the
5509 /// specified less-than comparison will execute. If not computable, return
5510 /// CouldNotCompute.
5511 ScalarEvolution::BackedgeTakenInfo
5512 ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
5513 const Loop *L, bool isSigned) {
5514 // Only handle: "ADDREC < LoopInvariant".
5515 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
5517 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
5518 if (!AddRec || AddRec->getLoop() != L)
5519 return getCouldNotCompute();
5521 // Check to see if we have a flag which makes analysis easy.
5522 bool NoWrap = isSigned ? AddRec->hasNoSignedWrap() :
5523 AddRec->hasNoUnsignedWrap();
5525 if (AddRec->isAffine()) {
5526 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
5527 const SCEV *Step = AddRec->getStepRecurrence(*this);
5530 return getCouldNotCompute();
5531 if (Step->isOne()) {
5532 // With unit stride, the iteration never steps past the limit value.
5533 } else if (isKnownPositive(Step)) {
5534 // Test whether a positive iteration can step past the limit
5535 // value and past the maximum value for its type in a single step.
5536 // Note that it's not sufficient to check NoWrap here, because even
5537 // though the value after a wrap is undefined, it's not undefined
5538 // behavior, so if wrap does occur, the loop could either terminate or
5539 // loop infinitely, but in either case, the loop is guaranteed to
5540 // iterate at least until the iteration where the wrapping occurs.
5541 const SCEV *One = getConstant(Step->getType(), 1);
5543 APInt Max = APInt::getSignedMaxValue(BitWidth);
5544 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
5545 .slt(getSignedRange(RHS).getSignedMax()))
5546 return getCouldNotCompute();
5548 APInt Max = APInt::getMaxValue(BitWidth);
5549 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
5550 .ult(getUnsignedRange(RHS).getUnsignedMax()))
5551 return getCouldNotCompute();
5554 // TODO: Handle negative strides here and below.
5555 return getCouldNotCompute();
5557 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
5558 // m. So, we count the number of iterations in which {n,+,s} < m is true.
5559 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
5560 // treat m-n as signed nor unsigned due to overflow possibility.
5562 // First, we get the value of the LHS in the first iteration: n
5563 const SCEV *Start = AddRec->getOperand(0);
5565 // Determine the minimum constant start value.
5566 const SCEV *MinStart = getConstant(isSigned ?
5567 getSignedRange(Start).getSignedMin() :
5568 getUnsignedRange(Start).getUnsignedMin());
5570 // If we know that the condition is true in order to enter the loop,
5571 // then we know that it will run exactly (m-n)/s times. Otherwise, we
5572 // only know that it will execute (max(m,n)-n)/s times. In both cases,
5573 // the division must round up.
5574 const SCEV *End = RHS;
5575 if (!isLoopEntryGuardedByCond(L,
5576 isSigned ? ICmpInst::ICMP_SLT :
5578 getMinusSCEV(Start, Step), RHS))
5579 End = isSigned ? getSMaxExpr(RHS, Start)
5580 : getUMaxExpr(RHS, Start);
5582 // Determine the maximum constant end value.
5583 const SCEV *MaxEnd = getConstant(isSigned ?
5584 getSignedRange(End).getSignedMax() :
5585 getUnsignedRange(End).getUnsignedMax());
5587 // If MaxEnd is within a step of the maximum integer value in its type,
5588 // adjust it down to the minimum value which would produce the same effect.
5589 // This allows the subsequent ceiling division of (N+(step-1))/step to
5590 // compute the correct value.
5591 const SCEV *StepMinusOne = getMinusSCEV(Step,
5592 getConstant(Step->getType(), 1));
5595 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
5598 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
5601 // Finally, we subtract these two values and divide, rounding up, to get
5602 // the number of times the backedge is executed.
5603 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
5605 // The maximum backedge count is similar, except using the minimum start
5606 // value and the maximum end value.
5607 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step, NoWrap);
5609 return BackedgeTakenInfo(BECount, MaxBECount);
5612 return getCouldNotCompute();
5615 /// getNumIterationsInRange - Return the number of iterations of this loop that
5616 /// produce values in the specified constant range. Another way of looking at
5617 /// this is that it returns the first iteration number where the value is not in
5618 /// the condition, thus computing the exit count. If the iteration count can't
5619 /// be computed, an instance of SCEVCouldNotCompute is returned.
5620 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
5621 ScalarEvolution &SE) const {
5622 if (Range.isFullSet()) // Infinite loop.
5623 return SE.getCouldNotCompute();
5625 // If the start is a non-zero constant, shift the range to simplify things.
5626 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
5627 if (!SC->getValue()->isZero()) {
5628 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
5629 Operands[0] = SE.getConstant(SC->getType(), 0);
5630 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
5631 if (const SCEVAddRecExpr *ShiftedAddRec =
5632 dyn_cast<SCEVAddRecExpr>(Shifted))
5633 return ShiftedAddRec->getNumIterationsInRange(
5634 Range.subtract(SC->getValue()->getValue()), SE);
5635 // This is strange and shouldn't happen.
5636 return SE.getCouldNotCompute();
5639 // The only time we can solve this is when we have all constant indices.
5640 // Otherwise, we cannot determine the overflow conditions.
5641 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5642 if (!isa<SCEVConstant>(getOperand(i)))
5643 return SE.getCouldNotCompute();
5646 // Okay at this point we know that all elements of the chrec are constants and
5647 // that the start element is zero.
5649 // First check to see if the range contains zero. If not, the first
5651 unsigned BitWidth = SE.getTypeSizeInBits(getType());
5652 if (!Range.contains(APInt(BitWidth, 0)))
5653 return SE.getConstant(getType(), 0);
5656 // If this is an affine expression then we have this situation:
5657 // Solve {0,+,A} in Range === Ax in Range
5659 // We know that zero is in the range. If A is positive then we know that
5660 // the upper value of the range must be the first possible exit value.
5661 // If A is negative then the lower of the range is the last possible loop
5662 // value. Also note that we already checked for a full range.
5663 APInt One(BitWidth,1);
5664 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
5665 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
5667 // The exit value should be (End+A)/A.
5668 APInt ExitVal = (End + A).udiv(A);
5669 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
5671 // Evaluate at the exit value. If we really did fall out of the valid
5672 // range, then we computed our trip count, otherwise wrap around or other
5673 // things must have happened.
5674 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
5675 if (Range.contains(Val->getValue()))
5676 return SE.getCouldNotCompute(); // Something strange happened
5678 // Ensure that the previous value is in the range. This is a sanity check.
5679 assert(Range.contains(
5680 EvaluateConstantChrecAtConstant(this,
5681 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
5682 "Linear scev computation is off in a bad way!");
5683 return SE.getConstant(ExitValue);
5684 } else if (isQuadratic()) {
5685 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5686 // quadratic equation to solve it. To do this, we must frame our problem in
5687 // terms of figuring out when zero is crossed, instead of when
5688 // Range.getUpper() is crossed.
5689 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
5690 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
5691 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
5693 // Next, solve the constructed addrec
5694 std::pair<const SCEV *,const SCEV *> Roots =
5695 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
5696 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5697 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
5699 // Pick the smallest positive root value.
5700 if (ConstantInt *CB =
5701 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
5702 R1->getValue(), R2->getValue()))) {
5703 if (CB->getZExtValue() == false)
5704 std::swap(R1, R2); // R1 is the minimum root now.
5706 // Make sure the root is not off by one. The returned iteration should
5707 // not be in the range, but the previous one should be. When solving
5708 // for "X*X < 5", for example, we should not return a root of 2.
5709 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
5712 if (Range.contains(R1Val->getValue())) {
5713 // The next iteration must be out of the range...
5714 ConstantInt *NextVal =
5715 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
5717 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
5718 if (!Range.contains(R1Val->getValue()))
5719 return SE.getConstant(NextVal);
5720 return SE.getCouldNotCompute(); // Something strange happened
5723 // If R1 was not in the range, then it is a good return value. Make
5724 // sure that R1-1 WAS in the range though, just in case.
5725 ConstantInt *NextVal =
5726 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
5727 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
5728 if (Range.contains(R1Val->getValue()))
5730 return SE.getCouldNotCompute(); // Something strange happened
5735 return SE.getCouldNotCompute();
5740 //===----------------------------------------------------------------------===//
5741 // SCEVCallbackVH Class Implementation
5742 //===----------------------------------------------------------------------===//
5744 void ScalarEvolution::SCEVCallbackVH::deleted() {
5745 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
5746 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5747 SE->ConstantEvolutionLoopExitValue.erase(PN);
5748 SE->Scalars.erase(getValPtr());
5749 // this now dangles!
5752 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
5753 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
5755 // Forget all the expressions associated with users of the old value,
5756 // so that future queries will recompute the expressions using the new
5758 Value *Old = getValPtr();
5759 SmallVector<User *, 16> Worklist;
5760 SmallPtrSet<User *, 8> Visited;
5761 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5763 Worklist.push_back(*UI);
5764 while (!Worklist.empty()) {
5765 User *U = Worklist.pop_back_val();
5766 // Deleting the Old value will cause this to dangle. Postpone
5767 // that until everything else is done.
5770 if (!Visited.insert(U))
5772 if (PHINode *PN = dyn_cast<PHINode>(U))
5773 SE->ConstantEvolutionLoopExitValue.erase(PN);
5774 SE->Scalars.erase(U);
5775 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5777 Worklist.push_back(*UI);
5779 // Delete the Old value.
5780 if (PHINode *PN = dyn_cast<PHINode>(Old))
5781 SE->ConstantEvolutionLoopExitValue.erase(PN);
5782 SE->Scalars.erase(Old);
5783 // this now dangles!
5786 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
5787 : CallbackVH(V), SE(se) {}
5789 //===----------------------------------------------------------------------===//
5790 // ScalarEvolution Class Implementation
5791 //===----------------------------------------------------------------------===//
5793 ScalarEvolution::ScalarEvolution()
5794 : FunctionPass(ID), FirstUnknown(0) {
5797 bool ScalarEvolution::runOnFunction(Function &F) {
5799 LI = &getAnalysis<LoopInfo>();
5800 TD = getAnalysisIfAvailable<TargetData>();
5801 DT = &getAnalysis<DominatorTree>();
5805 void ScalarEvolution::releaseMemory() {
5806 // Iterate through all the SCEVUnknown instances and call their
5807 // destructors, so that they release their references to their values.
5808 for (SCEVUnknown *U = FirstUnknown; U; U = U->Next)
5813 BackedgeTakenCounts.clear();
5814 ConstantEvolutionLoopExitValue.clear();
5815 ValuesAtScopes.clear();
5816 UniqueSCEVs.clear();
5817 SCEVAllocator.Reset();
5820 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5821 AU.setPreservesAll();
5822 AU.addRequiredTransitive<LoopInfo>();
5823 AU.addRequiredTransitive<DominatorTree>();
5826 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
5827 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
5830 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
5832 // Print all inner loops first
5833 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5834 PrintLoopInfo(OS, SE, *I);
5837 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5840 SmallVector<BasicBlock *, 8> ExitBlocks;
5841 L->getExitBlocks(ExitBlocks);
5842 if (ExitBlocks.size() != 1)
5843 OS << "<multiple exits> ";
5845 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5846 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
5848 OS << "Unpredictable backedge-taken count. ";
5853 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5856 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5857 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5859 OS << "Unpredictable max backedge-taken count. ";
5865 void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
5866 // ScalarEvolution's implementation of the print method is to print
5867 // out SCEV values of all instructions that are interesting. Doing
5868 // this potentially causes it to create new SCEV objects though,
5869 // which technically conflicts with the const qualifier. This isn't
5870 // observable from outside the class though, so casting away the
5871 // const isn't dangerous.
5872 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
5874 OS << "Classifying expressions for: ";
5875 WriteAsOperand(OS, F, /*PrintType=*/false);
5877 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
5878 if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) {
5881 const SCEV *SV = SE.getSCEV(&*I);
5884 const Loop *L = LI->getLoopFor((*I).getParent());
5886 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
5893 OS << "\t\t" "Exits: ";
5894 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
5895 if (!ExitValue->isLoopInvariant(L)) {
5896 OS << "<<Unknown>>";
5905 OS << "Determining loop execution counts for: ";
5906 WriteAsOperand(OS, F, /*PrintType=*/false);
5908 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5909 PrintLoopInfo(OS, &SE, *I);