1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
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 #include "llvm/Analysis/ScalarEvolution.h"
62 #include "llvm/ADT/Optional.h"
63 #include "llvm/ADT/STLExtras.h"
64 #include "llvm/ADT/SmallPtrSet.h"
65 #include "llvm/ADT/Statistic.h"
66 #include "llvm/Analysis/AssumptionTracker.h"
67 #include "llvm/Analysis/ConstantFolding.h"
68 #include "llvm/Analysis/InstructionSimplify.h"
69 #include "llvm/Analysis/LoopInfo.h"
70 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
71 #include "llvm/Analysis/ValueTracking.h"
72 #include "llvm/IR/ConstantRange.h"
73 #include "llvm/IR/Constants.h"
74 #include "llvm/IR/DataLayout.h"
75 #include "llvm/IR/DerivedTypes.h"
76 #include "llvm/IR/Dominators.h"
77 #include "llvm/IR/GetElementPtrTypeIterator.h"
78 #include "llvm/IR/GlobalAlias.h"
79 #include "llvm/IR/GlobalVariable.h"
80 #include "llvm/IR/InstIterator.h"
81 #include "llvm/IR/Instructions.h"
82 #include "llvm/IR/LLVMContext.h"
83 #include "llvm/IR/Metadata.h"
84 #include "llvm/IR/Operator.h"
85 #include "llvm/Support/CommandLine.h"
86 #include "llvm/Support/Debug.h"
87 #include "llvm/Support/ErrorHandling.h"
88 #include "llvm/Support/MathExtras.h"
89 #include "llvm/Support/raw_ostream.h"
90 #include "llvm/Target/TargetLibraryInfo.h"
94 #define DEBUG_TYPE "scalar-evolution"
96 STATISTIC(NumArrayLenItCounts,
97 "Number of trip counts computed with array length");
98 STATISTIC(NumTripCountsComputed,
99 "Number of loops with predictable loop counts");
100 STATISTIC(NumTripCountsNotComputed,
101 "Number of loops without predictable loop counts");
102 STATISTIC(NumBruteForceTripCountsComputed,
103 "Number of loops with trip counts computed by force");
105 static cl::opt<unsigned>
106 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
107 cl::desc("Maximum number of iterations SCEV will "
108 "symbolically execute a constant "
112 // FIXME: Enable this with XDEBUG when the test suite is clean.
114 VerifySCEV("verify-scev",
115 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
117 INITIALIZE_PASS_BEGIN(ScalarEvolution, "scalar-evolution",
118 "Scalar Evolution Analysis", false, true)
119 INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
120 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
121 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
122 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
123 INITIALIZE_PASS_END(ScalarEvolution, "scalar-evolution",
124 "Scalar Evolution Analysis", false, true)
125 char ScalarEvolution::ID = 0;
127 //===----------------------------------------------------------------------===//
128 // SCEV class definitions
129 //===----------------------------------------------------------------------===//
131 //===----------------------------------------------------------------------===//
132 // Implementation of the SCEV class.
135 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
136 void SCEV::dump() const {
142 void SCEV::print(raw_ostream &OS) const {
143 switch (static_cast<SCEVTypes>(getSCEVType())) {
145 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
148 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
149 const SCEV *Op = Trunc->getOperand();
150 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
151 << *Trunc->getType() << ")";
155 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
156 const SCEV *Op = ZExt->getOperand();
157 OS << "(zext " << *Op->getType() << " " << *Op << " to "
158 << *ZExt->getType() << ")";
162 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
163 const SCEV *Op = SExt->getOperand();
164 OS << "(sext " << *Op->getType() << " " << *Op << " to "
165 << *SExt->getType() << ")";
169 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
170 OS << "{" << *AR->getOperand(0);
171 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
172 OS << ",+," << *AR->getOperand(i);
174 if (AR->getNoWrapFlags(FlagNUW))
176 if (AR->getNoWrapFlags(FlagNSW))
178 if (AR->getNoWrapFlags(FlagNW) &&
179 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
181 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
189 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
190 const char *OpStr = nullptr;
191 switch (NAry->getSCEVType()) {
192 case scAddExpr: OpStr = " + "; break;
193 case scMulExpr: OpStr = " * "; break;
194 case scUMaxExpr: OpStr = " umax "; break;
195 case scSMaxExpr: OpStr = " smax "; break;
198 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
201 if (std::next(I) != E)
205 switch (NAry->getSCEVType()) {
208 if (NAry->getNoWrapFlags(FlagNUW))
210 if (NAry->getNoWrapFlags(FlagNSW))
216 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
217 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
221 const SCEVUnknown *U = cast<SCEVUnknown>(this);
223 if (U->isSizeOf(AllocTy)) {
224 OS << "sizeof(" << *AllocTy << ")";
227 if (U->isAlignOf(AllocTy)) {
228 OS << "alignof(" << *AllocTy << ")";
234 if (U->isOffsetOf(CTy, FieldNo)) {
235 OS << "offsetof(" << *CTy << ", ";
236 FieldNo->printAsOperand(OS, false);
241 // Otherwise just print it normally.
242 U->getValue()->printAsOperand(OS, false);
245 case scCouldNotCompute:
246 OS << "***COULDNOTCOMPUTE***";
249 llvm_unreachable("Unknown SCEV kind!");
252 Type *SCEV::getType() const {
253 switch (static_cast<SCEVTypes>(getSCEVType())) {
255 return cast<SCEVConstant>(this)->getType();
259 return cast<SCEVCastExpr>(this)->getType();
264 return cast<SCEVNAryExpr>(this)->getType();
266 return cast<SCEVAddExpr>(this)->getType();
268 return cast<SCEVUDivExpr>(this)->getType();
270 return cast<SCEVUnknown>(this)->getType();
271 case scCouldNotCompute:
272 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
274 llvm_unreachable("Unknown SCEV kind!");
277 bool SCEV::isZero() const {
278 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
279 return SC->getValue()->isZero();
283 bool SCEV::isOne() const {
284 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
285 return SC->getValue()->isOne();
289 bool SCEV::isAllOnesValue() const {
290 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
291 return SC->getValue()->isAllOnesValue();
295 /// isNonConstantNegative - Return true if the specified scev is negated, but
297 bool SCEV::isNonConstantNegative() const {
298 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
299 if (!Mul) return false;
301 // If there is a constant factor, it will be first.
302 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
303 if (!SC) return false;
305 // Return true if the value is negative, this matches things like (-42 * V).
306 return SC->getValue()->getValue().isNegative();
309 SCEVCouldNotCompute::SCEVCouldNotCompute() :
310 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
312 bool SCEVCouldNotCompute::classof(const SCEV *S) {
313 return S->getSCEVType() == scCouldNotCompute;
316 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
318 ID.AddInteger(scConstant);
321 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
322 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
323 UniqueSCEVs.InsertNode(S, IP);
327 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
328 return getConstant(ConstantInt::get(getContext(), Val));
332 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
333 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
334 return getConstant(ConstantInt::get(ITy, V, isSigned));
337 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
338 unsigned SCEVTy, const SCEV *op, Type *ty)
339 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
341 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
342 const SCEV *op, Type *ty)
343 : SCEVCastExpr(ID, scTruncate, op, ty) {
344 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
345 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
346 "Cannot truncate non-integer value!");
349 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
350 const SCEV *op, Type *ty)
351 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
352 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
353 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
354 "Cannot zero extend non-integer value!");
357 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
358 const SCEV *op, Type *ty)
359 : SCEVCastExpr(ID, scSignExtend, op, ty) {
360 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
361 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
362 "Cannot sign extend non-integer value!");
365 void SCEVUnknown::deleted() {
366 // Clear this SCEVUnknown from various maps.
367 SE->forgetMemoizedResults(this);
369 // Remove this SCEVUnknown from the uniquing map.
370 SE->UniqueSCEVs.RemoveNode(this);
372 // Release the value.
376 void SCEVUnknown::allUsesReplacedWith(Value *New) {
377 // Clear this SCEVUnknown from various maps.
378 SE->forgetMemoizedResults(this);
380 // Remove this SCEVUnknown from the uniquing map.
381 SE->UniqueSCEVs.RemoveNode(this);
383 // Update this SCEVUnknown to point to the new value. This is needed
384 // because there may still be outstanding SCEVs which still point to
389 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
390 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
391 if (VCE->getOpcode() == Instruction::PtrToInt)
392 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
393 if (CE->getOpcode() == Instruction::GetElementPtr &&
394 CE->getOperand(0)->isNullValue() &&
395 CE->getNumOperands() == 2)
396 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
398 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
406 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
407 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
408 if (VCE->getOpcode() == Instruction::PtrToInt)
409 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
410 if (CE->getOpcode() == Instruction::GetElementPtr &&
411 CE->getOperand(0)->isNullValue()) {
413 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
414 if (StructType *STy = dyn_cast<StructType>(Ty))
415 if (!STy->isPacked() &&
416 CE->getNumOperands() == 3 &&
417 CE->getOperand(1)->isNullValue()) {
418 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
420 STy->getNumElements() == 2 &&
421 STy->getElementType(0)->isIntegerTy(1)) {
422 AllocTy = STy->getElementType(1);
431 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
432 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
433 if (VCE->getOpcode() == Instruction::PtrToInt)
434 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
435 if (CE->getOpcode() == Instruction::GetElementPtr &&
436 CE->getNumOperands() == 3 &&
437 CE->getOperand(0)->isNullValue() &&
438 CE->getOperand(1)->isNullValue()) {
440 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
441 // Ignore vector types here so that ScalarEvolutionExpander doesn't
442 // emit getelementptrs that index into vectors.
443 if (Ty->isStructTy() || Ty->isArrayTy()) {
445 FieldNo = CE->getOperand(2);
453 //===----------------------------------------------------------------------===//
455 //===----------------------------------------------------------------------===//
458 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
459 /// than the complexity of the RHS. This comparator is used to canonicalize
461 class SCEVComplexityCompare {
462 const LoopInfo *const LI;
464 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
466 // Return true or false if LHS is less than, or at least RHS, respectively.
467 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
468 return compare(LHS, RHS) < 0;
471 // Return negative, zero, or positive, if LHS is less than, equal to, or
472 // greater than RHS, respectively. A three-way result allows recursive
473 // comparisons to be more efficient.
474 int compare(const SCEV *LHS, const SCEV *RHS) const {
475 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
479 // Primarily, sort the SCEVs by their getSCEVType().
480 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
482 return (int)LType - (int)RType;
484 // Aside from the getSCEVType() ordering, the particular ordering
485 // isn't very important except that it's beneficial to be consistent,
486 // so that (a + b) and (b + a) don't end up as different expressions.
487 switch (static_cast<SCEVTypes>(LType)) {
489 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
490 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
492 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
493 // not as complete as it could be.
494 const Value *LV = LU->getValue(), *RV = RU->getValue();
496 // Order pointer values after integer values. This helps SCEVExpander
498 bool LIsPointer = LV->getType()->isPointerTy(),
499 RIsPointer = RV->getType()->isPointerTy();
500 if (LIsPointer != RIsPointer)
501 return (int)LIsPointer - (int)RIsPointer;
503 // Compare getValueID values.
504 unsigned LID = LV->getValueID(),
505 RID = RV->getValueID();
507 return (int)LID - (int)RID;
509 // Sort arguments by their position.
510 if (const Argument *LA = dyn_cast<Argument>(LV)) {
511 const Argument *RA = cast<Argument>(RV);
512 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
513 return (int)LArgNo - (int)RArgNo;
516 // For instructions, compare their loop depth, and their operand
517 // count. This is pretty loose.
518 if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
519 const Instruction *RInst = cast<Instruction>(RV);
521 // Compare loop depths.
522 const BasicBlock *LParent = LInst->getParent(),
523 *RParent = RInst->getParent();
524 if (LParent != RParent) {
525 unsigned LDepth = LI->getLoopDepth(LParent),
526 RDepth = LI->getLoopDepth(RParent);
527 if (LDepth != RDepth)
528 return (int)LDepth - (int)RDepth;
531 // Compare the number of operands.
532 unsigned LNumOps = LInst->getNumOperands(),
533 RNumOps = RInst->getNumOperands();
534 return (int)LNumOps - (int)RNumOps;
541 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
542 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
544 // Compare constant values.
545 const APInt &LA = LC->getValue()->getValue();
546 const APInt &RA = RC->getValue()->getValue();
547 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
548 if (LBitWidth != RBitWidth)
549 return (int)LBitWidth - (int)RBitWidth;
550 return LA.ult(RA) ? -1 : 1;
554 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
555 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
557 // Compare addrec loop depths.
558 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
559 if (LLoop != RLoop) {
560 unsigned LDepth = LLoop->getLoopDepth(),
561 RDepth = RLoop->getLoopDepth();
562 if (LDepth != RDepth)
563 return (int)LDepth - (int)RDepth;
566 // Addrec complexity grows with operand count.
567 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
568 if (LNumOps != RNumOps)
569 return (int)LNumOps - (int)RNumOps;
571 // Lexicographically compare.
572 for (unsigned i = 0; i != LNumOps; ++i) {
573 long X = compare(LA->getOperand(i), RA->getOperand(i));
585 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
586 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
588 // Lexicographically compare n-ary expressions.
589 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
590 if (LNumOps != RNumOps)
591 return (int)LNumOps - (int)RNumOps;
593 for (unsigned i = 0; i != LNumOps; ++i) {
596 long X = compare(LC->getOperand(i), RC->getOperand(i));
600 return (int)LNumOps - (int)RNumOps;
604 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
605 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
607 // Lexicographically compare udiv expressions.
608 long X = compare(LC->getLHS(), RC->getLHS());
611 return compare(LC->getRHS(), RC->getRHS());
617 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
618 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
620 // Compare cast expressions by operand.
621 return compare(LC->getOperand(), RC->getOperand());
624 case scCouldNotCompute:
625 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
627 llvm_unreachable("Unknown SCEV kind!");
632 /// GroupByComplexity - Given a list of SCEV objects, order them by their
633 /// complexity, and group objects of the same complexity together by value.
634 /// When this routine is finished, we know that any duplicates in the vector are
635 /// consecutive and that complexity is monotonically increasing.
637 /// Note that we go take special precautions to ensure that we get deterministic
638 /// results from this routine. In other words, we don't want the results of
639 /// this to depend on where the addresses of various SCEV objects happened to
642 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
644 if (Ops.size() < 2) return; // Noop
645 if (Ops.size() == 2) {
646 // This is the common case, which also happens to be trivially simple.
648 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
649 if (SCEVComplexityCompare(LI)(RHS, LHS))
654 // Do the rough sort by complexity.
655 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
657 // Now that we are sorted by complexity, group elements of the same
658 // complexity. Note that this is, at worst, N^2, but the vector is likely to
659 // be extremely short in practice. Note that we take this approach because we
660 // do not want to depend on the addresses of the objects we are grouping.
661 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
662 const SCEV *S = Ops[i];
663 unsigned Complexity = S->getSCEVType();
665 // If there are any objects of the same complexity and same value as this
667 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
668 if (Ops[j] == S) { // Found a duplicate.
669 // Move it to immediately after i'th element.
670 std::swap(Ops[i+1], Ops[j]);
671 ++i; // no need to rescan it.
672 if (i == e-2) return; // Done!
678 static const APInt srem(const SCEVConstant *C1, const SCEVConstant *C2) {
679 APInt A = C1->getValue()->getValue();
680 APInt B = C2->getValue()->getValue();
681 uint32_t ABW = A.getBitWidth();
682 uint32_t BBW = B.getBitWidth();
689 return APIntOps::srem(A, B);
692 static const APInt sdiv(const SCEVConstant *C1, const SCEVConstant *C2) {
693 APInt A = C1->getValue()->getValue();
694 APInt B = C2->getValue()->getValue();
695 uint32_t ABW = A.getBitWidth();
696 uint32_t BBW = B.getBitWidth();
703 return APIntOps::sdiv(A, B);
706 static const APInt urem(const SCEVConstant *C1, const SCEVConstant *C2) {
707 APInt A = C1->getValue()->getValue();
708 APInt B = C2->getValue()->getValue();
709 uint32_t ABW = A.getBitWidth();
710 uint32_t BBW = B.getBitWidth();
717 return APIntOps::urem(A, B);
720 static const APInt udiv(const SCEVConstant *C1, const SCEVConstant *C2) {
721 APInt A = C1->getValue()->getValue();
722 APInt B = C2->getValue()->getValue();
723 uint32_t ABW = A.getBitWidth();
724 uint32_t BBW = B.getBitWidth();
731 return APIntOps::udiv(A, B);
735 struct FindSCEVSize {
737 FindSCEVSize() : Size(0) {}
739 bool follow(const SCEV *S) {
741 // Keep looking at all operands of S.
744 bool isDone() const {
750 // Returns the size of the SCEV S.
751 static inline int sizeOfSCEV(const SCEV *S) {
753 SCEVTraversal<FindSCEVSize> ST(F);
760 template <typename Derived>
761 struct SCEVDivision : public SCEVVisitor<Derived, void> {
763 // Computes the Quotient and Remainder of the division of Numerator by
765 static void divide(ScalarEvolution &SE, const SCEV *Numerator,
766 const SCEV *Denominator, const SCEV **Quotient,
767 const SCEV **Remainder) {
768 assert(Numerator && Denominator && "Uninitialized SCEV");
770 Derived D(SE, Numerator, Denominator);
772 // Check for the trivial case here to avoid having to check for it in the
774 if (Numerator == Denominator) {
780 if (Numerator->isZero()) {
786 // Split the Denominator when it is a product.
787 if (const SCEVMulExpr *T = dyn_cast<const SCEVMulExpr>(Denominator)) {
789 *Quotient = Numerator;
790 for (const SCEV *Op : T->operands()) {
791 divide(SE, *Quotient, Op, &Q, &R);
794 // Bail out when the Numerator is not divisible by one of the terms of
798 *Remainder = Numerator;
807 *Quotient = D.Quotient;
808 *Remainder = D.Remainder;
811 // Except in the trivial case described above, we do not know how to divide
812 // Expr by Denominator for the following functions with empty implementation.
813 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
814 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
815 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
816 void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
817 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
818 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
819 void visitUnknown(const SCEVUnknown *Numerator) {}
820 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
822 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
823 const SCEV *StartQ, *StartR, *StepQ, *StepR;
824 assert(Numerator->isAffine() && "Numerator should be affine");
825 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
826 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
827 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
828 Numerator->getNoWrapFlags());
829 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
830 Numerator->getNoWrapFlags());
833 void visitAddExpr(const SCEVAddExpr *Numerator) {
834 SmallVector<const SCEV *, 2> Qs, Rs;
835 Type *Ty = Denominator->getType();
837 for (const SCEV *Op : Numerator->operands()) {
839 divide(SE, Op, Denominator, &Q, &R);
841 // Bail out if types do not match.
842 if (Ty != Q->getType() || Ty != R->getType()) {
844 Remainder = Numerator;
852 if (Qs.size() == 1) {
858 Quotient = SE.getAddExpr(Qs);
859 Remainder = SE.getAddExpr(Rs);
862 void visitMulExpr(const SCEVMulExpr *Numerator) {
863 SmallVector<const SCEV *, 2> Qs;
864 Type *Ty = Denominator->getType();
866 bool FoundDenominatorTerm = false;
867 for (const SCEV *Op : Numerator->operands()) {
868 // Bail out if types do not match.
869 if (Ty != Op->getType()) {
871 Remainder = Numerator;
875 if (FoundDenominatorTerm) {
880 // Check whether Denominator divides one of the product operands.
882 divide(SE, Op, Denominator, &Q, &R);
888 // Bail out if types do not match.
889 if (Ty != Q->getType()) {
891 Remainder = Numerator;
895 FoundDenominatorTerm = true;
899 if (FoundDenominatorTerm) {
904 Quotient = SE.getMulExpr(Qs);
908 if (!isa<SCEVUnknown>(Denominator)) {
910 Remainder = Numerator;
914 // The Remainder is obtained by replacing Denominator by 0 in Numerator.
915 ValueToValueMap RewriteMap;
916 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
917 cast<SCEVConstant>(Zero)->getValue();
918 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
920 if (Remainder->isZero()) {
921 // The Quotient is obtained by replacing Denominator by 1 in Numerator.
922 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
923 cast<SCEVConstant>(One)->getValue();
925 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
929 // Quotient is (Numerator - Remainder) divided by Denominator.
931 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
932 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) {
933 // This SCEV does not seem to simplify: fail the division here.
935 Remainder = Numerator;
938 divide(SE, Diff, Denominator, &Q, &R);
940 "(Numerator - Remainder) should evenly divide Denominator");
945 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
946 const SCEV *Denominator)
947 : SE(S), Denominator(Denominator) {
948 Zero = SE.getConstant(Denominator->getType(), 0);
949 One = SE.getConstant(Denominator->getType(), 1);
951 // By default, we don't know how to divide Expr by Denominator.
952 // Providing the default here simplifies the rest of the code.
954 Remainder = Numerator;
958 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
960 friend struct SCEVSDivision;
961 friend struct SCEVUDivision;
964 struct SCEVSDivision : public SCEVDivision<SCEVSDivision> {
965 SCEVSDivision(ScalarEvolution &S, const SCEV *Numerator,
966 const SCEV *Denominator)
967 : SCEVDivision(S, Numerator, Denominator) {}
969 void visitConstant(const SCEVConstant *Numerator) {
970 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
971 Quotient = SE.getConstant(sdiv(Numerator, D));
972 Remainder = SE.getConstant(srem(Numerator, D));
978 struct SCEVUDivision : public SCEVDivision<SCEVUDivision> {
979 SCEVUDivision(ScalarEvolution &S, const SCEV *Numerator,
980 const SCEV *Denominator)
981 : SCEVDivision(S, Numerator, Denominator) {}
983 void visitConstant(const SCEVConstant *Numerator) {
984 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
985 Quotient = SE.getConstant(udiv(Numerator, D));
986 Remainder = SE.getConstant(urem(Numerator, D));
994 //===----------------------------------------------------------------------===//
995 // Simple SCEV method implementations
996 //===----------------------------------------------------------------------===//
998 /// BinomialCoefficient - Compute BC(It, K). The result has width W.
1000 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
1001 ScalarEvolution &SE,
1003 // Handle the simplest case efficiently.
1005 return SE.getTruncateOrZeroExtend(It, ResultTy);
1007 // We are using the following formula for BC(It, K):
1009 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1011 // Suppose, W is the bitwidth of the return value. We must be prepared for
1012 // overflow. Hence, we must assure that the result of our computation is
1013 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
1014 // safe in modular arithmetic.
1016 // However, this code doesn't use exactly that formula; the formula it uses
1017 // is something like the following, where T is the number of factors of 2 in
1018 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1021 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
1023 // This formula is trivially equivalent to the previous formula. However,
1024 // this formula can be implemented much more efficiently. The trick is that
1025 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1026 // arithmetic. To do exact division in modular arithmetic, all we have
1027 // to do is multiply by the inverse. Therefore, this step can be done at
1030 // The next issue is how to safely do the division by 2^T. The way this
1031 // is done is by doing the multiplication step at a width of at least W + T
1032 // bits. This way, the bottom W+T bits of the product are accurate. Then,
1033 // when we perform the division by 2^T (which is equivalent to a right shift
1034 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
1035 // truncated out after the division by 2^T.
1037 // In comparison to just directly using the first formula, this technique
1038 // is much more efficient; using the first formula requires W * K bits,
1039 // but this formula less than W + K bits. Also, the first formula requires
1040 // a division step, whereas this formula only requires multiplies and shifts.
1042 // It doesn't matter whether the subtraction step is done in the calculation
1043 // width or the input iteration count's width; if the subtraction overflows,
1044 // the result must be zero anyway. We prefer here to do it in the width of
1045 // the induction variable because it helps a lot for certain cases; CodeGen
1046 // isn't smart enough to ignore the overflow, which leads to much less
1047 // efficient code if the width of the subtraction is wider than the native
1050 // (It's possible to not widen at all by pulling out factors of 2 before
1051 // the multiplication; for example, K=2 can be calculated as
1052 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1053 // extra arithmetic, so it's not an obvious win, and it gets
1054 // much more complicated for K > 3.)
1056 // Protection from insane SCEVs; this bound is conservative,
1057 // but it probably doesn't matter.
1059 return SE.getCouldNotCompute();
1061 unsigned W = SE.getTypeSizeInBits(ResultTy);
1063 // Calculate K! / 2^T and T; we divide out the factors of two before
1064 // multiplying for calculating K! / 2^T to avoid overflow.
1065 // Other overflow doesn't matter because we only care about the bottom
1066 // W bits of the result.
1067 APInt OddFactorial(W, 1);
1069 for (unsigned i = 3; i <= K; ++i) {
1071 unsigned TwoFactors = Mult.countTrailingZeros();
1073 Mult = Mult.lshr(TwoFactors);
1074 OddFactorial *= Mult;
1077 // We need at least W + T bits for the multiplication step
1078 unsigned CalculationBits = W + T;
1080 // Calculate 2^T, at width T+W.
1081 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1083 // Calculate the multiplicative inverse of K! / 2^T;
1084 // this multiplication factor will perform the exact division by
1086 APInt Mod = APInt::getSignedMinValue(W+1);
1087 APInt MultiplyFactor = OddFactorial.zext(W+1);
1088 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1089 MultiplyFactor = MultiplyFactor.trunc(W);
1091 // Calculate the product, at width T+W
1092 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1094 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1095 for (unsigned i = 1; i != K; ++i) {
1096 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1097 Dividend = SE.getMulExpr(Dividend,
1098 SE.getTruncateOrZeroExtend(S, CalculationTy));
1102 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1104 // Truncate the result, and divide by K! / 2^T.
1106 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1107 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1110 /// evaluateAtIteration - Return the value of this chain of recurrences at
1111 /// the specified iteration number. We can evaluate this recurrence by
1112 /// multiplying each element in the chain by the binomial coefficient
1113 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
1115 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1117 /// where BC(It, k) stands for binomial coefficient.
1119 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1120 ScalarEvolution &SE) const {
1121 const SCEV *Result = getStart();
1122 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1123 // The computation is correct in the face of overflow provided that the
1124 // multiplication is performed _after_ the evaluation of the binomial
1126 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1127 if (isa<SCEVCouldNotCompute>(Coeff))
1130 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1135 //===----------------------------------------------------------------------===//
1136 // SCEV Expression folder implementations
1137 //===----------------------------------------------------------------------===//
1139 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
1141 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1142 "This is not a truncating conversion!");
1143 assert(isSCEVable(Ty) &&
1144 "This is not a conversion to a SCEVable type!");
1145 Ty = getEffectiveSCEVType(Ty);
1147 FoldingSetNodeID ID;
1148 ID.AddInteger(scTruncate);
1152 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1154 // Fold if the operand is constant.
1155 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1157 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1159 // trunc(trunc(x)) --> trunc(x)
1160 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1161 return getTruncateExpr(ST->getOperand(), Ty);
1163 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1164 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1165 return getTruncateOrSignExtend(SS->getOperand(), Ty);
1167 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1168 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1169 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1171 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
1172 // eliminate all the truncates.
1173 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1174 SmallVector<const SCEV *, 4> Operands;
1175 bool hasTrunc = false;
1176 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1177 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
1178 hasTrunc = isa<SCEVTruncateExpr>(S);
1179 Operands.push_back(S);
1182 return getAddExpr(Operands);
1183 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
1186 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
1187 // eliminate all the truncates.
1188 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1189 SmallVector<const SCEV *, 4> Operands;
1190 bool hasTrunc = false;
1191 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1192 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
1193 hasTrunc = isa<SCEVTruncateExpr>(S);
1194 Operands.push_back(S);
1197 return getMulExpr(Operands);
1198 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
1201 // If the input value is a chrec scev, truncate the chrec's operands.
1202 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1203 SmallVector<const SCEV *, 4> Operands;
1204 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1205 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
1206 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1209 // The cast wasn't folded; create an explicit cast node. We can reuse
1210 // the existing insert position since if we get here, we won't have
1211 // made any changes which would invalidate it.
1212 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1214 UniqueSCEVs.InsertNode(S, IP);
1218 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
1220 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1221 "This is not an extending conversion!");
1222 assert(isSCEVable(Ty) &&
1223 "This is not a conversion to a SCEVable type!");
1224 Ty = getEffectiveSCEVType(Ty);
1226 // Fold if the operand is constant.
1227 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1229 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1231 // zext(zext(x)) --> zext(x)
1232 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1233 return getZeroExtendExpr(SZ->getOperand(), Ty);
1235 // Before doing any expensive analysis, check to see if we've already
1236 // computed a SCEV for this Op and Ty.
1237 FoldingSetNodeID ID;
1238 ID.AddInteger(scZeroExtend);
1242 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1244 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1245 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1246 // It's possible the bits taken off by the truncate were all zero bits. If
1247 // so, we should be able to simplify this further.
1248 const SCEV *X = ST->getOperand();
1249 ConstantRange CR = getUnsignedRange(X);
1250 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1251 unsigned NewBits = getTypeSizeInBits(Ty);
1252 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1253 CR.zextOrTrunc(NewBits)))
1254 return getTruncateOrZeroExtend(X, Ty);
1257 // If the input value is a chrec scev, and we can prove that the value
1258 // did not overflow the old, smaller, value, we can zero extend all of the
1259 // operands (often constants). This allows analysis of something like
1260 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1261 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1262 if (AR->isAffine()) {
1263 const SCEV *Start = AR->getStart();
1264 const SCEV *Step = AR->getStepRecurrence(*this);
1265 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1266 const Loop *L = AR->getLoop();
1268 // If we have special knowledge that this addrec won't overflow,
1269 // we don't need to do any further analysis.
1270 if (AR->getNoWrapFlags(SCEV::FlagNUW))
1271 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1272 getZeroExtendExpr(Step, Ty),
1273 L, AR->getNoWrapFlags());
1275 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1276 // Note that this serves two purposes: It filters out loops that are
1277 // simply not analyzable, and it covers the case where this code is
1278 // being called from within backedge-taken count analysis, such that
1279 // attempting to ask for the backedge-taken count would likely result
1280 // in infinite recursion. In the later case, the analysis code will
1281 // cope with a conservative value, and it will take care to purge
1282 // that value once it has finished.
1283 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1284 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1285 // Manually compute the final value for AR, checking for
1288 // Check whether the backedge-taken count can be losslessly casted to
1289 // the addrec's type. The count is always unsigned.
1290 const SCEV *CastedMaxBECount =
1291 getTruncateOrZeroExtend(MaxBECount, Start->getType());
1292 const SCEV *RecastedMaxBECount =
1293 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1294 if (MaxBECount == RecastedMaxBECount) {
1295 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1296 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1297 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
1298 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy);
1299 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy);
1300 const SCEV *WideMaxBECount =
1301 getZeroExtendExpr(CastedMaxBECount, WideTy);
1302 const SCEV *OperandExtendedAdd =
1303 getAddExpr(WideStart,
1304 getMulExpr(WideMaxBECount,
1305 getZeroExtendExpr(Step, WideTy)));
1306 if (ZAdd == OperandExtendedAdd) {
1307 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1308 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1309 // Return the expression with the addrec on the outside.
1310 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1311 getZeroExtendExpr(Step, Ty),
1312 L, AR->getNoWrapFlags());
1314 // Similar to above, only this time treat the step value as signed.
1315 // This covers loops that count down.
1316 OperandExtendedAdd =
1317 getAddExpr(WideStart,
1318 getMulExpr(WideMaxBECount,
1319 getSignExtendExpr(Step, WideTy)));
1320 if (ZAdd == OperandExtendedAdd) {
1321 // Cache knowledge of AR NW, which is propagated to this AddRec.
1322 // Negative step causes unsigned wrap, but it still can't self-wrap.
1323 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1324 // Return the expression with the addrec on the outside.
1325 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1326 getSignExtendExpr(Step, Ty),
1327 L, AR->getNoWrapFlags());
1331 // If the backedge is guarded by a comparison with the pre-inc value
1332 // the addrec is safe. Also, if the entry is guarded by a comparison
1333 // with the start value and the backedge is guarded by a comparison
1334 // with the post-inc value, the addrec is safe.
1335 if (isKnownPositive(Step)) {
1336 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1337 getUnsignedRange(Step).getUnsignedMax());
1338 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1339 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
1340 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
1341 AR->getPostIncExpr(*this), N))) {
1342 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1343 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1344 // Return the expression with the addrec on the outside.
1345 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1346 getZeroExtendExpr(Step, Ty),
1347 L, AR->getNoWrapFlags());
1349 } else if (isKnownNegative(Step)) {
1350 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1351 getSignedRange(Step).getSignedMin());
1352 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1353 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
1354 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1355 AR->getPostIncExpr(*this), N))) {
1356 // Cache knowledge of AR NW, which is propagated to this AddRec.
1357 // Negative step causes unsigned wrap, but it still can't self-wrap.
1358 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1359 // Return the expression with the addrec on the outside.
1360 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1361 getSignExtendExpr(Step, Ty),
1362 L, AR->getNoWrapFlags());
1368 // The cast wasn't folded; create an explicit cast node.
1369 // Recompute the insert position, as it may have been invalidated.
1370 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1371 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1373 UniqueSCEVs.InsertNode(S, IP);
1377 // Get the limit of a recurrence such that incrementing by Step cannot cause
1378 // signed overflow as long as the value of the recurrence within the loop does
1379 // not exceed this limit before incrementing.
1380 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1381 ICmpInst::Predicate *Pred,
1382 ScalarEvolution *SE) {
1383 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1384 if (SE->isKnownPositive(Step)) {
1385 *Pred = ICmpInst::ICMP_SLT;
1386 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1387 SE->getSignedRange(Step).getSignedMax());
1389 if (SE->isKnownNegative(Step)) {
1390 *Pred = ICmpInst::ICMP_SGT;
1391 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1392 SE->getSignedRange(Step).getSignedMin());
1397 // The recurrence AR has been shown to have no signed wrap. Typically, if we can
1398 // prove NSW for AR, then we can just as easily prove NSW for its preincrement
1399 // or postincrement sibling. This allows normalizing a sign extended AddRec as
1400 // such: {sext(Step + Start),+,Step} => {(Step + sext(Start),+,Step} As a
1401 // result, the expression "Step + sext(PreIncAR)" is congruent with
1402 // "sext(PostIncAR)"
1403 static const SCEV *getPreStartForSignExtend(const SCEVAddRecExpr *AR,
1405 ScalarEvolution *SE) {
1406 const Loop *L = AR->getLoop();
1407 const SCEV *Start = AR->getStart();
1408 const SCEV *Step = AR->getStepRecurrence(*SE);
1410 // Check for a simple looking step prior to loop entry.
1411 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1415 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1416 // subtraction is expensive. For this purpose, perform a quick and dirty
1417 // difference, by checking for Step in the operand list.
1418 SmallVector<const SCEV *, 4> DiffOps;
1419 for (const SCEV *Op : SA->operands())
1421 DiffOps.push_back(Op);
1423 if (DiffOps.size() == SA->getNumOperands())
1426 // This is a postinc AR. Check for overflow on the preinc recurrence using the
1427 // same three conditions that getSignExtendedExpr checks.
1429 // 1. NSW flags on the step increment.
1430 const SCEV *PreStart = SE->getAddExpr(DiffOps, SA->getNoWrapFlags());
1431 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1432 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1434 if (PreAR && PreAR->getNoWrapFlags(SCEV::FlagNSW))
1437 // 2. Direct overflow check on the step operation's expression.
1438 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1439 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1440 const SCEV *OperandExtendedStart =
1441 SE->getAddExpr(SE->getSignExtendExpr(PreStart, WideTy),
1442 SE->getSignExtendExpr(Step, WideTy));
1443 if (SE->getSignExtendExpr(Start, WideTy) == OperandExtendedStart) {
1444 // Cache knowledge of PreAR NSW.
1446 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(SCEV::FlagNSW);
1447 // FIXME: this optimization needs a unit test
1448 DEBUG(dbgs() << "SCEV: untested prestart overflow check\n");
1452 // 3. Loop precondition.
1453 ICmpInst::Predicate Pred;
1454 const SCEV *OverflowLimit = getOverflowLimitForStep(Step, &Pred, SE);
1456 if (OverflowLimit &&
1457 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) {
1463 // Get the normalized sign-extended expression for this AddRec's Start.
1464 static const SCEV *getSignExtendAddRecStart(const SCEVAddRecExpr *AR,
1466 ScalarEvolution *SE) {
1467 const SCEV *PreStart = getPreStartForSignExtend(AR, Ty, SE);
1469 return SE->getSignExtendExpr(AR->getStart(), Ty);
1471 return SE->getAddExpr(SE->getSignExtendExpr(AR->getStepRecurrence(*SE), Ty),
1472 SE->getSignExtendExpr(PreStart, Ty));
1475 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
1477 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1478 "This is not an extending conversion!");
1479 assert(isSCEVable(Ty) &&
1480 "This is not a conversion to a SCEVable type!");
1481 Ty = getEffectiveSCEVType(Ty);
1483 // Fold if the operand is constant.
1484 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1486 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1488 // sext(sext(x)) --> sext(x)
1489 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1490 return getSignExtendExpr(SS->getOperand(), Ty);
1492 // sext(zext(x)) --> zext(x)
1493 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1494 return getZeroExtendExpr(SZ->getOperand(), Ty);
1496 // Before doing any expensive analysis, check to see if we've already
1497 // computed a SCEV for this Op and Ty.
1498 FoldingSetNodeID ID;
1499 ID.AddInteger(scSignExtend);
1503 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1505 // If the input value is provably positive, build a zext instead.
1506 if (isKnownNonNegative(Op))
1507 return getZeroExtendExpr(Op, Ty);
1509 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1510 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1511 // It's possible the bits taken off by the truncate were all sign bits. If
1512 // so, we should be able to simplify this further.
1513 const SCEV *X = ST->getOperand();
1514 ConstantRange CR = getSignedRange(X);
1515 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1516 unsigned NewBits = getTypeSizeInBits(Ty);
1517 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1518 CR.sextOrTrunc(NewBits)))
1519 return getTruncateOrSignExtend(X, Ty);
1522 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
1523 if (auto SA = dyn_cast<SCEVAddExpr>(Op)) {
1524 if (SA->getNumOperands() == 2) {
1525 auto SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1526 auto SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
1528 if (auto SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
1529 const APInt &C1 = SC1->getValue()->getValue();
1530 const APInt &C2 = SC2->getValue()->getValue();
1531 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
1532 C2.ugt(C1) && C2.isPowerOf2())
1533 return getAddExpr(getSignExtendExpr(SC1, Ty),
1534 getSignExtendExpr(SMul, Ty));
1539 // If the input value is a chrec scev, and we can prove that the value
1540 // did not overflow the old, smaller, value, we can sign extend all of the
1541 // operands (often constants). This allows analysis of something like
1542 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1543 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1544 if (AR->isAffine()) {
1545 const SCEV *Start = AR->getStart();
1546 const SCEV *Step = AR->getStepRecurrence(*this);
1547 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1548 const Loop *L = AR->getLoop();
1550 // If we have special knowledge that this addrec won't overflow,
1551 // we don't need to do any further analysis.
1552 if (AR->getNoWrapFlags(SCEV::FlagNSW))
1553 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
1554 getSignExtendExpr(Step, Ty),
1557 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1558 // Note that this serves two purposes: It filters out loops that are
1559 // simply not analyzable, and it covers the case where this code is
1560 // being called from within backedge-taken count analysis, such that
1561 // attempting to ask for the backedge-taken count would likely result
1562 // in infinite recursion. In the later case, the analysis code will
1563 // cope with a conservative value, and it will take care to purge
1564 // that value once it has finished.
1565 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1566 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1567 // Manually compute the final value for AR, checking for
1570 // Check whether the backedge-taken count can be losslessly casted to
1571 // the addrec's type. The count is always unsigned.
1572 const SCEV *CastedMaxBECount =
1573 getTruncateOrZeroExtend(MaxBECount, Start->getType());
1574 const SCEV *RecastedMaxBECount =
1575 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1576 if (MaxBECount == RecastedMaxBECount) {
1577 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1578 // Check whether Start+Step*MaxBECount has no signed overflow.
1579 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
1580 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy);
1581 const SCEV *WideStart = getSignExtendExpr(Start, WideTy);
1582 const SCEV *WideMaxBECount =
1583 getZeroExtendExpr(CastedMaxBECount, WideTy);
1584 const SCEV *OperandExtendedAdd =
1585 getAddExpr(WideStart,
1586 getMulExpr(WideMaxBECount,
1587 getSignExtendExpr(Step, WideTy)));
1588 if (SAdd == OperandExtendedAdd) {
1589 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1590 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1591 // Return the expression with the addrec on the outside.
1592 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
1593 getSignExtendExpr(Step, Ty),
1594 L, AR->getNoWrapFlags());
1596 // Similar to above, only this time treat the step value as unsigned.
1597 // This covers loops that count up with an unsigned step.
1598 OperandExtendedAdd =
1599 getAddExpr(WideStart,
1600 getMulExpr(WideMaxBECount,
1601 getZeroExtendExpr(Step, WideTy)));
1602 if (SAdd == OperandExtendedAdd) {
1603 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1604 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1605 // Return the expression with the addrec on the outside.
1606 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
1607 getZeroExtendExpr(Step, Ty),
1608 L, AR->getNoWrapFlags());
1612 // If the backedge is guarded by a comparison with the pre-inc value
1613 // the addrec is safe. Also, if the entry is guarded by a comparison
1614 // with the start value and the backedge is guarded by a comparison
1615 // with the post-inc value, the addrec is safe.
1616 ICmpInst::Predicate Pred;
1617 const SCEV *OverflowLimit = getOverflowLimitForStep(Step, &Pred, this);
1618 if (OverflowLimit &&
1619 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1620 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1621 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1623 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1624 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1625 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
1626 getSignExtendExpr(Step, Ty),
1627 L, AR->getNoWrapFlags());
1630 // If Start and Step are constants, check if we can apply this
1632 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
1633 auto SC1 = dyn_cast<SCEVConstant>(Start);
1634 auto SC2 = dyn_cast<SCEVConstant>(Step);
1636 const APInt &C1 = SC1->getValue()->getValue();
1637 const APInt &C2 = SC2->getValue()->getValue();
1638 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1640 Start = getSignExtendExpr(Start, Ty);
1641 const SCEV *NewAR = getAddRecExpr(getConstant(AR->getType(), 0), Step,
1642 L, AR->getNoWrapFlags());
1643 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty));
1648 // The cast wasn't folded; create an explicit cast node.
1649 // Recompute the insert position, as it may have been invalidated.
1650 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1651 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1653 UniqueSCEVs.InsertNode(S, IP);
1657 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1658 /// unspecified bits out to the given type.
1660 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1662 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1663 "This is not an extending conversion!");
1664 assert(isSCEVable(Ty) &&
1665 "This is not a conversion to a SCEVable type!");
1666 Ty = getEffectiveSCEVType(Ty);
1668 // Sign-extend negative constants.
1669 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1670 if (SC->getValue()->getValue().isNegative())
1671 return getSignExtendExpr(Op, Ty);
1673 // Peel off a truncate cast.
1674 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
1675 const SCEV *NewOp = T->getOperand();
1676 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1677 return getAnyExtendExpr(NewOp, Ty);
1678 return getTruncateOrNoop(NewOp, Ty);
1681 // Next try a zext cast. If the cast is folded, use it.
1682 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
1683 if (!isa<SCEVZeroExtendExpr>(ZExt))
1686 // Next try a sext cast. If the cast is folded, use it.
1687 const SCEV *SExt = getSignExtendExpr(Op, Ty);
1688 if (!isa<SCEVSignExtendExpr>(SExt))
1691 // Force the cast to be folded into the operands of an addrec.
1692 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1693 SmallVector<const SCEV *, 4> Ops;
1694 for (const SCEV *Op : AR->operands())
1695 Ops.push_back(getAnyExtendExpr(Op, Ty));
1696 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
1699 // If the expression is obviously signed, use the sext cast value.
1700 if (isa<SCEVSMaxExpr>(Op))
1703 // Absent any other information, use the zext cast value.
1707 /// CollectAddOperandsWithScales - Process the given Ops list, which is
1708 /// a list of operands to be added under the given scale, update the given
1709 /// map. This is a helper function for getAddRecExpr. As an example of
1710 /// what it does, given a sequence of operands that would form an add
1711 /// expression like this:
1713 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
1715 /// where A and B are constants, update the map with these values:
1717 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1719 /// and add 13 + A*B*29 to AccumulatedConstant.
1720 /// This will allow getAddRecExpr to produce this:
1722 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1724 /// This form often exposes folding opportunities that are hidden in
1725 /// the original operand list.
1727 /// Return true iff it appears that any interesting folding opportunities
1728 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
1729 /// the common case where no interesting opportunities are present, and
1730 /// is also used as a check to avoid infinite recursion.
1733 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1734 SmallVectorImpl<const SCEV *> &NewOps,
1735 APInt &AccumulatedConstant,
1736 const SCEV *const *Ops, size_t NumOperands,
1738 ScalarEvolution &SE) {
1739 bool Interesting = false;
1741 // Iterate over the add operands. They are sorted, with constants first.
1743 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1745 // Pull a buried constant out to the outside.
1746 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1748 AccumulatedConstant += Scale * C->getValue()->getValue();
1751 // Next comes everything else. We're especially interested in multiplies
1752 // here, but they're in the middle, so just visit the rest with one loop.
1753 for (; i != NumOperands; ++i) {
1754 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1755 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1757 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1758 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1759 // A multiplication of a constant with another add; recurse.
1760 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
1762 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1763 Add->op_begin(), Add->getNumOperands(),
1766 // A multiplication of a constant with some other value. Update
1768 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1769 const SCEV *Key = SE.getMulExpr(MulOps);
1770 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1771 M.insert(std::make_pair(Key, NewScale));
1773 NewOps.push_back(Pair.first->first);
1775 Pair.first->second += NewScale;
1776 // The map already had an entry for this value, which may indicate
1777 // a folding opportunity.
1782 // An ordinary operand. Update the map.
1783 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1784 M.insert(std::make_pair(Ops[i], Scale));
1786 NewOps.push_back(Pair.first->first);
1788 Pair.first->second += Scale;
1789 // The map already had an entry for this value, which may indicate
1790 // a folding opportunity.
1800 struct APIntCompare {
1801 bool operator()(const APInt &LHS, const APInt &RHS) const {
1802 return LHS.ult(RHS);
1807 /// getAddExpr - Get a canonical add expression, or something simpler if
1809 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1810 SCEV::NoWrapFlags Flags) {
1811 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
1812 "only nuw or nsw allowed");
1813 assert(!Ops.empty() && "Cannot get empty add!");
1814 if (Ops.size() == 1) return Ops[0];
1816 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
1817 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1818 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
1819 "SCEVAddExpr operand types don't match!");
1822 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
1824 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
1825 SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
1826 if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
1828 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
1829 E = Ops.end(); I != E; ++I)
1830 if (!isKnownNonNegative(*I)) {
1834 if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
1837 // Sort by complexity, this groups all similar expression types together.
1838 GroupByComplexity(Ops, LI);
1840 // If there are any constants, fold them together.
1842 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1844 assert(Idx < Ops.size());
1845 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1846 // We found two constants, fold them together!
1847 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1848 RHSC->getValue()->getValue());
1849 if (Ops.size() == 2) return Ops[0];
1850 Ops.erase(Ops.begin()+1); // Erase the folded element
1851 LHSC = cast<SCEVConstant>(Ops[0]);
1854 // If we are left with a constant zero being added, strip it off.
1855 if (LHSC->getValue()->isZero()) {
1856 Ops.erase(Ops.begin());
1860 if (Ops.size() == 1) return Ops[0];
1863 // Okay, check to see if the same value occurs in the operand list more than
1864 // once. If so, merge them together into an multiply expression. Since we
1865 // sorted the list, these values are required to be adjacent.
1866 Type *Ty = Ops[0]->getType();
1867 bool FoundMatch = false;
1868 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
1869 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1870 // Scan ahead to count how many equal operands there are.
1872 while (i+Count != e && Ops[i+Count] == Ops[i])
1874 // Merge the values into a multiply.
1875 const SCEV *Scale = getConstant(Ty, Count);
1876 const SCEV *Mul = getMulExpr(Scale, Ops[i]);
1877 if (Ops.size() == Count)
1880 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
1881 --i; e -= Count - 1;
1885 return getAddExpr(Ops, Flags);
1887 // Check for truncates. If all the operands are truncated from the same
1888 // type, see if factoring out the truncate would permit the result to be
1889 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1890 // if the contents of the resulting outer trunc fold to something simple.
1891 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1892 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1893 Type *DstType = Trunc->getType();
1894 Type *SrcType = Trunc->getOperand()->getType();
1895 SmallVector<const SCEV *, 8> LargeOps;
1897 // Check all the operands to see if they can be represented in the
1898 // source type of the truncate.
1899 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1900 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1901 if (T->getOperand()->getType() != SrcType) {
1905 LargeOps.push_back(T->getOperand());
1906 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1907 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
1908 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
1909 SmallVector<const SCEV *, 8> LargeMulOps;
1910 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1911 if (const SCEVTruncateExpr *T =
1912 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1913 if (T->getOperand()->getType() != SrcType) {
1917 LargeMulOps.push_back(T->getOperand());
1918 } else if (const SCEVConstant *C =
1919 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1920 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
1927 LargeOps.push_back(getMulExpr(LargeMulOps));
1934 // Evaluate the expression in the larger type.
1935 const SCEV *Fold = getAddExpr(LargeOps, Flags);
1936 // If it folds to something simple, use it. Otherwise, don't.
1937 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1938 return getTruncateExpr(Fold, DstType);
1942 // Skip past any other cast SCEVs.
1943 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1946 // If there are add operands they would be next.
1947 if (Idx < Ops.size()) {
1948 bool DeletedAdd = false;
1949 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
1950 // If we have an add, expand the add operands onto the end of the operands
1952 Ops.erase(Ops.begin()+Idx);
1953 Ops.append(Add->op_begin(), Add->op_end());
1957 // If we deleted at least one add, we added operands to the end of the list,
1958 // and they are not necessarily sorted. Recurse to resort and resimplify
1959 // any operands we just acquired.
1961 return getAddExpr(Ops);
1964 // Skip over the add expression until we get to a multiply.
1965 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1968 // Check to see if there are any folding opportunities present with
1969 // operands multiplied by constant values.
1970 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1971 uint64_t BitWidth = getTypeSizeInBits(Ty);
1972 DenseMap<const SCEV *, APInt> M;
1973 SmallVector<const SCEV *, 8> NewOps;
1974 APInt AccumulatedConstant(BitWidth, 0);
1975 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1976 Ops.data(), Ops.size(),
1977 APInt(BitWidth, 1), *this)) {
1978 // Some interesting folding opportunity is present, so its worthwhile to
1979 // re-generate the operands list. Group the operands by constant scale,
1980 // to avoid multiplying by the same constant scale multiple times.
1981 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1982 for (SmallVectorImpl<const SCEV *>::const_iterator I = NewOps.begin(),
1983 E = NewOps.end(); I != E; ++I)
1984 MulOpLists[M.find(*I)->second].push_back(*I);
1985 // Re-generate the operands list.
1987 if (AccumulatedConstant != 0)
1988 Ops.push_back(getConstant(AccumulatedConstant));
1989 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1990 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
1992 Ops.push_back(getMulExpr(getConstant(I->first),
1993 getAddExpr(I->second)));
1995 return getConstant(Ty, 0);
1996 if (Ops.size() == 1)
1998 return getAddExpr(Ops);
2002 // If we are adding something to a multiply expression, make sure the
2003 // something is not already an operand of the multiply. If so, merge it into
2005 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2006 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2007 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2008 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2009 if (isa<SCEVConstant>(MulOpSCEV))
2011 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2012 if (MulOpSCEV == Ops[AddOp]) {
2013 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2014 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2015 if (Mul->getNumOperands() != 2) {
2016 // If the multiply has more than two operands, we must get the
2018 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2019 Mul->op_begin()+MulOp);
2020 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2021 InnerMul = getMulExpr(MulOps);
2023 const SCEV *One = getConstant(Ty, 1);
2024 const SCEV *AddOne = getAddExpr(One, InnerMul);
2025 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
2026 if (Ops.size() == 2) return OuterMul;
2028 Ops.erase(Ops.begin()+AddOp);
2029 Ops.erase(Ops.begin()+Idx-1);
2031 Ops.erase(Ops.begin()+Idx);
2032 Ops.erase(Ops.begin()+AddOp-1);
2034 Ops.push_back(OuterMul);
2035 return getAddExpr(Ops);
2038 // Check this multiply against other multiplies being added together.
2039 for (unsigned OtherMulIdx = Idx+1;
2040 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2042 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2043 // If MulOp occurs in OtherMul, we can fold the two multiplies
2045 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2046 OMulOp != e; ++OMulOp)
2047 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2048 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2049 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2050 if (Mul->getNumOperands() != 2) {
2051 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2052 Mul->op_begin()+MulOp);
2053 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2054 InnerMul1 = getMulExpr(MulOps);
2056 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2057 if (OtherMul->getNumOperands() != 2) {
2058 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2059 OtherMul->op_begin()+OMulOp);
2060 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2061 InnerMul2 = getMulExpr(MulOps);
2063 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
2064 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
2065 if (Ops.size() == 2) return OuterMul;
2066 Ops.erase(Ops.begin()+Idx);
2067 Ops.erase(Ops.begin()+OtherMulIdx-1);
2068 Ops.push_back(OuterMul);
2069 return getAddExpr(Ops);
2075 // If there are any add recurrences in the operands list, see if any other
2076 // added values are loop invariant. If so, we can fold them into the
2078 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2081 // Scan over all recurrences, trying to fold loop invariants into them.
2082 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2083 // Scan all of the other operands to this add and add them to the vector if
2084 // they are loop invariant w.r.t. the recurrence.
2085 SmallVector<const SCEV *, 8> LIOps;
2086 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2087 const Loop *AddRecLoop = AddRec->getLoop();
2088 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2089 if (isLoopInvariant(Ops[i], AddRecLoop)) {
2090 LIOps.push_back(Ops[i]);
2091 Ops.erase(Ops.begin()+i);
2095 // If we found some loop invariants, fold them into the recurrence.
2096 if (!LIOps.empty()) {
2097 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2098 LIOps.push_back(AddRec->getStart());
2100 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2102 AddRecOps[0] = getAddExpr(LIOps);
2104 // Build the new addrec. Propagate the NUW and NSW flags if both the
2105 // outer add and the inner addrec are guaranteed to have no overflow.
2106 // Always propagate NW.
2107 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2108 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2110 // If all of the other operands were loop invariant, we are done.
2111 if (Ops.size() == 1) return NewRec;
2113 // Otherwise, add the folded AddRec by the non-invariant parts.
2114 for (unsigned i = 0;; ++i)
2115 if (Ops[i] == AddRec) {
2119 return getAddExpr(Ops);
2122 // Okay, if there weren't any loop invariants to be folded, check to see if
2123 // there are multiple AddRec's with the same loop induction variable being
2124 // added together. If so, we can fold them.
2125 for (unsigned OtherIdx = Idx+1;
2126 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2128 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2129 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2130 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2132 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2134 if (const SCEVAddRecExpr *OtherAddRec =
2135 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
2136 if (OtherAddRec->getLoop() == AddRecLoop) {
2137 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2139 if (i >= AddRecOps.size()) {
2140 AddRecOps.append(OtherAddRec->op_begin()+i,
2141 OtherAddRec->op_end());
2144 AddRecOps[i] = getAddExpr(AddRecOps[i],
2145 OtherAddRec->getOperand(i));
2147 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2149 // Step size has changed, so we cannot guarantee no self-wraparound.
2150 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2151 return getAddExpr(Ops);
2154 // Otherwise couldn't fold anything into this recurrence. Move onto the
2158 // Okay, it looks like we really DO need an add expr. Check to see if we
2159 // already have one, otherwise create a new one.
2160 FoldingSetNodeID ID;
2161 ID.AddInteger(scAddExpr);
2162 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2163 ID.AddPointer(Ops[i]);
2166 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2168 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2169 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2170 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
2172 UniqueSCEVs.InsertNode(S, IP);
2174 S->setNoWrapFlags(Flags);
2178 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2180 if (j > 1 && k / j != i) Overflow = true;
2184 /// Compute the result of "n choose k", the binomial coefficient. If an
2185 /// intermediate computation overflows, Overflow will be set and the return will
2186 /// be garbage. Overflow is not cleared on absence of overflow.
2187 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2188 // We use the multiplicative formula:
2189 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2190 // At each iteration, we take the n-th term of the numeral and divide by the
2191 // (k-n)th term of the denominator. This division will always produce an
2192 // integral result, and helps reduce the chance of overflow in the
2193 // intermediate computations. However, we can still overflow even when the
2194 // final result would fit.
2196 if (n == 0 || n == k) return 1;
2197 if (k > n) return 0;
2203 for (uint64_t i = 1; i <= k; ++i) {
2204 r = umul_ov(r, n-(i-1), Overflow);
2210 /// Determine if any of the operands in this SCEV are a constant or if
2211 /// any of the add or multiply expressions in this SCEV contain a constant.
2212 static bool containsConstantSomewhere(const SCEV *StartExpr) {
2213 SmallVector<const SCEV *, 4> Ops;
2214 Ops.push_back(StartExpr);
2215 while (!Ops.empty()) {
2216 const SCEV *CurrentExpr = Ops.pop_back_val();
2217 if (isa<SCEVConstant>(*CurrentExpr))
2220 if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) {
2221 const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr);
2222 for (const SCEV *Operand : CurrentNAry->operands())
2223 Ops.push_back(Operand);
2229 /// getMulExpr - Get a canonical multiply expression, or something simpler if
2231 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2232 SCEV::NoWrapFlags Flags) {
2233 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2234 "only nuw or nsw allowed");
2235 assert(!Ops.empty() && "Cannot get empty mul!");
2236 if (Ops.size() == 1) return Ops[0];
2238 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2239 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2240 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2241 "SCEVMulExpr operand types don't match!");
2244 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2246 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2247 SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
2248 if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
2250 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
2251 E = Ops.end(); I != E; ++I)
2252 if (!isKnownNonNegative(*I)) {
2256 if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2259 // Sort by complexity, this groups all similar expression types together.
2260 GroupByComplexity(Ops, LI);
2262 // If there are any constants, fold them together.
2264 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2266 // C1*(C2+V) -> C1*C2 + C1*V
2267 if (Ops.size() == 2)
2268 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2269 // If any of Add's ops are Adds or Muls with a constant,
2270 // apply this transformation as well.
2271 if (Add->getNumOperands() == 2)
2272 if (containsConstantSomewhere(Add))
2273 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
2274 getMulExpr(LHSC, Add->getOperand(1)));
2277 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2278 // We found two constants, fold them together!
2279 ConstantInt *Fold = ConstantInt::get(getContext(),
2280 LHSC->getValue()->getValue() *
2281 RHSC->getValue()->getValue());
2282 Ops[0] = getConstant(Fold);
2283 Ops.erase(Ops.begin()+1); // Erase the folded element
2284 if (Ops.size() == 1) return Ops[0];
2285 LHSC = cast<SCEVConstant>(Ops[0]);
2288 // If we are left with a constant one being multiplied, strip it off.
2289 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
2290 Ops.erase(Ops.begin());
2292 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2293 // If we have a multiply of zero, it will always be zero.
2295 } else if (Ops[0]->isAllOnesValue()) {
2296 // If we have a mul by -1 of an add, try distributing the -1 among the
2298 if (Ops.size() == 2) {
2299 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2300 SmallVector<const SCEV *, 4> NewOps;
2301 bool AnyFolded = false;
2302 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(),
2303 E = Add->op_end(); I != E; ++I) {
2304 const SCEV *Mul = getMulExpr(Ops[0], *I);
2305 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2306 NewOps.push_back(Mul);
2309 return getAddExpr(NewOps);
2311 else if (const SCEVAddRecExpr *
2312 AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2313 // Negation preserves a recurrence's no self-wrap property.
2314 SmallVector<const SCEV *, 4> Operands;
2315 for (SCEVAddRecExpr::op_iterator I = AddRec->op_begin(),
2316 E = AddRec->op_end(); I != E; ++I) {
2317 Operands.push_back(getMulExpr(Ops[0], *I));
2319 return getAddRecExpr(Operands, AddRec->getLoop(),
2320 AddRec->getNoWrapFlags(SCEV::FlagNW));
2325 if (Ops.size() == 1)
2329 // Skip over the add expression until we get to a multiply.
2330 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2333 // If there are mul operands inline them all into this expression.
2334 if (Idx < Ops.size()) {
2335 bool DeletedMul = false;
2336 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2337 // If we have an mul, expand the mul operands onto the end of the operands
2339 Ops.erase(Ops.begin()+Idx);
2340 Ops.append(Mul->op_begin(), Mul->op_end());
2344 // If we deleted at least one mul, we added operands to the end of the list,
2345 // and they are not necessarily sorted. Recurse to resort and resimplify
2346 // any operands we just acquired.
2348 return getMulExpr(Ops);
2351 // If there are any add recurrences in the operands list, see if any other
2352 // added values are loop invariant. If so, we can fold them into the
2354 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2357 // Scan over all recurrences, trying to fold loop invariants into them.
2358 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2359 // Scan all of the other operands to this mul and add them to the vector if
2360 // they are loop invariant w.r.t. the recurrence.
2361 SmallVector<const SCEV *, 8> LIOps;
2362 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2363 const Loop *AddRecLoop = AddRec->getLoop();
2364 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2365 if (isLoopInvariant(Ops[i], AddRecLoop)) {
2366 LIOps.push_back(Ops[i]);
2367 Ops.erase(Ops.begin()+i);
2371 // If we found some loop invariants, fold them into the recurrence.
2372 if (!LIOps.empty()) {
2373 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
2374 SmallVector<const SCEV *, 4> NewOps;
2375 NewOps.reserve(AddRec->getNumOperands());
2376 const SCEV *Scale = getMulExpr(LIOps);
2377 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2378 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
2380 // Build the new addrec. Propagate the NUW and NSW flags if both the
2381 // outer mul and the inner addrec are guaranteed to have no overflow.
2383 // No self-wrap cannot be guaranteed after changing the step size, but
2384 // will be inferred if either NUW or NSW is true.
2385 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2386 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
2388 // If all of the other operands were loop invariant, we are done.
2389 if (Ops.size() == 1) return NewRec;
2391 // Otherwise, multiply the folded AddRec by the non-invariant parts.
2392 for (unsigned i = 0;; ++i)
2393 if (Ops[i] == AddRec) {
2397 return getMulExpr(Ops);
2400 // Okay, if there weren't any loop invariants to be folded, check to see if
2401 // there are multiple AddRec's with the same loop induction variable being
2402 // multiplied together. If so, we can fold them.
2404 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2405 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2406 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2407 // ]]],+,...up to x=2n}.
2408 // Note that the arguments to choose() are always integers with values
2409 // known at compile time, never SCEV objects.
2411 // The implementation avoids pointless extra computations when the two
2412 // addrec's are of different length (mathematically, it's equivalent to
2413 // an infinite stream of zeros on the right).
2414 bool OpsModified = false;
2415 for (unsigned OtherIdx = Idx+1;
2416 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2418 const SCEVAddRecExpr *OtherAddRec =
2419 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2420 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
2423 bool Overflow = false;
2424 Type *Ty = AddRec->getType();
2425 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2426 SmallVector<const SCEV*, 7> AddRecOps;
2427 for (int x = 0, xe = AddRec->getNumOperands() +
2428 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
2429 const SCEV *Term = getConstant(Ty, 0);
2430 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2431 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2432 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2433 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2434 z < ze && !Overflow; ++z) {
2435 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2437 if (LargerThan64Bits)
2438 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2440 Coeff = Coeff1*Coeff2;
2441 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2442 const SCEV *Term1 = AddRec->getOperand(y-z);
2443 const SCEV *Term2 = OtherAddRec->getOperand(z);
2444 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
2447 AddRecOps.push_back(Term);
2450 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2452 if (Ops.size() == 2) return NewAddRec;
2453 Ops[Idx] = NewAddRec;
2454 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2456 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2462 return getMulExpr(Ops);
2464 // Otherwise couldn't fold anything into this recurrence. Move onto the
2468 // Okay, it looks like we really DO need an mul expr. Check to see if we
2469 // already have one, otherwise create a new one.
2470 FoldingSetNodeID ID;
2471 ID.AddInteger(scMulExpr);
2472 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2473 ID.AddPointer(Ops[i]);
2476 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2478 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2479 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2480 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2482 UniqueSCEVs.InsertNode(S, IP);
2484 S->setNoWrapFlags(Flags);
2488 /// getUDivExpr - Get a canonical unsigned division expression, or something
2489 /// simpler if possible.
2490 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2492 assert(getEffectiveSCEVType(LHS->getType()) ==
2493 getEffectiveSCEVType(RHS->getType()) &&
2494 "SCEVUDivExpr operand types don't match!");
2496 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
2497 if (RHSC->getValue()->equalsInt(1))
2498 return LHS; // X udiv 1 --> x
2499 // If the denominator is zero, the result of the udiv is undefined. Don't
2500 // try to analyze it, because the resolution chosen here may differ from
2501 // the resolution chosen in other parts of the compiler.
2502 if (!RHSC->getValue()->isZero()) {
2503 // Determine if the division can be folded into the operands of
2505 // TODO: Generalize this to non-constants by using known-bits information.
2506 Type *Ty = LHS->getType();
2507 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
2508 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
2509 // For non-power-of-two values, effectively round the value up to the
2510 // nearest power of two.
2511 if (!RHSC->getValue()->getValue().isPowerOf2())
2513 IntegerType *ExtTy =
2514 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
2515 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2516 if (const SCEVConstant *Step =
2517 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2518 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
2519 const APInt &StepInt = Step->getValue()->getValue();
2520 const APInt &DivInt = RHSC->getValue()->getValue();
2521 if (!StepInt.urem(DivInt) &&
2522 getZeroExtendExpr(AR, ExtTy) ==
2523 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2524 getZeroExtendExpr(Step, ExtTy),
2525 AR->getLoop(), SCEV::FlagAnyWrap)) {
2526 SmallVector<const SCEV *, 4> Operands;
2527 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
2528 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
2529 return getAddRecExpr(Operands, AR->getLoop(),
2532 /// Get a canonical UDivExpr for a recurrence.
2533 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2534 // We can currently only fold X%N if X is constant.
2535 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2536 if (StartC && !DivInt.urem(StepInt) &&
2537 getZeroExtendExpr(AR, ExtTy) ==
2538 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2539 getZeroExtendExpr(Step, ExtTy),
2540 AR->getLoop(), SCEV::FlagAnyWrap)) {
2541 const APInt &StartInt = StartC->getValue()->getValue();
2542 const APInt &StartRem = StartInt.urem(StepInt);
2544 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2545 AR->getLoop(), SCEV::FlagNW);
2548 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2549 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2550 SmallVector<const SCEV *, 4> Operands;
2551 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
2552 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
2553 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2554 // Find an operand that's safely divisible.
2555 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2556 const SCEV *Op = M->getOperand(i);
2557 const SCEV *Div = getUDivExpr(Op, RHSC);
2558 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2559 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2562 return getMulExpr(Operands);
2566 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
2567 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
2568 SmallVector<const SCEV *, 4> Operands;
2569 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
2570 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
2571 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2573 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2574 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2575 if (isa<SCEVUDivExpr>(Op) ||
2576 getMulExpr(Op, RHS) != A->getOperand(i))
2578 Operands.push_back(Op);
2580 if (Operands.size() == A->getNumOperands())
2581 return getAddExpr(Operands);
2585 // Fold if both operands are constant.
2586 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2587 Constant *LHSCV = LHSC->getValue();
2588 Constant *RHSCV = RHSC->getValue();
2589 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2595 FoldingSetNodeID ID;
2596 ID.AddInteger(scUDivExpr);
2600 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2601 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2603 UniqueSCEVs.InsertNode(S, IP);
2607 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
2608 APInt A = C1->getValue()->getValue().abs();
2609 APInt B = C2->getValue()->getValue().abs();
2610 uint32_t ABW = A.getBitWidth();
2611 uint32_t BBW = B.getBitWidth();
2618 return APIntOps::GreatestCommonDivisor(A, B);
2621 /// getUDivExactExpr - Get a canonical unsigned division expression, or
2622 /// something simpler if possible. There is no representation for an exact udiv
2623 /// in SCEV IR, but we can attempt to remove factors from the LHS and RHS.
2624 /// We can't do this when it's not exact because the udiv may be clearing bits.
2625 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
2627 // TODO: we could try to find factors in all sorts of things, but for now we
2628 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
2629 // end of this file for inspiration.
2631 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
2633 return getUDivExpr(LHS, RHS);
2635 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
2636 // If the mulexpr multiplies by a constant, then that constant must be the
2637 // first element of the mulexpr.
2638 if (const SCEVConstant *LHSCst =
2639 dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
2640 if (LHSCst == RHSCst) {
2641 SmallVector<const SCEV *, 2> Operands;
2642 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2643 return getMulExpr(Operands);
2646 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
2647 // that there's a factor provided by one of the other terms. We need to
2649 APInt Factor = gcd(LHSCst, RHSCst);
2650 if (!Factor.isIntN(1)) {
2651 LHSCst = cast<SCEVConstant>(
2652 getConstant(LHSCst->getValue()->getValue().udiv(Factor)));
2653 RHSCst = cast<SCEVConstant>(
2654 getConstant(RHSCst->getValue()->getValue().udiv(Factor)));
2655 SmallVector<const SCEV *, 2> Operands;
2656 Operands.push_back(LHSCst);
2657 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2658 LHS = getMulExpr(Operands);
2660 Mul = dyn_cast<SCEVMulExpr>(LHS);
2662 return getUDivExactExpr(LHS, RHS);
2667 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
2668 if (Mul->getOperand(i) == RHS) {
2669 SmallVector<const SCEV *, 2> Operands;
2670 Operands.append(Mul->op_begin(), Mul->op_begin() + i);
2671 Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
2672 return getMulExpr(Operands);
2676 return getUDivExpr(LHS, RHS);
2679 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
2680 /// Simplify the expression as much as possible.
2681 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
2683 SCEV::NoWrapFlags Flags) {
2684 SmallVector<const SCEV *, 4> Operands;
2685 Operands.push_back(Start);
2686 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
2687 if (StepChrec->getLoop() == L) {
2688 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
2689 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
2692 Operands.push_back(Step);
2693 return getAddRecExpr(Operands, L, Flags);
2696 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
2697 /// Simplify the expression as much as possible.
2699 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
2700 const Loop *L, SCEV::NoWrapFlags Flags) {
2701 if (Operands.size() == 1) return Operands[0];
2703 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
2704 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
2705 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
2706 "SCEVAddRecExpr operand types don't match!");
2707 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2708 assert(isLoopInvariant(Operands[i], L) &&
2709 "SCEVAddRecExpr operand is not loop-invariant!");
2712 if (Operands.back()->isZero()) {
2713 Operands.pop_back();
2714 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
2717 // It's tempting to want to call getMaxBackedgeTakenCount count here and
2718 // use that information to infer NUW and NSW flags. However, computing a
2719 // BE count requires calling getAddRecExpr, so we may not yet have a
2720 // meaningful BE count at this point (and if we don't, we'd be stuck
2721 // with a SCEVCouldNotCompute as the cached BE count).
2723 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2725 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2726 SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
2727 if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
2729 for (SmallVectorImpl<const SCEV *>::const_iterator I = Operands.begin(),
2730 E = Operands.end(); I != E; ++I)
2731 if (!isKnownNonNegative(*I)) {
2735 if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2738 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
2739 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
2740 const Loop *NestedLoop = NestedAR->getLoop();
2741 if (L->contains(NestedLoop) ?
2742 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
2743 (!NestedLoop->contains(L) &&
2744 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
2745 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
2746 NestedAR->op_end());
2747 Operands[0] = NestedAR->getStart();
2748 // AddRecs require their operands be loop-invariant with respect to their
2749 // loops. Don't perform this transformation if it would break this
2751 bool AllInvariant = true;
2752 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2753 if (!isLoopInvariant(Operands[i], L)) {
2754 AllInvariant = false;
2758 // Create a recurrence for the outer loop with the same step size.
2760 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
2761 // inner recurrence has the same property.
2762 SCEV::NoWrapFlags OuterFlags =
2763 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
2765 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
2766 AllInvariant = true;
2767 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
2768 if (!isLoopInvariant(NestedOperands[i], NestedLoop)) {
2769 AllInvariant = false;
2773 // Ok, both add recurrences are valid after the transformation.
2775 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
2776 // the outer recurrence has the same property.
2777 SCEV::NoWrapFlags InnerFlags =
2778 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
2779 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
2782 // Reset Operands to its original state.
2783 Operands[0] = NestedAR;
2787 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2788 // already have one, otherwise create a new one.
2789 FoldingSetNodeID ID;
2790 ID.AddInteger(scAddRecExpr);
2791 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2792 ID.AddPointer(Operands[i]);
2796 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2798 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2799 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
2800 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2801 O, Operands.size(), L);
2802 UniqueSCEVs.InsertNode(S, IP);
2804 S->setNoWrapFlags(Flags);
2808 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2810 SmallVector<const SCEV *, 2> Ops;
2813 return getSMaxExpr(Ops);
2817 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2818 assert(!Ops.empty() && "Cannot get empty smax!");
2819 if (Ops.size() == 1) return Ops[0];
2821 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2822 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2823 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2824 "SCEVSMaxExpr operand types don't match!");
2827 // Sort by complexity, this groups all similar expression types together.
2828 GroupByComplexity(Ops, LI);
2830 // If there are any constants, fold them together.
2832 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2834 assert(Idx < Ops.size());
2835 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2836 // We found two constants, fold them together!
2837 ConstantInt *Fold = ConstantInt::get(getContext(),
2838 APIntOps::smax(LHSC->getValue()->getValue(),
2839 RHSC->getValue()->getValue()));
2840 Ops[0] = getConstant(Fold);
2841 Ops.erase(Ops.begin()+1); // Erase the folded element
2842 if (Ops.size() == 1) return Ops[0];
2843 LHSC = cast<SCEVConstant>(Ops[0]);
2846 // If we are left with a constant minimum-int, strip it off.
2847 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2848 Ops.erase(Ops.begin());
2850 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2851 // If we have an smax with a constant maximum-int, it will always be
2856 if (Ops.size() == 1) return Ops[0];
2859 // Find the first SMax
2860 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2863 // Check to see if one of the operands is an SMax. If so, expand its operands
2864 // onto our operand list, and recurse to simplify.
2865 if (Idx < Ops.size()) {
2866 bool DeletedSMax = false;
2867 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
2868 Ops.erase(Ops.begin()+Idx);
2869 Ops.append(SMax->op_begin(), SMax->op_end());
2874 return getSMaxExpr(Ops);
2877 // Okay, check to see if the same value occurs in the operand list twice. If
2878 // so, delete one. Since we sorted the list, these values are required to
2880 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2881 // X smax Y smax Y --> X smax Y
2882 // X smax Y --> X, if X is always greater than Y
2883 if (Ops[i] == Ops[i+1] ||
2884 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
2885 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2887 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
2888 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2892 if (Ops.size() == 1) return Ops[0];
2894 assert(!Ops.empty() && "Reduced smax down to nothing!");
2896 // Okay, it looks like we really DO need an smax expr. Check to see if we
2897 // already have one, otherwise create a new one.
2898 FoldingSetNodeID ID;
2899 ID.AddInteger(scSMaxExpr);
2900 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2901 ID.AddPointer(Ops[i]);
2903 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2904 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2905 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2906 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
2908 UniqueSCEVs.InsertNode(S, IP);
2912 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2914 SmallVector<const SCEV *, 2> Ops;
2917 return getUMaxExpr(Ops);
2921 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2922 assert(!Ops.empty() && "Cannot get empty umax!");
2923 if (Ops.size() == 1) return Ops[0];
2925 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2926 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2927 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2928 "SCEVUMaxExpr operand types don't match!");
2931 // Sort by complexity, this groups all similar expression types together.
2932 GroupByComplexity(Ops, LI);
2934 // If there are any constants, fold them together.
2936 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2938 assert(Idx < Ops.size());
2939 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2940 // We found two constants, fold them together!
2941 ConstantInt *Fold = ConstantInt::get(getContext(),
2942 APIntOps::umax(LHSC->getValue()->getValue(),
2943 RHSC->getValue()->getValue()));
2944 Ops[0] = getConstant(Fold);
2945 Ops.erase(Ops.begin()+1); // Erase the folded element
2946 if (Ops.size() == 1) return Ops[0];
2947 LHSC = cast<SCEVConstant>(Ops[0]);
2950 // If we are left with a constant minimum-int, strip it off.
2951 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2952 Ops.erase(Ops.begin());
2954 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2955 // If we have an umax with a constant maximum-int, it will always be
2960 if (Ops.size() == 1) return Ops[0];
2963 // Find the first UMax
2964 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2967 // Check to see if one of the operands is a UMax. If so, expand its operands
2968 // onto our operand list, and recurse to simplify.
2969 if (Idx < Ops.size()) {
2970 bool DeletedUMax = false;
2971 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
2972 Ops.erase(Ops.begin()+Idx);
2973 Ops.append(UMax->op_begin(), UMax->op_end());
2978 return getUMaxExpr(Ops);
2981 // Okay, check to see if the same value occurs in the operand list twice. If
2982 // so, delete one. Since we sorted the list, these values are required to
2984 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2985 // X umax Y umax Y --> X umax Y
2986 // X umax Y --> X, if X is always greater than Y
2987 if (Ops[i] == Ops[i+1] ||
2988 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
2989 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2991 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
2992 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2996 if (Ops.size() == 1) return Ops[0];
2998 assert(!Ops.empty() && "Reduced umax down to nothing!");
3000 // Okay, it looks like we really DO need a umax expr. Check to see if we
3001 // already have one, otherwise create a new one.
3002 FoldingSetNodeID ID;
3003 ID.AddInteger(scUMaxExpr);
3004 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3005 ID.AddPointer(Ops[i]);
3007 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3008 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3009 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3010 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3012 UniqueSCEVs.InsertNode(S, IP);
3016 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3018 // ~smax(~x, ~y) == smin(x, y).
3019 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3022 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3024 // ~umax(~x, ~y) == umin(x, y)
3025 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3028 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3029 // If we have DataLayout, we can bypass creating a target-independent
3030 // constant expression and then folding it back into a ConstantInt.
3031 // This is just a compile-time optimization.
3033 return getConstant(IntTy, DL->getTypeAllocSize(AllocTy));
3035 Constant *C = ConstantExpr::getSizeOf(AllocTy);
3036 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
3037 if (Constant *Folded = ConstantFoldConstantExpression(CE, DL, TLI))
3039 Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
3040 assert(Ty == IntTy && "Effective SCEV type doesn't match");
3041 return getTruncateOrZeroExtend(getSCEV(C), Ty);
3044 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3047 // If we have DataLayout, we can bypass creating a target-independent
3048 // constant expression and then folding it back into a ConstantInt.
3049 // This is just a compile-time optimization.
3051 return getConstant(IntTy,
3052 DL->getStructLayout(STy)->getElementOffset(FieldNo));
3055 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
3056 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
3057 if (Constant *Folded = ConstantFoldConstantExpression(CE, DL, TLI))
3060 Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
3061 return getTruncateOrZeroExtend(getSCEV(C), Ty);
3064 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3065 // Don't attempt to do anything other than create a SCEVUnknown object
3066 // here. createSCEV only calls getUnknown after checking for all other
3067 // interesting possibilities, and any other code that calls getUnknown
3068 // is doing so in order to hide a value from SCEV canonicalization.
3070 FoldingSetNodeID ID;
3071 ID.AddInteger(scUnknown);
3074 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3075 assert(cast<SCEVUnknown>(S)->getValue() == V &&
3076 "Stale SCEVUnknown in uniquing map!");
3079 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3081 FirstUnknown = cast<SCEVUnknown>(S);
3082 UniqueSCEVs.InsertNode(S, IP);
3086 //===----------------------------------------------------------------------===//
3087 // Basic SCEV Analysis and PHI Idiom Recognition Code
3090 /// isSCEVable - Test if values of the given type are analyzable within
3091 /// the SCEV framework. This primarily includes integer types, and it
3092 /// can optionally include pointer types if the ScalarEvolution class
3093 /// has access to target-specific information.
3094 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3095 // Integers and pointers are always SCEVable.
3096 return Ty->isIntegerTy() || Ty->isPointerTy();
3099 /// getTypeSizeInBits - Return the size in bits of the specified type,
3100 /// for which isSCEVable must return true.
3101 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3102 assert(isSCEVable(Ty) && "Type is not SCEVable!");
3104 // If we have a DataLayout, use it!
3106 return DL->getTypeSizeInBits(Ty);
3108 // Integer types have fixed sizes.
3109 if (Ty->isIntegerTy())
3110 return Ty->getPrimitiveSizeInBits();
3112 // The only other support type is pointer. Without DataLayout, conservatively
3113 // assume pointers are 64-bit.
3114 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
3118 /// getEffectiveSCEVType - Return a type with the same bitwidth as
3119 /// the given type and which represents how SCEV will treat the given
3120 /// type, for which isSCEVable must return true. For pointer types,
3121 /// this is the pointer-sized integer type.
3122 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3123 assert(isSCEVable(Ty) && "Type is not SCEVable!");
3125 if (Ty->isIntegerTy()) {
3129 // The only other support type is pointer.
3130 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3133 return DL->getIntPtrType(Ty);
3135 // Without DataLayout, conservatively assume pointers are 64-bit.
3136 return Type::getInt64Ty(getContext());
3139 const SCEV *ScalarEvolution::getCouldNotCompute() {
3140 return &CouldNotCompute;
3144 // Helper class working with SCEVTraversal to figure out if a SCEV contains
3145 // a SCEVUnknown with null value-pointer. FindInvalidSCEVUnknown::FindOne
3146 // is set iff if find such SCEVUnknown.
3148 struct FindInvalidSCEVUnknown {
3150 FindInvalidSCEVUnknown() { FindOne = false; }
3151 bool follow(const SCEV *S) {
3152 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
3156 if (!cast<SCEVUnknown>(S)->getValue())
3163 bool isDone() const { return FindOne; }
3167 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3168 FindInvalidSCEVUnknown F;
3169 SCEVTraversal<FindInvalidSCEVUnknown> ST(F);
3175 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
3176 /// expression and create a new one.
3177 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3178 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3180 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3181 if (I != ValueExprMap.end()) {
3182 const SCEV *S = I->second;
3183 if (checkValidity(S))
3186 ValueExprMap.erase(I);
3188 const SCEV *S = createSCEV(V);
3190 // The process of creating a SCEV for V may have caused other SCEVs
3191 // to have been created, so it's necessary to insert the new entry
3192 // from scratch, rather than trying to remember the insert position
3194 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(V, this), S));
3198 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
3200 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
3201 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3203 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3205 Type *Ty = V->getType();
3206 Ty = getEffectiveSCEVType(Ty);
3207 return getMulExpr(V,
3208 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
3211 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
3212 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3213 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3215 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3217 Type *Ty = V->getType();
3218 Ty = getEffectiveSCEVType(Ty);
3219 const SCEV *AllOnes =
3220 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3221 return getMinusSCEV(AllOnes, V);
3224 /// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
3225 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3226 SCEV::NoWrapFlags Flags) {
3227 assert(!maskFlags(Flags, SCEV::FlagNUW) && "subtraction does not have NUW");
3229 // Fast path: X - X --> 0.
3231 return getConstant(LHS->getType(), 0);
3234 return getAddExpr(LHS, getNegativeSCEV(RHS), Flags);
3237 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
3238 /// input value to the specified type. If the type must be extended, it is zero
3241 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3242 Type *SrcTy = V->getType();
3243 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3244 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3245 "Cannot truncate or zero extend with non-integer arguments!");
3246 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3247 return V; // No conversion
3248 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3249 return getTruncateExpr(V, Ty);
3250 return getZeroExtendExpr(V, Ty);
3253 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
3254 /// input value to the specified type. If the type must be extended, it is sign
3257 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
3259 Type *SrcTy = V->getType();
3260 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3261 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3262 "Cannot truncate or zero extend with non-integer arguments!");
3263 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3264 return V; // No conversion
3265 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3266 return getTruncateExpr(V, Ty);
3267 return getSignExtendExpr(V, Ty);
3270 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
3271 /// input value to the specified type. If the type must be extended, it is zero
3272 /// extended. The conversion must not be narrowing.
3274 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3275 Type *SrcTy = V->getType();
3276 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3277 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3278 "Cannot noop or zero extend with non-integer arguments!");
3279 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3280 "getNoopOrZeroExtend cannot truncate!");
3281 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3282 return V; // No conversion
3283 return getZeroExtendExpr(V, Ty);
3286 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
3287 /// input value to the specified type. If the type must be extended, it is sign
3288 /// extended. The conversion must not be narrowing.
3290 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3291 Type *SrcTy = V->getType();
3292 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3293 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3294 "Cannot noop or sign extend with non-integer arguments!");
3295 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3296 "getNoopOrSignExtend cannot truncate!");
3297 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3298 return V; // No conversion
3299 return getSignExtendExpr(V, Ty);
3302 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
3303 /// the input value to the specified type. If the type must be extended,
3304 /// it is extended with unspecified bits. The conversion must not be
3307 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3308 Type *SrcTy = V->getType();
3309 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3310 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3311 "Cannot noop or any extend with non-integer arguments!");
3312 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3313 "getNoopOrAnyExtend cannot truncate!");
3314 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3315 return V; // No conversion
3316 return getAnyExtendExpr(V, Ty);
3319 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
3320 /// input value to the specified type. The conversion must not be widening.
3322 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3323 Type *SrcTy = V->getType();
3324 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3325 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3326 "Cannot truncate or noop with non-integer arguments!");
3327 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3328 "getTruncateOrNoop cannot extend!");
3329 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3330 return V; // No conversion
3331 return getTruncateExpr(V, Ty);
3334 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
3335 /// the types using zero-extension, and then perform a umax operation
3337 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3339 const SCEV *PromotedLHS = LHS;
3340 const SCEV *PromotedRHS = RHS;
3342 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3343 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3345 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3347 return getUMaxExpr(PromotedLHS, PromotedRHS);
3350 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
3351 /// the types using zero-extension, and then perform a umin operation
3353 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3355 const SCEV *PromotedLHS = LHS;
3356 const SCEV *PromotedRHS = RHS;
3358 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3359 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3361 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3363 return getUMinExpr(PromotedLHS, PromotedRHS);
3366 /// getPointerBase - Transitively follow the chain of pointer-type operands
3367 /// until reaching a SCEV that does not have a single pointer operand. This
3368 /// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
3369 /// but corner cases do exist.
3370 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3371 // A pointer operand may evaluate to a nonpointer expression, such as null.
3372 if (!V->getType()->isPointerTy())
3375 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3376 return getPointerBase(Cast->getOperand());
3378 else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
3379 const SCEV *PtrOp = nullptr;
3380 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
3382 if ((*I)->getType()->isPointerTy()) {
3383 // Cannot find the base of an expression with multiple pointer operands.
3391 return getPointerBase(PtrOp);
3396 /// PushDefUseChildren - Push users of the given Instruction
3397 /// onto the given Worklist.
3399 PushDefUseChildren(Instruction *I,
3400 SmallVectorImpl<Instruction *> &Worklist) {
3401 // Push the def-use children onto the Worklist stack.
3402 for (User *U : I->users())
3403 Worklist.push_back(cast<Instruction>(U));
3406 /// ForgetSymbolicValue - This looks up computed SCEV values for all
3407 /// instructions that depend on the given instruction and removes them from
3408 /// the ValueExprMapType map if they reference SymName. This is used during PHI
3411 ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
3412 SmallVector<Instruction *, 16> Worklist;
3413 PushDefUseChildren(PN, Worklist);
3415 SmallPtrSet<Instruction *, 8> Visited;
3417 while (!Worklist.empty()) {
3418 Instruction *I = Worklist.pop_back_val();
3419 if (!Visited.insert(I).second)
3422 ValueExprMapType::iterator It =
3423 ValueExprMap.find_as(static_cast<Value *>(I));
3424 if (It != ValueExprMap.end()) {
3425 const SCEV *Old = It->second;
3427 // Short-circuit the def-use traversal if the symbolic name
3428 // ceases to appear in expressions.
3429 if (Old != SymName && !hasOperand(Old, SymName))
3432 // SCEVUnknown for a PHI either means that it has an unrecognized
3433 // structure, it's a PHI that's in the progress of being computed
3434 // by createNodeForPHI, or it's a single-value PHI. In the first case,
3435 // additional loop trip count information isn't going to change anything.
3436 // In the second case, createNodeForPHI will perform the necessary
3437 // updates on its own when it gets to that point. In the third, we do
3438 // want to forget the SCEVUnknown.
3439 if (!isa<PHINode>(I) ||
3440 !isa<SCEVUnknown>(Old) ||
3441 (I != PN && Old == SymName)) {
3442 forgetMemoizedResults(Old);
3443 ValueExprMap.erase(It);
3447 PushDefUseChildren(I, Worklist);
3451 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
3452 /// a loop header, making it a potential recurrence, or it doesn't.
3454 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
3455 if (const Loop *L = LI->getLoopFor(PN->getParent()))
3456 if (L->getHeader() == PN->getParent()) {
3457 // The loop may have multiple entrances or multiple exits; we can analyze
3458 // this phi as an addrec if it has a unique entry value and a unique
3460 Value *BEValueV = nullptr, *StartValueV = nullptr;
3461 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3462 Value *V = PN->getIncomingValue(i);
3463 if (L->contains(PN->getIncomingBlock(i))) {
3466 } else if (BEValueV != V) {
3470 } else if (!StartValueV) {
3472 } else if (StartValueV != V) {
3473 StartValueV = nullptr;
3477 if (BEValueV && StartValueV) {
3478 // While we are analyzing this PHI node, handle its value symbolically.
3479 const SCEV *SymbolicName = getUnknown(PN);
3480 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
3481 "PHI node already processed?");
3482 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
3484 // Using this symbolic name for the PHI, analyze the value coming around
3486 const SCEV *BEValue = getSCEV(BEValueV);
3488 // NOTE: If BEValue is loop invariant, we know that the PHI node just
3489 // has a special value for the first iteration of the loop.
3491 // If the value coming around the backedge is an add with the symbolic
3492 // value we just inserted, then we found a simple induction variable!
3493 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
3494 // If there is a single occurrence of the symbolic value, replace it
3495 // with a recurrence.
3496 unsigned FoundIndex = Add->getNumOperands();
3497 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
3498 if (Add->getOperand(i) == SymbolicName)
3499 if (FoundIndex == e) {
3504 if (FoundIndex != Add->getNumOperands()) {
3505 // Create an add with everything but the specified operand.
3506 SmallVector<const SCEV *, 8> Ops;
3507 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
3508 if (i != FoundIndex)
3509 Ops.push_back(Add->getOperand(i));
3510 const SCEV *Accum = getAddExpr(Ops);
3512 // This is not a valid addrec if the step amount is varying each
3513 // loop iteration, but is not itself an addrec in this loop.
3514 if (isLoopInvariant(Accum, L) ||
3515 (isa<SCEVAddRecExpr>(Accum) &&
3516 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
3517 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
3519 // If the increment doesn't overflow, then neither the addrec nor
3520 // the post-increment will overflow.
3521 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
3522 if (OBO->hasNoUnsignedWrap())
3523 Flags = setFlags(Flags, SCEV::FlagNUW);
3524 if (OBO->hasNoSignedWrap())
3525 Flags = setFlags(Flags, SCEV::FlagNSW);
3526 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
3527 // If the increment is an inbounds GEP, then we know the address
3528 // space cannot be wrapped around. We cannot make any guarantee
3529 // about signed or unsigned overflow because pointers are
3530 // unsigned but we may have a negative index from the base
3531 // pointer. We can guarantee that no unsigned wrap occurs if the
3532 // indices form a positive value.
3533 if (GEP->isInBounds()) {
3534 Flags = setFlags(Flags, SCEV::FlagNW);
3536 const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
3537 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
3538 Flags = setFlags(Flags, SCEV::FlagNUW);
3540 } else if (const SubOperator *OBO =
3541 dyn_cast<SubOperator>(BEValueV)) {
3542 if (OBO->hasNoUnsignedWrap())
3543 Flags = setFlags(Flags, SCEV::FlagNUW);
3544 if (OBO->hasNoSignedWrap())
3545 Flags = setFlags(Flags, SCEV::FlagNSW);
3548 const SCEV *StartVal = getSCEV(StartValueV);
3549 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
3551 // Since the no-wrap flags are on the increment, they apply to the
3552 // post-incremented value as well.
3553 if (isLoopInvariant(Accum, L))
3554 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
3557 // Okay, for the entire analysis of this edge we assumed the PHI
3558 // to be symbolic. We now need to go back and purge all of the
3559 // entries for the scalars that use the symbolic expression.
3560 ForgetSymbolicName(PN, SymbolicName);
3561 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
3565 } else if (const SCEVAddRecExpr *AddRec =
3566 dyn_cast<SCEVAddRecExpr>(BEValue)) {
3567 // Otherwise, this could be a loop like this:
3568 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
3569 // In this case, j = {1,+,1} and BEValue is j.
3570 // Because the other in-value of i (0) fits the evolution of BEValue
3571 // i really is an addrec evolution.
3572 if (AddRec->getLoop() == L && AddRec->isAffine()) {
3573 const SCEV *StartVal = getSCEV(StartValueV);
3575 // If StartVal = j.start - j.stride, we can use StartVal as the
3576 // initial step of the addrec evolution.
3577 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
3578 AddRec->getOperand(1))) {
3579 // FIXME: For constant StartVal, we should be able to infer
3581 const SCEV *PHISCEV =
3582 getAddRecExpr(StartVal, AddRec->getOperand(1), L,
3585 // Okay, for the entire analysis of this edge we assumed the PHI
3586 // to be symbolic. We now need to go back and purge all of the
3587 // entries for the scalars that use the symbolic expression.
3588 ForgetSymbolicName(PN, SymbolicName);
3589 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
3597 // If the PHI has a single incoming value, follow that value, unless the
3598 // PHI's incoming blocks are in a different loop, in which case doing so
3599 // risks breaking LCSSA form. Instcombine would normally zap these, but
3600 // it doesn't have DominatorTree information, so it may miss cases.
3601 if (Value *V = SimplifyInstruction(PN, DL, TLI, DT, AT))
3602 if (LI->replacementPreservesLCSSAForm(PN, V))
3605 // If it's not a loop phi, we can't handle it yet.
3606 return getUnknown(PN);
3609 /// createNodeForGEP - Expand GEP instructions into add and multiply
3610 /// operations. This allows them to be analyzed by regular SCEV code.
3612 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
3613 Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
3614 Value *Base = GEP->getOperand(0);
3615 // Don't attempt to analyze GEPs over unsized objects.
3616 if (!Base->getType()->getPointerElementType()->isSized())
3617 return getUnknown(GEP);
3619 // Don't blindly transfer the inbounds flag from the GEP instruction to the
3620 // Add expression, because the Instruction may be guarded by control flow
3621 // and the no-overflow bits may not be valid for the expression in any
3623 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3625 const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
3626 gep_type_iterator GTI = gep_type_begin(GEP);
3627 for (GetElementPtrInst::op_iterator I = std::next(GEP->op_begin()),
3631 // Compute the (potentially symbolic) offset in bytes for this index.
3632 if (StructType *STy = dyn_cast<StructType>(*GTI++)) {
3633 // For a struct, add the member offset.
3634 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
3635 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3637 // Add the field offset to the running total offset.
3638 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3640 // For an array, add the element offset, explicitly scaled.
3641 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, *GTI);
3642 const SCEV *IndexS = getSCEV(Index);
3643 // Getelementptr indices are signed.
3644 IndexS = getTruncateOrSignExtend(IndexS, IntPtrTy);
3646 // Multiply the index by the element size to compute the element offset.
3647 const SCEV *LocalOffset = getMulExpr(IndexS, ElementSize, Wrap);
3649 // Add the element offset to the running total offset.
3650 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3654 // Get the SCEV for the GEP base.
3655 const SCEV *BaseS = getSCEV(Base);
3657 // Add the total offset from all the GEP indices to the base.
3658 return getAddExpr(BaseS, TotalOffset, Wrap);
3661 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
3662 /// guaranteed to end in (at every loop iteration). It is, at the same time,
3663 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
3664 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
3666 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
3667 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
3668 return C->getValue()->getValue().countTrailingZeros();
3670 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
3671 return std::min(GetMinTrailingZeros(T->getOperand()),
3672 (uint32_t)getTypeSizeInBits(T->getType()));
3674 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
3675 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
3676 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
3677 getTypeSizeInBits(E->getType()) : OpRes;
3680 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
3681 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
3682 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
3683 getTypeSizeInBits(E->getType()) : OpRes;
3686 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
3687 // The result is the min of all operands results.
3688 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
3689 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
3690 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
3694 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
3695 // The result is the sum of all operands results.
3696 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
3697 uint32_t BitWidth = getTypeSizeInBits(M->getType());
3698 for (unsigned i = 1, e = M->getNumOperands();
3699 SumOpRes != BitWidth && i != e; ++i)
3700 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
3705 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
3706 // The result is the min of all operands results.
3707 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
3708 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
3709 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
3713 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
3714 // The result is the min of all operands results.
3715 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
3716 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
3717 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
3721 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
3722 // The result is the min of all operands results.
3723 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
3724 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
3725 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
3729 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3730 // For a SCEVUnknown, ask ValueTracking.
3731 unsigned BitWidth = getTypeSizeInBits(U->getType());
3732 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3733 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, AT, nullptr, DT);
3734 return Zeros.countTrailingOnes();
3741 /// GetRangeFromMetadata - Helper method to assign a range to V from
3742 /// metadata present in the IR.
3743 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
3744 if (Instruction *I = dyn_cast<Instruction>(V)) {
3745 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) {
3746 ConstantRange TotalRange(
3747 cast<IntegerType>(I->getType())->getBitWidth(), false);
3749 unsigned NumRanges = MD->getNumOperands() / 2;
3750 assert(NumRanges >= 1);
3752 for (unsigned i = 0; i < NumRanges; ++i) {
3753 ConstantInt *Lower =
3754 mdconst::extract<ConstantInt>(MD->getOperand(2 * i + 0));
3755 ConstantInt *Upper =
3756 mdconst::extract<ConstantInt>(MD->getOperand(2 * i + 1));
3757 ConstantRange Range(Lower->getValue(), Upper->getValue());
3758 TotalRange = TotalRange.unionWith(Range);
3768 /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
3771 ScalarEvolution::getUnsignedRange(const SCEV *S) {
3772 // See if we've computed this range already.
3773 DenseMap<const SCEV *, ConstantRange>::iterator I = UnsignedRanges.find(S);
3774 if (I != UnsignedRanges.end())
3777 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
3778 return setUnsignedRange(C, ConstantRange(C->getValue()->getValue()));
3780 unsigned BitWidth = getTypeSizeInBits(S->getType());
3781 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3783 // If the value has known zeros, the maximum unsigned value will have those
3784 // known zeros as well.
3785 uint32_t TZ = GetMinTrailingZeros(S);
3787 ConservativeResult =
3788 ConstantRange(APInt::getMinValue(BitWidth),
3789 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
3791 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3792 ConstantRange X = getUnsignedRange(Add->getOperand(0));
3793 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3794 X = X.add(getUnsignedRange(Add->getOperand(i)));
3795 return setUnsignedRange(Add, ConservativeResult.intersectWith(X));
3798 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3799 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
3800 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3801 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
3802 return setUnsignedRange(Mul, ConservativeResult.intersectWith(X));
3805 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3806 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
3807 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3808 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
3809 return setUnsignedRange(SMax, ConservativeResult.intersectWith(X));
3812 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3813 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
3814 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3815 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
3816 return setUnsignedRange(UMax, ConservativeResult.intersectWith(X));
3819 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3820 ConstantRange X = getUnsignedRange(UDiv->getLHS());
3821 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
3822 return setUnsignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
3825 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3826 ConstantRange X = getUnsignedRange(ZExt->getOperand());
3827 return setUnsignedRange(ZExt,
3828 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
3831 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3832 ConstantRange X = getUnsignedRange(SExt->getOperand());
3833 return setUnsignedRange(SExt,
3834 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
3837 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3838 ConstantRange X = getUnsignedRange(Trunc->getOperand());
3839 return setUnsignedRange(Trunc,
3840 ConservativeResult.intersectWith(X.truncate(BitWidth)));
3843 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
3844 // If there's no unsigned wrap, the value will never be less than its
3846 if (AddRec->getNoWrapFlags(SCEV::FlagNUW))
3847 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
3848 if (!C->getValue()->isZero())
3849 ConservativeResult =
3850 ConservativeResult.intersectWith(
3851 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0)));
3853 // TODO: non-affine addrec
3854 if (AddRec->isAffine()) {
3855 Type *Ty = AddRec->getType();
3856 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
3857 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3858 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
3859 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3861 const SCEV *Start = AddRec->getStart();
3862 const SCEV *Step = AddRec->getStepRecurrence(*this);
3864 ConstantRange StartRange = getUnsignedRange(Start);
3865 ConstantRange StepRange = getSignedRange(Step);
3866 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3867 ConstantRange EndRange =
3868 StartRange.add(MaxBECountRange.multiply(StepRange));
3870 // Check for overflow. This must be done with ConstantRange arithmetic
3871 // because we could be called from within the ScalarEvolution overflow
3873 ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
3874 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3875 ConstantRange ExtMaxBECountRange =
3876 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3877 ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
3878 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3880 return setUnsignedRange(AddRec, ConservativeResult);
3882 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
3883 EndRange.getUnsignedMin());
3884 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
3885 EndRange.getUnsignedMax());
3886 if (Min.isMinValue() && Max.isMaxValue())
3887 return setUnsignedRange(AddRec, ConservativeResult);
3888 return setUnsignedRange(AddRec,
3889 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
3893 return setUnsignedRange(AddRec, ConservativeResult);
3896 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3897 // Check if the IR explicitly contains !range metadata.
3898 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
3899 if (MDRange.hasValue())
3900 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
3902 // For a SCEVUnknown, ask ValueTracking.
3903 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3904 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, AT, nullptr, DT);
3905 if (Ones == ~Zeros + 1)
3906 return setUnsignedRange(U, ConservativeResult);
3907 return setUnsignedRange(U,
3908 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)));
3911 return setUnsignedRange(S, ConservativeResult);
3914 /// getSignedRange - Determine the signed range for a particular SCEV.
3917 ScalarEvolution::getSignedRange(const SCEV *S) {
3918 // See if we've computed this range already.
3919 DenseMap<const SCEV *, ConstantRange>::iterator I = SignedRanges.find(S);
3920 if (I != SignedRanges.end())
3923 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
3924 return setSignedRange(C, ConstantRange(C->getValue()->getValue()));
3926 unsigned BitWidth = getTypeSizeInBits(S->getType());
3927 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3929 // If the value has known zeros, the maximum signed value will have those
3930 // known zeros as well.
3931 uint32_t TZ = GetMinTrailingZeros(S);
3933 ConservativeResult =
3934 ConstantRange(APInt::getSignedMinValue(BitWidth),
3935 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
3937 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3938 ConstantRange X = getSignedRange(Add->getOperand(0));
3939 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3940 X = X.add(getSignedRange(Add->getOperand(i)));
3941 return setSignedRange(Add, ConservativeResult.intersectWith(X));
3944 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3945 ConstantRange X = getSignedRange(Mul->getOperand(0));
3946 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3947 X = X.multiply(getSignedRange(Mul->getOperand(i)));
3948 return setSignedRange(Mul, ConservativeResult.intersectWith(X));
3951 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3952 ConstantRange X = getSignedRange(SMax->getOperand(0));
3953 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3954 X = X.smax(getSignedRange(SMax->getOperand(i)));
3955 return setSignedRange(SMax, ConservativeResult.intersectWith(X));
3958 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3959 ConstantRange X = getSignedRange(UMax->getOperand(0));
3960 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3961 X = X.umax(getSignedRange(UMax->getOperand(i)));
3962 return setSignedRange(UMax, ConservativeResult.intersectWith(X));
3965 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3966 ConstantRange X = getSignedRange(UDiv->getLHS());
3967 ConstantRange Y = getSignedRange(UDiv->getRHS());
3968 return setSignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
3971 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3972 ConstantRange X = getSignedRange(ZExt->getOperand());
3973 return setSignedRange(ZExt,
3974 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
3977 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3978 ConstantRange X = getSignedRange(SExt->getOperand());
3979 return setSignedRange(SExt,
3980 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
3983 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3984 ConstantRange X = getSignedRange(Trunc->getOperand());
3985 return setSignedRange(Trunc,
3986 ConservativeResult.intersectWith(X.truncate(BitWidth)));
3989 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
3990 // If there's no signed wrap, and all the operands have the same sign or
3991 // zero, the value won't ever change sign.
3992 if (AddRec->getNoWrapFlags(SCEV::FlagNSW)) {
3993 bool AllNonNeg = true;
3994 bool AllNonPos = true;
3995 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3996 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3997 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
4000 ConservativeResult = ConservativeResult.intersectWith(
4001 ConstantRange(APInt(BitWidth, 0),
4002 APInt::getSignedMinValue(BitWidth)));
4004 ConservativeResult = ConservativeResult.intersectWith(
4005 ConstantRange(APInt::getSignedMinValue(BitWidth),
4006 APInt(BitWidth, 1)));
4009 // TODO: non-affine addrec
4010 if (AddRec->isAffine()) {
4011 Type *Ty = AddRec->getType();
4012 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
4013 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
4014 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
4015 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
4017 const SCEV *Start = AddRec->getStart();
4018 const SCEV *Step = AddRec->getStepRecurrence(*this);
4020 ConstantRange StartRange = getSignedRange(Start);
4021 ConstantRange StepRange = getSignedRange(Step);
4022 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
4023 ConstantRange EndRange =
4024 StartRange.add(MaxBECountRange.multiply(StepRange));
4026 // Check for overflow. This must be done with ConstantRange arithmetic
4027 // because we could be called from within the ScalarEvolution overflow
4029 ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
4030 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
4031 ConstantRange ExtMaxBECountRange =
4032 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
4033 ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
4034 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
4036 return setSignedRange(AddRec, ConservativeResult);
4038 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
4039 EndRange.getSignedMin());
4040 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
4041 EndRange.getSignedMax());
4042 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
4043 return setSignedRange(AddRec, ConservativeResult);
4044 return setSignedRange(AddRec,
4045 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
4049 return setSignedRange(AddRec, ConservativeResult);
4052 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4053 // Check if the IR explicitly contains !range metadata.
4054 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
4055 if (MDRange.hasValue())
4056 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
4058 // For a SCEVUnknown, ask ValueTracking.
4059 if (!U->getValue()->getType()->isIntegerTy() && !DL)
4060 return setSignedRange(U, ConservativeResult);
4061 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, AT, nullptr, DT);
4063 return setSignedRange(U, ConservativeResult);
4064 return setSignedRange(U, ConservativeResult.intersectWith(
4065 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
4066 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1)));
4069 return setSignedRange(S, ConservativeResult);
4072 /// createSCEV - We know that there is no SCEV for the specified value.
4073 /// Analyze the expression.
4075 const SCEV *ScalarEvolution::createSCEV(Value *V) {
4076 if (!isSCEVable(V->getType()))
4077 return getUnknown(V);
4079 unsigned Opcode = Instruction::UserOp1;
4080 if (Instruction *I = dyn_cast<Instruction>(V)) {
4081 Opcode = I->getOpcode();
4083 // Don't attempt to analyze instructions in blocks that aren't
4084 // reachable. Such instructions don't matter, and they aren't required
4085 // to obey basic rules for definitions dominating uses which this
4086 // analysis depends on.
4087 if (!DT->isReachableFromEntry(I->getParent()))
4088 return getUnknown(V);
4089 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
4090 Opcode = CE->getOpcode();
4091 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
4092 return getConstant(CI);
4093 else if (isa<ConstantPointerNull>(V))
4094 return getConstant(V->getType(), 0);
4095 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
4096 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
4098 return getUnknown(V);
4100 Operator *U = cast<Operator>(V);
4102 case Instruction::Add: {
4103 // The simple thing to do would be to just call getSCEV on both operands
4104 // and call getAddExpr with the result. However if we're looking at a
4105 // bunch of things all added together, this can be quite inefficient,
4106 // because it leads to N-1 getAddExpr calls for N ultimate operands.
4107 // Instead, gather up all the operands and make a single getAddExpr call.
4108 // LLVM IR canonical form means we need only traverse the left operands.
4110 // Don't apply this instruction's NSW or NUW flags to the new
4111 // expression. The instruction may be guarded by control flow that the
4112 // no-wrap behavior depends on. Non-control-equivalent instructions can be
4113 // mapped to the same SCEV expression, and it would be incorrect to transfer
4114 // NSW/NUW semantics to those operations.
4115 SmallVector<const SCEV *, 4> AddOps;
4116 AddOps.push_back(getSCEV(U->getOperand(1)));
4117 for (Value *Op = U->getOperand(0); ; Op = U->getOperand(0)) {
4118 unsigned Opcode = Op->getValueID() - Value::InstructionVal;
4119 if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
4121 U = cast<Operator>(Op);
4122 const SCEV *Op1 = getSCEV(U->getOperand(1));
4123 if (Opcode == Instruction::Sub)
4124 AddOps.push_back(getNegativeSCEV(Op1));
4126 AddOps.push_back(Op1);
4128 AddOps.push_back(getSCEV(U->getOperand(0)));
4129 return getAddExpr(AddOps);
4131 case Instruction::Mul: {
4132 // Don't transfer NSW/NUW for the same reason as AddExpr.
4133 SmallVector<const SCEV *, 4> MulOps;
4134 MulOps.push_back(getSCEV(U->getOperand(1)));
4135 for (Value *Op = U->getOperand(0);
4136 Op->getValueID() == Instruction::Mul + Value::InstructionVal;
4137 Op = U->getOperand(0)) {
4138 U = cast<Operator>(Op);
4139 MulOps.push_back(getSCEV(U->getOperand(1)));
4141 MulOps.push_back(getSCEV(U->getOperand(0)));
4142 return getMulExpr(MulOps);
4144 case Instruction::UDiv:
4145 return getUDivExpr(getSCEV(U->getOperand(0)),
4146 getSCEV(U->getOperand(1)));
4147 case Instruction::Sub:
4148 return getMinusSCEV(getSCEV(U->getOperand(0)),
4149 getSCEV(U->getOperand(1)));
4150 case Instruction::And:
4151 // For an expression like x&255 that merely masks off the high bits,
4152 // use zext(trunc(x)) as the SCEV expression.
4153 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
4154 if (CI->isNullValue())
4155 return getSCEV(U->getOperand(1));
4156 if (CI->isAllOnesValue())
4157 return getSCEV(U->getOperand(0));
4158 const APInt &A = CI->getValue();
4160 // Instcombine's ShrinkDemandedConstant may strip bits out of
4161 // constants, obscuring what would otherwise be a low-bits mask.
4162 // Use computeKnownBits to compute what ShrinkDemandedConstant
4163 // knew about to reconstruct a low-bits mask value.
4164 unsigned LZ = A.countLeadingZeros();
4165 unsigned TZ = A.countTrailingZeros();
4166 unsigned BitWidth = A.getBitWidth();
4167 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4168 computeKnownBits(U->getOperand(0), KnownZero, KnownOne, DL,
4169 0, AT, nullptr, DT);
4171 APInt EffectiveMask =
4172 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
4173 if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) {
4174 const SCEV *MulCount = getConstant(
4175 ConstantInt::get(getContext(), APInt::getOneBitSet(BitWidth, TZ)));
4179 getUDivExactExpr(getSCEV(U->getOperand(0)), MulCount),
4180 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
4187 case Instruction::Or:
4188 // If the RHS of the Or is a constant, we may have something like:
4189 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
4190 // optimizations will transparently handle this case.
4192 // In order for this transformation to be safe, the LHS must be of the
4193 // form X*(2^n) and the Or constant must be less than 2^n.
4194 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
4195 const SCEV *LHS = getSCEV(U->getOperand(0));
4196 const APInt &CIVal = CI->getValue();
4197 if (GetMinTrailingZeros(LHS) >=
4198 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
4199 // Build a plain add SCEV.
4200 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
4201 // If the LHS of the add was an addrec and it has no-wrap flags,
4202 // transfer the no-wrap flags, since an or won't introduce a wrap.
4203 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
4204 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
4205 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
4206 OldAR->getNoWrapFlags());
4212 case Instruction::Xor:
4213 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
4214 // If the RHS of the xor is a signbit, then this is just an add.
4215 // Instcombine turns add of signbit into xor as a strength reduction step.
4216 if (CI->getValue().isSignBit())
4217 return getAddExpr(getSCEV(U->getOperand(0)),
4218 getSCEV(U->getOperand(1)));
4220 // If the RHS of xor is -1, then this is a not operation.
4221 if (CI->isAllOnesValue())
4222 return getNotSCEV(getSCEV(U->getOperand(0)));
4224 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
4225 // This is a variant of the check for xor with -1, and it handles
4226 // the case where instcombine has trimmed non-demanded bits out
4227 // of an xor with -1.
4228 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
4229 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
4230 if (BO->getOpcode() == Instruction::And &&
4231 LCI->getValue() == CI->getValue())
4232 if (const SCEVZeroExtendExpr *Z =
4233 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
4234 Type *UTy = U->getType();
4235 const SCEV *Z0 = Z->getOperand();
4236 Type *Z0Ty = Z0->getType();
4237 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
4239 // If C is a low-bits mask, the zero extend is serving to
4240 // mask off the high bits. Complement the operand and
4241 // re-apply the zext.
4242 if (APIntOps::isMask(Z0TySize, CI->getValue()))
4243 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
4245 // If C is a single bit, it may be in the sign-bit position
4246 // before the zero-extend. In this case, represent the xor
4247 // using an add, which is equivalent, and re-apply the zext.
4248 APInt Trunc = CI->getValue().trunc(Z0TySize);
4249 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
4251 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
4257 case Instruction::Shl:
4258 // Turn shift left of a constant amount into a multiply.
4259 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
4260 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
4262 // If the shift count is not less than the bitwidth, the result of
4263 // the shift is undefined. Don't try to analyze it, because the
4264 // resolution chosen here may differ from the resolution chosen in
4265 // other parts of the compiler.
4266 if (SA->getValue().uge(BitWidth))
4269 Constant *X = ConstantInt::get(getContext(),
4270 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4271 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
4275 case Instruction::LShr:
4276 // Turn logical shift right of a constant into a unsigned divide.
4277 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
4278 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
4280 // If the shift count is not less than the bitwidth, the result of
4281 // the shift is undefined. Don't try to analyze it, because the
4282 // resolution chosen here may differ from the resolution chosen in
4283 // other parts of the compiler.
4284 if (SA->getValue().uge(BitWidth))
4287 Constant *X = ConstantInt::get(getContext(),
4288 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4289 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
4293 case Instruction::AShr:
4294 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
4295 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
4296 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
4297 if (L->getOpcode() == Instruction::Shl &&
4298 L->getOperand(1) == U->getOperand(1)) {
4299 uint64_t BitWidth = getTypeSizeInBits(U->getType());
4301 // If the shift count is not less than the bitwidth, the result of
4302 // the shift is undefined. Don't try to analyze it, because the
4303 // resolution chosen here may differ from the resolution chosen in
4304 // other parts of the compiler.
4305 if (CI->getValue().uge(BitWidth))
4308 uint64_t Amt = BitWidth - CI->getZExtValue();
4309 if (Amt == BitWidth)
4310 return getSCEV(L->getOperand(0)); // shift by zero --> noop
4312 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
4313 IntegerType::get(getContext(),
4319 case Instruction::Trunc:
4320 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
4322 case Instruction::ZExt:
4323 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
4325 case Instruction::SExt:
4326 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
4328 case Instruction::BitCast:
4329 // BitCasts are no-op casts so we just eliminate the cast.
4330 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
4331 return getSCEV(U->getOperand(0));
4334 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
4335 // lead to pointer expressions which cannot safely be expanded to GEPs,
4336 // because ScalarEvolution doesn't respect the GEP aliasing rules when
4337 // simplifying integer expressions.
4339 case Instruction::GetElementPtr:
4340 return createNodeForGEP(cast<GEPOperator>(U));
4342 case Instruction::PHI:
4343 return createNodeForPHI(cast<PHINode>(U));
4345 case Instruction::Select:
4346 // This could be a smax or umax that was lowered earlier.
4347 // Try to recover it.
4348 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
4349 Value *LHS = ICI->getOperand(0);
4350 Value *RHS = ICI->getOperand(1);
4351 switch (ICI->getPredicate()) {
4352 case ICmpInst::ICMP_SLT:
4353 case ICmpInst::ICMP_SLE:
4354 std::swap(LHS, RHS);
4356 case ICmpInst::ICMP_SGT:
4357 case ICmpInst::ICMP_SGE:
4358 // a >s b ? a+x : b+x -> smax(a, b)+x
4359 // a >s b ? b+x : a+x -> smin(a, b)+x
4360 if (LHS->getType() == U->getType()) {
4361 const SCEV *LS = getSCEV(LHS);
4362 const SCEV *RS = getSCEV(RHS);
4363 const SCEV *LA = getSCEV(U->getOperand(1));
4364 const SCEV *RA = getSCEV(U->getOperand(2));
4365 const SCEV *LDiff = getMinusSCEV(LA, LS);
4366 const SCEV *RDiff = getMinusSCEV(RA, RS);
4368 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
4369 LDiff = getMinusSCEV(LA, RS);
4370 RDiff = getMinusSCEV(RA, LS);
4372 return getAddExpr(getSMinExpr(LS, RS), LDiff);
4375 case ICmpInst::ICMP_ULT:
4376 case ICmpInst::ICMP_ULE:
4377 std::swap(LHS, RHS);
4379 case ICmpInst::ICMP_UGT:
4380 case ICmpInst::ICMP_UGE:
4381 // a >u b ? a+x : b+x -> umax(a, b)+x
4382 // a >u b ? b+x : a+x -> umin(a, b)+x
4383 if (LHS->getType() == U->getType()) {
4384 const SCEV *LS = getSCEV(LHS);
4385 const SCEV *RS = getSCEV(RHS);
4386 const SCEV *LA = getSCEV(U->getOperand(1));
4387 const SCEV *RA = getSCEV(U->getOperand(2));
4388 const SCEV *LDiff = getMinusSCEV(LA, LS);
4389 const SCEV *RDiff = getMinusSCEV(RA, RS);
4391 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4392 LDiff = getMinusSCEV(LA, RS);
4393 RDiff = getMinusSCEV(RA, LS);
4395 return getAddExpr(getUMinExpr(LS, RS), LDiff);
4398 case ICmpInst::ICMP_NE:
4399 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
4400 if (LHS->getType() == U->getType() &&
4401 isa<ConstantInt>(RHS) &&
4402 cast<ConstantInt>(RHS)->isZero()) {
4403 const SCEV *One = getConstant(LHS->getType(), 1);
4404 const SCEV *LS = getSCEV(LHS);
4405 const SCEV *LA = getSCEV(U->getOperand(1));
4406 const SCEV *RA = getSCEV(U->getOperand(2));
4407 const SCEV *LDiff = getMinusSCEV(LA, LS);
4408 const SCEV *RDiff = getMinusSCEV(RA, One);
4410 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4413 case ICmpInst::ICMP_EQ:
4414 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
4415 if (LHS->getType() == U->getType() &&
4416 isa<ConstantInt>(RHS) &&
4417 cast<ConstantInt>(RHS)->isZero()) {
4418 const SCEV *One = getConstant(LHS->getType(), 1);
4419 const SCEV *LS = getSCEV(LHS);
4420 const SCEV *LA = getSCEV(U->getOperand(1));
4421 const SCEV *RA = getSCEV(U->getOperand(2));
4422 const SCEV *LDiff = getMinusSCEV(LA, One);
4423 const SCEV *RDiff = getMinusSCEV(RA, LS);
4425 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4433 default: // We cannot analyze this expression.
4437 return getUnknown(V);
4442 //===----------------------------------------------------------------------===//
4443 // Iteration Count Computation Code
4446 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) {
4447 if (BasicBlock *ExitingBB = L->getExitingBlock())
4448 return getSmallConstantTripCount(L, ExitingBB);
4450 // No trip count information for multiple exits.
4454 /// getSmallConstantTripCount - Returns the maximum trip count of this loop as a
4455 /// normal unsigned value. Returns 0 if the trip count is unknown or not
4456 /// constant. Will also return 0 if the maximum trip count is very large (>=
4459 /// This "trip count" assumes that control exits via ExitingBlock. More
4460 /// precisely, it is the number of times that control may reach ExitingBlock
4461 /// before taking the branch. For loops with multiple exits, it may not be the
4462 /// number times that the loop header executes because the loop may exit
4463 /// prematurely via another branch.
4464 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L,
4465 BasicBlock *ExitingBlock) {
4466 assert(ExitingBlock && "Must pass a non-null exiting block!");
4467 assert(L->isLoopExiting(ExitingBlock) &&
4468 "Exiting block must actually branch out of the loop!");
4469 const SCEVConstant *ExitCount =
4470 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
4474 ConstantInt *ExitConst = ExitCount->getValue();
4476 // Guard against huge trip counts.
4477 if (ExitConst->getValue().getActiveBits() > 32)
4480 // In case of integer overflow, this returns 0, which is correct.
4481 return ((unsigned)ExitConst->getZExtValue()) + 1;
4484 unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) {
4485 if (BasicBlock *ExitingBB = L->getExitingBlock())
4486 return getSmallConstantTripMultiple(L, ExitingBB);
4488 // No trip multiple information for multiple exits.
4492 /// getSmallConstantTripMultiple - Returns the largest constant divisor of the
4493 /// trip count of this loop as a normal unsigned value, if possible. This
4494 /// means that the actual trip count is always a multiple of the returned
4495 /// value (don't forget the trip count could very well be zero as well!).
4497 /// Returns 1 if the trip count is unknown or not guaranteed to be the
4498 /// multiple of a constant (which is also the case if the trip count is simply
4499 /// constant, use getSmallConstantTripCount for that case), Will also return 1
4500 /// if the trip count is very large (>= 2^32).
4502 /// As explained in the comments for getSmallConstantTripCount, this assumes
4503 /// that control exits the loop via ExitingBlock.
4505 ScalarEvolution::getSmallConstantTripMultiple(Loop *L,
4506 BasicBlock *ExitingBlock) {
4507 assert(ExitingBlock && "Must pass a non-null exiting block!");
4508 assert(L->isLoopExiting(ExitingBlock) &&
4509 "Exiting block must actually branch out of the loop!");
4510 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
4511 if (ExitCount == getCouldNotCompute())
4514 // Get the trip count from the BE count by adding 1.
4515 const SCEV *TCMul = getAddExpr(ExitCount,
4516 getConstant(ExitCount->getType(), 1));
4517 // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt
4518 // to factor simple cases.
4519 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul))
4520 TCMul = Mul->getOperand(0);
4522 const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul);
4526 ConstantInt *Result = MulC->getValue();
4528 // Guard against huge trip counts (this requires checking
4529 // for zero to handle the case where the trip count == -1 and the
4531 if (!Result || Result->getValue().getActiveBits() > 32 ||
4532 Result->getValue().getActiveBits() == 0)
4535 return (unsigned)Result->getZExtValue();
4538 // getExitCount - Get the expression for the number of loop iterations for which
4539 // this loop is guaranteed not to exit via ExitingBlock. Otherwise return
4540 // SCEVCouldNotCompute.
4541 const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) {
4542 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
4545 /// getBackedgeTakenCount - If the specified loop has a predictable
4546 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
4547 /// object. The backedge-taken count is the number of times the loop header
4548 /// will be branched to from within the loop. This is one less than the
4549 /// trip count of the loop, since it doesn't count the first iteration,
4550 /// when the header is branched to from outside the loop.
4552 /// Note that it is not valid to call this method on a loop without a
4553 /// loop-invariant backedge-taken count (see
4554 /// hasLoopInvariantBackedgeTakenCount).
4556 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
4557 return getBackedgeTakenInfo(L).getExact(this);
4560 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
4561 /// return the least SCEV value that is known never to be less than the
4562 /// actual backedge taken count.
4563 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
4564 return getBackedgeTakenInfo(L).getMax(this);
4567 /// PushLoopPHIs - Push PHI nodes in the header of the given loop
4568 /// onto the given Worklist.
4570 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
4571 BasicBlock *Header = L->getHeader();
4573 // Push all Loop-header PHIs onto the Worklist stack.
4574 for (BasicBlock::iterator I = Header->begin();
4575 PHINode *PN = dyn_cast<PHINode>(I); ++I)
4576 Worklist.push_back(PN);
4579 const ScalarEvolution::BackedgeTakenInfo &
4580 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
4581 // Initially insert an invalid entry for this loop. If the insertion
4582 // succeeds, proceed to actually compute a backedge-taken count and
4583 // update the value. The temporary CouldNotCompute value tells SCEV
4584 // code elsewhere that it shouldn't attempt to request a new
4585 // backedge-taken count, which could result in infinite recursion.
4586 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
4587 BackedgeTakenCounts.insert(std::make_pair(L, BackedgeTakenInfo()));
4589 return Pair.first->second;
4591 // ComputeBackedgeTakenCount may allocate memory for its result. Inserting it
4592 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
4593 // must be cleared in this scope.
4594 BackedgeTakenInfo Result = ComputeBackedgeTakenCount(L);
4596 if (Result.getExact(this) != getCouldNotCompute()) {
4597 assert(isLoopInvariant(Result.getExact(this), L) &&
4598 isLoopInvariant(Result.getMax(this), L) &&
4599 "Computed backedge-taken count isn't loop invariant for loop!");
4600 ++NumTripCountsComputed;
4602 else if (Result.getMax(this) == getCouldNotCompute() &&
4603 isa<PHINode>(L->getHeader()->begin())) {
4604 // Only count loops that have phi nodes as not being computable.
4605 ++NumTripCountsNotComputed;
4608 // Now that we know more about the trip count for this loop, forget any
4609 // existing SCEV values for PHI nodes in this loop since they are only
4610 // conservative estimates made without the benefit of trip count
4611 // information. This is similar to the code in forgetLoop, except that
4612 // it handles SCEVUnknown PHI nodes specially.
4613 if (Result.hasAnyInfo()) {
4614 SmallVector<Instruction *, 16> Worklist;
4615 PushLoopPHIs(L, Worklist);
4617 SmallPtrSet<Instruction *, 8> Visited;
4618 while (!Worklist.empty()) {
4619 Instruction *I = Worklist.pop_back_val();
4620 if (!Visited.insert(I).second)
4623 ValueExprMapType::iterator It =
4624 ValueExprMap.find_as(static_cast<Value *>(I));
4625 if (It != ValueExprMap.end()) {
4626 const SCEV *Old = It->second;
4628 // SCEVUnknown for a PHI either means that it has an unrecognized
4629 // structure, or it's a PHI that's in the progress of being computed
4630 // by createNodeForPHI. In the former case, additional loop trip
4631 // count information isn't going to change anything. In the later
4632 // case, createNodeForPHI will perform the necessary updates on its
4633 // own when it gets to that point.
4634 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
4635 forgetMemoizedResults(Old);
4636 ValueExprMap.erase(It);
4638 if (PHINode *PN = dyn_cast<PHINode>(I))
4639 ConstantEvolutionLoopExitValue.erase(PN);
4642 PushDefUseChildren(I, Worklist);
4646 // Re-lookup the insert position, since the call to
4647 // ComputeBackedgeTakenCount above could result in a
4648 // recusive call to getBackedgeTakenInfo (on a different
4649 // loop), which would invalidate the iterator computed
4651 return BackedgeTakenCounts.find(L)->second = Result;
4654 /// forgetLoop - This method should be called by the client when it has
4655 /// changed a loop in a way that may effect ScalarEvolution's ability to
4656 /// compute a trip count, or if the loop is deleted.
4657 void ScalarEvolution::forgetLoop(const Loop *L) {
4658 // Drop any stored trip count value.
4659 DenseMap<const Loop*, BackedgeTakenInfo>::iterator BTCPos =
4660 BackedgeTakenCounts.find(L);
4661 if (BTCPos != BackedgeTakenCounts.end()) {
4662 BTCPos->second.clear();
4663 BackedgeTakenCounts.erase(BTCPos);
4666 // Drop information about expressions based on loop-header PHIs.
4667 SmallVector<Instruction *, 16> Worklist;
4668 PushLoopPHIs(L, Worklist);
4670 SmallPtrSet<Instruction *, 8> Visited;
4671 while (!Worklist.empty()) {
4672 Instruction *I = Worklist.pop_back_val();
4673 if (!Visited.insert(I).second)
4676 ValueExprMapType::iterator It =
4677 ValueExprMap.find_as(static_cast<Value *>(I));
4678 if (It != ValueExprMap.end()) {
4679 forgetMemoizedResults(It->second);
4680 ValueExprMap.erase(It);
4681 if (PHINode *PN = dyn_cast<PHINode>(I))
4682 ConstantEvolutionLoopExitValue.erase(PN);
4685 PushDefUseChildren(I, Worklist);
4688 // Forget all contained loops too, to avoid dangling entries in the
4689 // ValuesAtScopes map.
4690 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4694 /// forgetValue - This method should be called by the client when it has
4695 /// changed a value in a way that may effect its value, or which may
4696 /// disconnect it from a def-use chain linking it to a loop.
4697 void ScalarEvolution::forgetValue(Value *V) {
4698 Instruction *I = dyn_cast<Instruction>(V);
4701 // Drop information about expressions based on loop-header PHIs.
4702 SmallVector<Instruction *, 16> Worklist;
4703 Worklist.push_back(I);
4705 SmallPtrSet<Instruction *, 8> Visited;
4706 while (!Worklist.empty()) {
4707 I = Worklist.pop_back_val();
4708 if (!Visited.insert(I).second)
4711 ValueExprMapType::iterator It =
4712 ValueExprMap.find_as(static_cast<Value *>(I));
4713 if (It != ValueExprMap.end()) {
4714 forgetMemoizedResults(It->second);
4715 ValueExprMap.erase(It);
4716 if (PHINode *PN = dyn_cast<PHINode>(I))
4717 ConstantEvolutionLoopExitValue.erase(PN);
4720 PushDefUseChildren(I, Worklist);
4724 /// getExact - Get the exact loop backedge taken count considering all loop
4725 /// exits. A computable result can only be return for loops with a single exit.
4726 /// Returning the minimum taken count among all exits is incorrect because one
4727 /// of the loop's exit limit's may have been skipped. HowFarToZero assumes that
4728 /// the limit of each loop test is never skipped. This is a valid assumption as
4729 /// long as the loop exits via that test. For precise results, it is the
4730 /// caller's responsibility to specify the relevant loop exit using
4731 /// getExact(ExitingBlock, SE).
4733 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE) const {
4734 // If any exits were not computable, the loop is not computable.
4735 if (!ExitNotTaken.isCompleteList()) return SE->getCouldNotCompute();
4737 // We need exactly one computable exit.
4738 if (!ExitNotTaken.ExitingBlock) return SE->getCouldNotCompute();
4739 assert(ExitNotTaken.ExactNotTaken && "uninitialized not-taken info");
4741 const SCEV *BECount = nullptr;
4742 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
4743 ENT != nullptr; ENT = ENT->getNextExit()) {
4745 assert(ENT->ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
4748 BECount = ENT->ExactNotTaken;
4749 else if (BECount != ENT->ExactNotTaken)
4750 return SE->getCouldNotCompute();
4752 assert(BECount && "Invalid not taken count for loop exit");
4756 /// getExact - Get the exact not taken count for this loop exit.
4758 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
4759 ScalarEvolution *SE) const {
4760 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
4761 ENT != nullptr; ENT = ENT->getNextExit()) {
4763 if (ENT->ExitingBlock == ExitingBlock)
4764 return ENT->ExactNotTaken;
4766 return SE->getCouldNotCompute();
4769 /// getMax - Get the max backedge taken count for the loop.
4771 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
4772 return Max ? Max : SE->getCouldNotCompute();
4775 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
4776 ScalarEvolution *SE) const {
4777 if (Max && Max != SE->getCouldNotCompute() && SE->hasOperand(Max, S))
4780 if (!ExitNotTaken.ExitingBlock)
4783 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
4784 ENT != nullptr; ENT = ENT->getNextExit()) {
4786 if (ENT->ExactNotTaken != SE->getCouldNotCompute()
4787 && SE->hasOperand(ENT->ExactNotTaken, S)) {
4794 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
4795 /// computable exit into a persistent ExitNotTakenInfo array.
4796 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
4797 SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts,
4798 bool Complete, const SCEV *MaxCount) : Max(MaxCount) {
4801 ExitNotTaken.setIncomplete();
4803 unsigned NumExits = ExitCounts.size();
4804 if (NumExits == 0) return;
4806 ExitNotTaken.ExitingBlock = ExitCounts[0].first;
4807 ExitNotTaken.ExactNotTaken = ExitCounts[0].second;
4808 if (NumExits == 1) return;
4810 // Handle the rare case of multiple computable exits.
4811 ExitNotTakenInfo *ENT = new ExitNotTakenInfo[NumExits-1];
4813 ExitNotTakenInfo *PrevENT = &ExitNotTaken;
4814 for (unsigned i = 1; i < NumExits; ++i, PrevENT = ENT, ++ENT) {
4815 PrevENT->setNextExit(ENT);
4816 ENT->ExitingBlock = ExitCounts[i].first;
4817 ENT->ExactNotTaken = ExitCounts[i].second;
4821 /// clear - Invalidate this result and free the ExitNotTakenInfo array.
4822 void ScalarEvolution::BackedgeTakenInfo::clear() {
4823 ExitNotTaken.ExitingBlock = nullptr;
4824 ExitNotTaken.ExactNotTaken = nullptr;
4825 delete[] ExitNotTaken.getNextExit();
4828 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
4829 /// of the specified loop will execute.
4830 ScalarEvolution::BackedgeTakenInfo
4831 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
4832 SmallVector<BasicBlock *, 8> ExitingBlocks;
4833 L->getExitingBlocks(ExitingBlocks);
4835 SmallVector<std::pair<BasicBlock *, const SCEV *>, 4> ExitCounts;
4836 bool CouldComputeBECount = true;
4837 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
4838 const SCEV *MustExitMaxBECount = nullptr;
4839 const SCEV *MayExitMaxBECount = nullptr;
4841 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
4842 // and compute maxBECount.
4843 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
4844 BasicBlock *ExitBB = ExitingBlocks[i];
4845 ExitLimit EL = ComputeExitLimit(L, ExitBB);
4847 // 1. For each exit that can be computed, add an entry to ExitCounts.
4848 // CouldComputeBECount is true only if all exits can be computed.
4849 if (EL.Exact == getCouldNotCompute())
4850 // We couldn't compute an exact value for this exit, so
4851 // we won't be able to compute an exact value for the loop.
4852 CouldComputeBECount = false;
4854 ExitCounts.push_back(std::make_pair(ExitBB, EL.Exact));
4856 // 2. Derive the loop's MaxBECount from each exit's max number of
4857 // non-exiting iterations. Partition the loop exits into two kinds:
4858 // LoopMustExits and LoopMayExits.
4860 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
4861 // is a LoopMayExit. If any computable LoopMustExit is found, then
4862 // MaxBECount is the minimum EL.Max of computable LoopMustExits. Otherwise,
4863 // MaxBECount is conservatively the maximum EL.Max, where CouldNotCompute is
4864 // considered greater than any computable EL.Max.
4865 if (EL.Max != getCouldNotCompute() && Latch &&
4866 DT->dominates(ExitBB, Latch)) {
4867 if (!MustExitMaxBECount)
4868 MustExitMaxBECount = EL.Max;
4870 MustExitMaxBECount =
4871 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.Max);
4873 } else if (MayExitMaxBECount != getCouldNotCompute()) {
4874 if (!MayExitMaxBECount || EL.Max == getCouldNotCompute())
4875 MayExitMaxBECount = EL.Max;
4878 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.Max);
4882 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
4883 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
4884 return BackedgeTakenInfo(ExitCounts, CouldComputeBECount, MaxBECount);
4887 /// ComputeExitLimit - Compute the number of times the backedge of the specified
4888 /// loop will execute if it exits via the specified block.
4889 ScalarEvolution::ExitLimit
4890 ScalarEvolution::ComputeExitLimit(const Loop *L, BasicBlock *ExitingBlock) {
4892 // Okay, we've chosen an exiting block. See what condition causes us to
4893 // exit at this block and remember the exit block and whether all other targets
4894 // lead to the loop header.
4895 bool MustExecuteLoopHeader = true;
4896 BasicBlock *Exit = nullptr;
4897 for (succ_iterator SI = succ_begin(ExitingBlock), SE = succ_end(ExitingBlock);
4899 if (!L->contains(*SI)) {
4900 if (Exit) // Multiple exit successors.
4901 return getCouldNotCompute();
4903 } else if (*SI != L->getHeader()) {
4904 MustExecuteLoopHeader = false;
4907 // At this point, we know we have a conditional branch that determines whether
4908 // the loop is exited. However, we don't know if the branch is executed each
4909 // time through the loop. If not, then the execution count of the branch will
4910 // not be equal to the trip count of the loop.
4912 // Currently we check for this by checking to see if the Exit branch goes to
4913 // the loop header. If so, we know it will always execute the same number of
4914 // times as the loop. We also handle the case where the exit block *is* the
4915 // loop header. This is common for un-rotated loops.
4917 // If both of those tests fail, walk up the unique predecessor chain to the
4918 // header, stopping if there is an edge that doesn't exit the loop. If the
4919 // header is reached, the execution count of the branch will be equal to the
4920 // trip count of the loop.
4922 // More extensive analysis could be done to handle more cases here.
4924 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
4925 // The simple checks failed, try climbing the unique predecessor chain
4926 // up to the header.
4928 for (BasicBlock *BB = ExitingBlock; BB; ) {
4929 BasicBlock *Pred = BB->getUniquePredecessor();
4931 return getCouldNotCompute();
4932 TerminatorInst *PredTerm = Pred->getTerminator();
4933 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
4934 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
4937 // If the predecessor has a successor that isn't BB and isn't
4938 // outside the loop, assume the worst.
4939 if (L->contains(PredSucc))
4940 return getCouldNotCompute();
4942 if (Pred == L->getHeader()) {
4949 return getCouldNotCompute();
4952 bool IsOnlyExit = (L->getExitingBlock() != nullptr);
4953 TerminatorInst *Term = ExitingBlock->getTerminator();
4954 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
4955 assert(BI->isConditional() && "If unconditional, it can't be in loop!");
4956 // Proceed to the next level to examine the exit condition expression.
4957 return ComputeExitLimitFromCond(L, BI->getCondition(), BI->getSuccessor(0),
4958 BI->getSuccessor(1),
4959 /*ControlsExit=*/IsOnlyExit);
4962 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
4963 return ComputeExitLimitFromSingleExitSwitch(L, SI, Exit,
4964 /*ControlsExit=*/IsOnlyExit);
4966 return getCouldNotCompute();
4969 /// ComputeExitLimitFromCond - Compute the number of times the
4970 /// backedge of the specified loop will execute if its exit condition
4971 /// were a conditional branch of ExitCond, TBB, and FBB.
4973 /// @param ControlsExit is true if ExitCond directly controls the exit
4974 /// branch. In this case, we can assume that the loop exits only if the
4975 /// condition is true and can infer that failing to meet the condition prior to
4976 /// integer wraparound results in undefined behavior.
4977 ScalarEvolution::ExitLimit
4978 ScalarEvolution::ComputeExitLimitFromCond(const Loop *L,
4982 bool ControlsExit) {
4983 // Check if the controlling expression for this loop is an And or Or.
4984 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
4985 if (BO->getOpcode() == Instruction::And) {
4986 // Recurse on the operands of the and.
4987 bool EitherMayExit = L->contains(TBB);
4988 ExitLimit EL0 = ComputeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
4989 ControlsExit && !EitherMayExit);
4990 ExitLimit EL1 = ComputeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
4991 ControlsExit && !EitherMayExit);
4992 const SCEV *BECount = getCouldNotCompute();
4993 const SCEV *MaxBECount = getCouldNotCompute();
4994 if (EitherMayExit) {
4995 // Both conditions must be true for the loop to continue executing.
4996 // Choose the less conservative count.
4997 if (EL0.Exact == getCouldNotCompute() ||
4998 EL1.Exact == getCouldNotCompute())
4999 BECount = getCouldNotCompute();
5001 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
5002 if (EL0.Max == getCouldNotCompute())
5003 MaxBECount = EL1.Max;
5004 else if (EL1.Max == getCouldNotCompute())
5005 MaxBECount = EL0.Max;
5007 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
5009 // Both conditions must be true at the same time for the loop to exit.
5010 // For now, be conservative.
5011 assert(L->contains(FBB) && "Loop block has no successor in loop!");
5012 if (EL0.Max == EL1.Max)
5013 MaxBECount = EL0.Max;
5014 if (EL0.Exact == EL1.Exact)
5015 BECount = EL0.Exact;
5018 return ExitLimit(BECount, MaxBECount);
5020 if (BO->getOpcode() == Instruction::Or) {
5021 // Recurse on the operands of the or.
5022 bool EitherMayExit = L->contains(FBB);
5023 ExitLimit EL0 = ComputeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
5024 ControlsExit && !EitherMayExit);
5025 ExitLimit EL1 = ComputeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
5026 ControlsExit && !EitherMayExit);
5027 const SCEV *BECount = getCouldNotCompute();
5028 const SCEV *MaxBECount = getCouldNotCompute();
5029 if (EitherMayExit) {
5030 // Both conditions must be false for the loop to continue executing.
5031 // Choose the less conservative count.
5032 if (EL0.Exact == getCouldNotCompute() ||
5033 EL1.Exact == getCouldNotCompute())
5034 BECount = getCouldNotCompute();
5036 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
5037 if (EL0.Max == getCouldNotCompute())
5038 MaxBECount = EL1.Max;
5039 else if (EL1.Max == getCouldNotCompute())
5040 MaxBECount = EL0.Max;
5042 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
5044 // Both conditions must be false at the same time for the loop to exit.
5045 // For now, be conservative.
5046 assert(L->contains(TBB) && "Loop block has no successor in loop!");
5047 if (EL0.Max == EL1.Max)
5048 MaxBECount = EL0.Max;
5049 if (EL0.Exact == EL1.Exact)
5050 BECount = EL0.Exact;
5053 return ExitLimit(BECount, MaxBECount);
5057 // With an icmp, it may be feasible to compute an exact backedge-taken count.
5058 // Proceed to the next level to examine the icmp.
5059 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
5060 return ComputeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
5062 // Check for a constant condition. These are normally stripped out by
5063 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
5064 // preserve the CFG and is temporarily leaving constant conditions
5066 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
5067 if (L->contains(FBB) == !CI->getZExtValue())
5068 // The backedge is always taken.
5069 return getCouldNotCompute();
5071 // The backedge is never taken.
5072 return getConstant(CI->getType(), 0);
5075 // If it's not an integer or pointer comparison then compute it the hard way.
5076 return ComputeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
5079 /// ComputeExitLimitFromICmp - Compute the number of times the
5080 /// backedge of the specified loop will execute if its exit condition
5081 /// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
5082 ScalarEvolution::ExitLimit
5083 ScalarEvolution::ComputeExitLimitFromICmp(const Loop *L,
5087 bool ControlsExit) {
5089 // If the condition was exit on true, convert the condition to exit on false
5090 ICmpInst::Predicate Cond;
5091 if (!L->contains(FBB))
5092 Cond = ExitCond->getPredicate();
5094 Cond = ExitCond->getInversePredicate();
5096 // Handle common loops like: for (X = "string"; *X; ++X)
5097 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
5098 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
5100 ComputeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
5101 if (ItCnt.hasAnyInfo())
5105 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
5106 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
5108 // Try to evaluate any dependencies out of the loop.
5109 LHS = getSCEVAtScope(LHS, L);
5110 RHS = getSCEVAtScope(RHS, L);
5112 // At this point, we would like to compute how many iterations of the
5113 // loop the predicate will return true for these inputs.
5114 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
5115 // If there is a loop-invariant, force it into the RHS.
5116 std::swap(LHS, RHS);
5117 Cond = ICmpInst::getSwappedPredicate(Cond);
5120 // Simplify the operands before analyzing them.
5121 (void)SimplifyICmpOperands(Cond, LHS, RHS);
5123 // If we have a comparison of a chrec against a constant, try to use value
5124 // ranges to answer this query.
5125 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
5126 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
5127 if (AddRec->getLoop() == L) {
5128 // Form the constant range.
5129 ConstantRange CompRange(
5130 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
5132 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
5133 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
5137 case ICmpInst::ICMP_NE: { // while (X != Y)
5138 // Convert to: while (X-Y != 0)
5139 ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
5140 if (EL.hasAnyInfo()) return EL;
5143 case ICmpInst::ICMP_EQ: { // while (X == Y)
5144 // Convert to: while (X-Y == 0)
5145 ExitLimit EL = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
5146 if (EL.hasAnyInfo()) return EL;
5149 case ICmpInst::ICMP_SLT:
5150 case ICmpInst::ICMP_ULT: { // while (X < Y)
5151 bool IsSigned = Cond == ICmpInst::ICMP_SLT;
5152 ExitLimit EL = HowManyLessThans(LHS, RHS, L, IsSigned, ControlsExit);
5153 if (EL.hasAnyInfo()) return EL;
5156 case ICmpInst::ICMP_SGT:
5157 case ICmpInst::ICMP_UGT: { // while (X > Y)
5158 bool IsSigned = Cond == ICmpInst::ICMP_SGT;
5159 ExitLimit EL = HowManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit);
5160 if (EL.hasAnyInfo()) return EL;
5165 dbgs() << "ComputeBackedgeTakenCount ";
5166 if (ExitCond->getOperand(0)->getType()->isUnsigned())
5167 dbgs() << "[unsigned] ";
5168 dbgs() << *LHS << " "
5169 << Instruction::getOpcodeName(Instruction::ICmp)
5170 << " " << *RHS << "\n";
5174 return ComputeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
5177 ScalarEvolution::ExitLimit
5178 ScalarEvolution::ComputeExitLimitFromSingleExitSwitch(const Loop *L,
5180 BasicBlock *ExitingBlock,
5181 bool ControlsExit) {
5182 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
5184 // Give up if the exit is the default dest of a switch.
5185 if (Switch->getDefaultDest() == ExitingBlock)
5186 return getCouldNotCompute();
5188 assert(L->contains(Switch->getDefaultDest()) &&
5189 "Default case must not exit the loop!");
5190 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
5191 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
5193 // while (X != Y) --> while (X-Y != 0)
5194 ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
5195 if (EL.hasAnyInfo())
5198 return getCouldNotCompute();
5201 static ConstantInt *
5202 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
5203 ScalarEvolution &SE) {
5204 const SCEV *InVal = SE.getConstant(C);
5205 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
5206 assert(isa<SCEVConstant>(Val) &&
5207 "Evaluation of SCEV at constant didn't fold correctly?");
5208 return cast<SCEVConstant>(Val)->getValue();
5211 /// ComputeLoadConstantCompareExitLimit - Given an exit condition of
5212 /// 'icmp op load X, cst', try to see if we can compute the backedge
5213 /// execution count.
5214 ScalarEvolution::ExitLimit
5215 ScalarEvolution::ComputeLoadConstantCompareExitLimit(
5219 ICmpInst::Predicate predicate) {
5221 if (LI->isVolatile()) return getCouldNotCompute();
5223 // Check to see if the loaded pointer is a getelementptr of a global.
5224 // TODO: Use SCEV instead of manually grubbing with GEPs.
5225 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
5226 if (!GEP) return getCouldNotCompute();
5228 // Make sure that it is really a constant global we are gepping, with an
5229 // initializer, and make sure the first IDX is really 0.
5230 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
5231 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
5232 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
5233 !cast<Constant>(GEP->getOperand(1))->isNullValue())
5234 return getCouldNotCompute();
5236 // Okay, we allow one non-constant index into the GEP instruction.
5237 Value *VarIdx = nullptr;
5238 std::vector<Constant*> Indexes;
5239 unsigned VarIdxNum = 0;
5240 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
5241 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5242 Indexes.push_back(CI);
5243 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
5244 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
5245 VarIdx = GEP->getOperand(i);
5247 Indexes.push_back(nullptr);
5250 // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
5252 return getCouldNotCompute();
5254 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
5255 // Check to see if X is a loop variant variable value now.
5256 const SCEV *Idx = getSCEV(VarIdx);
5257 Idx = getSCEVAtScope(Idx, L);
5259 // We can only recognize very limited forms of loop index expressions, in
5260 // particular, only affine AddRec's like {C1,+,C2}.
5261 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
5262 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
5263 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
5264 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
5265 return getCouldNotCompute();
5267 unsigned MaxSteps = MaxBruteForceIterations;
5268 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
5269 ConstantInt *ItCst = ConstantInt::get(
5270 cast<IntegerType>(IdxExpr->getType()), IterationNum);
5271 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
5273 // Form the GEP offset.
5274 Indexes[VarIdxNum] = Val;
5276 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
5278 if (!Result) break; // Cannot compute!
5280 // Evaluate the condition for this iteration.
5281 Result = ConstantExpr::getICmp(predicate, Result, RHS);
5282 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
5283 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
5285 dbgs() << "\n***\n*** Computed loop count " << *ItCst
5286 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
5289 ++NumArrayLenItCounts;
5290 return getConstant(ItCst); // Found terminating iteration!
5293 return getCouldNotCompute();
5297 /// CanConstantFold - Return true if we can constant fold an instruction of the
5298 /// specified type, assuming that all operands were constants.
5299 static bool CanConstantFold(const Instruction *I) {
5300 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
5301 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
5305 if (const CallInst *CI = dyn_cast<CallInst>(I))
5306 if (const Function *F = CI->getCalledFunction())
5307 return canConstantFoldCallTo(F);
5311 /// Determine whether this instruction can constant evolve within this loop
5312 /// assuming its operands can all constant evolve.
5313 static bool canConstantEvolve(Instruction *I, const Loop *L) {
5314 // An instruction outside of the loop can't be derived from a loop PHI.
5315 if (!L->contains(I)) return false;
5317 if (isa<PHINode>(I)) {
5318 if (L->getHeader() == I->getParent())
5321 // We don't currently keep track of the control flow needed to evaluate
5322 // PHIs, so we cannot handle PHIs inside of loops.
5326 // If we won't be able to constant fold this expression even if the operands
5327 // are constants, bail early.
5328 return CanConstantFold(I);
5331 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
5332 /// recursing through each instruction operand until reaching a loop header phi.
5334 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
5335 DenseMap<Instruction *, PHINode *> &PHIMap) {
5337 // Otherwise, we can evaluate this instruction if all of its operands are
5338 // constant or derived from a PHI node themselves.
5339 PHINode *PHI = nullptr;
5340 for (Instruction::op_iterator OpI = UseInst->op_begin(),
5341 OpE = UseInst->op_end(); OpI != OpE; ++OpI) {
5343 if (isa<Constant>(*OpI)) continue;
5345 Instruction *OpInst = dyn_cast<Instruction>(*OpI);
5346 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
5348 PHINode *P = dyn_cast<PHINode>(OpInst);
5350 // If this operand is already visited, reuse the prior result.
5351 // We may have P != PHI if this is the deepest point at which the
5352 // inconsistent paths meet.
5353 P = PHIMap.lookup(OpInst);
5355 // Recurse and memoize the results, whether a phi is found or not.
5356 // This recursive call invalidates pointers into PHIMap.
5357 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap);
5361 return nullptr; // Not evolving from PHI
5362 if (PHI && PHI != P)
5363 return nullptr; // Evolving from multiple different PHIs.
5366 // This is a expression evolving from a constant PHI!
5370 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
5371 /// in the loop that V is derived from. We allow arbitrary operations along the
5372 /// way, but the operands of an operation must either be constants or a value
5373 /// derived from a constant PHI. If this expression does not fit with these
5374 /// constraints, return null.
5375 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
5376 Instruction *I = dyn_cast<Instruction>(V);
5377 if (!I || !canConstantEvolve(I, L)) return nullptr;
5379 if (PHINode *PN = dyn_cast<PHINode>(I)) {
5383 // Record non-constant instructions contained by the loop.
5384 DenseMap<Instruction *, PHINode *> PHIMap;
5385 return getConstantEvolvingPHIOperands(I, L, PHIMap);
5388 /// EvaluateExpression - Given an expression that passes the
5389 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
5390 /// in the loop has the value PHIVal. If we can't fold this expression for some
5391 /// reason, return null.
5392 static Constant *EvaluateExpression(Value *V, const Loop *L,
5393 DenseMap<Instruction *, Constant *> &Vals,
5394 const DataLayout *DL,
5395 const TargetLibraryInfo *TLI) {
5396 // Convenient constant check, but redundant for recursive calls.
5397 if (Constant *C = dyn_cast<Constant>(V)) return C;
5398 Instruction *I = dyn_cast<Instruction>(V);
5399 if (!I) return nullptr;
5401 if (Constant *C = Vals.lookup(I)) return C;
5403 // An instruction inside the loop depends on a value outside the loop that we
5404 // weren't given a mapping for, or a value such as a call inside the loop.
5405 if (!canConstantEvolve(I, L)) return nullptr;
5407 // An unmapped PHI can be due to a branch or another loop inside this loop,
5408 // or due to this not being the initial iteration through a loop where we
5409 // couldn't compute the evolution of this particular PHI last time.
5410 if (isa<PHINode>(I)) return nullptr;
5412 std::vector<Constant*> Operands(I->getNumOperands());
5414 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
5415 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
5417 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
5418 if (!Operands[i]) return nullptr;
5421 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
5423 if (!C) return nullptr;
5427 if (CmpInst *CI = dyn_cast<CmpInst>(I))
5428 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
5429 Operands[1], DL, TLI);
5430 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
5431 if (!LI->isVolatile())
5432 return ConstantFoldLoadFromConstPtr(Operands[0], DL);
5434 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Operands, DL,
5438 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
5439 /// in the header of its containing loop, we know the loop executes a
5440 /// constant number of times, and the PHI node is just a recurrence
5441 /// involving constants, fold it.
5443 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
5446 DenseMap<PHINode*, Constant*>::const_iterator I =
5447 ConstantEvolutionLoopExitValue.find(PN);
5448 if (I != ConstantEvolutionLoopExitValue.end())
5451 if (BEs.ugt(MaxBruteForceIterations))
5452 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
5454 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
5456 DenseMap<Instruction *, Constant *> CurrentIterVals;
5457 BasicBlock *Header = L->getHeader();
5458 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
5460 // Since the loop is canonicalized, the PHI node must have two entries. One
5461 // entry must be a constant (coming in from outside of the loop), and the
5462 // second must be derived from the same PHI.
5463 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
5464 PHINode *PHI = nullptr;
5465 for (BasicBlock::iterator I = Header->begin();
5466 (PHI = dyn_cast<PHINode>(I)); ++I) {
5467 Constant *StartCST =
5468 dyn_cast<Constant>(PHI->getIncomingValue(!SecondIsBackedge));
5469 if (!StartCST) continue;
5470 CurrentIterVals[PHI] = StartCST;
5472 if (!CurrentIterVals.count(PN))
5473 return RetVal = nullptr;
5475 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
5477 // Execute the loop symbolically to determine the exit value.
5478 if (BEs.getActiveBits() >= 32)
5479 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
5481 unsigned NumIterations = BEs.getZExtValue(); // must be in range
5482 unsigned IterationNum = 0;
5483 for (; ; ++IterationNum) {
5484 if (IterationNum == NumIterations)
5485 return RetVal = CurrentIterVals[PN]; // Got exit value!
5487 // Compute the value of the PHIs for the next iteration.
5488 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
5489 DenseMap<Instruction *, Constant *> NextIterVals;
5490 Constant *NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL,
5493 return nullptr; // Couldn't evaluate!
5494 NextIterVals[PN] = NextPHI;
5496 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
5498 // Also evaluate the other PHI nodes. However, we don't get to stop if we
5499 // cease to be able to evaluate one of them or if they stop evolving,
5500 // because that doesn't necessarily prevent us from computing PN.
5501 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
5502 for (DenseMap<Instruction *, Constant *>::const_iterator
5503 I = CurrentIterVals.begin(), E = CurrentIterVals.end(); I != E; ++I){
5504 PHINode *PHI = dyn_cast<PHINode>(I->first);
5505 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
5506 PHIsToCompute.push_back(std::make_pair(PHI, I->second));
5508 // We use two distinct loops because EvaluateExpression may invalidate any
5509 // iterators into CurrentIterVals.
5510 for (SmallVectorImpl<std::pair<PHINode *, Constant*> >::const_iterator
5511 I = PHIsToCompute.begin(), E = PHIsToCompute.end(); I != E; ++I) {
5512 PHINode *PHI = I->first;
5513 Constant *&NextPHI = NextIterVals[PHI];
5514 if (!NextPHI) { // Not already computed.
5515 Value *BEValue = PHI->getIncomingValue(SecondIsBackedge);
5516 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, TLI);
5518 if (NextPHI != I->second)
5519 StoppedEvolving = false;
5522 // If all entries in CurrentIterVals == NextIterVals then we can stop
5523 // iterating, the loop can't continue to change.
5524 if (StoppedEvolving)
5525 return RetVal = CurrentIterVals[PN];
5527 CurrentIterVals.swap(NextIterVals);
5531 /// ComputeExitCountExhaustively - If the loop is known to execute a
5532 /// constant number of times (the condition evolves only from constants),
5533 /// try to evaluate a few iterations of the loop until we get the exit
5534 /// condition gets a value of ExitWhen (true or false). If we cannot
5535 /// evaluate the trip count of the loop, return getCouldNotCompute().
5536 const SCEV *ScalarEvolution::ComputeExitCountExhaustively(const Loop *L,
5539 PHINode *PN = getConstantEvolvingPHI(Cond, L);
5540 if (!PN) return getCouldNotCompute();
5542 // If the loop is canonicalized, the PHI will have exactly two entries.
5543 // That's the only form we support here.
5544 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
5546 DenseMap<Instruction *, Constant *> CurrentIterVals;
5547 BasicBlock *Header = L->getHeader();
5548 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
5550 // One entry must be a constant (coming in from outside of the loop), and the
5551 // second must be derived from the same PHI.
5552 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
5553 PHINode *PHI = nullptr;
5554 for (BasicBlock::iterator I = Header->begin();
5555 (PHI = dyn_cast<PHINode>(I)); ++I) {
5556 Constant *StartCST =
5557 dyn_cast<Constant>(PHI->getIncomingValue(!SecondIsBackedge));
5558 if (!StartCST) continue;
5559 CurrentIterVals[PHI] = StartCST;
5561 if (!CurrentIterVals.count(PN))
5562 return getCouldNotCompute();
5564 // Okay, we find a PHI node that defines the trip count of this loop. Execute
5565 // the loop symbolically to determine when the condition gets a value of
5568 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
5569 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
5570 ConstantInt *CondVal =
5571 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, L, CurrentIterVals,
5574 // Couldn't symbolically evaluate.
5575 if (!CondVal) return getCouldNotCompute();
5577 if (CondVal->getValue() == uint64_t(ExitWhen)) {
5578 ++NumBruteForceTripCountsComputed;
5579 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
5582 // Update all the PHI nodes for the next iteration.
5583 DenseMap<Instruction *, Constant *> NextIterVals;
5585 // Create a list of which PHIs we need to compute. We want to do this before
5586 // calling EvaluateExpression on them because that may invalidate iterators
5587 // into CurrentIterVals.
5588 SmallVector<PHINode *, 8> PHIsToCompute;
5589 for (DenseMap<Instruction *, Constant *>::const_iterator
5590 I = CurrentIterVals.begin(), E = CurrentIterVals.end(); I != E; ++I){
5591 PHINode *PHI = dyn_cast<PHINode>(I->first);
5592 if (!PHI || PHI->getParent() != Header) continue;
5593 PHIsToCompute.push_back(PHI);
5595 for (SmallVectorImpl<PHINode *>::const_iterator I = PHIsToCompute.begin(),
5596 E = PHIsToCompute.end(); I != E; ++I) {
5598 Constant *&NextPHI = NextIterVals[PHI];
5599 if (NextPHI) continue; // Already computed!
5601 Value *BEValue = PHI->getIncomingValue(SecondIsBackedge);
5602 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, TLI);
5604 CurrentIterVals.swap(NextIterVals);
5607 // Too many iterations were needed to evaluate.
5608 return getCouldNotCompute();
5611 /// getSCEVAtScope - Return a SCEV expression for the specified value
5612 /// at the specified scope in the program. The L value specifies a loop
5613 /// nest to evaluate the expression at, where null is the top-level or a
5614 /// specified loop is immediately inside of the loop.
5616 /// This method can be used to compute the exit value for a variable defined
5617 /// in a loop by querying what the value will hold in the parent loop.
5619 /// In the case that a relevant loop exit value cannot be computed, the
5620 /// original value V is returned.
5621 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
5622 // Check to see if we've folded this expression at this loop before.
5623 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = ValuesAtScopes[V];
5624 for (unsigned u = 0; u < Values.size(); u++) {
5625 if (Values[u].first == L)
5626 return Values[u].second ? Values[u].second : V;
5628 Values.push_back(std::make_pair(L, static_cast<const SCEV *>(nullptr)));
5629 // Otherwise compute it.
5630 const SCEV *C = computeSCEVAtScope(V, L);
5631 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values2 = ValuesAtScopes[V];
5632 for (unsigned u = Values2.size(); u > 0; u--) {
5633 if (Values2[u - 1].first == L) {
5634 Values2[u - 1].second = C;
5641 /// This builds up a Constant using the ConstantExpr interface. That way, we
5642 /// will return Constants for objects which aren't represented by a
5643 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
5644 /// Returns NULL if the SCEV isn't representable as a Constant.
5645 static Constant *BuildConstantFromSCEV(const SCEV *V) {
5646 switch (static_cast<SCEVTypes>(V->getSCEVType())) {
5647 case scCouldNotCompute:
5651 return cast<SCEVConstant>(V)->getValue();
5653 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
5654 case scSignExtend: {
5655 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
5656 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
5657 return ConstantExpr::getSExt(CastOp, SS->getType());
5660 case scZeroExtend: {
5661 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
5662 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
5663 return ConstantExpr::getZExt(CastOp, SZ->getType());
5667 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
5668 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
5669 return ConstantExpr::getTrunc(CastOp, ST->getType());
5673 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
5674 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
5675 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
5676 unsigned AS = PTy->getAddressSpace();
5677 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
5678 C = ConstantExpr::getBitCast(C, DestPtrTy);
5680 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
5681 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
5682 if (!C2) return nullptr;
5685 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
5686 unsigned AS = C2->getType()->getPointerAddressSpace();
5688 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
5689 // The offsets have been converted to bytes. We can add bytes to an
5690 // i8* by GEP with the byte count in the first index.
5691 C = ConstantExpr::getBitCast(C, DestPtrTy);
5694 // Don't bother trying to sum two pointers. We probably can't
5695 // statically compute a load that results from it anyway.
5696 if (C2->getType()->isPointerTy())
5699 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
5700 if (PTy->getElementType()->isStructTy())
5701 C2 = ConstantExpr::getIntegerCast(
5702 C2, Type::getInt32Ty(C->getContext()), true);
5703 C = ConstantExpr::getGetElementPtr(C, C2);
5705 C = ConstantExpr::getAdd(C, C2);
5712 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
5713 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
5714 // Don't bother with pointers at all.
5715 if (C->getType()->isPointerTy()) return nullptr;
5716 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
5717 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
5718 if (!C2 || C2->getType()->isPointerTy()) return nullptr;
5719 C = ConstantExpr::getMul(C, C2);
5726 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
5727 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
5728 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
5729 if (LHS->getType() == RHS->getType())
5730 return ConstantExpr::getUDiv(LHS, RHS);
5735 break; // TODO: smax, umax.
5740 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
5741 if (isa<SCEVConstant>(V)) return V;
5743 // If this instruction is evolved from a constant-evolving PHI, compute the
5744 // exit value from the loop without using SCEVs.
5745 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
5746 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
5747 const Loop *LI = (*this->LI)[I->getParent()];
5748 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
5749 if (PHINode *PN = dyn_cast<PHINode>(I))
5750 if (PN->getParent() == LI->getHeader()) {
5751 // Okay, there is no closed form solution for the PHI node. Check
5752 // to see if the loop that contains it has a known backedge-taken
5753 // count. If so, we may be able to force computation of the exit
5755 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
5756 if (const SCEVConstant *BTCC =
5757 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
5758 // Okay, we know how many times the containing loop executes. If
5759 // this is a constant evolving PHI node, get the final value at
5760 // the specified iteration number.
5761 Constant *RV = getConstantEvolutionLoopExitValue(PN,
5762 BTCC->getValue()->getValue(),
5764 if (RV) return getSCEV(RV);
5768 // Okay, this is an expression that we cannot symbolically evaluate
5769 // into a SCEV. Check to see if it's possible to symbolically evaluate
5770 // the arguments into constants, and if so, try to constant propagate the
5771 // result. This is particularly useful for computing loop exit values.
5772 if (CanConstantFold(I)) {
5773 SmallVector<Constant *, 4> Operands;
5774 bool MadeImprovement = false;
5775 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
5776 Value *Op = I->getOperand(i);
5777 if (Constant *C = dyn_cast<Constant>(Op)) {
5778 Operands.push_back(C);
5782 // If any of the operands is non-constant and if they are
5783 // non-integer and non-pointer, don't even try to analyze them
5784 // with scev techniques.
5785 if (!isSCEVable(Op->getType()))
5788 const SCEV *OrigV = getSCEV(Op);
5789 const SCEV *OpV = getSCEVAtScope(OrigV, L);
5790 MadeImprovement |= OrigV != OpV;
5792 Constant *C = BuildConstantFromSCEV(OpV);
5794 if (C->getType() != Op->getType())
5795 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
5799 Operands.push_back(C);
5802 // Check to see if getSCEVAtScope actually made an improvement.
5803 if (MadeImprovement) {
5804 Constant *C = nullptr;
5805 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
5806 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
5807 Operands[0], Operands[1], DL,
5809 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
5810 if (!LI->isVolatile())
5811 C = ConstantFoldLoadFromConstPtr(Operands[0], DL);
5813 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
5821 // This is some other type of SCEVUnknown, just return it.
5825 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
5826 // Avoid performing the look-up in the common case where the specified
5827 // expression has no loop-variant portions.
5828 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
5829 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
5830 if (OpAtScope != Comm->getOperand(i)) {
5831 // Okay, at least one of these operands is loop variant but might be
5832 // foldable. Build a new instance of the folded commutative expression.
5833 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
5834 Comm->op_begin()+i);
5835 NewOps.push_back(OpAtScope);
5837 for (++i; i != e; ++i) {
5838 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
5839 NewOps.push_back(OpAtScope);
5841 if (isa<SCEVAddExpr>(Comm))
5842 return getAddExpr(NewOps);
5843 if (isa<SCEVMulExpr>(Comm))
5844 return getMulExpr(NewOps);
5845 if (isa<SCEVSMaxExpr>(Comm))
5846 return getSMaxExpr(NewOps);
5847 if (isa<SCEVUMaxExpr>(Comm))
5848 return getUMaxExpr(NewOps);
5849 llvm_unreachable("Unknown commutative SCEV type!");
5852 // If we got here, all operands are loop invariant.
5856 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
5857 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
5858 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
5859 if (LHS == Div->getLHS() && RHS == Div->getRHS())
5860 return Div; // must be loop invariant
5861 return getUDivExpr(LHS, RHS);
5864 // If this is a loop recurrence for a loop that does not contain L, then we
5865 // are dealing with the final value computed by the loop.
5866 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
5867 // First, attempt to evaluate each operand.
5868 // Avoid performing the look-up in the common case where the specified
5869 // expression has no loop-variant portions.
5870 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
5871 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
5872 if (OpAtScope == AddRec->getOperand(i))
5875 // Okay, at least one of these operands is loop variant but might be
5876 // foldable. Build a new instance of the folded commutative expression.
5877 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
5878 AddRec->op_begin()+i);
5879 NewOps.push_back(OpAtScope);
5880 for (++i; i != e; ++i)
5881 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
5883 const SCEV *FoldedRec =
5884 getAddRecExpr(NewOps, AddRec->getLoop(),
5885 AddRec->getNoWrapFlags(SCEV::FlagNW));
5886 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
5887 // The addrec may be folded to a nonrecurrence, for example, if the
5888 // induction variable is multiplied by zero after constant folding. Go
5889 // ahead and return the folded value.
5895 // If the scope is outside the addrec's loop, evaluate it by using the
5896 // loop exit value of the addrec.
5897 if (!AddRec->getLoop()->contains(L)) {
5898 // To evaluate this recurrence, we need to know how many times the AddRec
5899 // loop iterates. Compute this now.
5900 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
5901 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
5903 // Then, evaluate the AddRec.
5904 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
5910 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
5911 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
5912 if (Op == Cast->getOperand())
5913 return Cast; // must be loop invariant
5914 return getZeroExtendExpr(Op, Cast->getType());
5917 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
5918 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
5919 if (Op == Cast->getOperand())
5920 return Cast; // must be loop invariant
5921 return getSignExtendExpr(Op, Cast->getType());
5924 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
5925 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
5926 if (Op == Cast->getOperand())
5927 return Cast; // must be loop invariant
5928 return getTruncateExpr(Op, Cast->getType());
5931 llvm_unreachable("Unknown SCEV type!");
5934 /// getSCEVAtScope - This is a convenience function which does
5935 /// getSCEVAtScope(getSCEV(V), L).
5936 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
5937 return getSCEVAtScope(getSCEV(V), L);
5940 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
5941 /// following equation:
5943 /// A * X = B (mod N)
5945 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
5946 /// A and B isn't important.
5948 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
5949 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
5950 ScalarEvolution &SE) {
5951 uint32_t BW = A.getBitWidth();
5952 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
5953 assert(A != 0 && "A must be non-zero.");
5957 // The gcd of A and N may have only one prime factor: 2. The number of
5958 // trailing zeros in A is its multiplicity
5959 uint32_t Mult2 = A.countTrailingZeros();
5962 // 2. Check if B is divisible by D.
5964 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
5965 // is not less than multiplicity of this prime factor for D.
5966 if (B.countTrailingZeros() < Mult2)
5967 return SE.getCouldNotCompute();
5969 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
5972 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
5973 // bit width during computations.
5974 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
5975 APInt Mod(BW + 1, 0);
5976 Mod.setBit(BW - Mult2); // Mod = N / D
5977 APInt I = AD.multiplicativeInverse(Mod);
5979 // 4. Compute the minimum unsigned root of the equation:
5980 // I * (B / D) mod (N / D)
5981 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
5983 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
5985 return SE.getConstant(Result.trunc(BW));
5988 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
5989 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
5990 /// might be the same) or two SCEVCouldNotCompute objects.
5992 static std::pair<const SCEV *,const SCEV *>
5993 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
5994 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
5995 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
5996 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
5997 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
5999 // We currently can only solve this if the coefficients are constants.
6000 if (!LC || !MC || !NC) {
6001 const SCEV *CNC = SE.getCouldNotCompute();
6002 return std::make_pair(CNC, CNC);
6005 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
6006 const APInt &L = LC->getValue()->getValue();
6007 const APInt &M = MC->getValue()->getValue();
6008 const APInt &N = NC->getValue()->getValue();
6009 APInt Two(BitWidth, 2);
6010 APInt Four(BitWidth, 4);
6013 using namespace APIntOps;
6015 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
6016 // The B coefficient is M-N/2
6020 // The A coefficient is N/2
6021 APInt A(N.sdiv(Two));
6023 // Compute the B^2-4ac term.
6026 SqrtTerm -= Four * (A * C);
6028 if (SqrtTerm.isNegative()) {
6029 // The loop is provably infinite.
6030 const SCEV *CNC = SE.getCouldNotCompute();
6031 return std::make_pair(CNC, CNC);
6034 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
6035 // integer value or else APInt::sqrt() will assert.
6036 APInt SqrtVal(SqrtTerm.sqrt());
6038 // Compute the two solutions for the quadratic formula.
6039 // The divisions must be performed as signed divisions.
6042 if (TwoA.isMinValue()) {
6043 const SCEV *CNC = SE.getCouldNotCompute();
6044 return std::make_pair(CNC, CNC);
6047 LLVMContext &Context = SE.getContext();
6049 ConstantInt *Solution1 =
6050 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
6051 ConstantInt *Solution2 =
6052 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
6054 return std::make_pair(SE.getConstant(Solution1),
6055 SE.getConstant(Solution2));
6056 } // end APIntOps namespace
6059 /// HowFarToZero - Return the number of times a backedge comparing the specified
6060 /// value to zero will execute. If not computable, return CouldNotCompute.
6062 /// This is only used for loops with a "x != y" exit test. The exit condition is
6063 /// now expressed as a single expression, V = x-y. So the exit test is
6064 /// effectively V != 0. We know and take advantage of the fact that this
6065 /// expression only being used in a comparison by zero context.
6066 ScalarEvolution::ExitLimit
6067 ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L, bool ControlsExit) {
6068 // If the value is a constant
6069 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
6070 // If the value is already zero, the branch will execute zero times.
6071 if (C->getValue()->isZero()) return C;
6072 return getCouldNotCompute(); // Otherwise it will loop infinitely.
6075 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
6076 if (!AddRec || AddRec->getLoop() != L)
6077 return getCouldNotCompute();
6079 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
6080 // the quadratic equation to solve it.
6081 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
6082 std::pair<const SCEV *,const SCEV *> Roots =
6083 SolveQuadraticEquation(AddRec, *this);
6084 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
6085 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
6088 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
6089 << " sol#2: " << *R2 << "\n";
6091 // Pick the smallest positive root value.
6092 if (ConstantInt *CB =
6093 dyn_cast<ConstantInt>(ConstantExpr::getICmp(CmpInst::ICMP_ULT,
6096 if (CB->getZExtValue() == false)
6097 std::swap(R1, R2); // R1 is the minimum root now.
6099 // We can only use this value if the chrec ends up with an exact zero
6100 // value at this index. When solving for "X*X != 5", for example, we
6101 // should not accept a root of 2.
6102 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
6104 return R1; // We found a quadratic root!
6107 return getCouldNotCompute();
6110 // Otherwise we can only handle this if it is affine.
6111 if (!AddRec->isAffine())
6112 return getCouldNotCompute();
6114 // If this is an affine expression, the execution count of this branch is
6115 // the minimum unsigned root of the following equation:
6117 // Start + Step*N = 0 (mod 2^BW)
6121 // Step*N = -Start (mod 2^BW)
6123 // where BW is the common bit width of Start and Step.
6125 // Get the initial value for the loop.
6126 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
6127 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
6129 // For now we handle only constant steps.
6131 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
6132 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
6133 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
6134 // We have not yet seen any such cases.
6135 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
6136 if (!StepC || StepC->getValue()->equalsInt(0))
6137 return getCouldNotCompute();
6139 // For positive steps (counting up until unsigned overflow):
6140 // N = -Start/Step (as unsigned)
6141 // For negative steps (counting down to zero):
6143 // First compute the unsigned distance from zero in the direction of Step.
6144 bool CountDown = StepC->getValue()->getValue().isNegative();
6145 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
6147 // Handle unitary steps, which cannot wraparound.
6148 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
6149 // N = Distance (as unsigned)
6150 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
6151 ConstantRange CR = getUnsignedRange(Start);
6152 const SCEV *MaxBECount;
6153 if (!CountDown && CR.getUnsignedMin().isMinValue())
6154 // When counting up, the worst starting value is 1, not 0.
6155 MaxBECount = CR.getUnsignedMax().isMinValue()
6156 ? getConstant(APInt::getMinValue(CR.getBitWidth()))
6157 : getConstant(APInt::getMaxValue(CR.getBitWidth()));
6159 MaxBECount = getConstant(CountDown ? CR.getUnsignedMax()
6160 : -CR.getUnsignedMin());
6161 return ExitLimit(Distance, MaxBECount);
6164 // If the step exactly divides the distance then unsigned divide computes the
6167 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
6168 SCEVUDivision::divide(SE, Distance, Step, &Q, &R);
6171 getUDivExactExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
6172 return ExitLimit(Exact, Exact);
6175 // If the condition controls loop exit (the loop exits only if the expression
6176 // is true) and the addition is no-wrap we can use unsigned divide to
6177 // compute the backedge count. In this case, the step may not divide the
6178 // distance, but we don't care because if the condition is "missed" the loop
6179 // will have undefined behavior due to wrapping.
6180 if (ControlsExit && AddRec->getNoWrapFlags(SCEV::FlagNW)) {
6182 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
6183 return ExitLimit(Exact, Exact);
6186 // Then, try to solve the above equation provided that Start is constant.
6187 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
6188 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
6189 -StartC->getValue()->getValue(),
6191 return getCouldNotCompute();
6194 /// HowFarToNonZero - Return the number of times a backedge checking the
6195 /// specified value for nonzero will execute. If not computable, return
6197 ScalarEvolution::ExitLimit
6198 ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
6199 // Loops that look like: while (X == 0) are very strange indeed. We don't
6200 // handle them yet except for the trivial case. This could be expanded in the
6201 // future as needed.
6203 // If the value is a constant, check to see if it is known to be non-zero
6204 // already. If so, the backedge will execute zero times.
6205 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
6206 if (!C->getValue()->isNullValue())
6207 return getConstant(C->getType(), 0);
6208 return getCouldNotCompute(); // Otherwise it will loop infinitely.
6211 // We could implement others, but I really doubt anyone writes loops like
6212 // this, and if they did, they would already be constant folded.
6213 return getCouldNotCompute();
6216 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
6217 /// (which may not be an immediate predecessor) which has exactly one
6218 /// successor from which BB is reachable, or null if no such block is
6221 std::pair<BasicBlock *, BasicBlock *>
6222 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
6223 // If the block has a unique predecessor, then there is no path from the
6224 // predecessor to the block that does not go through the direct edge
6225 // from the predecessor to the block.
6226 if (BasicBlock *Pred = BB->getSinglePredecessor())
6227 return std::make_pair(Pred, BB);
6229 // A loop's header is defined to be a block that dominates the loop.
6230 // If the header has a unique predecessor outside the loop, it must be
6231 // a block that has exactly one successor that can reach the loop.
6232 if (Loop *L = LI->getLoopFor(BB))
6233 return std::make_pair(L->getLoopPredecessor(), L->getHeader());
6235 return std::pair<BasicBlock *, BasicBlock *>();
6238 /// HasSameValue - SCEV structural equivalence is usually sufficient for
6239 /// testing whether two expressions are equal, however for the purposes of
6240 /// looking for a condition guarding a loop, it can be useful to be a little
6241 /// more general, since a front-end may have replicated the controlling
6244 static bool HasSameValue(const SCEV *A, const SCEV *B) {
6245 // Quick check to see if they are the same SCEV.
6246 if (A == B) return true;
6248 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
6249 // two different instructions with the same value. Check for this case.
6250 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
6251 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
6252 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
6253 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
6254 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
6257 // Otherwise assume they may have a different value.
6261 /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
6262 /// predicate Pred. Return true iff any changes were made.
6264 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
6265 const SCEV *&LHS, const SCEV *&RHS,
6267 bool Changed = false;
6269 // If we hit the max recursion limit bail out.
6273 // Canonicalize a constant to the right side.
6274 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
6275 // Check for both operands constant.
6276 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
6277 if (ConstantExpr::getICmp(Pred,
6279 RHSC->getValue())->isNullValue())
6280 goto trivially_false;
6282 goto trivially_true;
6284 // Otherwise swap the operands to put the constant on the right.
6285 std::swap(LHS, RHS);
6286 Pred = ICmpInst::getSwappedPredicate(Pred);
6290 // If we're comparing an addrec with a value which is loop-invariant in the
6291 // addrec's loop, put the addrec on the left. Also make a dominance check,
6292 // as both operands could be addrecs loop-invariant in each other's loop.
6293 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
6294 const Loop *L = AR->getLoop();
6295 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
6296 std::swap(LHS, RHS);
6297 Pred = ICmpInst::getSwappedPredicate(Pred);
6302 // If there's a constant operand, canonicalize comparisons with boundary
6303 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
6304 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
6305 const APInt &RA = RC->getValue()->getValue();
6307 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
6308 case ICmpInst::ICMP_EQ:
6309 case ICmpInst::ICMP_NE:
6310 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
6312 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
6313 if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
6314 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
6315 ME->getOperand(0)->isAllOnesValue()) {
6316 RHS = AE->getOperand(1);
6317 LHS = ME->getOperand(1);
6321 case ICmpInst::ICMP_UGE:
6322 if ((RA - 1).isMinValue()) {
6323 Pred = ICmpInst::ICMP_NE;
6324 RHS = getConstant(RA - 1);
6328 if (RA.isMaxValue()) {
6329 Pred = ICmpInst::ICMP_EQ;
6333 if (RA.isMinValue()) goto trivially_true;
6335 Pred = ICmpInst::ICMP_UGT;
6336 RHS = getConstant(RA - 1);
6339 case ICmpInst::ICMP_ULE:
6340 if ((RA + 1).isMaxValue()) {
6341 Pred = ICmpInst::ICMP_NE;
6342 RHS = getConstant(RA + 1);
6346 if (RA.isMinValue()) {
6347 Pred = ICmpInst::ICMP_EQ;
6351 if (RA.isMaxValue()) goto trivially_true;
6353 Pred = ICmpInst::ICMP_ULT;
6354 RHS = getConstant(RA + 1);
6357 case ICmpInst::ICMP_SGE:
6358 if ((RA - 1).isMinSignedValue()) {
6359 Pred = ICmpInst::ICMP_NE;
6360 RHS = getConstant(RA - 1);
6364 if (RA.isMaxSignedValue()) {
6365 Pred = ICmpInst::ICMP_EQ;
6369 if (RA.isMinSignedValue()) goto trivially_true;
6371 Pred = ICmpInst::ICMP_SGT;
6372 RHS = getConstant(RA - 1);
6375 case ICmpInst::ICMP_SLE:
6376 if ((RA + 1).isMaxSignedValue()) {
6377 Pred = ICmpInst::ICMP_NE;
6378 RHS = getConstant(RA + 1);
6382 if (RA.isMinSignedValue()) {
6383 Pred = ICmpInst::ICMP_EQ;
6387 if (RA.isMaxSignedValue()) goto trivially_true;
6389 Pred = ICmpInst::ICMP_SLT;
6390 RHS = getConstant(RA + 1);
6393 case ICmpInst::ICMP_UGT:
6394 if (RA.isMinValue()) {
6395 Pred = ICmpInst::ICMP_NE;
6399 if ((RA + 1).isMaxValue()) {
6400 Pred = ICmpInst::ICMP_EQ;
6401 RHS = getConstant(RA + 1);
6405 if (RA.isMaxValue()) goto trivially_false;
6407 case ICmpInst::ICMP_ULT:
6408 if (RA.isMaxValue()) {
6409 Pred = ICmpInst::ICMP_NE;
6413 if ((RA - 1).isMinValue()) {
6414 Pred = ICmpInst::ICMP_EQ;
6415 RHS = getConstant(RA - 1);
6419 if (RA.isMinValue()) goto trivially_false;
6421 case ICmpInst::ICMP_SGT:
6422 if (RA.isMinSignedValue()) {
6423 Pred = ICmpInst::ICMP_NE;
6427 if ((RA + 1).isMaxSignedValue()) {
6428 Pred = ICmpInst::ICMP_EQ;
6429 RHS = getConstant(RA + 1);
6433 if (RA.isMaxSignedValue()) goto trivially_false;
6435 case ICmpInst::ICMP_SLT:
6436 if (RA.isMaxSignedValue()) {
6437 Pred = ICmpInst::ICMP_NE;
6441 if ((RA - 1).isMinSignedValue()) {
6442 Pred = ICmpInst::ICMP_EQ;
6443 RHS = getConstant(RA - 1);
6447 if (RA.isMinSignedValue()) goto trivially_false;
6452 // Check for obvious equality.
6453 if (HasSameValue(LHS, RHS)) {
6454 if (ICmpInst::isTrueWhenEqual(Pred))
6455 goto trivially_true;
6456 if (ICmpInst::isFalseWhenEqual(Pred))
6457 goto trivially_false;
6460 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
6461 // adding or subtracting 1 from one of the operands.
6463 case ICmpInst::ICMP_SLE:
6464 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
6465 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
6467 Pred = ICmpInst::ICMP_SLT;
6469 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
6470 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
6472 Pred = ICmpInst::ICMP_SLT;
6476 case ICmpInst::ICMP_SGE:
6477 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
6478 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
6480 Pred = ICmpInst::ICMP_SGT;
6482 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
6483 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
6485 Pred = ICmpInst::ICMP_SGT;
6489 case ICmpInst::ICMP_ULE:
6490 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
6491 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
6493 Pred = ICmpInst::ICMP_ULT;
6495 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
6496 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
6498 Pred = ICmpInst::ICMP_ULT;
6502 case ICmpInst::ICMP_UGE:
6503 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
6504 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
6506 Pred = ICmpInst::ICMP_UGT;
6508 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
6509 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
6511 Pred = ICmpInst::ICMP_UGT;
6519 // TODO: More simplifications are possible here.
6521 // Recursively simplify until we either hit a recursion limit or nothing
6524 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
6530 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
6531 Pred = ICmpInst::ICMP_EQ;
6536 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
6537 Pred = ICmpInst::ICMP_NE;
6541 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
6542 return getSignedRange(S).getSignedMax().isNegative();
6545 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
6546 return getSignedRange(S).getSignedMin().isStrictlyPositive();
6549 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
6550 return !getSignedRange(S).getSignedMin().isNegative();
6553 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
6554 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
6557 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
6558 return isKnownNegative(S) || isKnownPositive(S);
6561 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
6562 const SCEV *LHS, const SCEV *RHS) {
6563 // Canonicalize the inputs first.
6564 (void)SimplifyICmpOperands(Pred, LHS, RHS);
6566 // If LHS or RHS is an addrec, check to see if the condition is true in
6567 // every iteration of the loop.
6568 // If LHS and RHS are both addrec, both conditions must be true in
6569 // every iteration of the loop.
6570 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
6571 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
6572 bool LeftGuarded = false;
6573 bool RightGuarded = false;
6575 const Loop *L = LAR->getLoop();
6576 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
6577 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
6578 if (!RAR) return true;
6583 const Loop *L = RAR->getLoop();
6584 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
6585 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
6586 if (!LAR) return true;
6587 RightGuarded = true;
6590 if (LeftGuarded && RightGuarded)
6593 // Otherwise see what can be done with known constant ranges.
6594 return isKnownPredicateWithRanges(Pred, LHS, RHS);
6598 ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
6599 const SCEV *LHS, const SCEV *RHS) {
6600 if (HasSameValue(LHS, RHS))
6601 return ICmpInst::isTrueWhenEqual(Pred);
6603 // This code is split out from isKnownPredicate because it is called from
6604 // within isLoopEntryGuardedByCond.
6607 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
6608 case ICmpInst::ICMP_SGT:
6609 std::swap(LHS, RHS);
6610 case ICmpInst::ICMP_SLT: {
6611 ConstantRange LHSRange = getSignedRange(LHS);
6612 ConstantRange RHSRange = getSignedRange(RHS);
6613 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
6615 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
6619 case ICmpInst::ICMP_SGE:
6620 std::swap(LHS, RHS);
6621 case ICmpInst::ICMP_SLE: {
6622 ConstantRange LHSRange = getSignedRange(LHS);
6623 ConstantRange RHSRange = getSignedRange(RHS);
6624 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
6626 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
6630 case ICmpInst::ICMP_UGT:
6631 std::swap(LHS, RHS);
6632 case ICmpInst::ICMP_ULT: {
6633 ConstantRange LHSRange = getUnsignedRange(LHS);
6634 ConstantRange RHSRange = getUnsignedRange(RHS);
6635 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
6637 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
6641 case ICmpInst::ICMP_UGE:
6642 std::swap(LHS, RHS);
6643 case ICmpInst::ICMP_ULE: {
6644 ConstantRange LHSRange = getUnsignedRange(LHS);
6645 ConstantRange RHSRange = getUnsignedRange(RHS);
6646 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
6648 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
6652 case ICmpInst::ICMP_NE: {
6653 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
6655 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
6658 const SCEV *Diff = getMinusSCEV(LHS, RHS);
6659 if (isKnownNonZero(Diff))
6663 case ICmpInst::ICMP_EQ:
6664 // The check at the top of the function catches the case where
6665 // the values are known to be equal.
6671 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
6672 /// protected by a conditional between LHS and RHS. This is used to
6673 /// to eliminate casts.
6675 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
6676 ICmpInst::Predicate Pred,
6677 const SCEV *LHS, const SCEV *RHS) {
6678 // Interpret a null as meaning no loop, where there is obviously no guard
6679 // (interprocedural conditions notwithstanding).
6680 if (!L) return true;
6682 if (isKnownPredicateWithRanges(Pred, LHS, RHS)) return true;
6684 BasicBlock *Latch = L->getLoopLatch();
6688 BranchInst *LoopContinuePredicate =
6689 dyn_cast<BranchInst>(Latch->getTerminator());
6690 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
6691 isImpliedCond(Pred, LHS, RHS,
6692 LoopContinuePredicate->getCondition(),
6693 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
6696 // Check conditions due to any @llvm.assume intrinsics.
6697 for (auto &CI : AT->assumptions(F)) {
6698 if (!DT->dominates(CI, Latch->getTerminator()))
6701 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
6708 /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
6709 /// by a conditional between LHS and RHS. This is used to help avoid max
6710 /// expressions in loop trip counts, and to eliminate casts.
6712 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
6713 ICmpInst::Predicate Pred,
6714 const SCEV *LHS, const SCEV *RHS) {
6715 // Interpret a null as meaning no loop, where there is obviously no guard
6716 // (interprocedural conditions notwithstanding).
6717 if (!L) return false;
6719 if (isKnownPredicateWithRanges(Pred, LHS, RHS)) return true;
6721 // Starting at the loop predecessor, climb up the predecessor chain, as long
6722 // as there are predecessors that can be found that have unique successors
6723 // leading to the original header.
6724 for (std::pair<BasicBlock *, BasicBlock *>
6725 Pair(L->getLoopPredecessor(), L->getHeader());
6727 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
6729 BranchInst *LoopEntryPredicate =
6730 dyn_cast<BranchInst>(Pair.first->getTerminator());
6731 if (!LoopEntryPredicate ||
6732 LoopEntryPredicate->isUnconditional())
6735 if (isImpliedCond(Pred, LHS, RHS,
6736 LoopEntryPredicate->getCondition(),
6737 LoopEntryPredicate->getSuccessor(0) != Pair.second))
6741 // Check conditions due to any @llvm.assume intrinsics.
6742 for (auto &CI : AT->assumptions(F)) {
6743 if (!DT->dominates(CI, L->getHeader()))
6746 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
6753 /// RAII wrapper to prevent recursive application of isImpliedCond.
6754 /// ScalarEvolution's PendingLoopPredicates set must be empty unless we are
6755 /// currently evaluating isImpliedCond.
6756 struct MarkPendingLoopPredicate {
6758 DenseSet<Value*> &LoopPreds;
6761 MarkPendingLoopPredicate(Value *C, DenseSet<Value*> &LP)
6762 : Cond(C), LoopPreds(LP) {
6763 Pending = !LoopPreds.insert(Cond).second;
6765 ~MarkPendingLoopPredicate() {
6767 LoopPreds.erase(Cond);
6771 /// isImpliedCond - Test whether the condition described by Pred, LHS,
6772 /// and RHS is true whenever the given Cond value evaluates to true.
6773 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
6774 const SCEV *LHS, const SCEV *RHS,
6775 Value *FoundCondValue,
6777 MarkPendingLoopPredicate Mark(FoundCondValue, PendingLoopPredicates);
6781 // Recursively handle And and Or conditions.
6782 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
6783 if (BO->getOpcode() == Instruction::And) {
6785 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
6786 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
6787 } else if (BO->getOpcode() == Instruction::Or) {
6789 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
6790 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
6794 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
6795 if (!ICI) return false;
6797 // Bail if the ICmp's operands' types are wider than the needed type
6798 // before attempting to call getSCEV on them. This avoids infinite
6799 // recursion, since the analysis of widening casts can require loop
6800 // exit condition information for overflow checking, which would
6802 if (getTypeSizeInBits(LHS->getType()) <
6803 getTypeSizeInBits(ICI->getOperand(0)->getType()))
6806 // Now that we found a conditional branch that dominates the loop or controls
6807 // the loop latch. Check to see if it is the comparison we are looking for.
6808 ICmpInst::Predicate FoundPred;
6810 FoundPred = ICI->getInversePredicate();
6812 FoundPred = ICI->getPredicate();
6814 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
6815 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
6817 // Balance the types. The case where FoundLHS' type is wider than
6818 // LHS' type is checked for above.
6819 if (getTypeSizeInBits(LHS->getType()) >
6820 getTypeSizeInBits(FoundLHS->getType())) {
6821 if (CmpInst::isSigned(FoundPred)) {
6822 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
6823 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
6825 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
6826 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
6830 // Canonicalize the query to match the way instcombine will have
6831 // canonicalized the comparison.
6832 if (SimplifyICmpOperands(Pred, LHS, RHS))
6834 return CmpInst::isTrueWhenEqual(Pred);
6835 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
6836 if (FoundLHS == FoundRHS)
6837 return CmpInst::isFalseWhenEqual(FoundPred);
6839 // Check to see if we can make the LHS or RHS match.
6840 if (LHS == FoundRHS || RHS == FoundLHS) {
6841 if (isa<SCEVConstant>(RHS)) {
6842 std::swap(FoundLHS, FoundRHS);
6843 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
6845 std::swap(LHS, RHS);
6846 Pred = ICmpInst::getSwappedPredicate(Pred);
6850 // Check whether the found predicate is the same as the desired predicate.
6851 if (FoundPred == Pred)
6852 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
6854 // Check whether swapping the found predicate makes it the same as the
6855 // desired predicate.
6856 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
6857 if (isa<SCEVConstant>(RHS))
6858 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
6860 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
6861 RHS, LHS, FoundLHS, FoundRHS);
6864 // Check if we can make progress by sharpening ranges.
6865 if (FoundPred == ICmpInst::ICMP_NE &&
6866 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
6868 const SCEVConstant *C = nullptr;
6869 const SCEV *V = nullptr;
6871 if (isa<SCEVConstant>(FoundLHS)) {
6872 C = cast<SCEVConstant>(FoundLHS);
6875 C = cast<SCEVConstant>(FoundRHS);
6879 // The guarding predicate tells us that C != V. If the known range
6880 // of V is [C, t), we can sharpen the range to [C + 1, t). The
6881 // range we consider has to correspond to same signedness as the
6882 // predicate we're interested in folding.
6884 APInt Min = ICmpInst::isSigned(Pred) ?
6885 getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin();
6887 if (Min == C->getValue()->getValue()) {
6888 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
6889 // This is true even if (Min + 1) wraps around -- in case of
6890 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
6892 APInt SharperMin = Min + 1;
6895 case ICmpInst::ICMP_SGE:
6896 case ICmpInst::ICMP_UGE:
6897 // We know V `Pred` SharperMin. If this implies LHS `Pred`
6899 if (isImpliedCondOperands(Pred, LHS, RHS, V,
6900 getConstant(SharperMin)))
6903 case ICmpInst::ICMP_SGT:
6904 case ICmpInst::ICMP_UGT:
6905 // We know from the range information that (V `Pred` Min ||
6906 // V == Min). We know from the guarding condition that !(V
6907 // == Min). This gives us
6909 // V `Pred` Min || V == Min && !(V == Min)
6912 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
6914 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
6924 // Check whether the actual condition is beyond sufficient.
6925 if (FoundPred == ICmpInst::ICMP_EQ)
6926 if (ICmpInst::isTrueWhenEqual(Pred))
6927 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
6929 if (Pred == ICmpInst::ICMP_NE)
6930 if (!ICmpInst::isTrueWhenEqual(FoundPred))
6931 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
6934 // Otherwise assume the worst.
6938 /// isImpliedCondOperands - Test whether the condition described by Pred,
6939 /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
6940 /// and FoundRHS is true.
6941 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
6942 const SCEV *LHS, const SCEV *RHS,
6943 const SCEV *FoundLHS,
6944 const SCEV *FoundRHS) {
6945 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
6946 FoundLHS, FoundRHS) ||
6947 // ~x < ~y --> x > y
6948 isImpliedCondOperandsHelper(Pred, LHS, RHS,
6949 getNotSCEV(FoundRHS),
6950 getNotSCEV(FoundLHS));
6953 /// isImpliedCondOperandsHelper - Test whether the condition described by
6954 /// Pred, LHS, and RHS is true whenever the condition described by Pred,
6955 /// FoundLHS, and FoundRHS is true.
6957 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
6958 const SCEV *LHS, const SCEV *RHS,
6959 const SCEV *FoundLHS,
6960 const SCEV *FoundRHS) {
6962 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
6963 case ICmpInst::ICMP_EQ:
6964 case ICmpInst::ICMP_NE:
6965 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
6968 case ICmpInst::ICMP_SLT:
6969 case ICmpInst::ICMP_SLE:
6970 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
6971 isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS))
6974 case ICmpInst::ICMP_SGT:
6975 case ICmpInst::ICMP_SGE:
6976 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
6977 isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS))
6980 case ICmpInst::ICMP_ULT:
6981 case ICmpInst::ICMP_ULE:
6982 if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
6983 isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS))
6986 case ICmpInst::ICMP_UGT:
6987 case ICmpInst::ICMP_UGE:
6988 if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
6989 isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS))
6997 // Verify if an linear IV with positive stride can overflow when in a
6998 // less-than comparison, knowing the invariant term of the comparison, the
6999 // stride and the knowledge of NSW/NUW flags on the recurrence.
7000 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
7001 bool IsSigned, bool NoWrap) {
7002 if (NoWrap) return false;
7004 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
7005 const SCEV *One = getConstant(Stride->getType(), 1);
7008 APInt MaxRHS = getSignedRange(RHS).getSignedMax();
7009 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
7010 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
7013 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
7014 return (MaxValue - MaxStrideMinusOne).slt(MaxRHS);
7017 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
7018 APInt MaxValue = APInt::getMaxValue(BitWidth);
7019 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
7022 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
7023 return (MaxValue - MaxStrideMinusOne).ult(MaxRHS);
7026 // Verify if an linear IV with negative stride can overflow when in a
7027 // greater-than comparison, knowing the invariant term of the comparison,
7028 // the stride and the knowledge of NSW/NUW flags on the recurrence.
7029 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
7030 bool IsSigned, bool NoWrap) {
7031 if (NoWrap) return false;
7033 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
7034 const SCEV *One = getConstant(Stride->getType(), 1);
7037 APInt MinRHS = getSignedRange(RHS).getSignedMin();
7038 APInt MinValue = APInt::getSignedMinValue(BitWidth);
7039 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
7042 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
7043 return (MinValue + MaxStrideMinusOne).sgt(MinRHS);
7046 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
7047 APInt MinValue = APInt::getMinValue(BitWidth);
7048 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
7051 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
7052 return (MinValue + MaxStrideMinusOne).ugt(MinRHS);
7055 // Compute the backedge taken count knowing the interval difference, the
7056 // stride and presence of the equality in the comparison.
7057 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
7059 const SCEV *One = getConstant(Step->getType(), 1);
7060 Delta = Equality ? getAddExpr(Delta, Step)
7061 : getAddExpr(Delta, getMinusSCEV(Step, One));
7062 return getUDivExpr(Delta, Step);
7065 /// HowManyLessThans - Return the number of times a backedge containing the
7066 /// specified less-than comparison will execute. If not computable, return
7067 /// CouldNotCompute.
7069 /// @param ControlsExit is true when the LHS < RHS condition directly controls
7070 /// the branch (loops exits only if condition is true). In this case, we can use
7071 /// NoWrapFlags to skip overflow checks.
7072 ScalarEvolution::ExitLimit
7073 ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
7074 const Loop *L, bool IsSigned,
7075 bool ControlsExit) {
7076 // We handle only IV < Invariant
7077 if (!isLoopInvariant(RHS, L))
7078 return getCouldNotCompute();
7080 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
7082 // Avoid weird loops
7083 if (!IV || IV->getLoop() != L || !IV->isAffine())
7084 return getCouldNotCompute();
7086 bool NoWrap = ControlsExit &&
7087 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
7089 const SCEV *Stride = IV->getStepRecurrence(*this);
7091 // Avoid negative or zero stride values
7092 if (!isKnownPositive(Stride))
7093 return getCouldNotCompute();
7095 // Avoid proven overflow cases: this will ensure that the backedge taken count
7096 // will not generate any unsigned overflow. Relaxed no-overflow conditions
7097 // exploit NoWrapFlags, allowing to optimize in presence of undefined
7098 // behaviors like the case of C language.
7099 if (!Stride->isOne() && doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
7100 return getCouldNotCompute();
7102 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
7103 : ICmpInst::ICMP_ULT;
7104 const SCEV *Start = IV->getStart();
7105 const SCEV *End = RHS;
7106 if (!isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) {
7107 const SCEV *Diff = getMinusSCEV(RHS, Start);
7108 // If we have NoWrap set, then we can assume that the increment won't
7109 // overflow, in which case if RHS - Start is a constant, we don't need to
7110 // do a max operation since we can just figure it out statically
7111 if (NoWrap && isa<SCEVConstant>(Diff)) {
7112 APInt D = dyn_cast<const SCEVConstant>(Diff)->getValue()->getValue();
7116 End = IsSigned ? getSMaxExpr(RHS, Start)
7117 : getUMaxExpr(RHS, Start);
7120 const SCEV *BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
7122 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
7123 : getUnsignedRange(Start).getUnsignedMin();
7125 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
7126 : getUnsignedRange(Stride).getUnsignedMin();
7128 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
7129 APInt Limit = IsSigned ? APInt::getSignedMaxValue(BitWidth) - (MinStride - 1)
7130 : APInt::getMaxValue(BitWidth) - (MinStride - 1);
7132 // Although End can be a MAX expression we estimate MaxEnd considering only
7133 // the case End = RHS. This is safe because in the other case (End - Start)
7134 // is zero, leading to a zero maximum backedge taken count.
7136 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
7137 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
7139 const SCEV *MaxBECount;
7140 if (isa<SCEVConstant>(BECount))
7141 MaxBECount = BECount;
7143 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
7144 getConstant(MinStride), false);
7146 if (isa<SCEVCouldNotCompute>(MaxBECount))
7147 MaxBECount = BECount;
7149 return ExitLimit(BECount, MaxBECount);
7152 ScalarEvolution::ExitLimit
7153 ScalarEvolution::HowManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
7154 const Loop *L, bool IsSigned,
7155 bool ControlsExit) {
7156 // We handle only IV > Invariant
7157 if (!isLoopInvariant(RHS, L))
7158 return getCouldNotCompute();
7160 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
7162 // Avoid weird loops
7163 if (!IV || IV->getLoop() != L || !IV->isAffine())
7164 return getCouldNotCompute();
7166 bool NoWrap = ControlsExit &&
7167 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
7169 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
7171 // Avoid negative or zero stride values
7172 if (!isKnownPositive(Stride))
7173 return getCouldNotCompute();
7175 // Avoid proven overflow cases: this will ensure that the backedge taken count
7176 // will not generate any unsigned overflow. Relaxed no-overflow conditions
7177 // exploit NoWrapFlags, allowing to optimize in presence of undefined
7178 // behaviors like the case of C language.
7179 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
7180 return getCouldNotCompute();
7182 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
7183 : ICmpInst::ICMP_UGT;
7185 const SCEV *Start = IV->getStart();
7186 const SCEV *End = RHS;
7187 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
7188 const SCEV *Diff = getMinusSCEV(RHS, Start);
7189 // If we have NoWrap set, then we can assume that the increment won't
7190 // overflow, in which case if RHS - Start is a constant, we don't need to
7191 // do a max operation since we can just figure it out statically
7192 if (NoWrap && isa<SCEVConstant>(Diff)) {
7193 APInt D = dyn_cast<const SCEVConstant>(Diff)->getValue()->getValue();
7194 if (!D.isNegative())
7197 End = IsSigned ? getSMinExpr(RHS, Start)
7198 : getUMinExpr(RHS, Start);
7201 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
7203 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
7204 : getUnsignedRange(Start).getUnsignedMax();
7206 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
7207 : getUnsignedRange(Stride).getUnsignedMin();
7209 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
7210 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
7211 : APInt::getMinValue(BitWidth) + (MinStride - 1);
7213 // Although End can be a MIN expression we estimate MinEnd considering only
7214 // the case End = RHS. This is safe because in the other case (Start - End)
7215 // is zero, leading to a zero maximum backedge taken count.
7217 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
7218 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
7221 const SCEV *MaxBECount = getCouldNotCompute();
7222 if (isa<SCEVConstant>(BECount))
7223 MaxBECount = BECount;
7225 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
7226 getConstant(MinStride), false);
7228 if (isa<SCEVCouldNotCompute>(MaxBECount))
7229 MaxBECount = BECount;
7231 return ExitLimit(BECount, MaxBECount);
7234 /// getNumIterationsInRange - Return the number of iterations of this loop that
7235 /// produce values in the specified constant range. Another way of looking at
7236 /// this is that it returns the first iteration number where the value is not in
7237 /// the condition, thus computing the exit count. If the iteration count can't
7238 /// be computed, an instance of SCEVCouldNotCompute is returned.
7239 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
7240 ScalarEvolution &SE) const {
7241 if (Range.isFullSet()) // Infinite loop.
7242 return SE.getCouldNotCompute();
7244 // If the start is a non-zero constant, shift the range to simplify things.
7245 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
7246 if (!SC->getValue()->isZero()) {
7247 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
7248 Operands[0] = SE.getConstant(SC->getType(), 0);
7249 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
7250 getNoWrapFlags(FlagNW));
7251 if (const SCEVAddRecExpr *ShiftedAddRec =
7252 dyn_cast<SCEVAddRecExpr>(Shifted))
7253 return ShiftedAddRec->getNumIterationsInRange(
7254 Range.subtract(SC->getValue()->getValue()), SE);
7255 // This is strange and shouldn't happen.
7256 return SE.getCouldNotCompute();
7259 // The only time we can solve this is when we have all constant indices.
7260 // Otherwise, we cannot determine the overflow conditions.
7261 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
7262 if (!isa<SCEVConstant>(getOperand(i)))
7263 return SE.getCouldNotCompute();
7266 // Okay at this point we know that all elements of the chrec are constants and
7267 // that the start element is zero.
7269 // First check to see if the range contains zero. If not, the first
7271 unsigned BitWidth = SE.getTypeSizeInBits(getType());
7272 if (!Range.contains(APInt(BitWidth, 0)))
7273 return SE.getConstant(getType(), 0);
7276 // If this is an affine expression then we have this situation:
7277 // Solve {0,+,A} in Range === Ax in Range
7279 // We know that zero is in the range. If A is positive then we know that
7280 // the upper value of the range must be the first possible exit value.
7281 // If A is negative then the lower of the range is the last possible loop
7282 // value. Also note that we already checked for a full range.
7283 APInt One(BitWidth,1);
7284 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
7285 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
7287 // The exit value should be (End+A)/A.
7288 APInt ExitVal = (End + A).udiv(A);
7289 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
7291 // Evaluate at the exit value. If we really did fall out of the valid
7292 // range, then we computed our trip count, otherwise wrap around or other
7293 // things must have happened.
7294 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
7295 if (Range.contains(Val->getValue()))
7296 return SE.getCouldNotCompute(); // Something strange happened
7298 // Ensure that the previous value is in the range. This is a sanity check.
7299 assert(Range.contains(
7300 EvaluateConstantChrecAtConstant(this,
7301 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
7302 "Linear scev computation is off in a bad way!");
7303 return SE.getConstant(ExitValue);
7304 } else if (isQuadratic()) {
7305 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
7306 // quadratic equation to solve it. To do this, we must frame our problem in
7307 // terms of figuring out when zero is crossed, instead of when
7308 // Range.getUpper() is crossed.
7309 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
7310 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
7311 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(),
7312 // getNoWrapFlags(FlagNW)
7315 // Next, solve the constructed addrec
7316 std::pair<const SCEV *,const SCEV *> Roots =
7317 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
7318 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
7319 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
7321 // Pick the smallest positive root value.
7322 if (ConstantInt *CB =
7323 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
7324 R1->getValue(), R2->getValue()))) {
7325 if (CB->getZExtValue() == false)
7326 std::swap(R1, R2); // R1 is the minimum root now.
7328 // Make sure the root is not off by one. The returned iteration should
7329 // not be in the range, but the previous one should be. When solving
7330 // for "X*X < 5", for example, we should not return a root of 2.
7331 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
7334 if (Range.contains(R1Val->getValue())) {
7335 // The next iteration must be out of the range...
7336 ConstantInt *NextVal =
7337 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
7339 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
7340 if (!Range.contains(R1Val->getValue()))
7341 return SE.getConstant(NextVal);
7342 return SE.getCouldNotCompute(); // Something strange happened
7345 // If R1 was not in the range, then it is a good return value. Make
7346 // sure that R1-1 WAS in the range though, just in case.
7347 ConstantInt *NextVal =
7348 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
7349 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
7350 if (Range.contains(R1Val->getValue()))
7352 return SE.getCouldNotCompute(); // Something strange happened
7357 return SE.getCouldNotCompute();
7363 FindUndefs() : Found(false) {}
7365 bool follow(const SCEV *S) {
7366 if (const SCEVUnknown *C = dyn_cast<SCEVUnknown>(S)) {
7367 if (isa<UndefValue>(C->getValue()))
7369 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
7370 if (isa<UndefValue>(C->getValue()))
7374 // Keep looking if we haven't found it yet.
7377 bool isDone() const {
7378 // Stop recursion if we have found an undef.
7384 // Return true when S contains at least an undef value.
7386 containsUndefs(const SCEV *S) {
7388 SCEVTraversal<FindUndefs> ST(F);
7395 // Collect all steps of SCEV expressions.
7396 struct SCEVCollectStrides {
7397 ScalarEvolution &SE;
7398 SmallVectorImpl<const SCEV *> &Strides;
7400 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
7401 : SE(SE), Strides(S) {}
7403 bool follow(const SCEV *S) {
7404 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
7405 Strides.push_back(AR->getStepRecurrence(SE));
7408 bool isDone() const { return false; }
7411 // Collect all SCEVUnknown and SCEVMulExpr expressions.
7412 struct SCEVCollectTerms {
7413 SmallVectorImpl<const SCEV *> &Terms;
7415 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
7418 bool follow(const SCEV *S) {
7419 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S)) {
7420 if (!containsUndefs(S))
7423 // Stop recursion: once we collected a term, do not walk its operands.
7430 bool isDone() const { return false; }
7434 /// Find parametric terms in this SCEVAddRecExpr.
7435 void SCEVAddRecExpr::collectParametricTerms(
7436 ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &Terms) const {
7437 SmallVector<const SCEV *, 4> Strides;
7438 SCEVCollectStrides StrideCollector(SE, Strides);
7439 visitAll(this, StrideCollector);
7442 dbgs() << "Strides:\n";
7443 for (const SCEV *S : Strides)
7444 dbgs() << *S << "\n";
7447 for (const SCEV *S : Strides) {
7448 SCEVCollectTerms TermCollector(Terms);
7449 visitAll(S, TermCollector);
7453 dbgs() << "Terms:\n";
7454 for (const SCEV *T : Terms)
7455 dbgs() << *T << "\n";
7459 static bool findArrayDimensionsRec(ScalarEvolution &SE,
7460 SmallVectorImpl<const SCEV *> &Terms,
7461 SmallVectorImpl<const SCEV *> &Sizes) {
7462 int Last = Terms.size() - 1;
7463 const SCEV *Step = Terms[Last];
7465 // End of recursion.
7467 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
7468 SmallVector<const SCEV *, 2> Qs;
7469 for (const SCEV *Op : M->operands())
7470 if (!isa<SCEVConstant>(Op))
7473 Step = SE.getMulExpr(Qs);
7476 Sizes.push_back(Step);
7480 for (const SCEV *&Term : Terms) {
7481 // Normalize the terms before the next call to findArrayDimensionsRec.
7483 SCEVSDivision::divide(SE, Term, Step, &Q, &R);
7485 // Bail out when GCD does not evenly divide one of the terms.
7492 // Remove all SCEVConstants.
7493 Terms.erase(std::remove_if(Terms.begin(), Terms.end(), [](const SCEV *E) {
7494 return isa<SCEVConstant>(E);
7498 if (Terms.size() > 0)
7499 if (!findArrayDimensionsRec(SE, Terms, Sizes))
7502 Sizes.push_back(Step);
7507 struct FindParameter {
7508 bool FoundParameter;
7509 FindParameter() : FoundParameter(false) {}
7511 bool follow(const SCEV *S) {
7512 if (isa<SCEVUnknown>(S)) {
7513 FoundParameter = true;
7514 // Stop recursion: we found a parameter.
7520 bool isDone() const {
7521 // Stop recursion if we have found a parameter.
7522 return FoundParameter;
7527 // Returns true when S contains at least a SCEVUnknown parameter.
7529 containsParameters(const SCEV *S) {
7531 SCEVTraversal<FindParameter> ST(F);
7534 return F.FoundParameter;
7537 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
7539 containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
7540 for (const SCEV *T : Terms)
7541 if (containsParameters(T))
7546 // Return the number of product terms in S.
7547 static inline int numberOfTerms(const SCEV *S) {
7548 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
7549 return Expr->getNumOperands();
7553 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
7554 if (isa<SCEVConstant>(T))
7557 if (isa<SCEVUnknown>(T))
7560 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
7561 SmallVector<const SCEV *, 2> Factors;
7562 for (const SCEV *Op : M->operands())
7563 if (!isa<SCEVConstant>(Op))
7564 Factors.push_back(Op);
7566 return SE.getMulExpr(Factors);
7572 /// Return the size of an element read or written by Inst.
7573 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
7575 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
7576 Ty = Store->getValueOperand()->getType();
7577 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
7578 Ty = Load->getType();
7582 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
7583 return getSizeOfExpr(ETy, Ty);
7586 /// Second step of delinearization: compute the array dimensions Sizes from the
7587 /// set of Terms extracted from the memory access function of this SCEVAddRec.
7588 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
7589 SmallVectorImpl<const SCEV *> &Sizes,
7590 const SCEV *ElementSize) const {
7592 if (Terms.size() < 1 || !ElementSize)
7595 // Early return when Terms do not contain parameters: we do not delinearize
7596 // non parametric SCEVs.
7597 if (!containsParameters(Terms))
7601 dbgs() << "Terms:\n";
7602 for (const SCEV *T : Terms)
7603 dbgs() << *T << "\n";
7606 // Remove duplicates.
7607 std::sort(Terms.begin(), Terms.end());
7608 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
7610 // Put larger terms first.
7611 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
7612 return numberOfTerms(LHS) > numberOfTerms(RHS);
7615 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
7617 // Divide all terms by the element size.
7618 for (const SCEV *&Term : Terms) {
7620 SCEVSDivision::divide(SE, Term, ElementSize, &Q, &R);
7624 SmallVector<const SCEV *, 4> NewTerms;
7626 // Remove constant factors.
7627 for (const SCEV *T : Terms)
7628 if (const SCEV *NewT = removeConstantFactors(SE, T))
7629 NewTerms.push_back(NewT);
7632 dbgs() << "Terms after sorting:\n";
7633 for (const SCEV *T : NewTerms)
7634 dbgs() << *T << "\n";
7637 if (NewTerms.empty() ||
7638 !findArrayDimensionsRec(SE, NewTerms, Sizes)) {
7643 // The last element to be pushed into Sizes is the size of an element.
7644 Sizes.push_back(ElementSize);
7647 dbgs() << "Sizes:\n";
7648 for (const SCEV *S : Sizes)
7649 dbgs() << *S << "\n";
7653 /// Third step of delinearization: compute the access functions for the
7654 /// Subscripts based on the dimensions in Sizes.
7655 void SCEVAddRecExpr::computeAccessFunctions(
7656 ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &Subscripts,
7657 SmallVectorImpl<const SCEV *> &Sizes) const {
7659 // Early exit in case this SCEV is not an affine multivariate function.
7660 if (Sizes.empty() || !this->isAffine())
7663 const SCEV *Res = this;
7664 int Last = Sizes.size() - 1;
7665 for (int i = Last; i >= 0; i--) {
7667 SCEVSDivision::divide(SE, Res, Sizes[i], &Q, &R);
7670 dbgs() << "Res: " << *Res << "\n";
7671 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
7672 dbgs() << "Res divided by Sizes[i]:\n";
7673 dbgs() << "Quotient: " << *Q << "\n";
7674 dbgs() << "Remainder: " << *R << "\n";
7679 // Do not record the last subscript corresponding to the size of elements in
7683 // Bail out if the remainder is too complex.
7684 if (isa<SCEVAddRecExpr>(R)) {
7693 // Record the access function for the current subscript.
7694 Subscripts.push_back(R);
7697 // Also push in last position the remainder of the last division: it will be
7698 // the access function of the innermost dimension.
7699 Subscripts.push_back(Res);
7701 std::reverse(Subscripts.begin(), Subscripts.end());
7704 dbgs() << "Subscripts:\n";
7705 for (const SCEV *S : Subscripts)
7706 dbgs() << *S << "\n";
7710 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
7711 /// sizes of an array access. Returns the remainder of the delinearization that
7712 /// is the offset start of the array. The SCEV->delinearize algorithm computes
7713 /// the multiples of SCEV coefficients: that is a pattern matching of sub
7714 /// expressions in the stride and base of a SCEV corresponding to the
7715 /// computation of a GCD (greatest common divisor) of base and stride. When
7716 /// SCEV->delinearize fails, it returns the SCEV unchanged.
7718 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
7720 /// void foo(long n, long m, long o, double A[n][m][o]) {
7722 /// for (long i = 0; i < n; i++)
7723 /// for (long j = 0; j < m; j++)
7724 /// for (long k = 0; k < o; k++)
7725 /// A[i][j][k] = 1.0;
7728 /// the delinearization input is the following AddRec SCEV:
7730 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
7732 /// From this SCEV, we are able to say that the base offset of the access is %A
7733 /// because it appears as an offset that does not divide any of the strides in
7736 /// CHECK: Base offset: %A
7738 /// and then SCEV->delinearize determines the size of some of the dimensions of
7739 /// the array as these are the multiples by which the strides are happening:
7741 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
7743 /// Note that the outermost dimension remains of UnknownSize because there are
7744 /// no strides that would help identifying the size of the last dimension: when
7745 /// the array has been statically allocated, one could compute the size of that
7746 /// dimension by dividing the overall size of the array by the size of the known
7747 /// dimensions: %m * %o * 8.
7749 /// Finally delinearize provides the access functions for the array reference
7750 /// that does correspond to A[i][j][k] of the above C testcase:
7752 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
7754 /// The testcases are checking the output of a function pass:
7755 /// DelinearizationPass that walks through all loads and stores of a function
7756 /// asking for the SCEV of the memory access with respect to all enclosing
7757 /// loops, calling SCEV->delinearize on that and printing the results.
7759 void SCEVAddRecExpr::delinearize(ScalarEvolution &SE,
7760 SmallVectorImpl<const SCEV *> &Subscripts,
7761 SmallVectorImpl<const SCEV *> &Sizes,
7762 const SCEV *ElementSize) const {
7763 // First step: collect parametric terms.
7764 SmallVector<const SCEV *, 4> Terms;
7765 collectParametricTerms(SE, Terms);
7770 // Second step: find subscript sizes.
7771 SE.findArrayDimensions(Terms, Sizes, ElementSize);
7776 // Third step: compute the access functions for each subscript.
7777 computeAccessFunctions(SE, Subscripts, Sizes);
7779 if (Subscripts.empty())
7783 dbgs() << "succeeded to delinearize " << *this << "\n";
7784 dbgs() << "ArrayDecl[UnknownSize]";
7785 for (const SCEV *S : Sizes)
7786 dbgs() << "[" << *S << "]";
7788 dbgs() << "\nArrayRef";
7789 for (const SCEV *S : Subscripts)
7790 dbgs() << "[" << *S << "]";
7795 //===----------------------------------------------------------------------===//
7796 // SCEVCallbackVH Class Implementation
7797 //===----------------------------------------------------------------------===//
7799 void ScalarEvolution::SCEVCallbackVH::deleted() {
7800 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
7801 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
7802 SE->ConstantEvolutionLoopExitValue.erase(PN);
7803 SE->ValueExprMap.erase(getValPtr());
7804 // this now dangles!
7807 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
7808 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
7810 // Forget all the expressions associated with users of the old value,
7811 // so that future queries will recompute the expressions using the new
7813 Value *Old = getValPtr();
7814 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
7815 SmallPtrSet<User *, 8> Visited;
7816 while (!Worklist.empty()) {
7817 User *U = Worklist.pop_back_val();
7818 // Deleting the Old value will cause this to dangle. Postpone
7819 // that until everything else is done.
7822 if (!Visited.insert(U).second)
7824 if (PHINode *PN = dyn_cast<PHINode>(U))
7825 SE->ConstantEvolutionLoopExitValue.erase(PN);
7826 SE->ValueExprMap.erase(U);
7827 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
7829 // Delete the Old value.
7830 if (PHINode *PN = dyn_cast<PHINode>(Old))
7831 SE->ConstantEvolutionLoopExitValue.erase(PN);
7832 SE->ValueExprMap.erase(Old);
7833 // this now dangles!
7836 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
7837 : CallbackVH(V), SE(se) {}
7839 //===----------------------------------------------------------------------===//
7840 // ScalarEvolution Class Implementation
7841 //===----------------------------------------------------------------------===//
7843 ScalarEvolution::ScalarEvolution()
7844 : FunctionPass(ID), ValuesAtScopes(64), LoopDispositions(64),
7845 BlockDispositions(64), FirstUnknown(nullptr) {
7846 initializeScalarEvolutionPass(*PassRegistry::getPassRegistry());
7849 bool ScalarEvolution::runOnFunction(Function &F) {
7851 AT = &getAnalysis<AssumptionTracker>();
7852 LI = &getAnalysis<LoopInfo>();
7853 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
7854 DL = DLP ? &DLP->getDataLayout() : nullptr;
7855 TLI = &getAnalysis<TargetLibraryInfo>();
7856 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
7860 void ScalarEvolution::releaseMemory() {
7861 // Iterate through all the SCEVUnknown instances and call their
7862 // destructors, so that they release their references to their values.
7863 for (SCEVUnknown *U = FirstUnknown; U; U = U->Next)
7865 FirstUnknown = nullptr;
7867 ValueExprMap.clear();
7869 // Free any extra memory created for ExitNotTakenInfo in the unlikely event
7870 // that a loop had multiple computable exits.
7871 for (DenseMap<const Loop*, BackedgeTakenInfo>::iterator I =
7872 BackedgeTakenCounts.begin(), E = BackedgeTakenCounts.end();
7877 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
7879 BackedgeTakenCounts.clear();
7880 ConstantEvolutionLoopExitValue.clear();
7881 ValuesAtScopes.clear();
7882 LoopDispositions.clear();
7883 BlockDispositions.clear();
7884 UnsignedRanges.clear();
7885 SignedRanges.clear();
7886 UniqueSCEVs.clear();
7887 SCEVAllocator.Reset();
7890 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
7891 AU.setPreservesAll();
7892 AU.addRequired<AssumptionTracker>();
7893 AU.addRequiredTransitive<LoopInfo>();
7894 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
7895 AU.addRequired<TargetLibraryInfo>();
7898 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
7899 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
7902 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
7904 // Print all inner loops first
7905 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
7906 PrintLoopInfo(OS, SE, *I);
7909 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
7912 SmallVector<BasicBlock *, 8> ExitBlocks;
7913 L->getExitBlocks(ExitBlocks);
7914 if (ExitBlocks.size() != 1)
7915 OS << "<multiple exits> ";
7917 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
7918 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
7920 OS << "Unpredictable backedge-taken count. ";
7925 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
7928 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
7929 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
7931 OS << "Unpredictable max backedge-taken count. ";
7937 void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
7938 // ScalarEvolution's implementation of the print method is to print
7939 // out SCEV values of all instructions that are interesting. Doing
7940 // this potentially causes it to create new SCEV objects though,
7941 // which technically conflicts with the const qualifier. This isn't
7942 // observable from outside the class though, so casting away the
7943 // const isn't dangerous.
7944 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
7946 OS << "Classifying expressions for: ";
7947 F->printAsOperand(OS, /*PrintType=*/false);
7949 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
7950 if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) {
7953 const SCEV *SV = SE.getSCEV(&*I);
7956 const Loop *L = LI->getLoopFor((*I).getParent());
7958 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
7965 OS << "\t\t" "Exits: ";
7966 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
7967 if (!SE.isLoopInvariant(ExitValue, L)) {
7968 OS << "<<Unknown>>";
7977 OS << "Determining loop execution counts for: ";
7978 F->printAsOperand(OS, /*PrintType=*/false);
7980 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
7981 PrintLoopInfo(OS, &SE, *I);
7984 ScalarEvolution::LoopDisposition
7985 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
7986 SmallVector<std::pair<const Loop *, LoopDisposition>, 2> &Values = LoopDispositions[S];
7987 for (unsigned u = 0; u < Values.size(); u++) {
7988 if (Values[u].first == L)
7989 return Values[u].second;
7991 Values.push_back(std::make_pair(L, LoopVariant));
7992 LoopDisposition D = computeLoopDisposition(S, L);
7993 SmallVector<std::pair<const Loop *, LoopDisposition>, 2> &Values2 = LoopDispositions[S];
7994 for (unsigned u = Values2.size(); u > 0; u--) {
7995 if (Values2[u - 1].first == L) {
7996 Values2[u - 1].second = D;
8003 ScalarEvolution::LoopDisposition
8004 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
8005 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
8007 return LoopInvariant;
8011 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
8012 case scAddRecExpr: {
8013 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
8015 // If L is the addrec's loop, it's computable.
8016 if (AR->getLoop() == L)
8017 return LoopComputable;
8019 // Add recurrences are never invariant in the function-body (null loop).
8023 // This recurrence is variant w.r.t. L if L contains AR's loop.
8024 if (L->contains(AR->getLoop()))
8027 // This recurrence is invariant w.r.t. L if AR's loop contains L.
8028 if (AR->getLoop()->contains(L))
8029 return LoopInvariant;
8031 // This recurrence is variant w.r.t. L if any of its operands
8033 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
8035 if (!isLoopInvariant(*I, L))
8038 // Otherwise it's loop-invariant.
8039 return LoopInvariant;
8045 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
8046 bool HasVarying = false;
8047 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
8049 LoopDisposition D = getLoopDisposition(*I, L);
8050 if (D == LoopVariant)
8052 if (D == LoopComputable)
8055 return HasVarying ? LoopComputable : LoopInvariant;
8058 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
8059 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
8060 if (LD == LoopVariant)
8062 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
8063 if (RD == LoopVariant)
8065 return (LD == LoopInvariant && RD == LoopInvariant) ?
8066 LoopInvariant : LoopComputable;
8069 // All non-instruction values are loop invariant. All instructions are loop
8070 // invariant if they are not contained in the specified loop.
8071 // Instructions are never considered invariant in the function body
8072 // (null loop) because they are defined within the "loop".
8073 if (Instruction *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
8074 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
8075 return LoopInvariant;
8076 case scCouldNotCompute:
8077 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
8079 llvm_unreachable("Unknown SCEV kind!");
8082 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
8083 return getLoopDisposition(S, L) == LoopInvariant;
8086 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
8087 return getLoopDisposition(S, L) == LoopComputable;
8090 ScalarEvolution::BlockDisposition
8091 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
8092 SmallVector<std::pair<const BasicBlock *, BlockDisposition>, 2> &Values = BlockDispositions[S];
8093 for (unsigned u = 0; u < Values.size(); u++) {
8094 if (Values[u].first == BB)
8095 return Values[u].second;
8097 Values.push_back(std::make_pair(BB, DoesNotDominateBlock));
8098 BlockDisposition D = computeBlockDisposition(S, BB);
8099 SmallVector<std::pair<const BasicBlock *, BlockDisposition>, 2> &Values2 = BlockDispositions[S];
8100 for (unsigned u = Values2.size(); u > 0; u--) {
8101 if (Values2[u - 1].first == BB) {
8102 Values2[u - 1].second = D;
8109 ScalarEvolution::BlockDisposition
8110 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
8111 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
8113 return ProperlyDominatesBlock;
8117 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
8118 case scAddRecExpr: {
8119 // This uses a "dominates" query instead of "properly dominates" query
8120 // to test for proper dominance too, because the instruction which
8121 // produces the addrec's value is a PHI, and a PHI effectively properly
8122 // dominates its entire containing block.
8123 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
8124 if (!DT->dominates(AR->getLoop()->getHeader(), BB))
8125 return DoesNotDominateBlock;
8127 // FALL THROUGH into SCEVNAryExpr handling.
8132 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
8134 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
8136 BlockDisposition D = getBlockDisposition(*I, BB);
8137 if (D == DoesNotDominateBlock)
8138 return DoesNotDominateBlock;
8139 if (D == DominatesBlock)
8142 return Proper ? ProperlyDominatesBlock : DominatesBlock;
8145 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
8146 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
8147 BlockDisposition LD = getBlockDisposition(LHS, BB);
8148 if (LD == DoesNotDominateBlock)
8149 return DoesNotDominateBlock;
8150 BlockDisposition RD = getBlockDisposition(RHS, BB);
8151 if (RD == DoesNotDominateBlock)
8152 return DoesNotDominateBlock;
8153 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
8154 ProperlyDominatesBlock : DominatesBlock;
8157 if (Instruction *I =
8158 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
8159 if (I->getParent() == BB)
8160 return DominatesBlock;
8161 if (DT->properlyDominates(I->getParent(), BB))
8162 return ProperlyDominatesBlock;
8163 return DoesNotDominateBlock;
8165 return ProperlyDominatesBlock;
8166 case scCouldNotCompute:
8167 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
8169 llvm_unreachable("Unknown SCEV kind!");
8172 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
8173 return getBlockDisposition(S, BB) >= DominatesBlock;
8176 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
8177 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
8181 // Search for a SCEV expression node within an expression tree.
8182 // Implements SCEVTraversal::Visitor.
8187 SCEVSearch(const SCEV *N): Node(N), IsFound(false) {}
8189 bool follow(const SCEV *S) {
8190 IsFound |= (S == Node);
8193 bool isDone() const { return IsFound; }
8197 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
8198 SCEVSearch Search(Op);
8199 visitAll(S, Search);
8200 return Search.IsFound;
8203 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
8204 ValuesAtScopes.erase(S);
8205 LoopDispositions.erase(S);
8206 BlockDispositions.erase(S);
8207 UnsignedRanges.erase(S);
8208 SignedRanges.erase(S);
8210 for (DenseMap<const Loop*, BackedgeTakenInfo>::iterator I =
8211 BackedgeTakenCounts.begin(), E = BackedgeTakenCounts.end(); I != E; ) {
8212 BackedgeTakenInfo &BEInfo = I->second;
8213 if (BEInfo.hasOperand(S, this)) {
8215 BackedgeTakenCounts.erase(I++);
8222 typedef DenseMap<const Loop *, std::string> VerifyMap;
8224 /// replaceSubString - Replaces all occurrences of From in Str with To.
8225 static void replaceSubString(std::string &Str, StringRef From, StringRef To) {
8227 while ((Pos = Str.find(From, Pos)) != std::string::npos) {
8228 Str.replace(Pos, From.size(), To.data(), To.size());
8233 /// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis.
8235 getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) {
8236 for (Loop::reverse_iterator I = L->rbegin(), E = L->rend(); I != E; ++I) {
8237 getLoopBackedgeTakenCounts(*I, Map, SE); // recurse.
8239 std::string &S = Map[L];
8241 raw_string_ostream OS(S);
8242 SE.getBackedgeTakenCount(L)->print(OS);
8244 // false and 0 are semantically equivalent. This can happen in dead loops.
8245 replaceSubString(OS.str(), "false", "0");
8246 // Remove wrap flags, their use in SCEV is highly fragile.
8247 // FIXME: Remove this when SCEV gets smarter about them.
8248 replaceSubString(OS.str(), "<nw>", "");
8249 replaceSubString(OS.str(), "<nsw>", "");
8250 replaceSubString(OS.str(), "<nuw>", "");
8255 void ScalarEvolution::verifyAnalysis() const {
8259 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
8261 // Gather stringified backedge taken counts for all loops using SCEV's caches.
8262 // FIXME: It would be much better to store actual values instead of strings,
8263 // but SCEV pointers will change if we drop the caches.
8264 VerifyMap BackedgeDumpsOld, BackedgeDumpsNew;
8265 for (LoopInfo::reverse_iterator I = LI->rbegin(), E = LI->rend(); I != E; ++I)
8266 getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE);
8268 // Gather stringified backedge taken counts for all loops without using
8271 for (LoopInfo::reverse_iterator I = LI->rbegin(), E = LI->rend(); I != E; ++I)
8272 getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE);
8274 // Now compare whether they're the same with and without caches. This allows
8275 // verifying that no pass changed the cache.
8276 assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() &&
8277 "New loops suddenly appeared!");
8279 for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(),
8280 OldE = BackedgeDumpsOld.end(),
8281 NewI = BackedgeDumpsNew.begin();
8282 OldI != OldE; ++OldI, ++NewI) {
8283 assert(OldI->first == NewI->first && "Loop order changed!");
8285 // Compare the stringified SCEVs. We don't care if undef backedgetaken count
8287 // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This
8288 // means that a pass is buggy or SCEV has to learn a new pattern but is
8289 // usually not harmful.
8290 if (OldI->second != NewI->second &&
8291 OldI->second.find("undef") == std::string::npos &&
8292 NewI->second.find("undef") == std::string::npos &&
8293 OldI->second != "***COULDNOTCOMPUTE***" &&
8294 NewI->second != "***COULDNOTCOMPUTE***") {
8295 dbgs() << "SCEVValidator: SCEV for loop '"
8296 << OldI->first->getHeader()->getName()
8297 << "' changed from '" << OldI->second
8298 << "' to '" << NewI->second << "'!\n";
8303 // TODO: Verify more things.