1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file contains the implementation of the scalar evolution analysis
10 // engine, which is used primarily to analyze expressions involving induction
11 // variables in loops.
13 // There are several aspects to this library. First is the representation of
14 // scalar expressions, which are represented as subclasses of the SCEV class.
15 // These classes are used to represent certain types of subexpressions that we
16 // can handle. We only create one SCEV of a particular shape, so
17 // pointer-comparisons for equality are legal.
19 // One important aspect of the SCEV objects is that they are never cyclic, even
20 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If
21 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
22 // recurrence) then we represent it directly as a recurrence node, otherwise we
23 // represent it as a SCEVUnknown node.
25 // In addition to being able to represent expressions of various types, we also
26 // have folders that are used to build the *canonical* representation for a
27 // particular expression. These folders are capable of using a variety of
28 // rewrite rules to simplify the expressions.
30 // Once the folders are defined, we can implement the more interesting
31 // higher-level code, such as the code that recognizes PHI nodes of various
32 // types, computes the execution count of a loop, etc.
34 // TODO: We should use these routines and value representations to implement
35 // dependence analysis!
37 //===----------------------------------------------------------------------===//
39 // There are several good references for the techniques used in this analysis.
41 // Chains of recurrences -- a method to expedite the evaluation
42 // of closed-form functions
43 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima
45 // On computational properties of chains of recurrences
48 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization
49 // Robert A. van Engelen
51 // Efficient Symbolic Analysis for Optimizing Compilers
52 // Robert A. van Engelen
54 // Using the chains of recurrences algebra for data dependence testing and
55 // induction variable substitution
56 // MS Thesis, Johnie Birch
58 //===----------------------------------------------------------------------===//
60 #include "llvm/Analysis/ScalarEvolution.h"
61 #include "llvm/ADT/APInt.h"
62 #include "llvm/ADT/ArrayRef.h"
63 #include "llvm/ADT/DenseMap.h"
64 #include "llvm/ADT/DepthFirstIterator.h"
65 #include "llvm/ADT/EquivalenceClasses.h"
66 #include "llvm/ADT/FoldingSet.h"
67 #include "llvm/ADT/None.h"
68 #include "llvm/ADT/Optional.h"
69 #include "llvm/ADT/STLExtras.h"
70 #include "llvm/ADT/ScopeExit.h"
71 #include "llvm/ADT/Sequence.h"
72 #include "llvm/ADT/SetVector.h"
73 #include "llvm/ADT/SmallPtrSet.h"
74 #include "llvm/ADT/SmallSet.h"
75 #include "llvm/ADT/SmallVector.h"
76 #include "llvm/ADT/Statistic.h"
77 #include "llvm/ADT/StringRef.h"
78 #include "llvm/Analysis/AssumptionCache.h"
79 #include "llvm/Analysis/ConstantFolding.h"
80 #include "llvm/Analysis/InstructionSimplify.h"
81 #include "llvm/Analysis/LoopInfo.h"
82 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
83 #include "llvm/Analysis/TargetLibraryInfo.h"
84 #include "llvm/Analysis/ValueTracking.h"
85 #include "llvm/Config/llvm-config.h"
86 #include "llvm/IR/Argument.h"
87 #include "llvm/IR/BasicBlock.h"
88 #include "llvm/IR/CFG.h"
89 #include "llvm/IR/CallSite.h"
90 #include "llvm/IR/Constant.h"
91 #include "llvm/IR/ConstantRange.h"
92 #include "llvm/IR/Constants.h"
93 #include "llvm/IR/DataLayout.h"
94 #include "llvm/IR/DerivedTypes.h"
95 #include "llvm/IR/Dominators.h"
96 #include "llvm/IR/Function.h"
97 #include "llvm/IR/GlobalAlias.h"
98 #include "llvm/IR/GlobalValue.h"
99 #include "llvm/IR/GlobalVariable.h"
100 #include "llvm/IR/InstIterator.h"
101 #include "llvm/IR/InstrTypes.h"
102 #include "llvm/IR/Instruction.h"
103 #include "llvm/IR/Instructions.h"
104 #include "llvm/IR/IntrinsicInst.h"
105 #include "llvm/IR/Intrinsics.h"
106 #include "llvm/IR/LLVMContext.h"
107 #include "llvm/IR/Metadata.h"
108 #include "llvm/IR/Operator.h"
109 #include "llvm/IR/PatternMatch.h"
110 #include "llvm/IR/Type.h"
111 #include "llvm/IR/Use.h"
112 #include "llvm/IR/User.h"
113 #include "llvm/IR/Value.h"
114 #include "llvm/IR/Verifier.h"
115 #include "llvm/Pass.h"
116 #include "llvm/Support/Casting.h"
117 #include "llvm/Support/CommandLine.h"
118 #include "llvm/Support/Compiler.h"
119 #include "llvm/Support/Debug.h"
120 #include "llvm/Support/ErrorHandling.h"
121 #include "llvm/Support/KnownBits.h"
122 #include "llvm/Support/SaveAndRestore.h"
123 #include "llvm/Support/raw_ostream.h"
136 using namespace llvm
;
138 #define DEBUG_TYPE "scalar-evolution"
140 STATISTIC(NumArrayLenItCounts
,
141 "Number of trip counts computed with array length");
142 STATISTIC(NumTripCountsComputed
,
143 "Number of loops with predictable loop counts");
144 STATISTIC(NumTripCountsNotComputed
,
145 "Number of loops without predictable loop counts");
146 STATISTIC(NumBruteForceTripCountsComputed
,
147 "Number of loops with trip counts computed by force");
149 static cl::opt
<unsigned>
150 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden
,
152 cl::desc("Maximum number of iterations SCEV will "
153 "symbolically execute a constant "
157 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
158 static cl::opt
<bool> VerifySCEV(
159 "verify-scev", cl::Hidden
,
160 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
162 VerifySCEVMap("verify-scev-maps", cl::Hidden
,
163 cl::desc("Verify no dangling value in ScalarEvolution's "
164 "ExprValueMap (slow)"));
166 static cl::opt
<bool> VerifyIR(
167 "scev-verify-ir", cl::Hidden
,
168 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
171 static cl::opt
<unsigned> MulOpsInlineThreshold(
172 "scev-mulops-inline-threshold", cl::Hidden
,
173 cl::desc("Threshold for inlining multiplication operands into a SCEV"),
176 static cl::opt
<unsigned> AddOpsInlineThreshold(
177 "scev-addops-inline-threshold", cl::Hidden
,
178 cl::desc("Threshold for inlining addition operands into a SCEV"),
181 static cl::opt
<unsigned> MaxSCEVCompareDepth(
182 "scalar-evolution-max-scev-compare-depth", cl::Hidden
,
183 cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
186 static cl::opt
<unsigned> MaxSCEVOperationsImplicationDepth(
187 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden
,
188 cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
191 static cl::opt
<unsigned> MaxValueCompareDepth(
192 "scalar-evolution-max-value-compare-depth", cl::Hidden
,
193 cl::desc("Maximum depth of recursive value complexity comparisons"),
196 static cl::opt
<unsigned>
197 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden
,
198 cl::desc("Maximum depth of recursive arithmetics"),
201 static cl::opt
<unsigned> MaxConstantEvolvingDepth(
202 "scalar-evolution-max-constant-evolving-depth", cl::Hidden
,
203 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
205 static cl::opt
<unsigned>
206 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden
,
207 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
210 static cl::opt
<unsigned>
211 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden
,
212 cl::desc("Max coefficients in AddRec during evolving"),
215 static cl::opt
<unsigned>
216 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden
,
217 cl::desc("Size of the expression which is considered huge"),
220 //===----------------------------------------------------------------------===//
221 // SCEV class definitions
222 //===----------------------------------------------------------------------===//
224 //===----------------------------------------------------------------------===//
225 // Implementation of the SCEV class.
228 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
229 LLVM_DUMP_METHOD
void SCEV::dump() const {
235 void SCEV::print(raw_ostream
&OS
) const {
236 switch (static_cast<SCEVTypes
>(getSCEVType())) {
238 cast
<SCEVConstant
>(this)->getValue()->printAsOperand(OS
, false);
241 const SCEVTruncateExpr
*Trunc
= cast
<SCEVTruncateExpr
>(this);
242 const SCEV
*Op
= Trunc
->getOperand();
243 OS
<< "(trunc " << *Op
->getType() << " " << *Op
<< " to "
244 << *Trunc
->getType() << ")";
248 const SCEVZeroExtendExpr
*ZExt
= cast
<SCEVZeroExtendExpr
>(this);
249 const SCEV
*Op
= ZExt
->getOperand();
250 OS
<< "(zext " << *Op
->getType() << " " << *Op
<< " to "
251 << *ZExt
->getType() << ")";
255 const SCEVSignExtendExpr
*SExt
= cast
<SCEVSignExtendExpr
>(this);
256 const SCEV
*Op
= SExt
->getOperand();
257 OS
<< "(sext " << *Op
->getType() << " " << *Op
<< " to "
258 << *SExt
->getType() << ")";
262 const SCEVAddRecExpr
*AR
= cast
<SCEVAddRecExpr
>(this);
263 OS
<< "{" << *AR
->getOperand(0);
264 for (unsigned i
= 1, e
= AR
->getNumOperands(); i
!= e
; ++i
)
265 OS
<< ",+," << *AR
->getOperand(i
);
267 if (AR
->hasNoUnsignedWrap())
269 if (AR
->hasNoSignedWrap())
271 if (AR
->hasNoSelfWrap() &&
272 !AR
->getNoWrapFlags((NoWrapFlags
)(FlagNUW
| FlagNSW
)))
274 AR
->getLoop()->getHeader()->printAsOperand(OS
, /*PrintType=*/false);
284 const SCEVNAryExpr
*NAry
= cast
<SCEVNAryExpr
>(this);
285 const char *OpStr
= nullptr;
286 switch (NAry
->getSCEVType()) {
287 case scAddExpr
: OpStr
= " + "; break;
288 case scMulExpr
: OpStr
= " * "; break;
289 case scUMaxExpr
: OpStr
= " umax "; break;
290 case scSMaxExpr
: OpStr
= " smax "; break;
299 for (SCEVNAryExpr::op_iterator I
= NAry
->op_begin(), E
= NAry
->op_end();
302 if (std::next(I
) != E
)
306 switch (NAry
->getSCEVType()) {
309 if (NAry
->hasNoUnsignedWrap())
311 if (NAry
->hasNoSignedWrap())
317 const SCEVUDivExpr
*UDiv
= cast
<SCEVUDivExpr
>(this);
318 OS
<< "(" << *UDiv
->getLHS() << " /u " << *UDiv
->getRHS() << ")";
322 const SCEVUnknown
*U
= cast
<SCEVUnknown
>(this);
324 if (U
->isSizeOf(AllocTy
)) {
325 OS
<< "sizeof(" << *AllocTy
<< ")";
328 if (U
->isAlignOf(AllocTy
)) {
329 OS
<< "alignof(" << *AllocTy
<< ")";
335 if (U
->isOffsetOf(CTy
, FieldNo
)) {
336 OS
<< "offsetof(" << *CTy
<< ", ";
337 FieldNo
->printAsOperand(OS
, false);
342 // Otherwise just print it normally.
343 U
->getValue()->printAsOperand(OS
, false);
346 case scCouldNotCompute
:
347 OS
<< "***COULDNOTCOMPUTE***";
350 llvm_unreachable("Unknown SCEV kind!");
353 Type
*SCEV::getType() const {
354 switch (static_cast<SCEVTypes
>(getSCEVType())) {
356 return cast
<SCEVConstant
>(this)->getType();
360 return cast
<SCEVCastExpr
>(this)->getType();
367 return cast
<SCEVNAryExpr
>(this)->getType();
369 return cast
<SCEVAddExpr
>(this)->getType();
371 return cast
<SCEVUDivExpr
>(this)->getType();
373 return cast
<SCEVUnknown
>(this)->getType();
374 case scCouldNotCompute
:
375 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
377 llvm_unreachable("Unknown SCEV kind!");
380 bool SCEV::isZero() const {
381 if (const SCEVConstant
*SC
= dyn_cast
<SCEVConstant
>(this))
382 return SC
->getValue()->isZero();
386 bool SCEV::isOne() const {
387 if (const SCEVConstant
*SC
= dyn_cast
<SCEVConstant
>(this))
388 return SC
->getValue()->isOne();
392 bool SCEV::isAllOnesValue() const {
393 if (const SCEVConstant
*SC
= dyn_cast
<SCEVConstant
>(this))
394 return SC
->getValue()->isMinusOne();
398 bool SCEV::isNonConstantNegative() const {
399 const SCEVMulExpr
*Mul
= dyn_cast
<SCEVMulExpr
>(this);
400 if (!Mul
) return false;
402 // If there is a constant factor, it will be first.
403 const SCEVConstant
*SC
= dyn_cast
<SCEVConstant
>(Mul
->getOperand(0));
404 if (!SC
) return false;
406 // Return true if the value is negative, this matches things like (-42 * V).
407 return SC
->getAPInt().isNegative();
410 SCEVCouldNotCompute::SCEVCouldNotCompute() :
411 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute
, 0) {}
413 bool SCEVCouldNotCompute::classof(const SCEV
*S
) {
414 return S
->getSCEVType() == scCouldNotCompute
;
417 const SCEV
*ScalarEvolution::getConstant(ConstantInt
*V
) {
419 ID
.AddInteger(scConstant
);
422 if (const SCEV
*S
= UniqueSCEVs
.FindNodeOrInsertPos(ID
, IP
)) return S
;
423 SCEV
*S
= new (SCEVAllocator
) SCEVConstant(ID
.Intern(SCEVAllocator
), V
);
424 UniqueSCEVs
.InsertNode(S
, IP
);
428 const SCEV
*ScalarEvolution::getConstant(const APInt
&Val
) {
429 return getConstant(ConstantInt::get(getContext(), Val
));
433 ScalarEvolution::getConstant(Type
*Ty
, uint64_t V
, bool isSigned
) {
434 IntegerType
*ITy
= cast
<IntegerType
>(getEffectiveSCEVType(Ty
));
435 return getConstant(ConstantInt::get(ITy
, V
, isSigned
));
438 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID
,
439 unsigned SCEVTy
, const SCEV
*op
, Type
*ty
)
440 : SCEV(ID
, SCEVTy
, computeExpressionSize(op
)), Op(op
), Ty(ty
) {}
442 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID
,
443 const SCEV
*op
, Type
*ty
)
444 : SCEVCastExpr(ID
, scTruncate
, op
, ty
) {
445 assert(Op
->getType()->isIntOrPtrTy() && Ty
->isIntOrPtrTy() &&
446 "Cannot truncate non-integer value!");
449 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID
,
450 const SCEV
*op
, Type
*ty
)
451 : SCEVCastExpr(ID
, scZeroExtend
, op
, ty
) {
452 assert(Op
->getType()->isIntOrPtrTy() && Ty
->isIntOrPtrTy() &&
453 "Cannot zero extend non-integer value!");
456 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID
,
457 const SCEV
*op
, Type
*ty
)
458 : SCEVCastExpr(ID
, scSignExtend
, op
, ty
) {
459 assert(Op
->getType()->isIntOrPtrTy() && Ty
->isIntOrPtrTy() &&
460 "Cannot sign extend non-integer value!");
463 void SCEVUnknown::deleted() {
464 // Clear this SCEVUnknown from various maps.
465 SE
->forgetMemoizedResults(this);
467 // Remove this SCEVUnknown from the uniquing map.
468 SE
->UniqueSCEVs
.RemoveNode(this);
470 // Release the value.
474 void SCEVUnknown::allUsesReplacedWith(Value
*New
) {
475 // Remove this SCEVUnknown from the uniquing map.
476 SE
->UniqueSCEVs
.RemoveNode(this);
478 // Update this SCEVUnknown to point to the new value. This is needed
479 // because there may still be outstanding SCEVs which still point to
484 bool SCEVUnknown::isSizeOf(Type
*&AllocTy
) const {
485 if (ConstantExpr
*VCE
= dyn_cast
<ConstantExpr
>(getValue()))
486 if (VCE
->getOpcode() == Instruction::PtrToInt
)
487 if (ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(VCE
->getOperand(0)))
488 if (CE
->getOpcode() == Instruction::GetElementPtr
&&
489 CE
->getOperand(0)->isNullValue() &&
490 CE
->getNumOperands() == 2)
491 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(CE
->getOperand(1)))
493 AllocTy
= cast
<PointerType
>(CE
->getOperand(0)->getType())
501 bool SCEVUnknown::isAlignOf(Type
*&AllocTy
) const {
502 if (ConstantExpr
*VCE
= dyn_cast
<ConstantExpr
>(getValue()))
503 if (VCE
->getOpcode() == Instruction::PtrToInt
)
504 if (ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(VCE
->getOperand(0)))
505 if (CE
->getOpcode() == Instruction::GetElementPtr
&&
506 CE
->getOperand(0)->isNullValue()) {
508 cast
<PointerType
>(CE
->getOperand(0)->getType())->getElementType();
509 if (StructType
*STy
= dyn_cast
<StructType
>(Ty
))
510 if (!STy
->isPacked() &&
511 CE
->getNumOperands() == 3 &&
512 CE
->getOperand(1)->isNullValue()) {
513 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(CE
->getOperand(2)))
515 STy
->getNumElements() == 2 &&
516 STy
->getElementType(0)->isIntegerTy(1)) {
517 AllocTy
= STy
->getElementType(1);
526 bool SCEVUnknown::isOffsetOf(Type
*&CTy
, Constant
*&FieldNo
) const {
527 if (ConstantExpr
*VCE
= dyn_cast
<ConstantExpr
>(getValue()))
528 if (VCE
->getOpcode() == Instruction::PtrToInt
)
529 if (ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(VCE
->getOperand(0)))
530 if (CE
->getOpcode() == Instruction::GetElementPtr
&&
531 CE
->getNumOperands() == 3 &&
532 CE
->getOperand(0)->isNullValue() &&
533 CE
->getOperand(1)->isNullValue()) {
535 cast
<PointerType
>(CE
->getOperand(0)->getType())->getElementType();
536 // Ignore vector types here so that ScalarEvolutionExpander doesn't
537 // emit getelementptrs that index into vectors.
538 if (Ty
->isStructTy() || Ty
->isArrayTy()) {
540 FieldNo
= CE
->getOperand(2);
548 //===----------------------------------------------------------------------===//
550 //===----------------------------------------------------------------------===//
552 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
553 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
554 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that
555 /// have been previously deemed to be "equally complex" by this routine. It is
556 /// intended to avoid exponential time complexity in cases like:
566 /// CompareValueComplexity(%f, %c)
568 /// Since we do not continue running this routine on expression trees once we
569 /// have seen unequal values, there is no need to track them in the cache.
571 CompareValueComplexity(EquivalenceClasses
<const Value
*> &EqCacheValue
,
572 const LoopInfo
*const LI
, Value
*LV
, Value
*RV
,
574 if (Depth
> MaxValueCompareDepth
|| EqCacheValue
.isEquivalent(LV
, RV
))
577 // Order pointer values after integer values. This helps SCEVExpander form
579 bool LIsPointer
= LV
->getType()->isPointerTy(),
580 RIsPointer
= RV
->getType()->isPointerTy();
581 if (LIsPointer
!= RIsPointer
)
582 return (int)LIsPointer
- (int)RIsPointer
;
584 // Compare getValueID values.
585 unsigned LID
= LV
->getValueID(), RID
= RV
->getValueID();
587 return (int)LID
- (int)RID
;
589 // Sort arguments by their position.
590 if (const auto *LA
= dyn_cast
<Argument
>(LV
)) {
591 const auto *RA
= cast
<Argument
>(RV
);
592 unsigned LArgNo
= LA
->getArgNo(), RArgNo
= RA
->getArgNo();
593 return (int)LArgNo
- (int)RArgNo
;
596 if (const auto *LGV
= dyn_cast
<GlobalValue
>(LV
)) {
597 const auto *RGV
= cast
<GlobalValue
>(RV
);
599 const auto IsGVNameSemantic
= [&](const GlobalValue
*GV
) {
600 auto LT
= GV
->getLinkage();
601 return !(GlobalValue::isPrivateLinkage(LT
) ||
602 GlobalValue::isInternalLinkage(LT
));
605 // Use the names to distinguish the two values, but only if the
606 // names are semantically important.
607 if (IsGVNameSemantic(LGV
) && IsGVNameSemantic(RGV
))
608 return LGV
->getName().compare(RGV
->getName());
611 // For instructions, compare their loop depth, and their operand count. This
613 if (const auto *LInst
= dyn_cast
<Instruction
>(LV
)) {
614 const auto *RInst
= cast
<Instruction
>(RV
);
616 // Compare loop depths.
617 const BasicBlock
*LParent
= LInst
->getParent(),
618 *RParent
= RInst
->getParent();
619 if (LParent
!= RParent
) {
620 unsigned LDepth
= LI
->getLoopDepth(LParent
),
621 RDepth
= LI
->getLoopDepth(RParent
);
622 if (LDepth
!= RDepth
)
623 return (int)LDepth
- (int)RDepth
;
626 // Compare the number of operands.
627 unsigned LNumOps
= LInst
->getNumOperands(),
628 RNumOps
= RInst
->getNumOperands();
629 if (LNumOps
!= RNumOps
)
630 return (int)LNumOps
- (int)RNumOps
;
632 for (unsigned Idx
: seq(0u, LNumOps
)) {
634 CompareValueComplexity(EqCacheValue
, LI
, LInst
->getOperand(Idx
),
635 RInst
->getOperand(Idx
), Depth
+ 1);
641 EqCacheValue
.unionSets(LV
, RV
);
645 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
646 // than RHS, respectively. A three-way result allows recursive comparisons to be
648 static int CompareSCEVComplexity(
649 EquivalenceClasses
<const SCEV
*> &EqCacheSCEV
,
650 EquivalenceClasses
<const Value
*> &EqCacheValue
,
651 const LoopInfo
*const LI
, const SCEV
*LHS
, const SCEV
*RHS
,
652 DominatorTree
&DT
, unsigned Depth
= 0) {
653 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
657 // Primarily, sort the SCEVs by their getSCEVType().
658 unsigned LType
= LHS
->getSCEVType(), RType
= RHS
->getSCEVType();
660 return (int)LType
- (int)RType
;
662 if (Depth
> MaxSCEVCompareDepth
|| EqCacheSCEV
.isEquivalent(LHS
, RHS
))
664 // Aside from the getSCEVType() ordering, the particular ordering
665 // isn't very important except that it's beneficial to be consistent,
666 // so that (a + b) and (b + a) don't end up as different expressions.
667 switch (static_cast<SCEVTypes
>(LType
)) {
669 const SCEVUnknown
*LU
= cast
<SCEVUnknown
>(LHS
);
670 const SCEVUnknown
*RU
= cast
<SCEVUnknown
>(RHS
);
672 int X
= CompareValueComplexity(EqCacheValue
, LI
, LU
->getValue(),
673 RU
->getValue(), Depth
+ 1);
675 EqCacheSCEV
.unionSets(LHS
, RHS
);
680 const SCEVConstant
*LC
= cast
<SCEVConstant
>(LHS
);
681 const SCEVConstant
*RC
= cast
<SCEVConstant
>(RHS
);
683 // Compare constant values.
684 const APInt
&LA
= LC
->getAPInt();
685 const APInt
&RA
= RC
->getAPInt();
686 unsigned LBitWidth
= LA
.getBitWidth(), RBitWidth
= RA
.getBitWidth();
687 if (LBitWidth
!= RBitWidth
)
688 return (int)LBitWidth
- (int)RBitWidth
;
689 return LA
.ult(RA
) ? -1 : 1;
693 const SCEVAddRecExpr
*LA
= cast
<SCEVAddRecExpr
>(LHS
);
694 const SCEVAddRecExpr
*RA
= cast
<SCEVAddRecExpr
>(RHS
);
696 // There is always a dominance between two recs that are used by one SCEV,
697 // so we can safely sort recs by loop header dominance. We require such
698 // order in getAddExpr.
699 const Loop
*LLoop
= LA
->getLoop(), *RLoop
= RA
->getLoop();
700 if (LLoop
!= RLoop
) {
701 const BasicBlock
*LHead
= LLoop
->getHeader(), *RHead
= RLoop
->getHeader();
702 assert(LHead
!= RHead
&& "Two loops share the same header?");
703 if (DT
.dominates(LHead
, RHead
))
706 assert(DT
.dominates(RHead
, LHead
) &&
707 "No dominance between recurrences used by one SCEV?");
711 // Addrec complexity grows with operand count.
712 unsigned LNumOps
= LA
->getNumOperands(), RNumOps
= RA
->getNumOperands();
713 if (LNumOps
!= RNumOps
)
714 return (int)LNumOps
- (int)RNumOps
;
716 // Lexicographically compare.
717 for (unsigned i
= 0; i
!= LNumOps
; ++i
) {
718 int X
= CompareSCEVComplexity(EqCacheSCEV
, EqCacheValue
, LI
,
719 LA
->getOperand(i
), RA
->getOperand(i
), DT
,
724 EqCacheSCEV
.unionSets(LHS
, RHS
);
734 const SCEVNAryExpr
*LC
= cast
<SCEVNAryExpr
>(LHS
);
735 const SCEVNAryExpr
*RC
= cast
<SCEVNAryExpr
>(RHS
);
737 // Lexicographically compare n-ary expressions.
738 unsigned LNumOps
= LC
->getNumOperands(), RNumOps
= RC
->getNumOperands();
739 if (LNumOps
!= RNumOps
)
740 return (int)LNumOps
- (int)RNumOps
;
742 for (unsigned i
= 0; i
!= LNumOps
; ++i
) {
743 int X
= CompareSCEVComplexity(EqCacheSCEV
, EqCacheValue
, LI
,
744 LC
->getOperand(i
), RC
->getOperand(i
), DT
,
749 EqCacheSCEV
.unionSets(LHS
, RHS
);
754 const SCEVUDivExpr
*LC
= cast
<SCEVUDivExpr
>(LHS
);
755 const SCEVUDivExpr
*RC
= cast
<SCEVUDivExpr
>(RHS
);
757 // Lexicographically compare udiv expressions.
758 int X
= CompareSCEVComplexity(EqCacheSCEV
, EqCacheValue
, LI
, LC
->getLHS(),
759 RC
->getLHS(), DT
, Depth
+ 1);
762 X
= CompareSCEVComplexity(EqCacheSCEV
, EqCacheValue
, LI
, LC
->getRHS(),
763 RC
->getRHS(), DT
, Depth
+ 1);
765 EqCacheSCEV
.unionSets(LHS
, RHS
);
772 const SCEVCastExpr
*LC
= cast
<SCEVCastExpr
>(LHS
);
773 const SCEVCastExpr
*RC
= cast
<SCEVCastExpr
>(RHS
);
775 // Compare cast expressions by operand.
776 int X
= CompareSCEVComplexity(EqCacheSCEV
, EqCacheValue
, LI
,
777 LC
->getOperand(), RC
->getOperand(), DT
,
780 EqCacheSCEV
.unionSets(LHS
, RHS
);
784 case scCouldNotCompute
:
785 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
787 llvm_unreachable("Unknown SCEV kind!");
790 /// Given a list of SCEV objects, order them by their complexity, and group
791 /// objects of the same complexity together by value. When this routine is
792 /// finished, we know that any duplicates in the vector are consecutive and that
793 /// complexity is monotonically increasing.
795 /// Note that we go take special precautions to ensure that we get deterministic
796 /// results from this routine. In other words, we don't want the results of
797 /// this to depend on where the addresses of various SCEV objects happened to
799 static void GroupByComplexity(SmallVectorImpl
<const SCEV
*> &Ops
,
800 LoopInfo
*LI
, DominatorTree
&DT
) {
801 if (Ops
.size() < 2) return; // Noop
803 EquivalenceClasses
<const SCEV
*> EqCacheSCEV
;
804 EquivalenceClasses
<const Value
*> EqCacheValue
;
805 if (Ops
.size() == 2) {
806 // This is the common case, which also happens to be trivially simple.
808 const SCEV
*&LHS
= Ops
[0], *&RHS
= Ops
[1];
809 if (CompareSCEVComplexity(EqCacheSCEV
, EqCacheValue
, LI
, RHS
, LHS
, DT
) < 0)
814 // Do the rough sort by complexity.
815 llvm::stable_sort(Ops
, [&](const SCEV
*LHS
, const SCEV
*RHS
) {
816 return CompareSCEVComplexity(EqCacheSCEV
, EqCacheValue
, LI
, LHS
, RHS
, DT
) <
820 // Now that we are sorted by complexity, group elements of the same
821 // complexity. Note that this is, at worst, N^2, but the vector is likely to
822 // be extremely short in practice. Note that we take this approach because we
823 // do not want to depend on the addresses of the objects we are grouping.
824 for (unsigned i
= 0, e
= Ops
.size(); i
!= e
-2; ++i
) {
825 const SCEV
*S
= Ops
[i
];
826 unsigned Complexity
= S
->getSCEVType();
828 // If there are any objects of the same complexity and same value as this
830 for (unsigned j
= i
+1; j
!= e
&& Ops
[j
]->getSCEVType() == Complexity
; ++j
) {
831 if (Ops
[j
] == S
) { // Found a duplicate.
832 // Move it to immediately after i'th element.
833 std::swap(Ops
[i
+1], Ops
[j
]);
834 ++i
; // no need to rescan it.
835 if (i
== e
-2) return; // Done!
841 // Returns the size of the SCEV S.
842 static inline int sizeOfSCEV(const SCEV
*S
) {
843 struct FindSCEVSize
{
846 FindSCEVSize() = default;
848 bool follow(const SCEV
*S
) {
850 // Keep looking at all operands of S.
854 bool isDone() const {
860 SCEVTraversal
<FindSCEVSize
> ST(F
);
865 /// Returns true if the subtree of \p S contains at least HugeExprThreshold
867 static bool isHugeExpression(const SCEV
*S
) {
868 return S
->getExpressionSize() >= HugeExprThreshold
;
871 /// Returns true of \p Ops contains a huge SCEV (see definition above).
872 static bool hasHugeExpression(ArrayRef
<const SCEV
*> Ops
) {
873 return any_of(Ops
, isHugeExpression
);
878 struct SCEVDivision
: public SCEVVisitor
<SCEVDivision
, void> {
880 // Computes the Quotient and Remainder of the division of Numerator by
882 static void divide(ScalarEvolution
&SE
, const SCEV
*Numerator
,
883 const SCEV
*Denominator
, const SCEV
**Quotient
,
884 const SCEV
**Remainder
) {
885 assert(Numerator
&& Denominator
&& "Uninitialized SCEV");
887 SCEVDivision
D(SE
, Numerator
, Denominator
);
889 // Check for the trivial case here to avoid having to check for it in the
891 if (Numerator
== Denominator
) {
897 if (Numerator
->isZero()) {
903 // A simple case when N/1. The quotient is N.
904 if (Denominator
->isOne()) {
905 *Quotient
= Numerator
;
910 // Split the Denominator when it is a product.
911 if (const SCEVMulExpr
*T
= dyn_cast
<SCEVMulExpr
>(Denominator
)) {
913 *Quotient
= Numerator
;
914 for (const SCEV
*Op
: T
->operands()) {
915 divide(SE
, *Quotient
, Op
, &Q
, &R
);
918 // Bail out when the Numerator is not divisible by one of the terms of
922 *Remainder
= Numerator
;
931 *Quotient
= D
.Quotient
;
932 *Remainder
= D
.Remainder
;
935 // Except in the trivial case described above, we do not know how to divide
936 // Expr by Denominator for the following functions with empty implementation.
937 void visitTruncateExpr(const SCEVTruncateExpr
*Numerator
) {}
938 void visitZeroExtendExpr(const SCEVZeroExtendExpr
*Numerator
) {}
939 void visitSignExtendExpr(const SCEVSignExtendExpr
*Numerator
) {}
940 void visitUDivExpr(const SCEVUDivExpr
*Numerator
) {}
941 void visitSMaxExpr(const SCEVSMaxExpr
*Numerator
) {}
942 void visitUMaxExpr(const SCEVUMaxExpr
*Numerator
) {}
943 void visitSMinExpr(const SCEVSMinExpr
*Numerator
) {}
944 void visitUMinExpr(const SCEVUMinExpr
*Numerator
) {}
945 void visitUnknown(const SCEVUnknown
*Numerator
) {}
946 void visitCouldNotCompute(const SCEVCouldNotCompute
*Numerator
) {}
948 void visitConstant(const SCEVConstant
*Numerator
) {
949 if (const SCEVConstant
*D
= dyn_cast
<SCEVConstant
>(Denominator
)) {
950 APInt NumeratorVal
= Numerator
->getAPInt();
951 APInt DenominatorVal
= D
->getAPInt();
952 uint32_t NumeratorBW
= NumeratorVal
.getBitWidth();
953 uint32_t DenominatorBW
= DenominatorVal
.getBitWidth();
955 if (NumeratorBW
> DenominatorBW
)
956 DenominatorVal
= DenominatorVal
.sext(NumeratorBW
);
957 else if (NumeratorBW
< DenominatorBW
)
958 NumeratorVal
= NumeratorVal
.sext(DenominatorBW
);
960 APInt
QuotientVal(NumeratorVal
.getBitWidth(), 0);
961 APInt
RemainderVal(NumeratorVal
.getBitWidth(), 0);
962 APInt::sdivrem(NumeratorVal
, DenominatorVal
, QuotientVal
, RemainderVal
);
963 Quotient
= SE
.getConstant(QuotientVal
);
964 Remainder
= SE
.getConstant(RemainderVal
);
969 void visitAddRecExpr(const SCEVAddRecExpr
*Numerator
) {
970 const SCEV
*StartQ
, *StartR
, *StepQ
, *StepR
;
971 if (!Numerator
->isAffine())
972 return cannotDivide(Numerator
);
973 divide(SE
, Numerator
->getStart(), Denominator
, &StartQ
, &StartR
);
974 divide(SE
, Numerator
->getStepRecurrence(SE
), Denominator
, &StepQ
, &StepR
);
975 // Bail out if the types do not match.
976 Type
*Ty
= Denominator
->getType();
977 if (Ty
!= StartQ
->getType() || Ty
!= StartR
->getType() ||
978 Ty
!= StepQ
->getType() || Ty
!= StepR
->getType())
979 return cannotDivide(Numerator
);
980 Quotient
= SE
.getAddRecExpr(StartQ
, StepQ
, Numerator
->getLoop(),
981 Numerator
->getNoWrapFlags());
982 Remainder
= SE
.getAddRecExpr(StartR
, StepR
, Numerator
->getLoop(),
983 Numerator
->getNoWrapFlags());
986 void visitAddExpr(const SCEVAddExpr
*Numerator
) {
987 SmallVector
<const SCEV
*, 2> Qs
, Rs
;
988 Type
*Ty
= Denominator
->getType();
990 for (const SCEV
*Op
: Numerator
->operands()) {
992 divide(SE
, Op
, Denominator
, &Q
, &R
);
994 // Bail out if types do not match.
995 if (Ty
!= Q
->getType() || Ty
!= R
->getType())
996 return cannotDivide(Numerator
);
1002 if (Qs
.size() == 1) {
1008 Quotient
= SE
.getAddExpr(Qs
);
1009 Remainder
= SE
.getAddExpr(Rs
);
1012 void visitMulExpr(const SCEVMulExpr
*Numerator
) {
1013 SmallVector
<const SCEV
*, 2> Qs
;
1014 Type
*Ty
= Denominator
->getType();
1016 bool FoundDenominatorTerm
= false;
1017 for (const SCEV
*Op
: Numerator
->operands()) {
1018 // Bail out if types do not match.
1019 if (Ty
!= Op
->getType())
1020 return cannotDivide(Numerator
);
1022 if (FoundDenominatorTerm
) {
1027 // Check whether Denominator divides one of the product operands.
1029 divide(SE
, Op
, Denominator
, &Q
, &R
);
1035 // Bail out if types do not match.
1036 if (Ty
!= Q
->getType())
1037 return cannotDivide(Numerator
);
1039 FoundDenominatorTerm
= true;
1043 if (FoundDenominatorTerm
) {
1048 Quotient
= SE
.getMulExpr(Qs
);
1052 if (!isa
<SCEVUnknown
>(Denominator
))
1053 return cannotDivide(Numerator
);
1055 // The Remainder is obtained by replacing Denominator by 0 in Numerator.
1056 ValueToValueMap RewriteMap
;
1057 RewriteMap
[cast
<SCEVUnknown
>(Denominator
)->getValue()] =
1058 cast
<SCEVConstant
>(Zero
)->getValue();
1059 Remainder
= SCEVParameterRewriter::rewrite(Numerator
, SE
, RewriteMap
, true);
1061 if (Remainder
->isZero()) {
1062 // The Quotient is obtained by replacing Denominator by 1 in Numerator.
1063 RewriteMap
[cast
<SCEVUnknown
>(Denominator
)->getValue()] =
1064 cast
<SCEVConstant
>(One
)->getValue();
1066 SCEVParameterRewriter::rewrite(Numerator
, SE
, RewriteMap
, true);
1070 // Quotient is (Numerator - Remainder) divided by Denominator.
1072 const SCEV
*Diff
= SE
.getMinusSCEV(Numerator
, Remainder
);
1073 // This SCEV does not seem to simplify: fail the division here.
1074 if (sizeOfSCEV(Diff
) > sizeOfSCEV(Numerator
))
1075 return cannotDivide(Numerator
);
1076 divide(SE
, Diff
, Denominator
, &Q
, &R
);
1078 return cannotDivide(Numerator
);
1083 SCEVDivision(ScalarEvolution
&S
, const SCEV
*Numerator
,
1084 const SCEV
*Denominator
)
1085 : SE(S
), Denominator(Denominator
) {
1086 Zero
= SE
.getZero(Denominator
->getType());
1087 One
= SE
.getOne(Denominator
->getType());
1089 // We generally do not know how to divide Expr by Denominator. We
1090 // initialize the division to a "cannot divide" state to simplify the rest
1092 cannotDivide(Numerator
);
1095 // Convenience function for giving up on the division. We set the quotient to
1096 // be equal to zero and the remainder to be equal to the numerator.
1097 void cannotDivide(const SCEV
*Numerator
) {
1099 Remainder
= Numerator
;
1102 ScalarEvolution
&SE
;
1103 const SCEV
*Denominator
, *Quotient
, *Remainder
, *Zero
, *One
;
1106 } // end anonymous namespace
1108 //===----------------------------------------------------------------------===//
1109 // Simple SCEV method implementations
1110 //===----------------------------------------------------------------------===//
1112 /// Compute BC(It, K). The result has width W. Assume, K > 0.
1113 static const SCEV
*BinomialCoefficient(const SCEV
*It
, unsigned K
,
1114 ScalarEvolution
&SE
,
1116 // Handle the simplest case efficiently.
1118 return SE
.getTruncateOrZeroExtend(It
, ResultTy
);
1120 // We are using the following formula for BC(It, K):
1122 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1124 // Suppose, W is the bitwidth of the return value. We must be prepared for
1125 // overflow. Hence, we must assure that the result of our computation is
1126 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
1127 // safe in modular arithmetic.
1129 // However, this code doesn't use exactly that formula; the formula it uses
1130 // is something like the following, where T is the number of factors of 2 in
1131 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1134 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
1136 // This formula is trivially equivalent to the previous formula. However,
1137 // this formula can be implemented much more efficiently. The trick is that
1138 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1139 // arithmetic. To do exact division in modular arithmetic, all we have
1140 // to do is multiply by the inverse. Therefore, this step can be done at
1143 // The next issue is how to safely do the division by 2^T. The way this
1144 // is done is by doing the multiplication step at a width of at least W + T
1145 // bits. This way, the bottom W+T bits of the product are accurate. Then,
1146 // when we perform the division by 2^T (which is equivalent to a right shift
1147 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
1148 // truncated out after the division by 2^T.
1150 // In comparison to just directly using the first formula, this technique
1151 // is much more efficient; using the first formula requires W * K bits,
1152 // but this formula less than W + K bits. Also, the first formula requires
1153 // a division step, whereas this formula only requires multiplies and shifts.
1155 // It doesn't matter whether the subtraction step is done in the calculation
1156 // width or the input iteration count's width; if the subtraction overflows,
1157 // the result must be zero anyway. We prefer here to do it in the width of
1158 // the induction variable because it helps a lot for certain cases; CodeGen
1159 // isn't smart enough to ignore the overflow, which leads to much less
1160 // efficient code if the width of the subtraction is wider than the native
1163 // (It's possible to not widen at all by pulling out factors of 2 before
1164 // the multiplication; for example, K=2 can be calculated as
1165 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1166 // extra arithmetic, so it's not an obvious win, and it gets
1167 // much more complicated for K > 3.)
1169 // Protection from insane SCEVs; this bound is conservative,
1170 // but it probably doesn't matter.
1172 return SE
.getCouldNotCompute();
1174 unsigned W
= SE
.getTypeSizeInBits(ResultTy
);
1176 // Calculate K! / 2^T and T; we divide out the factors of two before
1177 // multiplying for calculating K! / 2^T to avoid overflow.
1178 // Other overflow doesn't matter because we only care about the bottom
1179 // W bits of the result.
1180 APInt
OddFactorial(W
, 1);
1182 for (unsigned i
= 3; i
<= K
; ++i
) {
1184 unsigned TwoFactors
= Mult
.countTrailingZeros();
1186 Mult
.lshrInPlace(TwoFactors
);
1187 OddFactorial
*= Mult
;
1190 // We need at least W + T bits for the multiplication step
1191 unsigned CalculationBits
= W
+ T
;
1193 // Calculate 2^T, at width T+W.
1194 APInt DivFactor
= APInt::getOneBitSet(CalculationBits
, T
);
1196 // Calculate the multiplicative inverse of K! / 2^T;
1197 // this multiplication factor will perform the exact division by
1199 APInt Mod
= APInt::getSignedMinValue(W
+1);
1200 APInt MultiplyFactor
= OddFactorial
.zext(W
+1);
1201 MultiplyFactor
= MultiplyFactor
.multiplicativeInverse(Mod
);
1202 MultiplyFactor
= MultiplyFactor
.trunc(W
);
1204 // Calculate the product, at width T+W
1205 IntegerType
*CalculationTy
= IntegerType::get(SE
.getContext(),
1207 const SCEV
*Dividend
= SE
.getTruncateOrZeroExtend(It
, CalculationTy
);
1208 for (unsigned i
= 1; i
!= K
; ++i
) {
1209 const SCEV
*S
= SE
.getMinusSCEV(It
, SE
.getConstant(It
->getType(), i
));
1210 Dividend
= SE
.getMulExpr(Dividend
,
1211 SE
.getTruncateOrZeroExtend(S
, CalculationTy
));
1215 const SCEV
*DivResult
= SE
.getUDivExpr(Dividend
, SE
.getConstant(DivFactor
));
1217 // Truncate the result, and divide by K! / 2^T.
1219 return SE
.getMulExpr(SE
.getConstant(MultiplyFactor
),
1220 SE
.getTruncateOrZeroExtend(DivResult
, ResultTy
));
1223 /// Return the value of this chain of recurrences at the specified iteration
1224 /// number. We can evaluate this recurrence by multiplying each element in the
1225 /// chain by the binomial coefficient corresponding to it. In other words, we
1226 /// can evaluate {A,+,B,+,C,+,D} as:
1228 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1230 /// where BC(It, k) stands for binomial coefficient.
1231 const SCEV
*SCEVAddRecExpr::evaluateAtIteration(const SCEV
*It
,
1232 ScalarEvolution
&SE
) const {
1233 const SCEV
*Result
= getStart();
1234 for (unsigned i
= 1, e
= getNumOperands(); i
!= e
; ++i
) {
1235 // The computation is correct in the face of overflow provided that the
1236 // multiplication is performed _after_ the evaluation of the binomial
1238 const SCEV
*Coeff
= BinomialCoefficient(It
, i
, SE
, getType());
1239 if (isa
<SCEVCouldNotCompute
>(Coeff
))
1242 Result
= SE
.getAddExpr(Result
, SE
.getMulExpr(getOperand(i
), Coeff
));
1247 //===----------------------------------------------------------------------===//
1248 // SCEV Expression folder implementations
1249 //===----------------------------------------------------------------------===//
1251 const SCEV
*ScalarEvolution::getTruncateExpr(const SCEV
*Op
, Type
*Ty
,
1253 assert(getTypeSizeInBits(Op
->getType()) > getTypeSizeInBits(Ty
) &&
1254 "This is not a truncating conversion!");
1255 assert(isSCEVable(Ty
) &&
1256 "This is not a conversion to a SCEVable type!");
1257 Ty
= getEffectiveSCEVType(Ty
);
1259 FoldingSetNodeID ID
;
1260 ID
.AddInteger(scTruncate
);
1264 if (const SCEV
*S
= UniqueSCEVs
.FindNodeOrInsertPos(ID
, IP
)) return S
;
1266 // Fold if the operand is constant.
1267 if (const SCEVConstant
*SC
= dyn_cast
<SCEVConstant
>(Op
))
1269 cast
<ConstantInt
>(ConstantExpr::getTrunc(SC
->getValue(), Ty
)));
1271 // trunc(trunc(x)) --> trunc(x)
1272 if (const SCEVTruncateExpr
*ST
= dyn_cast
<SCEVTruncateExpr
>(Op
))
1273 return getTruncateExpr(ST
->getOperand(), Ty
, Depth
+ 1);
1275 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1276 if (const SCEVSignExtendExpr
*SS
= dyn_cast
<SCEVSignExtendExpr
>(Op
))
1277 return getTruncateOrSignExtend(SS
->getOperand(), Ty
, Depth
+ 1);
1279 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1280 if (const SCEVZeroExtendExpr
*SZ
= dyn_cast
<SCEVZeroExtendExpr
>(Op
))
1281 return getTruncateOrZeroExtend(SZ
->getOperand(), Ty
, Depth
+ 1);
1283 if (Depth
> MaxCastDepth
) {
1285 new (SCEVAllocator
) SCEVTruncateExpr(ID
.Intern(SCEVAllocator
), Op
, Ty
);
1286 UniqueSCEVs
.InsertNode(S
, IP
);
1287 addToLoopUseLists(S
);
1291 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1292 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1293 // if after transforming we have at most one truncate, not counting truncates
1294 // that replace other casts.
1295 if (isa
<SCEVAddExpr
>(Op
) || isa
<SCEVMulExpr
>(Op
)) {
1296 auto *CommOp
= cast
<SCEVCommutativeExpr
>(Op
);
1297 SmallVector
<const SCEV
*, 4> Operands
;
1298 unsigned numTruncs
= 0;
1299 for (unsigned i
= 0, e
= CommOp
->getNumOperands(); i
!= e
&& numTruncs
< 2;
1301 const SCEV
*S
= getTruncateExpr(CommOp
->getOperand(i
), Ty
, Depth
+ 1);
1302 if (!isa
<SCEVCastExpr
>(CommOp
->getOperand(i
)) && isa
<SCEVTruncateExpr
>(S
))
1304 Operands
.push_back(S
);
1306 if (numTruncs
< 2) {
1307 if (isa
<SCEVAddExpr
>(Op
))
1308 return getAddExpr(Operands
);
1309 else if (isa
<SCEVMulExpr
>(Op
))
1310 return getMulExpr(Operands
);
1312 llvm_unreachable("Unexpected SCEV type for Op.");
1314 // Although we checked in the beginning that ID is not in the cache, it is
1315 // possible that during recursion and different modification ID was inserted
1316 // into the cache. So if we find it, just return it.
1317 if (const SCEV
*S
= UniqueSCEVs
.FindNodeOrInsertPos(ID
, IP
))
1321 // If the input value is a chrec scev, truncate the chrec's operands.
1322 if (const SCEVAddRecExpr
*AddRec
= dyn_cast
<SCEVAddRecExpr
>(Op
)) {
1323 SmallVector
<const SCEV
*, 4> Operands
;
1324 for (const SCEV
*Op
: AddRec
->operands())
1325 Operands
.push_back(getTruncateExpr(Op
, Ty
, Depth
+ 1));
1326 return getAddRecExpr(Operands
, AddRec
->getLoop(), SCEV::FlagAnyWrap
);
1329 // The cast wasn't folded; create an explicit cast node. We can reuse
1330 // the existing insert position since if we get here, we won't have
1331 // made any changes which would invalidate it.
1332 SCEV
*S
= new (SCEVAllocator
) SCEVTruncateExpr(ID
.Intern(SCEVAllocator
),
1334 UniqueSCEVs
.InsertNode(S
, IP
);
1335 addToLoopUseLists(S
);
1339 // Get the limit of a recurrence such that incrementing by Step cannot cause
1340 // signed overflow as long as the value of the recurrence within the
1341 // loop does not exceed this limit before incrementing.
1342 static const SCEV
*getSignedOverflowLimitForStep(const SCEV
*Step
,
1343 ICmpInst::Predicate
*Pred
,
1344 ScalarEvolution
*SE
) {
1345 unsigned BitWidth
= SE
->getTypeSizeInBits(Step
->getType());
1346 if (SE
->isKnownPositive(Step
)) {
1347 *Pred
= ICmpInst::ICMP_SLT
;
1348 return SE
->getConstant(APInt::getSignedMinValue(BitWidth
) -
1349 SE
->getSignedRangeMax(Step
));
1351 if (SE
->isKnownNegative(Step
)) {
1352 *Pred
= ICmpInst::ICMP_SGT
;
1353 return SE
->getConstant(APInt::getSignedMaxValue(BitWidth
) -
1354 SE
->getSignedRangeMin(Step
));
1359 // Get the limit of a recurrence such that incrementing by Step cannot cause
1360 // unsigned overflow as long as the value of the recurrence within the loop does
1361 // not exceed this limit before incrementing.
1362 static const SCEV
*getUnsignedOverflowLimitForStep(const SCEV
*Step
,
1363 ICmpInst::Predicate
*Pred
,
1364 ScalarEvolution
*SE
) {
1365 unsigned BitWidth
= SE
->getTypeSizeInBits(Step
->getType());
1366 *Pred
= ICmpInst::ICMP_ULT
;
1368 return SE
->getConstant(APInt::getMinValue(BitWidth
) -
1369 SE
->getUnsignedRangeMax(Step
));
1374 struct ExtendOpTraitsBase
{
1375 typedef const SCEV
*(ScalarEvolution::*GetExtendExprTy
)(const SCEV
*, Type
*,
1379 // Used to make code generic over signed and unsigned overflow.
1380 template <typename ExtendOp
> struct ExtendOpTraits
{
1383 // static const SCEV::NoWrapFlags WrapType;
1385 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1387 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1388 // ICmpInst::Predicate *Pred,
1389 // ScalarEvolution *SE);
1393 struct ExtendOpTraits
<SCEVSignExtendExpr
> : public ExtendOpTraitsBase
{
1394 static const SCEV::NoWrapFlags WrapType
= SCEV::FlagNSW
;
1396 static const GetExtendExprTy GetExtendExpr
;
1398 static const SCEV
*getOverflowLimitForStep(const SCEV
*Step
,
1399 ICmpInst::Predicate
*Pred
,
1400 ScalarEvolution
*SE
) {
1401 return getSignedOverflowLimitForStep(Step
, Pred
, SE
);
1405 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits
<
1406 SCEVSignExtendExpr
>::GetExtendExpr
= &ScalarEvolution::getSignExtendExpr
;
1409 struct ExtendOpTraits
<SCEVZeroExtendExpr
> : public ExtendOpTraitsBase
{
1410 static const SCEV::NoWrapFlags WrapType
= SCEV::FlagNUW
;
1412 static const GetExtendExprTy GetExtendExpr
;
1414 static const SCEV
*getOverflowLimitForStep(const SCEV
*Step
,
1415 ICmpInst::Predicate
*Pred
,
1416 ScalarEvolution
*SE
) {
1417 return getUnsignedOverflowLimitForStep(Step
, Pred
, SE
);
1421 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits
<
1422 SCEVZeroExtendExpr
>::GetExtendExpr
= &ScalarEvolution::getZeroExtendExpr
;
1424 } // end anonymous namespace
1426 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1427 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1428 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1429 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1430 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1431 // expression "Step + sext/zext(PreIncAR)" is congruent with
1432 // "sext/zext(PostIncAR)"
1433 template <typename ExtendOpTy
>
1434 static const SCEV
*getPreStartForExtend(const SCEVAddRecExpr
*AR
, Type
*Ty
,
1435 ScalarEvolution
*SE
, unsigned Depth
) {
1436 auto WrapType
= ExtendOpTraits
<ExtendOpTy
>::WrapType
;
1437 auto GetExtendExpr
= ExtendOpTraits
<ExtendOpTy
>::GetExtendExpr
;
1439 const Loop
*L
= AR
->getLoop();
1440 const SCEV
*Start
= AR
->getStart();
1441 const SCEV
*Step
= AR
->getStepRecurrence(*SE
);
1443 // Check for a simple looking step prior to loop entry.
1444 const SCEVAddExpr
*SA
= dyn_cast
<SCEVAddExpr
>(Start
);
1448 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1449 // subtraction is expensive. For this purpose, perform a quick and dirty
1450 // difference, by checking for Step in the operand list.
1451 SmallVector
<const SCEV
*, 4> DiffOps
;
1452 for (const SCEV
*Op
: SA
->operands())
1454 DiffOps
.push_back(Op
);
1456 if (DiffOps
.size() == SA
->getNumOperands())
1459 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1462 // 1. NSW/NUW flags on the step increment.
1463 auto PreStartFlags
=
1464 ScalarEvolution::maskFlags(SA
->getNoWrapFlags(), SCEV::FlagNUW
);
1465 const SCEV
*PreStart
= SE
->getAddExpr(DiffOps
, PreStartFlags
);
1466 const SCEVAddRecExpr
*PreAR
= dyn_cast
<SCEVAddRecExpr
>(
1467 SE
->getAddRecExpr(PreStart
, Step
, L
, SCEV::FlagAnyWrap
));
1469 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1470 // "S+X does not sign/unsign-overflow".
1473 const SCEV
*BECount
= SE
->getBackedgeTakenCount(L
);
1474 if (PreAR
&& PreAR
->getNoWrapFlags(WrapType
) &&
1475 !isa
<SCEVCouldNotCompute
>(BECount
) && SE
->isKnownPositive(BECount
))
1478 // 2. Direct overflow check on the step operation's expression.
1479 unsigned BitWidth
= SE
->getTypeSizeInBits(AR
->getType());
1480 Type
*WideTy
= IntegerType::get(SE
->getContext(), BitWidth
* 2);
1481 const SCEV
*OperandExtendedStart
=
1482 SE
->getAddExpr((SE
->*GetExtendExpr
)(PreStart
, WideTy
, Depth
),
1483 (SE
->*GetExtendExpr
)(Step
, WideTy
, Depth
));
1484 if ((SE
->*GetExtendExpr
)(Start
, WideTy
, Depth
) == OperandExtendedStart
) {
1485 if (PreAR
&& AR
->getNoWrapFlags(WrapType
)) {
1486 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1487 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1488 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1489 const_cast<SCEVAddRecExpr
*>(PreAR
)->setNoWrapFlags(WrapType
);
1494 // 3. Loop precondition.
1495 ICmpInst::Predicate Pred
;
1496 const SCEV
*OverflowLimit
=
1497 ExtendOpTraits
<ExtendOpTy
>::getOverflowLimitForStep(Step
, &Pred
, SE
);
1499 if (OverflowLimit
&&
1500 SE
->isLoopEntryGuardedByCond(L
, Pred
, PreStart
, OverflowLimit
))
1506 // Get the normalized zero or sign extended expression for this AddRec's Start.
1507 template <typename ExtendOpTy
>
1508 static const SCEV
*getExtendAddRecStart(const SCEVAddRecExpr
*AR
, Type
*Ty
,
1509 ScalarEvolution
*SE
,
1511 auto GetExtendExpr
= ExtendOpTraits
<ExtendOpTy
>::GetExtendExpr
;
1513 const SCEV
*PreStart
= getPreStartForExtend
<ExtendOpTy
>(AR
, Ty
, SE
, Depth
);
1515 return (SE
->*GetExtendExpr
)(AR
->getStart(), Ty
, Depth
);
1517 return SE
->getAddExpr((SE
->*GetExtendExpr
)(AR
->getStepRecurrence(*SE
), Ty
,
1519 (SE
->*GetExtendExpr
)(PreStart
, Ty
, Depth
));
1522 // Try to prove away overflow by looking at "nearby" add recurrences. A
1523 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1524 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1528 // {S,+,X} == {S-T,+,X} + T
1529 // => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1531 // If ({S-T,+,X} + T) does not overflow ... (1)
1533 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1535 // If {S-T,+,X} does not overflow ... (2)
1537 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1538 // == {Ext(S-T)+Ext(T),+,Ext(X)}
1540 // If (S-T)+T does not overflow ... (3)
1542 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1543 // == {Ext(S),+,Ext(X)} == LHS
1545 // Thus, if (1), (2) and (3) are true for some T, then
1546 // Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1548 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1549 // does not overflow" restricted to the 0th iteration. Therefore we only need
1550 // to check for (1) and (2).
1552 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1553 // is `Delta` (defined below).
1554 template <typename ExtendOpTy
>
1555 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV
*Start
,
1558 auto WrapType
= ExtendOpTraits
<ExtendOpTy
>::WrapType
;
1560 // We restrict `Start` to a constant to prevent SCEV from spending too much
1561 // time here. It is correct (but more expensive) to continue with a
1562 // non-constant `Start` and do a general SCEV subtraction to compute
1563 // `PreStart` below.
1564 const SCEVConstant
*StartC
= dyn_cast
<SCEVConstant
>(Start
);
1568 APInt StartAI
= StartC
->getAPInt();
1570 for (unsigned Delta
: {-2, -1, 1, 2}) {
1571 const SCEV
*PreStart
= getConstant(StartAI
- Delta
);
1573 FoldingSetNodeID ID
;
1574 ID
.AddInteger(scAddRecExpr
);
1575 ID
.AddPointer(PreStart
);
1576 ID
.AddPointer(Step
);
1580 static_cast<SCEVAddRecExpr
*>(UniqueSCEVs
.FindNodeOrInsertPos(ID
, IP
));
1582 // Give up if we don't already have the add recurrence we need because
1583 // actually constructing an add recurrence is relatively expensive.
1584 if (PreAR
&& PreAR
->getNoWrapFlags(WrapType
)) { // proves (2)
1585 const SCEV
*DeltaS
= getConstant(StartC
->getType(), Delta
);
1586 ICmpInst::Predicate Pred
= ICmpInst::BAD_ICMP_PREDICATE
;
1587 const SCEV
*Limit
= ExtendOpTraits
<ExtendOpTy
>::getOverflowLimitForStep(
1588 DeltaS
, &Pred
, this);
1589 if (Limit
&& isKnownPredicate(Pred
, PreAR
, Limit
)) // proves (1)
1597 // Finds an integer D for an expression (C + x + y + ...) such that the top
1598 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1599 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1600 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1601 // the (C + x + y + ...) expression is \p WholeAddExpr.
1602 static APInt
extractConstantWithoutWrapping(ScalarEvolution
&SE
,
1603 const SCEVConstant
*ConstantTerm
,
1604 const SCEVAddExpr
*WholeAddExpr
) {
1605 const APInt C
= ConstantTerm
->getAPInt();
1606 const unsigned BitWidth
= C
.getBitWidth();
1607 // Find number of trailing zeros of (x + y + ...) w/o the C first:
1608 uint32_t TZ
= BitWidth
;
1609 for (unsigned I
= 1, E
= WholeAddExpr
->getNumOperands(); I
< E
&& TZ
; ++I
)
1610 TZ
= std::min(TZ
, SE
.GetMinTrailingZeros(WholeAddExpr
->getOperand(I
)));
1612 // Set D to be as many least significant bits of C as possible while still
1613 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1614 return TZ
< BitWidth
? C
.trunc(TZ
).zext(BitWidth
) : C
;
1616 return APInt(BitWidth
, 0);
1619 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1620 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1621 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1622 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1623 static APInt
extractConstantWithoutWrapping(ScalarEvolution
&SE
,
1624 const APInt
&ConstantStart
,
1626 const unsigned BitWidth
= ConstantStart
.getBitWidth();
1627 const uint32_t TZ
= SE
.GetMinTrailingZeros(Step
);
1629 return TZ
< BitWidth
? ConstantStart
.trunc(TZ
).zext(BitWidth
)
1631 return APInt(BitWidth
, 0);
1635 ScalarEvolution::getZeroExtendExpr(const SCEV
*Op
, Type
*Ty
, unsigned Depth
) {
1636 assert(getTypeSizeInBits(Op
->getType()) < getTypeSizeInBits(Ty
) &&
1637 "This is not an extending conversion!");
1638 assert(isSCEVable(Ty
) &&
1639 "This is not a conversion to a SCEVable type!");
1640 Ty
= getEffectiveSCEVType(Ty
);
1642 // Fold if the operand is constant.
1643 if (const SCEVConstant
*SC
= dyn_cast
<SCEVConstant
>(Op
))
1645 cast
<ConstantInt
>(ConstantExpr::getZExt(SC
->getValue(), Ty
)));
1647 // zext(zext(x)) --> zext(x)
1648 if (const SCEVZeroExtendExpr
*SZ
= dyn_cast
<SCEVZeroExtendExpr
>(Op
))
1649 return getZeroExtendExpr(SZ
->getOperand(), Ty
, Depth
+ 1);
1651 // Before doing any expensive analysis, check to see if we've already
1652 // computed a SCEV for this Op and Ty.
1653 FoldingSetNodeID ID
;
1654 ID
.AddInteger(scZeroExtend
);
1658 if (const SCEV
*S
= UniqueSCEVs
.FindNodeOrInsertPos(ID
, IP
)) return S
;
1659 if (Depth
> MaxCastDepth
) {
1660 SCEV
*S
= new (SCEVAllocator
) SCEVZeroExtendExpr(ID
.Intern(SCEVAllocator
),
1662 UniqueSCEVs
.InsertNode(S
, IP
);
1663 addToLoopUseLists(S
);
1667 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1668 if (const SCEVTruncateExpr
*ST
= dyn_cast
<SCEVTruncateExpr
>(Op
)) {
1669 // It's possible the bits taken off by the truncate were all zero bits. If
1670 // so, we should be able to simplify this further.
1671 const SCEV
*X
= ST
->getOperand();
1672 ConstantRange CR
= getUnsignedRange(X
);
1673 unsigned TruncBits
= getTypeSizeInBits(ST
->getType());
1674 unsigned NewBits
= getTypeSizeInBits(Ty
);
1675 if (CR
.truncate(TruncBits
).zeroExtend(NewBits
).contains(
1676 CR
.zextOrTrunc(NewBits
)))
1677 return getTruncateOrZeroExtend(X
, Ty
, Depth
);
1680 // If the input value is a chrec scev, and we can prove that the value
1681 // did not overflow the old, smaller, value, we can zero extend all of the
1682 // operands (often constants). This allows analysis of something like
1683 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1684 if (const SCEVAddRecExpr
*AR
= dyn_cast
<SCEVAddRecExpr
>(Op
))
1685 if (AR
->isAffine()) {
1686 const SCEV
*Start
= AR
->getStart();
1687 const SCEV
*Step
= AR
->getStepRecurrence(*this);
1688 unsigned BitWidth
= getTypeSizeInBits(AR
->getType());
1689 const Loop
*L
= AR
->getLoop();
1691 if (!AR
->hasNoUnsignedWrap()) {
1692 auto NewFlags
= proveNoWrapViaConstantRanges(AR
);
1693 const_cast<SCEVAddRecExpr
*>(AR
)->setNoWrapFlags(NewFlags
);
1696 // If we have special knowledge that this addrec won't overflow,
1697 // we don't need to do any further analysis.
1698 if (AR
->hasNoUnsignedWrap())
1699 return getAddRecExpr(
1700 getExtendAddRecStart
<SCEVZeroExtendExpr
>(AR
, Ty
, this, Depth
+ 1),
1701 getZeroExtendExpr(Step
, Ty
, Depth
+ 1), L
, AR
->getNoWrapFlags());
1703 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1704 // Note that this serves two purposes: It filters out loops that are
1705 // simply not analyzable, and it covers the case where this code is
1706 // being called from within backedge-taken count analysis, such that
1707 // attempting to ask for the backedge-taken count would likely result
1708 // in infinite recursion. In the later case, the analysis code will
1709 // cope with a conservative value, and it will take care to purge
1710 // that value once it has finished.
1711 const SCEV
*MaxBECount
= getConstantMaxBackedgeTakenCount(L
);
1712 if (!isa
<SCEVCouldNotCompute
>(MaxBECount
)) {
1713 // Manually compute the final value for AR, checking for
1716 // Check whether the backedge-taken count can be losslessly casted to
1717 // the addrec's type. The count is always unsigned.
1718 const SCEV
*CastedMaxBECount
=
1719 getTruncateOrZeroExtend(MaxBECount
, Start
->getType(), Depth
);
1720 const SCEV
*RecastedMaxBECount
= getTruncateOrZeroExtend(
1721 CastedMaxBECount
, MaxBECount
->getType(), Depth
);
1722 if (MaxBECount
== RecastedMaxBECount
) {
1723 Type
*WideTy
= IntegerType::get(getContext(), BitWidth
* 2);
1724 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1725 const SCEV
*ZMul
= getMulExpr(CastedMaxBECount
, Step
,
1726 SCEV::FlagAnyWrap
, Depth
+ 1);
1727 const SCEV
*ZAdd
= getZeroExtendExpr(getAddExpr(Start
, ZMul
,
1731 const SCEV
*WideStart
= getZeroExtendExpr(Start
, WideTy
, Depth
+ 1);
1732 const SCEV
*WideMaxBECount
=
1733 getZeroExtendExpr(CastedMaxBECount
, WideTy
, Depth
+ 1);
1734 const SCEV
*OperandExtendedAdd
=
1735 getAddExpr(WideStart
,
1736 getMulExpr(WideMaxBECount
,
1737 getZeroExtendExpr(Step
, WideTy
, Depth
+ 1),
1738 SCEV::FlagAnyWrap
, Depth
+ 1),
1739 SCEV::FlagAnyWrap
, Depth
+ 1);
1740 if (ZAdd
== OperandExtendedAdd
) {
1741 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1742 const_cast<SCEVAddRecExpr
*>(AR
)->setNoWrapFlags(SCEV::FlagNUW
);
1743 // Return the expression with the addrec on the outside.
1744 return getAddRecExpr(
1745 getExtendAddRecStart
<SCEVZeroExtendExpr
>(AR
, Ty
, this,
1747 getZeroExtendExpr(Step
, Ty
, Depth
+ 1), L
,
1748 AR
->getNoWrapFlags());
1750 // Similar to above, only this time treat the step value as signed.
1751 // This covers loops that count down.
1752 OperandExtendedAdd
=
1753 getAddExpr(WideStart
,
1754 getMulExpr(WideMaxBECount
,
1755 getSignExtendExpr(Step
, WideTy
, Depth
+ 1),
1756 SCEV::FlagAnyWrap
, Depth
+ 1),
1757 SCEV::FlagAnyWrap
, Depth
+ 1);
1758 if (ZAdd
== OperandExtendedAdd
) {
1759 // Cache knowledge of AR NW, which is propagated to this AddRec.
1760 // Negative step causes unsigned wrap, but it still can't self-wrap.
1761 const_cast<SCEVAddRecExpr
*>(AR
)->setNoWrapFlags(SCEV::FlagNW
);
1762 // Return the expression with the addrec on the outside.
1763 return getAddRecExpr(
1764 getExtendAddRecStart
<SCEVZeroExtendExpr
>(AR
, Ty
, this,
1766 getSignExtendExpr(Step
, Ty
, Depth
+ 1), L
,
1767 AR
->getNoWrapFlags());
1772 // Normally, in the cases we can prove no-overflow via a
1773 // backedge guarding condition, we can also compute a backedge
1774 // taken count for the loop. The exceptions are assumptions and
1775 // guards present in the loop -- SCEV is not great at exploiting
1776 // these to compute max backedge taken counts, but can still use
1777 // these to prove lack of overflow. Use this fact to avoid
1778 // doing extra work that may not pay off.
1779 if (!isa
<SCEVCouldNotCompute
>(MaxBECount
) || HasGuards
||
1780 !AC
.assumptions().empty()) {
1781 // If the backedge is guarded by a comparison with the pre-inc
1782 // value the addrec is safe. Also, if the entry is guarded by
1783 // a comparison with the start value and the backedge is
1784 // guarded by a comparison with the post-inc value, the addrec
1786 if (isKnownPositive(Step
)) {
1787 const SCEV
*N
= getConstant(APInt::getMinValue(BitWidth
) -
1788 getUnsignedRangeMax(Step
));
1789 if (isLoopBackedgeGuardedByCond(L
, ICmpInst::ICMP_ULT
, AR
, N
) ||
1790 isKnownOnEveryIteration(ICmpInst::ICMP_ULT
, AR
, N
)) {
1791 // Cache knowledge of AR NUW, which is propagated to this
1793 const_cast<SCEVAddRecExpr
*>(AR
)->setNoWrapFlags(SCEV::FlagNUW
);
1794 // Return the expression with the addrec on the outside.
1795 return getAddRecExpr(
1796 getExtendAddRecStart
<SCEVZeroExtendExpr
>(AR
, Ty
, this,
1798 getZeroExtendExpr(Step
, Ty
, Depth
+ 1), L
,
1799 AR
->getNoWrapFlags());
1801 } else if (isKnownNegative(Step
)) {
1802 const SCEV
*N
= getConstant(APInt::getMaxValue(BitWidth
) -
1803 getSignedRangeMin(Step
));
1804 if (isLoopBackedgeGuardedByCond(L
, ICmpInst::ICMP_UGT
, AR
, N
) ||
1805 isKnownOnEveryIteration(ICmpInst::ICMP_UGT
, AR
, N
)) {
1806 // Cache knowledge of AR NW, which is propagated to this
1807 // AddRec. Negative step causes unsigned wrap, but it
1808 // still can't self-wrap.
1809 const_cast<SCEVAddRecExpr
*>(AR
)->setNoWrapFlags(SCEV::FlagNW
);
1810 // Return the expression with the addrec on the outside.
1811 return getAddRecExpr(
1812 getExtendAddRecStart
<SCEVZeroExtendExpr
>(AR
, Ty
, this,
1814 getSignExtendExpr(Step
, Ty
, Depth
+ 1), L
,
1815 AR
->getNoWrapFlags());
1820 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1821 // if D + (C - D + Step * n) could be proven to not unsigned wrap
1822 // where D maximizes the number of trailing zeros of (C - D + Step * n)
1823 if (const auto *SC
= dyn_cast
<SCEVConstant
>(Start
)) {
1824 const APInt
&C
= SC
->getAPInt();
1825 const APInt
&D
= extractConstantWithoutWrapping(*this, C
, Step
);
1827 const SCEV
*SZExtD
= getZeroExtendExpr(getConstant(D
), Ty
, Depth
);
1828 const SCEV
*SResidual
=
1829 getAddRecExpr(getConstant(C
- D
), Step
, L
, AR
->getNoWrapFlags());
1830 const SCEV
*SZExtR
= getZeroExtendExpr(SResidual
, Ty
, Depth
+ 1);
1831 return getAddExpr(SZExtD
, SZExtR
,
1832 (SCEV::NoWrapFlags
)(SCEV::FlagNSW
| SCEV::FlagNUW
),
1837 if (proveNoWrapByVaryingStart
<SCEVZeroExtendExpr
>(Start
, Step
, L
)) {
1838 const_cast<SCEVAddRecExpr
*>(AR
)->setNoWrapFlags(SCEV::FlagNUW
);
1839 return getAddRecExpr(
1840 getExtendAddRecStart
<SCEVZeroExtendExpr
>(AR
, Ty
, this, Depth
+ 1),
1841 getZeroExtendExpr(Step
, Ty
, Depth
+ 1), L
, AR
->getNoWrapFlags());
1845 // zext(A % B) --> zext(A) % zext(B)
1849 if (matchURem(Op
, LHS
, RHS
))
1850 return getURemExpr(getZeroExtendExpr(LHS
, Ty
, Depth
+ 1),
1851 getZeroExtendExpr(RHS
, Ty
, Depth
+ 1));
1854 // zext(A / B) --> zext(A) / zext(B).
1855 if (auto *Div
= dyn_cast
<SCEVUDivExpr
>(Op
))
1856 return getUDivExpr(getZeroExtendExpr(Div
->getLHS(), Ty
, Depth
+ 1),
1857 getZeroExtendExpr(Div
->getRHS(), Ty
, Depth
+ 1));
1859 if (auto *SA
= dyn_cast
<SCEVAddExpr
>(Op
)) {
1860 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1861 if (SA
->hasNoUnsignedWrap()) {
1862 // If the addition does not unsign overflow then we can, by definition,
1863 // commute the zero extension with the addition operation.
1864 SmallVector
<const SCEV
*, 4> Ops
;
1865 for (const auto *Op
: SA
->operands())
1866 Ops
.push_back(getZeroExtendExpr(Op
, Ty
, Depth
+ 1));
1867 return getAddExpr(Ops
, SCEV::FlagNUW
, Depth
+ 1);
1870 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1871 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1872 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1874 // Often address arithmetics contain expressions like
1875 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1876 // This transformation is useful while proving that such expressions are
1877 // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1878 if (const auto *SC
= dyn_cast
<SCEVConstant
>(SA
->getOperand(0))) {
1879 const APInt
&D
= extractConstantWithoutWrapping(*this, SC
, SA
);
1881 const SCEV
*SZExtD
= getZeroExtendExpr(getConstant(D
), Ty
, Depth
);
1882 const SCEV
*SResidual
=
1883 getAddExpr(getConstant(-D
), SA
, SCEV::FlagAnyWrap
, Depth
);
1884 const SCEV
*SZExtR
= getZeroExtendExpr(SResidual
, Ty
, Depth
+ 1);
1885 return getAddExpr(SZExtD
, SZExtR
,
1886 (SCEV::NoWrapFlags
)(SCEV::FlagNSW
| SCEV::FlagNUW
),
1892 if (auto *SM
= dyn_cast
<SCEVMulExpr
>(Op
)) {
1893 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1894 if (SM
->hasNoUnsignedWrap()) {
1895 // If the multiply does not unsign overflow then we can, by definition,
1896 // commute the zero extension with the multiply operation.
1897 SmallVector
<const SCEV
*, 4> Ops
;
1898 for (const auto *Op
: SM
->operands())
1899 Ops
.push_back(getZeroExtendExpr(Op
, Ty
, Depth
+ 1));
1900 return getMulExpr(Ops
, SCEV::FlagNUW
, Depth
+ 1);
1903 // zext(2^K * (trunc X to iN)) to iM ->
1904 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1908 // zext(2^K * (trunc X to iN)) to iM
1909 // = zext((trunc X to iN) << K) to iM
1910 // = zext((trunc X to i{N-K}) << K)<nuw> to iM
1911 // (because shl removes the top K bits)
1912 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1913 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1915 if (SM
->getNumOperands() == 2)
1916 if (auto *MulLHS
= dyn_cast
<SCEVConstant
>(SM
->getOperand(0)))
1917 if (MulLHS
->getAPInt().isPowerOf2())
1918 if (auto *TruncRHS
= dyn_cast
<SCEVTruncateExpr
>(SM
->getOperand(1))) {
1919 int NewTruncBits
= getTypeSizeInBits(TruncRHS
->getType()) -
1920 MulLHS
->getAPInt().logBase2();
1921 Type
*NewTruncTy
= IntegerType::get(getContext(), NewTruncBits
);
1923 getZeroExtendExpr(MulLHS
, Ty
),
1925 getTruncateExpr(TruncRHS
->getOperand(), NewTruncTy
), Ty
),
1926 SCEV::FlagNUW
, Depth
+ 1);
1930 // The cast wasn't folded; create an explicit cast node.
1931 // Recompute the insert position, as it may have been invalidated.
1932 if (const SCEV
*S
= UniqueSCEVs
.FindNodeOrInsertPos(ID
, IP
)) return S
;
1933 SCEV
*S
= new (SCEVAllocator
) SCEVZeroExtendExpr(ID
.Intern(SCEVAllocator
),
1935 UniqueSCEVs
.InsertNode(S
, IP
);
1936 addToLoopUseLists(S
);
1941 ScalarEvolution::getSignExtendExpr(const SCEV
*Op
, Type
*Ty
, unsigned Depth
) {
1942 assert(getTypeSizeInBits(Op
->getType()) < getTypeSizeInBits(Ty
) &&
1943 "This is not an extending conversion!");
1944 assert(isSCEVable(Ty
) &&
1945 "This is not a conversion to a SCEVable type!");
1946 Ty
= getEffectiveSCEVType(Ty
);
1948 // Fold if the operand is constant.
1949 if (const SCEVConstant
*SC
= dyn_cast
<SCEVConstant
>(Op
))
1951 cast
<ConstantInt
>(ConstantExpr::getSExt(SC
->getValue(), Ty
)));
1953 // sext(sext(x)) --> sext(x)
1954 if (const SCEVSignExtendExpr
*SS
= dyn_cast
<SCEVSignExtendExpr
>(Op
))
1955 return getSignExtendExpr(SS
->getOperand(), Ty
, Depth
+ 1);
1957 // sext(zext(x)) --> zext(x)
1958 if (const SCEVZeroExtendExpr
*SZ
= dyn_cast
<SCEVZeroExtendExpr
>(Op
))
1959 return getZeroExtendExpr(SZ
->getOperand(), Ty
, Depth
+ 1);
1961 // Before doing any expensive analysis, check to see if we've already
1962 // computed a SCEV for this Op and Ty.
1963 FoldingSetNodeID ID
;
1964 ID
.AddInteger(scSignExtend
);
1968 if (const SCEV
*S
= UniqueSCEVs
.FindNodeOrInsertPos(ID
, IP
)) return S
;
1969 // Limit recursion depth.
1970 if (Depth
> MaxCastDepth
) {
1971 SCEV
*S
= new (SCEVAllocator
) SCEVSignExtendExpr(ID
.Intern(SCEVAllocator
),
1973 UniqueSCEVs
.InsertNode(S
, IP
);
1974 addToLoopUseLists(S
);
1978 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1979 if (const SCEVTruncateExpr
*ST
= dyn_cast
<SCEVTruncateExpr
>(Op
)) {
1980 // It's possible the bits taken off by the truncate were all sign bits. If
1981 // so, we should be able to simplify this further.
1982 const SCEV
*X
= ST
->getOperand();
1983 ConstantRange CR
= getSignedRange(X
);
1984 unsigned TruncBits
= getTypeSizeInBits(ST
->getType());
1985 unsigned NewBits
= getTypeSizeInBits(Ty
);
1986 if (CR
.truncate(TruncBits
).signExtend(NewBits
).contains(
1987 CR
.sextOrTrunc(NewBits
)))
1988 return getTruncateOrSignExtend(X
, Ty
, Depth
);
1991 if (auto *SA
= dyn_cast
<SCEVAddExpr
>(Op
)) {
1992 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1993 if (SA
->hasNoSignedWrap()) {
1994 // If the addition does not sign overflow then we can, by definition,
1995 // commute the sign extension with the addition operation.
1996 SmallVector
<const SCEV
*, 4> Ops
;
1997 for (const auto *Op
: SA
->operands())
1998 Ops
.push_back(getSignExtendExpr(Op
, Ty
, Depth
+ 1));
1999 return getAddExpr(Ops
, SCEV::FlagNSW
, Depth
+ 1);
2002 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
2003 // if D + (C - D + x + y + ...) could be proven to not signed wrap
2004 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
2006 // For instance, this will bring two seemingly different expressions:
2007 // 1 + sext(5 + 20 * %x + 24 * %y) and
2008 // sext(6 + 20 * %x + 24 * %y)
2009 // to the same form:
2010 // 2 + sext(4 + 20 * %x + 24 * %y)
2011 if (const auto *SC
= dyn_cast
<SCEVConstant
>(SA
->getOperand(0))) {
2012 const APInt
&D
= extractConstantWithoutWrapping(*this, SC
, SA
);
2014 const SCEV
*SSExtD
= getSignExtendExpr(getConstant(D
), Ty
, Depth
);
2015 const SCEV
*SResidual
=
2016 getAddExpr(getConstant(-D
), SA
, SCEV::FlagAnyWrap
, Depth
);
2017 const SCEV
*SSExtR
= getSignExtendExpr(SResidual
, Ty
, Depth
+ 1);
2018 return getAddExpr(SSExtD
, SSExtR
,
2019 (SCEV::NoWrapFlags
)(SCEV::FlagNSW
| SCEV::FlagNUW
),
2024 // If the input value is a chrec scev, and we can prove that the value
2025 // did not overflow the old, smaller, value, we can sign extend all of the
2026 // operands (often constants). This allows analysis of something like
2027 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
2028 if (const SCEVAddRecExpr
*AR
= dyn_cast
<SCEVAddRecExpr
>(Op
))
2029 if (AR
->isAffine()) {
2030 const SCEV
*Start
= AR
->getStart();
2031 const SCEV
*Step
= AR
->getStepRecurrence(*this);
2032 unsigned BitWidth
= getTypeSizeInBits(AR
->getType());
2033 const Loop
*L
= AR
->getLoop();
2035 if (!AR
->hasNoSignedWrap()) {
2036 auto NewFlags
= proveNoWrapViaConstantRanges(AR
);
2037 const_cast<SCEVAddRecExpr
*>(AR
)->setNoWrapFlags(NewFlags
);
2040 // If we have special knowledge that this addrec won't overflow,
2041 // we don't need to do any further analysis.
2042 if (AR
->hasNoSignedWrap())
2043 return getAddRecExpr(
2044 getExtendAddRecStart
<SCEVSignExtendExpr
>(AR
, Ty
, this, Depth
+ 1),
2045 getSignExtendExpr(Step
, Ty
, Depth
+ 1), L
, SCEV::FlagNSW
);
2047 // Check whether the backedge-taken count is SCEVCouldNotCompute.
2048 // Note that this serves two purposes: It filters out loops that are
2049 // simply not analyzable, and it covers the case where this code is
2050 // being called from within backedge-taken count analysis, such that
2051 // attempting to ask for the backedge-taken count would likely result
2052 // in infinite recursion. In the later case, the analysis code will
2053 // cope with a conservative value, and it will take care to purge
2054 // that value once it has finished.
2055 const SCEV
*MaxBECount
= getConstantMaxBackedgeTakenCount(L
);
2056 if (!isa
<SCEVCouldNotCompute
>(MaxBECount
)) {
2057 // Manually compute the final value for AR, checking for
2060 // Check whether the backedge-taken count can be losslessly casted to
2061 // the addrec's type. The count is always unsigned.
2062 const SCEV
*CastedMaxBECount
=
2063 getTruncateOrZeroExtend(MaxBECount
, Start
->getType(), Depth
);
2064 const SCEV
*RecastedMaxBECount
= getTruncateOrZeroExtend(
2065 CastedMaxBECount
, MaxBECount
->getType(), Depth
);
2066 if (MaxBECount
== RecastedMaxBECount
) {
2067 Type
*WideTy
= IntegerType::get(getContext(), BitWidth
* 2);
2068 // Check whether Start+Step*MaxBECount has no signed overflow.
2069 const SCEV
*SMul
= getMulExpr(CastedMaxBECount
, Step
,
2070 SCEV::FlagAnyWrap
, Depth
+ 1);
2071 const SCEV
*SAdd
= getSignExtendExpr(getAddExpr(Start
, SMul
,
2075 const SCEV
*WideStart
= getSignExtendExpr(Start
, WideTy
, Depth
+ 1);
2076 const SCEV
*WideMaxBECount
=
2077 getZeroExtendExpr(CastedMaxBECount
, WideTy
, Depth
+ 1);
2078 const SCEV
*OperandExtendedAdd
=
2079 getAddExpr(WideStart
,
2080 getMulExpr(WideMaxBECount
,
2081 getSignExtendExpr(Step
, WideTy
, Depth
+ 1),
2082 SCEV::FlagAnyWrap
, Depth
+ 1),
2083 SCEV::FlagAnyWrap
, Depth
+ 1);
2084 if (SAdd
== OperandExtendedAdd
) {
2085 // Cache knowledge of AR NSW, which is propagated to this AddRec.
2086 const_cast<SCEVAddRecExpr
*>(AR
)->setNoWrapFlags(SCEV::FlagNSW
);
2087 // Return the expression with the addrec on the outside.
2088 return getAddRecExpr(
2089 getExtendAddRecStart
<SCEVSignExtendExpr
>(AR
, Ty
, this,
2091 getSignExtendExpr(Step
, Ty
, Depth
+ 1), L
,
2092 AR
->getNoWrapFlags());
2094 // Similar to above, only this time treat the step value as unsigned.
2095 // This covers loops that count up with an unsigned step.
2096 OperandExtendedAdd
=
2097 getAddExpr(WideStart
,
2098 getMulExpr(WideMaxBECount
,
2099 getZeroExtendExpr(Step
, WideTy
, Depth
+ 1),
2100 SCEV::FlagAnyWrap
, Depth
+ 1),
2101 SCEV::FlagAnyWrap
, Depth
+ 1);
2102 if (SAdd
== OperandExtendedAdd
) {
2103 // If AR wraps around then
2105 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
2106 // => SAdd != OperandExtendedAdd
2108 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2109 // (SAdd == OperandExtendedAdd => AR is NW)
2111 const_cast<SCEVAddRecExpr
*>(AR
)->setNoWrapFlags(SCEV::FlagNW
);
2113 // Return the expression with the addrec on the outside.
2114 return getAddRecExpr(
2115 getExtendAddRecStart
<SCEVSignExtendExpr
>(AR
, Ty
, this,
2117 getZeroExtendExpr(Step
, Ty
, Depth
+ 1), L
,
2118 AR
->getNoWrapFlags());
2123 // Normally, in the cases we can prove no-overflow via a
2124 // backedge guarding condition, we can also compute a backedge
2125 // taken count for the loop. The exceptions are assumptions and
2126 // guards present in the loop -- SCEV is not great at exploiting
2127 // these to compute max backedge taken counts, but can still use
2128 // these to prove lack of overflow. Use this fact to avoid
2129 // doing extra work that may not pay off.
2131 if (!isa
<SCEVCouldNotCompute
>(MaxBECount
) || HasGuards
||
2132 !AC
.assumptions().empty()) {
2133 // If the backedge is guarded by a comparison with the pre-inc
2134 // value the addrec is safe. Also, if the entry is guarded by
2135 // a comparison with the start value and the backedge is
2136 // guarded by a comparison with the post-inc value, the addrec
2138 ICmpInst::Predicate Pred
;
2139 const SCEV
*OverflowLimit
=
2140 getSignedOverflowLimitForStep(Step
, &Pred
, this);
2141 if (OverflowLimit
&&
2142 (isLoopBackedgeGuardedByCond(L
, Pred
, AR
, OverflowLimit
) ||
2143 isKnownOnEveryIteration(Pred
, AR
, OverflowLimit
))) {
2144 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
2145 const_cast<SCEVAddRecExpr
*>(AR
)->setNoWrapFlags(SCEV::FlagNSW
);
2146 return getAddRecExpr(
2147 getExtendAddRecStart
<SCEVSignExtendExpr
>(AR
, Ty
, this, Depth
+ 1),
2148 getSignExtendExpr(Step
, Ty
, Depth
+ 1), L
, AR
->getNoWrapFlags());
2152 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2153 // if D + (C - D + Step * n) could be proven to not signed wrap
2154 // where D maximizes the number of trailing zeros of (C - D + Step * n)
2155 if (const auto *SC
= dyn_cast
<SCEVConstant
>(Start
)) {
2156 const APInt
&C
= SC
->getAPInt();
2157 const APInt
&D
= extractConstantWithoutWrapping(*this, C
, Step
);
2159 const SCEV
*SSExtD
= getSignExtendExpr(getConstant(D
), Ty
, Depth
);
2160 const SCEV
*SResidual
=
2161 getAddRecExpr(getConstant(C
- D
), Step
, L
, AR
->getNoWrapFlags());
2162 const SCEV
*SSExtR
= getSignExtendExpr(SResidual
, Ty
, Depth
+ 1);
2163 return getAddExpr(SSExtD
, SSExtR
,
2164 (SCEV::NoWrapFlags
)(SCEV::FlagNSW
| SCEV::FlagNUW
),
2169 if (proveNoWrapByVaryingStart
<SCEVSignExtendExpr
>(Start
, Step
, L
)) {
2170 const_cast<SCEVAddRecExpr
*>(AR
)->setNoWrapFlags(SCEV::FlagNSW
);
2171 return getAddRecExpr(
2172 getExtendAddRecStart
<SCEVSignExtendExpr
>(AR
, Ty
, this, Depth
+ 1),
2173 getSignExtendExpr(Step
, Ty
, Depth
+ 1), L
, AR
->getNoWrapFlags());
2177 // If the input value is provably positive and we could not simplify
2178 // away the sext build a zext instead.
2179 if (isKnownNonNegative(Op
))
2180 return getZeroExtendExpr(Op
, Ty
, Depth
+ 1);
2182 // The cast wasn't folded; create an explicit cast node.
2183 // Recompute the insert position, as it may have been invalidated.
2184 if (const SCEV
*S
= UniqueSCEVs
.FindNodeOrInsertPos(ID
, IP
)) return S
;
2185 SCEV
*S
= new (SCEVAllocator
) SCEVSignExtendExpr(ID
.Intern(SCEVAllocator
),
2187 UniqueSCEVs
.InsertNode(S
, IP
);
2188 addToLoopUseLists(S
);
2192 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2193 /// unspecified bits out to the given type.
2194 const SCEV
*ScalarEvolution::getAnyExtendExpr(const SCEV
*Op
,
2196 assert(getTypeSizeInBits(Op
->getType()) < getTypeSizeInBits(Ty
) &&
2197 "This is not an extending conversion!");
2198 assert(isSCEVable(Ty
) &&
2199 "This is not a conversion to a SCEVable type!");
2200 Ty
= getEffectiveSCEVType(Ty
);
2202 // Sign-extend negative constants.
2203 if (const SCEVConstant
*SC
= dyn_cast
<SCEVConstant
>(Op
))
2204 if (SC
->getAPInt().isNegative())
2205 return getSignExtendExpr(Op
, Ty
);
2207 // Peel off a truncate cast.
2208 if (const SCEVTruncateExpr
*T
= dyn_cast
<SCEVTruncateExpr
>(Op
)) {
2209 const SCEV
*NewOp
= T
->getOperand();
2210 if (getTypeSizeInBits(NewOp
->getType()) < getTypeSizeInBits(Ty
))
2211 return getAnyExtendExpr(NewOp
, Ty
);
2212 return getTruncateOrNoop(NewOp
, Ty
);
2215 // Next try a zext cast. If the cast is folded, use it.
2216 const SCEV
*ZExt
= getZeroExtendExpr(Op
, Ty
);
2217 if (!isa
<SCEVZeroExtendExpr
>(ZExt
))
2220 // Next try a sext cast. If the cast is folded, use it.
2221 const SCEV
*SExt
= getSignExtendExpr(Op
, Ty
);
2222 if (!isa
<SCEVSignExtendExpr
>(SExt
))
2225 // Force the cast to be folded into the operands of an addrec.
2226 if (const SCEVAddRecExpr
*AR
= dyn_cast
<SCEVAddRecExpr
>(Op
)) {
2227 SmallVector
<const SCEV
*, 4> Ops
;
2228 for (const SCEV
*Op
: AR
->operands())
2229 Ops
.push_back(getAnyExtendExpr(Op
, Ty
));
2230 return getAddRecExpr(Ops
, AR
->getLoop(), SCEV::FlagNW
);
2233 // If the expression is obviously signed, use the sext cast value.
2234 if (isa
<SCEVSMaxExpr
>(Op
))
2237 // Absent any other information, use the zext cast value.
2241 /// Process the given Ops list, which is a list of operands to be added under
2242 /// the given scale, update the given map. This is a helper function for
2243 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2244 /// that would form an add expression like this:
2246 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2248 /// where A and B are constants, update the map with these values:
2250 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2252 /// and add 13 + A*B*29 to AccumulatedConstant.
2253 /// This will allow getAddRecExpr to produce this:
2255 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2257 /// This form often exposes folding opportunities that are hidden in
2258 /// the original operand list.
2260 /// Return true iff it appears that any interesting folding opportunities
2261 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2262 /// the common case where no interesting opportunities are present, and
2263 /// is also used as a check to avoid infinite recursion.
2265 CollectAddOperandsWithScales(DenseMap
<const SCEV
*, APInt
> &M
,
2266 SmallVectorImpl
<const SCEV
*> &NewOps
,
2267 APInt
&AccumulatedConstant
,
2268 const SCEV
*const *Ops
, size_t NumOperands
,
2270 ScalarEvolution
&SE
) {
2271 bool Interesting
= false;
2273 // Iterate over the add operands. They are sorted, with constants first.
2275 while (const SCEVConstant
*C
= dyn_cast
<SCEVConstant
>(Ops
[i
])) {
2277 // Pull a buried constant out to the outside.
2278 if (Scale
!= 1 || AccumulatedConstant
!= 0 || C
->getValue()->isZero())
2280 AccumulatedConstant
+= Scale
* C
->getAPInt();
2283 // Next comes everything else. We're especially interested in multiplies
2284 // here, but they're in the middle, so just visit the rest with one loop.
2285 for (; i
!= NumOperands
; ++i
) {
2286 const SCEVMulExpr
*Mul
= dyn_cast
<SCEVMulExpr
>(Ops
[i
]);
2287 if (Mul
&& isa
<SCEVConstant
>(Mul
->getOperand(0))) {
2289 Scale
* cast
<SCEVConstant
>(Mul
->getOperand(0))->getAPInt();
2290 if (Mul
->getNumOperands() == 2 && isa
<SCEVAddExpr
>(Mul
->getOperand(1))) {
2291 // A multiplication of a constant with another add; recurse.
2292 const SCEVAddExpr
*Add
= cast
<SCEVAddExpr
>(Mul
->getOperand(1));
2294 CollectAddOperandsWithScales(M
, NewOps
, AccumulatedConstant
,
2295 Add
->op_begin(), Add
->getNumOperands(),
2298 // A multiplication of a constant with some other value. Update
2300 SmallVector
<const SCEV
*, 4> MulOps(Mul
->op_begin()+1, Mul
->op_end());
2301 const SCEV
*Key
= SE
.getMulExpr(MulOps
);
2302 auto Pair
= M
.insert({Key
, NewScale
});
2304 NewOps
.push_back(Pair
.first
->first
);
2306 Pair
.first
->second
+= NewScale
;
2307 // The map already had an entry for this value, which may indicate
2308 // a folding opportunity.
2313 // An ordinary operand. Update the map.
2314 std::pair
<DenseMap
<const SCEV
*, APInt
>::iterator
, bool> Pair
=
2315 M
.insert({Ops
[i
], Scale
});
2317 NewOps
.push_back(Pair
.first
->first
);
2319 Pair
.first
->second
+= Scale
;
2320 // The map already had an entry for this value, which may indicate
2321 // a folding opportunity.
2330 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2331 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2332 // can't-overflow flags for the operation if possible.
2333 static SCEV::NoWrapFlags
2334 StrengthenNoWrapFlags(ScalarEvolution
*SE
, SCEVTypes Type
,
2335 const ArrayRef
<const SCEV
*> Ops
,
2336 SCEV::NoWrapFlags Flags
) {
2337 using namespace std::placeholders
;
2339 using OBO
= OverflowingBinaryOperator
;
2342 Type
== scAddExpr
|| Type
== scAddRecExpr
|| Type
== scMulExpr
;
2344 assert(CanAnalyze
&& "don't call from other places!");
2346 int SignOrUnsignMask
= SCEV::FlagNUW
| SCEV::FlagNSW
;
2347 SCEV::NoWrapFlags SignOrUnsignWrap
=
2348 ScalarEvolution::maskFlags(Flags
, SignOrUnsignMask
);
2350 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2351 auto IsKnownNonNegative
= [&](const SCEV
*S
) {
2352 return SE
->isKnownNonNegative(S
);
2355 if (SignOrUnsignWrap
== SCEV::FlagNSW
&& all_of(Ops
, IsKnownNonNegative
))
2357 ScalarEvolution::setFlags(Flags
, (SCEV::NoWrapFlags
)SignOrUnsignMask
);
2359 SignOrUnsignWrap
= ScalarEvolution::maskFlags(Flags
, SignOrUnsignMask
);
2361 if (SignOrUnsignWrap
!= SignOrUnsignMask
&&
2362 (Type
== scAddExpr
|| Type
== scMulExpr
) && Ops
.size() == 2 &&
2363 isa
<SCEVConstant
>(Ops
[0])) {
2368 return Instruction::Add
;
2370 return Instruction::Mul
;
2372 llvm_unreachable("Unexpected SCEV op.");
2376 const APInt
&C
= cast
<SCEVConstant
>(Ops
[0])->getAPInt();
2378 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2379 if (!(SignOrUnsignWrap
& SCEV::FlagNSW
)) {
2380 auto NSWRegion
= ConstantRange::makeGuaranteedNoWrapRegion(
2381 Opcode
, C
, OBO::NoSignedWrap
);
2382 if (NSWRegion
.contains(SE
->getSignedRange(Ops
[1])))
2383 Flags
= ScalarEvolution::setFlags(Flags
, SCEV::FlagNSW
);
2386 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2387 if (!(SignOrUnsignWrap
& SCEV::FlagNUW
)) {
2388 auto NUWRegion
= ConstantRange::makeGuaranteedNoWrapRegion(
2389 Opcode
, C
, OBO::NoUnsignedWrap
);
2390 if (NUWRegion
.contains(SE
->getUnsignedRange(Ops
[1])))
2391 Flags
= ScalarEvolution::setFlags(Flags
, SCEV::FlagNUW
);
2398 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV
*S
, const Loop
*L
) {
2399 return isLoopInvariant(S
, L
) && properlyDominates(S
, L
->getHeader());
2402 /// Get a canonical add expression, or something simpler if possible.
2403 const SCEV
*ScalarEvolution::getAddExpr(SmallVectorImpl
<const SCEV
*> &Ops
,
2404 SCEV::NoWrapFlags Flags
,
2406 assert(!(Flags
& ~(SCEV::FlagNUW
| SCEV::FlagNSW
)) &&
2407 "only nuw or nsw allowed");
2408 assert(!Ops
.empty() && "Cannot get empty add!");
2409 if (Ops
.size() == 1) return Ops
[0];
2411 Type
*ETy
= getEffectiveSCEVType(Ops
[0]->getType());
2412 for (unsigned i
= 1, e
= Ops
.size(); i
!= e
; ++i
)
2413 assert(getEffectiveSCEVType(Ops
[i
]->getType()) == ETy
&&
2414 "SCEVAddExpr operand types don't match!");
2417 // Sort by complexity, this groups all similar expression types together.
2418 GroupByComplexity(Ops
, &LI
, DT
);
2420 Flags
= StrengthenNoWrapFlags(this, scAddExpr
, Ops
, Flags
);
2422 // If there are any constants, fold them together.
2424 if (const SCEVConstant
*LHSC
= dyn_cast
<SCEVConstant
>(Ops
[0])) {
2426 assert(Idx
< Ops
.size());
2427 while (const SCEVConstant
*RHSC
= dyn_cast
<SCEVConstant
>(Ops
[Idx
])) {
2428 // We found two constants, fold them together!
2429 Ops
[0] = getConstant(LHSC
->getAPInt() + RHSC
->getAPInt());
2430 if (Ops
.size() == 2) return Ops
[0];
2431 Ops
.erase(Ops
.begin()+1); // Erase the folded element
2432 LHSC
= cast
<SCEVConstant
>(Ops
[0]);
2435 // If we are left with a constant zero being added, strip it off.
2436 if (LHSC
->getValue()->isZero()) {
2437 Ops
.erase(Ops
.begin());
2441 if (Ops
.size() == 1) return Ops
[0];
2444 // Limit recursion calls depth.
2445 if (Depth
> MaxArithDepth
|| hasHugeExpression(Ops
))
2446 return getOrCreateAddExpr(Ops
, Flags
);
2448 // Okay, check to see if the same value occurs in the operand list more than
2449 // once. If so, merge them together into an multiply expression. Since we
2450 // sorted the list, these values are required to be adjacent.
2451 Type
*Ty
= Ops
[0]->getType();
2452 bool FoundMatch
= false;
2453 for (unsigned i
= 0, e
= Ops
.size(); i
!= e
-1; ++i
)
2454 if (Ops
[i
] == Ops
[i
+1]) { // X + Y + Y --> X + Y*2
2455 // Scan ahead to count how many equal operands there are.
2457 while (i
+Count
!= e
&& Ops
[i
+Count
] == Ops
[i
])
2459 // Merge the values into a multiply.
2460 const SCEV
*Scale
= getConstant(Ty
, Count
);
2461 const SCEV
*Mul
= getMulExpr(Scale
, Ops
[i
], SCEV::FlagAnyWrap
, Depth
+ 1);
2462 if (Ops
.size() == Count
)
2465 Ops
.erase(Ops
.begin()+i
+1, Ops
.begin()+i
+Count
);
2466 --i
; e
-= Count
- 1;
2470 return getAddExpr(Ops
, Flags
, Depth
+ 1);
2472 // Check for truncates. If all the operands are truncated from the same
2473 // type, see if factoring out the truncate would permit the result to be
2474 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2475 // if the contents of the resulting outer trunc fold to something simple.
2476 auto FindTruncSrcType
= [&]() -> Type
* {
2477 // We're ultimately looking to fold an addrec of truncs and muls of only
2478 // constants and truncs, so if we find any other types of SCEV
2479 // as operands of the addrec then we bail and return nullptr here.
2480 // Otherwise, we return the type of the operand of a trunc that we find.
2481 if (auto *T
= dyn_cast
<SCEVTruncateExpr
>(Ops
[Idx
]))
2482 return T
->getOperand()->getType();
2483 if (const auto *Mul
= dyn_cast
<SCEVMulExpr
>(Ops
[Idx
])) {
2484 const auto *LastOp
= Mul
->getOperand(Mul
->getNumOperands() - 1);
2485 if (const auto *T
= dyn_cast
<SCEVTruncateExpr
>(LastOp
))
2486 return T
->getOperand()->getType();
2490 if (auto *SrcType
= FindTruncSrcType()) {
2491 SmallVector
<const SCEV
*, 8> LargeOps
;
2493 // Check all the operands to see if they can be represented in the
2494 // source type of the truncate.
2495 for (unsigned i
= 0, e
= Ops
.size(); i
!= e
; ++i
) {
2496 if (const SCEVTruncateExpr
*T
= dyn_cast
<SCEVTruncateExpr
>(Ops
[i
])) {
2497 if (T
->getOperand()->getType() != SrcType
) {
2501 LargeOps
.push_back(T
->getOperand());
2502 } else if (const SCEVConstant
*C
= dyn_cast
<SCEVConstant
>(Ops
[i
])) {
2503 LargeOps
.push_back(getAnyExtendExpr(C
, SrcType
));
2504 } else if (const SCEVMulExpr
*M
= dyn_cast
<SCEVMulExpr
>(Ops
[i
])) {
2505 SmallVector
<const SCEV
*, 8> LargeMulOps
;
2506 for (unsigned j
= 0, f
= M
->getNumOperands(); j
!= f
&& Ok
; ++j
) {
2507 if (const SCEVTruncateExpr
*T
=
2508 dyn_cast
<SCEVTruncateExpr
>(M
->getOperand(j
))) {
2509 if (T
->getOperand()->getType() != SrcType
) {
2513 LargeMulOps
.push_back(T
->getOperand());
2514 } else if (const auto *C
= dyn_cast
<SCEVConstant
>(M
->getOperand(j
))) {
2515 LargeMulOps
.push_back(getAnyExtendExpr(C
, SrcType
));
2522 LargeOps
.push_back(getMulExpr(LargeMulOps
, SCEV::FlagAnyWrap
, Depth
+ 1));
2529 // Evaluate the expression in the larger type.
2530 const SCEV
*Fold
= getAddExpr(LargeOps
, SCEV::FlagAnyWrap
, Depth
+ 1);
2531 // If it folds to something simple, use it. Otherwise, don't.
2532 if (isa
<SCEVConstant
>(Fold
) || isa
<SCEVUnknown
>(Fold
))
2533 return getTruncateExpr(Fold
, Ty
);
2537 // Skip past any other cast SCEVs.
2538 while (Idx
< Ops
.size() && Ops
[Idx
]->getSCEVType() < scAddExpr
)
2541 // If there are add operands they would be next.
2542 if (Idx
< Ops
.size()) {
2543 bool DeletedAdd
= false;
2544 while (const SCEVAddExpr
*Add
= dyn_cast
<SCEVAddExpr
>(Ops
[Idx
])) {
2545 if (Ops
.size() > AddOpsInlineThreshold
||
2546 Add
->getNumOperands() > AddOpsInlineThreshold
)
2548 // If we have an add, expand the add operands onto the end of the operands
2550 Ops
.erase(Ops
.begin()+Idx
);
2551 Ops
.append(Add
->op_begin(), Add
->op_end());
2555 // If we deleted at least one add, we added operands to the end of the list,
2556 // and they are not necessarily sorted. Recurse to resort and resimplify
2557 // any operands we just acquired.
2559 return getAddExpr(Ops
, SCEV::FlagAnyWrap
, Depth
+ 1);
2562 // Skip over the add expression until we get to a multiply.
2563 while (Idx
< Ops
.size() && Ops
[Idx
]->getSCEVType() < scMulExpr
)
2566 // Check to see if there are any folding opportunities present with
2567 // operands multiplied by constant values.
2568 if (Idx
< Ops
.size() && isa
<SCEVMulExpr
>(Ops
[Idx
])) {
2569 uint64_t BitWidth
= getTypeSizeInBits(Ty
);
2570 DenseMap
<const SCEV
*, APInt
> M
;
2571 SmallVector
<const SCEV
*, 8> NewOps
;
2572 APInt
AccumulatedConstant(BitWidth
, 0);
2573 if (CollectAddOperandsWithScales(M
, NewOps
, AccumulatedConstant
,
2574 Ops
.data(), Ops
.size(),
2575 APInt(BitWidth
, 1), *this)) {
2576 struct APIntCompare
{
2577 bool operator()(const APInt
&LHS
, const APInt
&RHS
) const {
2578 return LHS
.ult(RHS
);
2582 // Some interesting folding opportunity is present, so its worthwhile to
2583 // re-generate the operands list. Group the operands by constant scale,
2584 // to avoid multiplying by the same constant scale multiple times.
2585 std::map
<APInt
, SmallVector
<const SCEV
*, 4>, APIntCompare
> MulOpLists
;
2586 for (const SCEV
*NewOp
: NewOps
)
2587 MulOpLists
[M
.find(NewOp
)->second
].push_back(NewOp
);
2588 // Re-generate the operands list.
2590 if (AccumulatedConstant
!= 0)
2591 Ops
.push_back(getConstant(AccumulatedConstant
));
2592 for (auto &MulOp
: MulOpLists
)
2593 if (MulOp
.first
!= 0)
2594 Ops
.push_back(getMulExpr(
2595 getConstant(MulOp
.first
),
2596 getAddExpr(MulOp
.second
, SCEV::FlagAnyWrap
, Depth
+ 1),
2597 SCEV::FlagAnyWrap
, Depth
+ 1));
2600 if (Ops
.size() == 1)
2602 return getAddExpr(Ops
, SCEV::FlagAnyWrap
, Depth
+ 1);
2606 // If we are adding something to a multiply expression, make sure the
2607 // something is not already an operand of the multiply. If so, merge it into
2609 for (; Idx
< Ops
.size() && isa
<SCEVMulExpr
>(Ops
[Idx
]); ++Idx
) {
2610 const SCEVMulExpr
*Mul
= cast
<SCEVMulExpr
>(Ops
[Idx
]);
2611 for (unsigned MulOp
= 0, e
= Mul
->getNumOperands(); MulOp
!= e
; ++MulOp
) {
2612 const SCEV
*MulOpSCEV
= Mul
->getOperand(MulOp
);
2613 if (isa
<SCEVConstant
>(MulOpSCEV
))
2615 for (unsigned AddOp
= 0, e
= Ops
.size(); AddOp
!= e
; ++AddOp
)
2616 if (MulOpSCEV
== Ops
[AddOp
]) {
2617 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2618 const SCEV
*InnerMul
= Mul
->getOperand(MulOp
== 0);
2619 if (Mul
->getNumOperands() != 2) {
2620 // If the multiply has more than two operands, we must get the
2622 SmallVector
<const SCEV
*, 4> MulOps(Mul
->op_begin(),
2623 Mul
->op_begin()+MulOp
);
2624 MulOps
.append(Mul
->op_begin()+MulOp
+1, Mul
->op_end());
2625 InnerMul
= getMulExpr(MulOps
, SCEV::FlagAnyWrap
, Depth
+ 1);
2627 SmallVector
<const SCEV
*, 2> TwoOps
= {getOne(Ty
), InnerMul
};
2628 const SCEV
*AddOne
= getAddExpr(TwoOps
, SCEV::FlagAnyWrap
, Depth
+ 1);
2629 const SCEV
*OuterMul
= getMulExpr(AddOne
, MulOpSCEV
,
2630 SCEV::FlagAnyWrap
, Depth
+ 1);
2631 if (Ops
.size() == 2) return OuterMul
;
2633 Ops
.erase(Ops
.begin()+AddOp
);
2634 Ops
.erase(Ops
.begin()+Idx
-1);
2636 Ops
.erase(Ops
.begin()+Idx
);
2637 Ops
.erase(Ops
.begin()+AddOp
-1);
2639 Ops
.push_back(OuterMul
);
2640 return getAddExpr(Ops
, SCEV::FlagAnyWrap
, Depth
+ 1);
2643 // Check this multiply against other multiplies being added together.
2644 for (unsigned OtherMulIdx
= Idx
+1;
2645 OtherMulIdx
< Ops
.size() && isa
<SCEVMulExpr
>(Ops
[OtherMulIdx
]);
2647 const SCEVMulExpr
*OtherMul
= cast
<SCEVMulExpr
>(Ops
[OtherMulIdx
]);
2648 // If MulOp occurs in OtherMul, we can fold the two multiplies
2650 for (unsigned OMulOp
= 0, e
= OtherMul
->getNumOperands();
2651 OMulOp
!= e
; ++OMulOp
)
2652 if (OtherMul
->getOperand(OMulOp
) == MulOpSCEV
) {
2653 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2654 const SCEV
*InnerMul1
= Mul
->getOperand(MulOp
== 0);
2655 if (Mul
->getNumOperands() != 2) {
2656 SmallVector
<const SCEV
*, 4> MulOps(Mul
->op_begin(),
2657 Mul
->op_begin()+MulOp
);
2658 MulOps
.append(Mul
->op_begin()+MulOp
+1, Mul
->op_end());
2659 InnerMul1
= getMulExpr(MulOps
, SCEV::FlagAnyWrap
, Depth
+ 1);
2661 const SCEV
*InnerMul2
= OtherMul
->getOperand(OMulOp
== 0);
2662 if (OtherMul
->getNumOperands() != 2) {
2663 SmallVector
<const SCEV
*, 4> MulOps(OtherMul
->op_begin(),
2664 OtherMul
->op_begin()+OMulOp
);
2665 MulOps
.append(OtherMul
->op_begin()+OMulOp
+1, OtherMul
->op_end());
2666 InnerMul2
= getMulExpr(MulOps
, SCEV::FlagAnyWrap
, Depth
+ 1);
2668 SmallVector
<const SCEV
*, 2> TwoOps
= {InnerMul1
, InnerMul2
};
2669 const SCEV
*InnerMulSum
=
2670 getAddExpr(TwoOps
, SCEV::FlagAnyWrap
, Depth
+ 1);
2671 const SCEV
*OuterMul
= getMulExpr(MulOpSCEV
, InnerMulSum
,
2672 SCEV::FlagAnyWrap
, Depth
+ 1);
2673 if (Ops
.size() == 2) return OuterMul
;
2674 Ops
.erase(Ops
.begin()+Idx
);
2675 Ops
.erase(Ops
.begin()+OtherMulIdx
-1);
2676 Ops
.push_back(OuterMul
);
2677 return getAddExpr(Ops
, SCEV::FlagAnyWrap
, Depth
+ 1);
2683 // If there are any add recurrences in the operands list, see if any other
2684 // added values are loop invariant. If so, we can fold them into the
2686 while (Idx
< Ops
.size() && Ops
[Idx
]->getSCEVType() < scAddRecExpr
)
2689 // Scan over all recurrences, trying to fold loop invariants into them.
2690 for (; Idx
< Ops
.size() && isa
<SCEVAddRecExpr
>(Ops
[Idx
]); ++Idx
) {
2691 // Scan all of the other operands to this add and add them to the vector if
2692 // they are loop invariant w.r.t. the recurrence.
2693 SmallVector
<const SCEV
*, 8> LIOps
;
2694 const SCEVAddRecExpr
*AddRec
= cast
<SCEVAddRecExpr
>(Ops
[Idx
]);
2695 const Loop
*AddRecLoop
= AddRec
->getLoop();
2696 for (unsigned i
= 0, e
= Ops
.size(); i
!= e
; ++i
)
2697 if (isAvailableAtLoopEntry(Ops
[i
], AddRecLoop
)) {
2698 LIOps
.push_back(Ops
[i
]);
2699 Ops
.erase(Ops
.begin()+i
);
2703 // If we found some loop invariants, fold them into the recurrence.
2704 if (!LIOps
.empty()) {
2705 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2706 LIOps
.push_back(AddRec
->getStart());
2708 SmallVector
<const SCEV
*, 4> AddRecOps(AddRec
->op_begin(),
2710 // This follows from the fact that the no-wrap flags on the outer add
2711 // expression are applicable on the 0th iteration, when the add recurrence
2712 // will be equal to its start value.
2713 AddRecOps
[0] = getAddExpr(LIOps
, Flags
, Depth
+ 1);
2715 // Build the new addrec. Propagate the NUW and NSW flags if both the
2716 // outer add and the inner addrec are guaranteed to have no overflow.
2717 // Always propagate NW.
2718 Flags
= AddRec
->getNoWrapFlags(setFlags(Flags
, SCEV::FlagNW
));
2719 const SCEV
*NewRec
= getAddRecExpr(AddRecOps
, AddRecLoop
, Flags
);
2721 // If all of the other operands were loop invariant, we are done.
2722 if (Ops
.size() == 1) return NewRec
;
2724 // Otherwise, add the folded AddRec by the non-invariant parts.
2725 for (unsigned i
= 0;; ++i
)
2726 if (Ops
[i
] == AddRec
) {
2730 return getAddExpr(Ops
, SCEV::FlagAnyWrap
, Depth
+ 1);
2733 // Okay, if there weren't any loop invariants to be folded, check to see if
2734 // there are multiple AddRec's with the same loop induction variable being
2735 // added together. If so, we can fold them.
2736 for (unsigned OtherIdx
= Idx
+1;
2737 OtherIdx
< Ops
.size() && isa
<SCEVAddRecExpr
>(Ops
[OtherIdx
]);
2739 // We expect the AddRecExpr's to be sorted in reverse dominance order,
2740 // so that the 1st found AddRecExpr is dominated by all others.
2741 assert(DT
.dominates(
2742 cast
<SCEVAddRecExpr
>(Ops
[OtherIdx
])->getLoop()->getHeader(),
2743 AddRec
->getLoop()->getHeader()) &&
2744 "AddRecExprs are not sorted in reverse dominance order?");
2745 if (AddRecLoop
== cast
<SCEVAddRecExpr
>(Ops
[OtherIdx
])->getLoop()) {
2746 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2747 SmallVector
<const SCEV
*, 4> AddRecOps(AddRec
->op_begin(),
2749 for (; OtherIdx
!= Ops
.size() && isa
<SCEVAddRecExpr
>(Ops
[OtherIdx
]);
2751 const auto *OtherAddRec
= cast
<SCEVAddRecExpr
>(Ops
[OtherIdx
]);
2752 if (OtherAddRec
->getLoop() == AddRecLoop
) {
2753 for (unsigned i
= 0, e
= OtherAddRec
->getNumOperands();
2755 if (i
>= AddRecOps
.size()) {
2756 AddRecOps
.append(OtherAddRec
->op_begin()+i
,
2757 OtherAddRec
->op_end());
2760 SmallVector
<const SCEV
*, 2> TwoOps
= {
2761 AddRecOps
[i
], OtherAddRec
->getOperand(i
)};
2762 AddRecOps
[i
] = getAddExpr(TwoOps
, SCEV::FlagAnyWrap
, Depth
+ 1);
2764 Ops
.erase(Ops
.begin() + OtherIdx
); --OtherIdx
;
2767 // Step size has changed, so we cannot guarantee no self-wraparound.
2768 Ops
[Idx
] = getAddRecExpr(AddRecOps
, AddRecLoop
, SCEV::FlagAnyWrap
);
2769 return getAddExpr(Ops
, SCEV::FlagAnyWrap
, Depth
+ 1);
2773 // Otherwise couldn't fold anything into this recurrence. Move onto the
2777 // Okay, it looks like we really DO need an add expr. Check to see if we
2778 // already have one, otherwise create a new one.
2779 return getOrCreateAddExpr(Ops
, Flags
);
2783 ScalarEvolution::getOrCreateAddExpr(ArrayRef
<const SCEV
*> Ops
,
2784 SCEV::NoWrapFlags Flags
) {
2785 FoldingSetNodeID ID
;
2786 ID
.AddInteger(scAddExpr
);
2787 for (const SCEV
*Op
: Ops
)
2791 static_cast<SCEVAddExpr
*>(UniqueSCEVs
.FindNodeOrInsertPos(ID
, IP
));
2793 const SCEV
**O
= SCEVAllocator
.Allocate
<const SCEV
*>(Ops
.size());
2794 std::uninitialized_copy(Ops
.begin(), Ops
.end(), O
);
2795 S
= new (SCEVAllocator
)
2796 SCEVAddExpr(ID
.Intern(SCEVAllocator
), O
, Ops
.size());
2797 UniqueSCEVs
.InsertNode(S
, IP
);
2798 addToLoopUseLists(S
);
2800 S
->setNoWrapFlags(Flags
);
2805 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef
<const SCEV
*> Ops
,
2806 const Loop
*L
, SCEV::NoWrapFlags Flags
) {
2807 FoldingSetNodeID ID
;
2808 ID
.AddInteger(scAddRecExpr
);
2809 for (unsigned i
= 0, e
= Ops
.size(); i
!= e
; ++i
)
2810 ID
.AddPointer(Ops
[i
]);
2814 static_cast<SCEVAddRecExpr
*>(UniqueSCEVs
.FindNodeOrInsertPos(ID
, IP
));
2816 const SCEV
**O
= SCEVAllocator
.Allocate
<const SCEV
*>(Ops
.size());
2817 std::uninitialized_copy(Ops
.begin(), Ops
.end(), O
);
2818 S
= new (SCEVAllocator
)
2819 SCEVAddRecExpr(ID
.Intern(SCEVAllocator
), O
, Ops
.size(), L
);
2820 UniqueSCEVs
.InsertNode(S
, IP
);
2821 addToLoopUseLists(S
);
2823 S
->setNoWrapFlags(Flags
);
2828 ScalarEvolution::getOrCreateMulExpr(ArrayRef
<const SCEV
*> Ops
,
2829 SCEV::NoWrapFlags Flags
) {
2830 FoldingSetNodeID ID
;
2831 ID
.AddInteger(scMulExpr
);
2832 for (unsigned i
= 0, e
= Ops
.size(); i
!= e
; ++i
)
2833 ID
.AddPointer(Ops
[i
]);
2836 static_cast<SCEVMulExpr
*>(UniqueSCEVs
.FindNodeOrInsertPos(ID
, IP
));
2838 const SCEV
**O
= SCEVAllocator
.Allocate
<const SCEV
*>(Ops
.size());
2839 std::uninitialized_copy(Ops
.begin(), Ops
.end(), O
);
2840 S
= new (SCEVAllocator
) SCEVMulExpr(ID
.Intern(SCEVAllocator
),
2842 UniqueSCEVs
.InsertNode(S
, IP
);
2843 addToLoopUseLists(S
);
2845 S
->setNoWrapFlags(Flags
);
2849 static uint64_t umul_ov(uint64_t i
, uint64_t j
, bool &Overflow
) {
2851 if (j
> 1 && k
/ j
!= i
) Overflow
= true;
2855 /// Compute the result of "n choose k", the binomial coefficient. If an
2856 /// intermediate computation overflows, Overflow will be set and the return will
2857 /// be garbage. Overflow is not cleared on absence of overflow.
2858 static uint64_t Choose(uint64_t n
, uint64_t k
, bool &Overflow
) {
2859 // We use the multiplicative formula:
2860 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2861 // At each iteration, we take the n-th term of the numeral and divide by the
2862 // (k-n)th term of the denominator. This division will always produce an
2863 // integral result, and helps reduce the chance of overflow in the
2864 // intermediate computations. However, we can still overflow even when the
2865 // final result would fit.
2867 if (n
== 0 || n
== k
) return 1;
2868 if (k
> n
) return 0;
2874 for (uint64_t i
= 1; i
<= k
; ++i
) {
2875 r
= umul_ov(r
, n
-(i
-1), Overflow
);
2881 /// Determine if any of the operands in this SCEV are a constant or if
2882 /// any of the add or multiply expressions in this SCEV contain a constant.
2883 static bool containsConstantInAddMulChain(const SCEV
*StartExpr
) {
2884 struct FindConstantInAddMulChain
{
2885 bool FoundConstant
= false;
2887 bool follow(const SCEV
*S
) {
2888 FoundConstant
|= isa
<SCEVConstant
>(S
);
2889 return isa
<SCEVAddExpr
>(S
) || isa
<SCEVMulExpr
>(S
);
2892 bool isDone() const {
2893 return FoundConstant
;
2897 FindConstantInAddMulChain F
;
2898 SCEVTraversal
<FindConstantInAddMulChain
> ST(F
);
2899 ST
.visitAll(StartExpr
);
2900 return F
.FoundConstant
;
2903 /// Get a canonical multiply expression, or something simpler if possible.
2904 const SCEV
*ScalarEvolution::getMulExpr(SmallVectorImpl
<const SCEV
*> &Ops
,
2905 SCEV::NoWrapFlags Flags
,
2907 assert(Flags
== maskFlags(Flags
, SCEV::FlagNUW
| SCEV::FlagNSW
) &&
2908 "only nuw or nsw allowed");
2909 assert(!Ops
.empty() && "Cannot get empty mul!");
2910 if (Ops
.size() == 1) return Ops
[0];
2912 Type
*ETy
= getEffectiveSCEVType(Ops
[0]->getType());
2913 for (unsigned i
= 1, e
= Ops
.size(); i
!= e
; ++i
)
2914 assert(getEffectiveSCEVType(Ops
[i
]->getType()) == ETy
&&
2915 "SCEVMulExpr operand types don't match!");
2918 // Sort by complexity, this groups all similar expression types together.
2919 GroupByComplexity(Ops
, &LI
, DT
);
2921 Flags
= StrengthenNoWrapFlags(this, scMulExpr
, Ops
, Flags
);
2923 // Limit recursion calls depth.
2924 if (Depth
> MaxArithDepth
|| hasHugeExpression(Ops
))
2925 return getOrCreateMulExpr(Ops
, Flags
);
2927 // If there are any constants, fold them together.
2929 if (const SCEVConstant
*LHSC
= dyn_cast
<SCEVConstant
>(Ops
[0])) {
2931 if (Ops
.size() == 2)
2932 // C1*(C2+V) -> C1*C2 + C1*V
2933 if (const SCEVAddExpr
*Add
= dyn_cast
<SCEVAddExpr
>(Ops
[1]))
2934 // If any of Add's ops are Adds or Muls with a constant, apply this
2935 // transformation as well.
2937 // TODO: There are some cases where this transformation is not
2938 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of
2939 // this transformation should be narrowed down.
2940 if (Add
->getNumOperands() == 2 && containsConstantInAddMulChain(Add
))
2941 return getAddExpr(getMulExpr(LHSC
, Add
->getOperand(0),
2942 SCEV::FlagAnyWrap
, Depth
+ 1),
2943 getMulExpr(LHSC
, Add
->getOperand(1),
2944 SCEV::FlagAnyWrap
, Depth
+ 1),
2945 SCEV::FlagAnyWrap
, Depth
+ 1);
2948 while (const SCEVConstant
*RHSC
= dyn_cast
<SCEVConstant
>(Ops
[Idx
])) {
2949 // We found two constants, fold them together!
2951 ConstantInt::get(getContext(), LHSC
->getAPInt() * RHSC
->getAPInt());
2952 Ops
[0] = getConstant(Fold
);
2953 Ops
.erase(Ops
.begin()+1); // Erase the folded element
2954 if (Ops
.size() == 1) return Ops
[0];
2955 LHSC
= cast
<SCEVConstant
>(Ops
[0]);
2958 // If we are left with a constant one being multiplied, strip it off.
2959 if (cast
<SCEVConstant
>(Ops
[0])->getValue()->isOne()) {
2960 Ops
.erase(Ops
.begin());
2962 } else if (cast
<SCEVConstant
>(Ops
[0])->getValue()->isZero()) {
2963 // If we have a multiply of zero, it will always be zero.
2965 } else if (Ops
[0]->isAllOnesValue()) {
2966 // If we have a mul by -1 of an add, try distributing the -1 among the
2968 if (Ops
.size() == 2) {
2969 if (const SCEVAddExpr
*Add
= dyn_cast
<SCEVAddExpr
>(Ops
[1])) {
2970 SmallVector
<const SCEV
*, 4> NewOps
;
2971 bool AnyFolded
= false;
2972 for (const SCEV
*AddOp
: Add
->operands()) {
2973 const SCEV
*Mul
= getMulExpr(Ops
[0], AddOp
, SCEV::FlagAnyWrap
,
2975 if (!isa
<SCEVMulExpr
>(Mul
)) AnyFolded
= true;
2976 NewOps
.push_back(Mul
);
2979 return getAddExpr(NewOps
, SCEV::FlagAnyWrap
, Depth
+ 1);
2980 } else if (const auto *AddRec
= dyn_cast
<SCEVAddRecExpr
>(Ops
[1])) {
2981 // Negation preserves a recurrence's no self-wrap property.
2982 SmallVector
<const SCEV
*, 4> Operands
;
2983 for (const SCEV
*AddRecOp
: AddRec
->operands())
2984 Operands
.push_back(getMulExpr(Ops
[0], AddRecOp
, SCEV::FlagAnyWrap
,
2987 return getAddRecExpr(Operands
, AddRec
->getLoop(),
2988 AddRec
->getNoWrapFlags(SCEV::FlagNW
));
2993 if (Ops
.size() == 1)
2997 // Skip over the add expression until we get to a multiply.
2998 while (Idx
< Ops
.size() && Ops
[Idx
]->getSCEVType() < scMulExpr
)
3001 // If there are mul operands inline them all into this expression.
3002 if (Idx
< Ops
.size()) {
3003 bool DeletedMul
= false;
3004 while (const SCEVMulExpr
*Mul
= dyn_cast
<SCEVMulExpr
>(Ops
[Idx
])) {
3005 if (Ops
.size() > MulOpsInlineThreshold
)
3007 // If we have an mul, expand the mul operands onto the end of the
3009 Ops
.erase(Ops
.begin()+Idx
);
3010 Ops
.append(Mul
->op_begin(), Mul
->op_end());
3014 // If we deleted at least one mul, we added operands to the end of the
3015 // list, and they are not necessarily sorted. Recurse to resort and
3016 // resimplify any operands we just acquired.
3018 return getMulExpr(Ops
, SCEV::FlagAnyWrap
, Depth
+ 1);
3021 // If there are any add recurrences in the operands list, see if any other
3022 // added values are loop invariant. If so, we can fold them into the
3024 while (Idx
< Ops
.size() && Ops
[Idx
]->getSCEVType() < scAddRecExpr
)
3027 // Scan over all recurrences, trying to fold loop invariants into them.
3028 for (; Idx
< Ops
.size() && isa
<SCEVAddRecExpr
>(Ops
[Idx
]); ++Idx
) {
3029 // Scan all of the other operands to this mul and add them to the vector
3030 // if they are loop invariant w.r.t. the recurrence.
3031 SmallVector
<const SCEV
*, 8> LIOps
;
3032 const SCEVAddRecExpr
*AddRec
= cast
<SCEVAddRecExpr
>(Ops
[Idx
]);
3033 const Loop
*AddRecLoop
= AddRec
->getLoop();
3034 for (unsigned i
= 0, e
= Ops
.size(); i
!= e
; ++i
)
3035 if (isAvailableAtLoopEntry(Ops
[i
], AddRecLoop
)) {
3036 LIOps
.push_back(Ops
[i
]);
3037 Ops
.erase(Ops
.begin()+i
);
3041 // If we found some loop invariants, fold them into the recurrence.
3042 if (!LIOps
.empty()) {
3043 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
3044 SmallVector
<const SCEV
*, 4> NewOps
;
3045 NewOps
.reserve(AddRec
->getNumOperands());
3046 const SCEV
*Scale
= getMulExpr(LIOps
, SCEV::FlagAnyWrap
, Depth
+ 1);
3047 for (unsigned i
= 0, e
= AddRec
->getNumOperands(); i
!= e
; ++i
)
3048 NewOps
.push_back(getMulExpr(Scale
, AddRec
->getOperand(i
),
3049 SCEV::FlagAnyWrap
, Depth
+ 1));
3051 // Build the new addrec. Propagate the NUW and NSW flags if both the
3052 // outer mul and the inner addrec are guaranteed to have no overflow.
3054 // No self-wrap cannot be guaranteed after changing the step size, but
3055 // will be inferred if either NUW or NSW is true.
3056 Flags
= AddRec
->getNoWrapFlags(clearFlags(Flags
, SCEV::FlagNW
));
3057 const SCEV
*NewRec
= getAddRecExpr(NewOps
, AddRecLoop
, Flags
);
3059 // If all of the other operands were loop invariant, we are done.
3060 if (Ops
.size() == 1) return NewRec
;
3062 // Otherwise, multiply the folded AddRec by the non-invariant parts.
3063 for (unsigned i
= 0;; ++i
)
3064 if (Ops
[i
] == AddRec
) {
3068 return getMulExpr(Ops
, SCEV::FlagAnyWrap
, Depth
+ 1);
3071 // Okay, if there weren't any loop invariants to be folded, check to see
3072 // if there are multiple AddRec's with the same loop induction variable
3073 // being multiplied together. If so, we can fold them.
3075 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3076 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3077 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3078 // ]]],+,...up to x=2n}.
3079 // Note that the arguments to choose() are always integers with values
3080 // known at compile time, never SCEV objects.
3082 // The implementation avoids pointless extra computations when the two
3083 // addrec's are of different length (mathematically, it's equivalent to
3084 // an infinite stream of zeros on the right).
3085 bool OpsModified
= false;
3086 for (unsigned OtherIdx
= Idx
+1;
3087 OtherIdx
!= Ops
.size() && isa
<SCEVAddRecExpr
>(Ops
[OtherIdx
]);
3089 const SCEVAddRecExpr
*OtherAddRec
=
3090 dyn_cast
<SCEVAddRecExpr
>(Ops
[OtherIdx
]);
3091 if (!OtherAddRec
|| OtherAddRec
->getLoop() != AddRecLoop
)
3094 // Limit max number of arguments to avoid creation of unreasonably big
3095 // SCEVAddRecs with very complex operands.
3096 if (AddRec
->getNumOperands() + OtherAddRec
->getNumOperands() - 1 >
3097 MaxAddRecSize
|| isHugeExpression(AddRec
) ||
3098 isHugeExpression(OtherAddRec
))
3101 bool Overflow
= false;
3102 Type
*Ty
= AddRec
->getType();
3103 bool LargerThan64Bits
= getTypeSizeInBits(Ty
) > 64;
3104 SmallVector
<const SCEV
*, 7> AddRecOps
;
3105 for (int x
= 0, xe
= AddRec
->getNumOperands() +
3106 OtherAddRec
->getNumOperands() - 1; x
!= xe
&& !Overflow
; ++x
) {
3107 SmallVector
<const SCEV
*, 7> SumOps
;
3108 for (int y
= x
, ye
= 2*x
+1; y
!= ye
&& !Overflow
; ++y
) {
3109 uint64_t Coeff1
= Choose(x
, 2*x
- y
, Overflow
);
3110 for (int z
= std::max(y
-x
, y
-(int)AddRec
->getNumOperands()+1),
3111 ze
= std::min(x
+1, (int)OtherAddRec
->getNumOperands());
3112 z
< ze
&& !Overflow
; ++z
) {
3113 uint64_t Coeff2
= Choose(2*x
- y
, x
-z
, Overflow
);
3115 if (LargerThan64Bits
)
3116 Coeff
= umul_ov(Coeff1
, Coeff2
, Overflow
);
3118 Coeff
= Coeff1
*Coeff2
;
3119 const SCEV
*CoeffTerm
= getConstant(Ty
, Coeff
);
3120 const SCEV
*Term1
= AddRec
->getOperand(y
-z
);
3121 const SCEV
*Term2
= OtherAddRec
->getOperand(z
);
3122 SumOps
.push_back(getMulExpr(CoeffTerm
, Term1
, Term2
,
3123 SCEV::FlagAnyWrap
, Depth
+ 1));
3127 SumOps
.push_back(getZero(Ty
));
3128 AddRecOps
.push_back(getAddExpr(SumOps
, SCEV::FlagAnyWrap
, Depth
+ 1));
3131 const SCEV
*NewAddRec
= getAddRecExpr(AddRecOps
, AddRecLoop
,
3133 if (Ops
.size() == 2) return NewAddRec
;
3134 Ops
[Idx
] = NewAddRec
;
3135 Ops
.erase(Ops
.begin() + OtherIdx
); --OtherIdx
;
3137 AddRec
= dyn_cast
<SCEVAddRecExpr
>(NewAddRec
);
3143 return getMulExpr(Ops
, SCEV::FlagAnyWrap
, Depth
+ 1);
3145 // Otherwise couldn't fold anything into this recurrence. Move onto the
3149 // Okay, it looks like we really DO need an mul expr. Check to see if we
3150 // already have one, otherwise create a new one.
3151 return getOrCreateMulExpr(Ops
, Flags
);
3154 /// Represents an unsigned remainder expression based on unsigned division.
3155 const SCEV
*ScalarEvolution::getURemExpr(const SCEV
*LHS
,
3157 assert(getEffectiveSCEVType(LHS
->getType()) ==
3158 getEffectiveSCEVType(RHS
->getType()) &&
3159 "SCEVURemExpr operand types don't match!");
3161 // Short-circuit easy cases
3162 if (const SCEVConstant
*RHSC
= dyn_cast
<SCEVConstant
>(RHS
)) {
3163 // If constant is one, the result is trivial
3164 if (RHSC
->getValue()->isOne())
3165 return getZero(LHS
->getType()); // X urem 1 --> 0
3167 // If constant is a power of two, fold into a zext(trunc(LHS)).
3168 if (RHSC
->getAPInt().isPowerOf2()) {
3169 Type
*FullTy
= LHS
->getType();
3171 IntegerType::get(getContext(), RHSC
->getAPInt().logBase2());
3172 return getZeroExtendExpr(getTruncateExpr(LHS
, TruncTy
), FullTy
);
3176 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3177 const SCEV
*UDiv
= getUDivExpr(LHS
, RHS
);
3178 const SCEV
*Mult
= getMulExpr(UDiv
, RHS
, SCEV::FlagNUW
);
3179 return getMinusSCEV(LHS
, Mult
, SCEV::FlagNUW
);
3182 /// Get a canonical unsigned division expression, or something simpler if
3184 const SCEV
*ScalarEvolution::getUDivExpr(const SCEV
*LHS
,
3186 assert(getEffectiveSCEVType(LHS
->getType()) ==
3187 getEffectiveSCEVType(RHS
->getType()) &&
3188 "SCEVUDivExpr operand types don't match!");
3190 if (const SCEVConstant
*RHSC
= dyn_cast
<SCEVConstant
>(RHS
)) {
3191 if (RHSC
->getValue()->isOne())
3192 return LHS
; // X udiv 1 --> x
3193 // If the denominator is zero, the result of the udiv is undefined. Don't
3194 // try to analyze it, because the resolution chosen here may differ from
3195 // the resolution chosen in other parts of the compiler.
3196 if (!RHSC
->getValue()->isZero()) {
3197 // Determine if the division can be folded into the operands of
3199 // TODO: Generalize this to non-constants by using known-bits information.
3200 Type
*Ty
= LHS
->getType();
3201 unsigned LZ
= RHSC
->getAPInt().countLeadingZeros();
3202 unsigned MaxShiftAmt
= getTypeSizeInBits(Ty
) - LZ
- 1;
3203 // For non-power-of-two values, effectively round the value up to the
3204 // nearest power of two.
3205 if (!RHSC
->getAPInt().isPowerOf2())
3207 IntegerType
*ExtTy
=
3208 IntegerType::get(getContext(), getTypeSizeInBits(Ty
) + MaxShiftAmt
);
3209 if (const SCEVAddRecExpr
*AR
= dyn_cast
<SCEVAddRecExpr
>(LHS
))
3210 if (const SCEVConstant
*Step
=
3211 dyn_cast
<SCEVConstant
>(AR
->getStepRecurrence(*this))) {
3212 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3213 const APInt
&StepInt
= Step
->getAPInt();
3214 const APInt
&DivInt
= RHSC
->getAPInt();
3215 if (!StepInt
.urem(DivInt
) &&
3216 getZeroExtendExpr(AR
, ExtTy
) ==
3217 getAddRecExpr(getZeroExtendExpr(AR
->getStart(), ExtTy
),
3218 getZeroExtendExpr(Step
, ExtTy
),
3219 AR
->getLoop(), SCEV::FlagAnyWrap
)) {
3220 SmallVector
<const SCEV
*, 4> Operands
;
3221 for (const SCEV
*Op
: AR
->operands())
3222 Operands
.push_back(getUDivExpr(Op
, RHS
));
3223 return getAddRecExpr(Operands
, AR
->getLoop(), SCEV::FlagNW
);
3225 /// Get a canonical UDivExpr for a recurrence.
3226 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3227 // We can currently only fold X%N if X is constant.
3228 const SCEVConstant
*StartC
= dyn_cast
<SCEVConstant
>(AR
->getStart());
3229 if (StartC
&& !DivInt
.urem(StepInt
) &&
3230 getZeroExtendExpr(AR
, ExtTy
) ==
3231 getAddRecExpr(getZeroExtendExpr(AR
->getStart(), ExtTy
),
3232 getZeroExtendExpr(Step
, ExtTy
),
3233 AR
->getLoop(), SCEV::FlagAnyWrap
)) {
3234 const APInt
&StartInt
= StartC
->getAPInt();
3235 const APInt
&StartRem
= StartInt
.urem(StepInt
);
3237 LHS
= getAddRecExpr(getConstant(StartInt
- StartRem
), Step
,
3238 AR
->getLoop(), SCEV::FlagNW
);
3241 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3242 if (const SCEVMulExpr
*M
= dyn_cast
<SCEVMulExpr
>(LHS
)) {
3243 SmallVector
<const SCEV
*, 4> Operands
;
3244 for (const SCEV
*Op
: M
->operands())
3245 Operands
.push_back(getZeroExtendExpr(Op
, ExtTy
));
3246 if (getZeroExtendExpr(M
, ExtTy
) == getMulExpr(Operands
))
3247 // Find an operand that's safely divisible.
3248 for (unsigned i
= 0, e
= M
->getNumOperands(); i
!= e
; ++i
) {
3249 const SCEV
*Op
= M
->getOperand(i
);
3250 const SCEV
*Div
= getUDivExpr(Op
, RHSC
);
3251 if (!isa
<SCEVUDivExpr
>(Div
) && getMulExpr(Div
, RHSC
) == Op
) {
3252 Operands
= SmallVector
<const SCEV
*, 4>(M
->op_begin(),
3255 return getMulExpr(Operands
);
3260 // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3261 if (const SCEVUDivExpr
*OtherDiv
= dyn_cast
<SCEVUDivExpr
>(LHS
)) {
3262 if (auto *DivisorConstant
=
3263 dyn_cast
<SCEVConstant
>(OtherDiv
->getRHS())) {
3264 bool Overflow
= false;
3266 DivisorConstant
->getAPInt().umul_ov(RHSC
->getAPInt(), Overflow
);
3268 return getConstant(RHSC
->getType(), 0, false);
3270 return getUDivExpr(OtherDiv
->getLHS(), getConstant(NewRHS
));
3274 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3275 if (const SCEVAddExpr
*A
= dyn_cast
<SCEVAddExpr
>(LHS
)) {
3276 SmallVector
<const SCEV
*, 4> Operands
;
3277 for (const SCEV
*Op
: A
->operands())
3278 Operands
.push_back(getZeroExtendExpr(Op
, ExtTy
));
3279 if (getZeroExtendExpr(A
, ExtTy
) == getAddExpr(Operands
)) {
3281 for (unsigned i
= 0, e
= A
->getNumOperands(); i
!= e
; ++i
) {
3282 const SCEV
*Op
= getUDivExpr(A
->getOperand(i
), RHS
);
3283 if (isa
<SCEVUDivExpr
>(Op
) ||
3284 getMulExpr(Op
, RHS
) != A
->getOperand(i
))
3286 Operands
.push_back(Op
);
3288 if (Operands
.size() == A
->getNumOperands())
3289 return getAddExpr(Operands
);
3293 // Fold if both operands are constant.
3294 if (const SCEVConstant
*LHSC
= dyn_cast
<SCEVConstant
>(LHS
)) {
3295 Constant
*LHSCV
= LHSC
->getValue();
3296 Constant
*RHSCV
= RHSC
->getValue();
3297 return getConstant(cast
<ConstantInt
>(ConstantExpr::getUDiv(LHSCV
,
3303 FoldingSetNodeID ID
;
3304 ID
.AddInteger(scUDivExpr
);
3308 if (const SCEV
*S
= UniqueSCEVs
.FindNodeOrInsertPos(ID
, IP
)) return S
;
3309 SCEV
*S
= new (SCEVAllocator
) SCEVUDivExpr(ID
.Intern(SCEVAllocator
),
3311 UniqueSCEVs
.InsertNode(S
, IP
);
3312 addToLoopUseLists(S
);
3316 static const APInt
gcd(const SCEVConstant
*C1
, const SCEVConstant
*C2
) {
3317 APInt A
= C1
->getAPInt().abs();
3318 APInt B
= C2
->getAPInt().abs();
3319 uint32_t ABW
= A
.getBitWidth();
3320 uint32_t BBW
= B
.getBitWidth();
3327 return APIntOps::GreatestCommonDivisor(std::move(A
), std::move(B
));
3330 /// Get a canonical unsigned division expression, or something simpler if
3331 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3332 /// can attempt to remove factors from the LHS and RHS. We can't do this when
3333 /// it's not exact because the udiv may be clearing bits.
3334 const SCEV
*ScalarEvolution::getUDivExactExpr(const SCEV
*LHS
,
3336 // TODO: we could try to find factors in all sorts of things, but for now we
3337 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3338 // end of this file for inspiration.
3340 const SCEVMulExpr
*Mul
= dyn_cast
<SCEVMulExpr
>(LHS
);
3341 if (!Mul
|| !Mul
->hasNoUnsignedWrap())
3342 return getUDivExpr(LHS
, RHS
);
3344 if (const SCEVConstant
*RHSCst
= dyn_cast
<SCEVConstant
>(RHS
)) {
3345 // If the mulexpr multiplies by a constant, then that constant must be the
3346 // first element of the mulexpr.
3347 if (const auto *LHSCst
= dyn_cast
<SCEVConstant
>(Mul
->getOperand(0))) {
3348 if (LHSCst
== RHSCst
) {
3349 SmallVector
<const SCEV
*, 2> Operands
;
3350 Operands
.append(Mul
->op_begin() + 1, Mul
->op_end());
3351 return getMulExpr(Operands
);
3354 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3355 // that there's a factor provided by one of the other terms. We need to
3357 APInt Factor
= gcd(LHSCst
, RHSCst
);
3358 if (!Factor
.isIntN(1)) {
3360 cast
<SCEVConstant
>(getConstant(LHSCst
->getAPInt().udiv(Factor
)));
3362 cast
<SCEVConstant
>(getConstant(RHSCst
->getAPInt().udiv(Factor
)));
3363 SmallVector
<const SCEV
*, 2> Operands
;
3364 Operands
.push_back(LHSCst
);
3365 Operands
.append(Mul
->op_begin() + 1, Mul
->op_end());
3366 LHS
= getMulExpr(Operands
);
3368 Mul
= dyn_cast
<SCEVMulExpr
>(LHS
);
3370 return getUDivExactExpr(LHS
, RHS
);
3375 for (int i
= 0, e
= Mul
->getNumOperands(); i
!= e
; ++i
) {
3376 if (Mul
->getOperand(i
) == RHS
) {
3377 SmallVector
<const SCEV
*, 2> Operands
;
3378 Operands
.append(Mul
->op_begin(), Mul
->op_begin() + i
);
3379 Operands
.append(Mul
->op_begin() + i
+ 1, Mul
->op_end());
3380 return getMulExpr(Operands
);
3384 return getUDivExpr(LHS
, RHS
);
3387 /// Get an add recurrence expression for the specified loop. Simplify the
3388 /// expression as much as possible.
3389 const SCEV
*ScalarEvolution::getAddRecExpr(const SCEV
*Start
, const SCEV
*Step
,
3391 SCEV::NoWrapFlags Flags
) {
3392 SmallVector
<const SCEV
*, 4> Operands
;
3393 Operands
.push_back(Start
);
3394 if (const SCEVAddRecExpr
*StepChrec
= dyn_cast
<SCEVAddRecExpr
>(Step
))
3395 if (StepChrec
->getLoop() == L
) {
3396 Operands
.append(StepChrec
->op_begin(), StepChrec
->op_end());
3397 return getAddRecExpr(Operands
, L
, maskFlags(Flags
, SCEV::FlagNW
));
3400 Operands
.push_back(Step
);
3401 return getAddRecExpr(Operands
, L
, Flags
);
3404 /// Get an add recurrence expression for the specified loop. Simplify the
3405 /// expression as much as possible.
3407 ScalarEvolution::getAddRecExpr(SmallVectorImpl
<const SCEV
*> &Operands
,
3408 const Loop
*L
, SCEV::NoWrapFlags Flags
) {
3409 if (Operands
.size() == 1) return Operands
[0];
3411 Type
*ETy
= getEffectiveSCEVType(Operands
[0]->getType());
3412 for (unsigned i
= 1, e
= Operands
.size(); i
!= e
; ++i
)
3413 assert(getEffectiveSCEVType(Operands
[i
]->getType()) == ETy
&&
3414 "SCEVAddRecExpr operand types don't match!");
3415 for (unsigned i
= 0, e
= Operands
.size(); i
!= e
; ++i
)
3416 assert(isLoopInvariant(Operands
[i
], L
) &&
3417 "SCEVAddRecExpr operand is not loop-invariant!");
3420 if (Operands
.back()->isZero()) {
3421 Operands
.pop_back();
3422 return getAddRecExpr(Operands
, L
, SCEV::FlagAnyWrap
); // {X,+,0} --> X
3425 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3426 // use that information to infer NUW and NSW flags. However, computing a
3427 // BE count requires calling getAddRecExpr, so we may not yet have a
3428 // meaningful BE count at this point (and if we don't, we'd be stuck
3429 // with a SCEVCouldNotCompute as the cached BE count).
3431 Flags
= StrengthenNoWrapFlags(this, scAddRecExpr
, Operands
, Flags
);
3433 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3434 if (const SCEVAddRecExpr
*NestedAR
= dyn_cast
<SCEVAddRecExpr
>(Operands
[0])) {
3435 const Loop
*NestedLoop
= NestedAR
->getLoop();
3436 if (L
->contains(NestedLoop
)
3437 ? (L
->getLoopDepth() < NestedLoop
->getLoopDepth())
3438 : (!NestedLoop
->contains(L
) &&
3439 DT
.dominates(L
->getHeader(), NestedLoop
->getHeader()))) {
3440 SmallVector
<const SCEV
*, 4> NestedOperands(NestedAR
->op_begin(),
3441 NestedAR
->op_end());
3442 Operands
[0] = NestedAR
->getStart();
3443 // AddRecs require their operands be loop-invariant with respect to their
3444 // loops. Don't perform this transformation if it would break this
3446 bool AllInvariant
= all_of(
3447 Operands
, [&](const SCEV
*Op
) { return isLoopInvariant(Op
, L
); });
3450 // Create a recurrence for the outer loop with the same step size.
3452 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3453 // inner recurrence has the same property.
3454 SCEV::NoWrapFlags OuterFlags
=
3455 maskFlags(Flags
, SCEV::FlagNW
| NestedAR
->getNoWrapFlags());
3457 NestedOperands
[0] = getAddRecExpr(Operands
, L
, OuterFlags
);
3458 AllInvariant
= all_of(NestedOperands
, [&](const SCEV
*Op
) {
3459 return isLoopInvariant(Op
, NestedLoop
);
3463 // Ok, both add recurrences are valid after the transformation.
3465 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3466 // the outer recurrence has the same property.
3467 SCEV::NoWrapFlags InnerFlags
=
3468 maskFlags(NestedAR
->getNoWrapFlags(), SCEV::FlagNW
| Flags
);
3469 return getAddRecExpr(NestedOperands
, NestedLoop
, InnerFlags
);
3472 // Reset Operands to its original state.
3473 Operands
[0] = NestedAR
;
3477 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3478 // already have one, otherwise create a new one.
3479 return getOrCreateAddRecExpr(Operands
, L
, Flags
);
3483 ScalarEvolution::getGEPExpr(GEPOperator
*GEP
,
3484 const SmallVectorImpl
<const SCEV
*> &IndexExprs
) {
3485 const SCEV
*BaseExpr
= getSCEV(GEP
->getPointerOperand());
3486 // getSCEV(Base)->getType() has the same address space as Base->getType()
3487 // because SCEV::getType() preserves the address space.
3488 Type
*IntPtrTy
= getEffectiveSCEVType(BaseExpr
->getType());
3489 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3490 // instruction to its SCEV, because the Instruction may be guarded by control
3491 // flow and the no-overflow bits may not be valid for the expression in any
3492 // context. This can be fixed similarly to how these flags are handled for
3494 SCEV::NoWrapFlags Wrap
= GEP
->isInBounds() ? SCEV::FlagNSW
3495 : SCEV::FlagAnyWrap
;
3497 const SCEV
*TotalOffset
= getZero(IntPtrTy
);
3498 // The array size is unimportant. The first thing we do on CurTy is getting
3499 // its element type.
3500 Type
*CurTy
= ArrayType::get(GEP
->getSourceElementType(), 0);
3501 for (const SCEV
*IndexExpr
: IndexExprs
) {
3502 // Compute the (potentially symbolic) offset in bytes for this index.
3503 if (StructType
*STy
= dyn_cast
<StructType
>(CurTy
)) {
3504 // For a struct, add the member offset.
3505 ConstantInt
*Index
= cast
<SCEVConstant
>(IndexExpr
)->getValue();
3506 unsigned FieldNo
= Index
->getZExtValue();
3507 const SCEV
*FieldOffset
= getOffsetOfExpr(IntPtrTy
, STy
, FieldNo
);
3509 // Add the field offset to the running total offset.
3510 TotalOffset
= getAddExpr(TotalOffset
, FieldOffset
);
3512 // Update CurTy to the type of the field at Index.
3513 CurTy
= STy
->getTypeAtIndex(Index
);
3515 // Update CurTy to its element type.
3516 CurTy
= cast
<SequentialType
>(CurTy
)->getElementType();
3517 // For an array, add the element offset, explicitly scaled.
3518 const SCEV
*ElementSize
= getSizeOfExpr(IntPtrTy
, CurTy
);
3519 // Getelementptr indices are signed.
3520 IndexExpr
= getTruncateOrSignExtend(IndexExpr
, IntPtrTy
);
3522 // Multiply the index by the element size to compute the element offset.
3523 const SCEV
*LocalOffset
= getMulExpr(IndexExpr
, ElementSize
, Wrap
);
3525 // Add the element offset to the running total offset.
3526 TotalOffset
= getAddExpr(TotalOffset
, LocalOffset
);
3530 // Add the total offset from all the GEP indices to the base.
3531 return getAddExpr(BaseExpr
, TotalOffset
, Wrap
);
3534 std::tuple
<const SCEV
*, FoldingSetNodeID
, void *>
3535 ScalarEvolution::findExistingSCEVInCache(int SCEVType
,
3536 ArrayRef
<const SCEV
*> Ops
) {
3537 FoldingSetNodeID ID
;
3539 ID
.AddInteger(SCEVType
);
3540 for (unsigned i
= 0, e
= Ops
.size(); i
!= e
; ++i
)
3541 ID
.AddPointer(Ops
[i
]);
3542 return std::tuple
<const SCEV
*, FoldingSetNodeID
, void *>(
3543 UniqueSCEVs
.FindNodeOrInsertPos(ID
, IP
), std::move(ID
), IP
);
3546 const SCEV
*ScalarEvolution::getMinMaxExpr(unsigned Kind
,
3547 SmallVectorImpl
<const SCEV
*> &Ops
) {
3548 assert(!Ops
.empty() && "Cannot get empty (u|s)(min|max)!");
3549 if (Ops
.size() == 1) return Ops
[0];
3551 Type
*ETy
= getEffectiveSCEVType(Ops
[0]->getType());
3552 for (unsigned i
= 1, e
= Ops
.size(); i
!= e
; ++i
)
3553 assert(getEffectiveSCEVType(Ops
[i
]->getType()) == ETy
&&
3554 "Operand types don't match!");
3557 bool IsSigned
= Kind
== scSMaxExpr
|| Kind
== scSMinExpr
;
3558 bool IsMax
= Kind
== scSMaxExpr
|| Kind
== scUMaxExpr
;
3560 // Sort by complexity, this groups all similar expression types together.
3561 GroupByComplexity(Ops
, &LI
, DT
);
3563 // Check if we have created the same expression before.
3564 if (const SCEV
*S
= std::get
<0>(findExistingSCEVInCache(Kind
, Ops
))) {
3568 // If there are any constants, fold them together.
3570 if (const SCEVConstant
*LHSC
= dyn_cast
<SCEVConstant
>(Ops
[0])) {
3572 assert(Idx
< Ops
.size());
3573 auto FoldOp
= [&](const APInt
&LHS
, const APInt
&RHS
) {
3574 if (Kind
== scSMaxExpr
)
3575 return APIntOps::smax(LHS
, RHS
);
3576 else if (Kind
== scSMinExpr
)
3577 return APIntOps::smin(LHS
, RHS
);
3578 else if (Kind
== scUMaxExpr
)
3579 return APIntOps::umax(LHS
, RHS
);
3580 else if (Kind
== scUMinExpr
)
3581 return APIntOps::umin(LHS
, RHS
);
3582 llvm_unreachable("Unknown SCEV min/max opcode");
3585 while (const SCEVConstant
*RHSC
= dyn_cast
<SCEVConstant
>(Ops
[Idx
])) {
3586 // We found two constants, fold them together!
3587 ConstantInt
*Fold
= ConstantInt::get(
3588 getContext(), FoldOp(LHSC
->getAPInt(), RHSC
->getAPInt()));
3589 Ops
[0] = getConstant(Fold
);
3590 Ops
.erase(Ops
.begin()+1); // Erase the folded element
3591 if (Ops
.size() == 1) return Ops
[0];
3592 LHSC
= cast
<SCEVConstant
>(Ops
[0]);
3595 bool IsMinV
= LHSC
->getValue()->isMinValue(IsSigned
);
3596 bool IsMaxV
= LHSC
->getValue()->isMaxValue(IsSigned
);
3598 if (IsMax
? IsMinV
: IsMaxV
) {
3599 // If we are left with a constant minimum(/maximum)-int, strip it off.
3600 Ops
.erase(Ops
.begin());
3602 } else if (IsMax
? IsMaxV
: IsMinV
) {
3603 // If we have a max(/min) with a constant maximum(/minimum)-int,
3604 // it will always be the extremum.
3608 if (Ops
.size() == 1) return Ops
[0];
3611 // Find the first operation of the same kind
3612 while (Idx
< Ops
.size() && Ops
[Idx
]->getSCEVType() < Kind
)
3615 // Check to see if one of the operands is of the same kind. If so, expand its
3616 // operands onto our operand list, and recurse to simplify.
3617 if (Idx
< Ops
.size()) {
3618 bool DeletedAny
= false;
3619 while (Ops
[Idx
]->getSCEVType() == Kind
) {
3620 const SCEVMinMaxExpr
*SMME
= cast
<SCEVMinMaxExpr
>(Ops
[Idx
]);
3621 Ops
.erase(Ops
.begin()+Idx
);
3622 Ops
.append(SMME
->op_begin(), SMME
->op_end());
3627 return getMinMaxExpr(Kind
, Ops
);
3630 // Okay, check to see if the same value occurs in the operand list twice. If
3631 // so, delete one. Since we sorted the list, these values are required to
3633 llvm::CmpInst::Predicate GEPred
=
3634 IsSigned
? ICmpInst::ICMP_SGE
: ICmpInst::ICMP_UGE
;
3635 llvm::CmpInst::Predicate LEPred
=
3636 IsSigned
? ICmpInst::ICMP_SLE
: ICmpInst::ICMP_ULE
;
3637 llvm::CmpInst::Predicate FirstPred
= IsMax
? GEPred
: LEPred
;
3638 llvm::CmpInst::Predicate SecondPred
= IsMax
? LEPred
: GEPred
;
3639 for (unsigned i
= 0, e
= Ops
.size() - 1; i
!= e
; ++i
) {
3640 if (Ops
[i
] == Ops
[i
+ 1] ||
3641 isKnownViaNonRecursiveReasoning(FirstPred
, Ops
[i
], Ops
[i
+ 1])) {
3642 // X op Y op Y --> X op Y
3643 // X op Y --> X, if we know X, Y are ordered appropriately
3644 Ops
.erase(Ops
.begin() + i
+ 1, Ops
.begin() + i
+ 2);
3647 } else if (isKnownViaNonRecursiveReasoning(SecondPred
, Ops
[i
],
3649 // X op Y --> Y, if we know X, Y are ordered appropriately
3650 Ops
.erase(Ops
.begin() + i
, Ops
.begin() + i
+ 1);
3656 if (Ops
.size() == 1) return Ops
[0];
3658 assert(!Ops
.empty() && "Reduced smax down to nothing!");
3660 // Okay, it looks like we really DO need an expr. Check to see if we
3661 // already have one, otherwise create a new one.
3662 const SCEV
*ExistingSCEV
;
3663 FoldingSetNodeID ID
;
3665 std::tie(ExistingSCEV
, ID
, IP
) = findExistingSCEVInCache(Kind
, Ops
);
3667 return ExistingSCEV
;
3668 const SCEV
**O
= SCEVAllocator
.Allocate
<const SCEV
*>(Ops
.size());
3669 std::uninitialized_copy(Ops
.begin(), Ops
.end(), O
);
3670 SCEV
*S
= new (SCEVAllocator
) SCEVMinMaxExpr(
3671 ID
.Intern(SCEVAllocator
), static_cast<SCEVTypes
>(Kind
), O
, Ops
.size());
3673 UniqueSCEVs
.InsertNode(S
, IP
);
3674 addToLoopUseLists(S
);
3678 const SCEV
*ScalarEvolution::getSMaxExpr(const SCEV
*LHS
, const SCEV
*RHS
) {
3679 SmallVector
<const SCEV
*, 2> Ops
= {LHS
, RHS
};
3680 return getSMaxExpr(Ops
);
3683 const SCEV
*ScalarEvolution::getSMaxExpr(SmallVectorImpl
<const SCEV
*> &Ops
) {
3684 return getMinMaxExpr(scSMaxExpr
, Ops
);
3687 const SCEV
*ScalarEvolution::getUMaxExpr(const SCEV
*LHS
, const SCEV
*RHS
) {
3688 SmallVector
<const SCEV
*, 2> Ops
= {LHS
, RHS
};
3689 return getUMaxExpr(Ops
);
3692 const SCEV
*ScalarEvolution::getUMaxExpr(SmallVectorImpl
<const SCEV
*> &Ops
) {
3693 return getMinMaxExpr(scUMaxExpr
, Ops
);
3696 const SCEV
*ScalarEvolution::getSMinExpr(const SCEV
*LHS
,
3698 SmallVector
<const SCEV
*, 2> Ops
= { LHS
, RHS
};
3699 return getSMinExpr(Ops
);
3702 const SCEV
*ScalarEvolution::getSMinExpr(SmallVectorImpl
<const SCEV
*> &Ops
) {
3703 return getMinMaxExpr(scSMinExpr
, Ops
);
3706 const SCEV
*ScalarEvolution::getUMinExpr(const SCEV
*LHS
,
3708 SmallVector
<const SCEV
*, 2> Ops
= { LHS
, RHS
};
3709 return getUMinExpr(Ops
);
3712 const SCEV
*ScalarEvolution::getUMinExpr(SmallVectorImpl
<const SCEV
*> &Ops
) {
3713 return getMinMaxExpr(scUMinExpr
, Ops
);
3716 const SCEV
*ScalarEvolution::getSizeOfExpr(Type
*IntTy
, Type
*AllocTy
) {
3717 // We can bypass creating a target-independent
3718 // constant expression and then folding it back into a ConstantInt.
3719 // This is just a compile-time optimization.
3720 return getConstant(IntTy
, getDataLayout().getTypeAllocSize(AllocTy
));
3723 const SCEV
*ScalarEvolution::getOffsetOfExpr(Type
*IntTy
,
3726 // We can bypass creating a target-independent
3727 // constant expression and then folding it back into a ConstantInt.
3728 // This is just a compile-time optimization.
3730 IntTy
, getDataLayout().getStructLayout(STy
)->getElementOffset(FieldNo
));
3733 const SCEV
*ScalarEvolution::getUnknown(Value
*V
) {
3734 // Don't attempt to do anything other than create a SCEVUnknown object
3735 // here. createSCEV only calls getUnknown after checking for all other
3736 // interesting possibilities, and any other code that calls getUnknown
3737 // is doing so in order to hide a value from SCEV canonicalization.
3739 FoldingSetNodeID ID
;
3740 ID
.AddInteger(scUnknown
);
3743 if (SCEV
*S
= UniqueSCEVs
.FindNodeOrInsertPos(ID
, IP
)) {
3744 assert(cast
<SCEVUnknown
>(S
)->getValue() == V
&&
3745 "Stale SCEVUnknown in uniquing map!");
3748 SCEV
*S
= new (SCEVAllocator
) SCEVUnknown(ID
.Intern(SCEVAllocator
), V
, this,
3750 FirstUnknown
= cast
<SCEVUnknown
>(S
);
3751 UniqueSCEVs
.InsertNode(S
, IP
);
3755 //===----------------------------------------------------------------------===//
3756 // Basic SCEV Analysis and PHI Idiom Recognition Code
3759 /// Test if values of the given type are analyzable within the SCEV
3760 /// framework. This primarily includes integer types, and it can optionally
3761 /// include pointer types if the ScalarEvolution class has access to
3762 /// target-specific information.
3763 bool ScalarEvolution::isSCEVable(Type
*Ty
) const {
3764 // Integers and pointers are always SCEVable.
3765 return Ty
->isIntOrPtrTy();
3768 /// Return the size in bits of the specified type, for which isSCEVable must
3770 uint64_t ScalarEvolution::getTypeSizeInBits(Type
*Ty
) const {
3771 assert(isSCEVable(Ty
) && "Type is not SCEVable!");
3772 if (Ty
->isPointerTy())
3773 return getDataLayout().getIndexTypeSizeInBits(Ty
);
3774 return getDataLayout().getTypeSizeInBits(Ty
);
3777 /// Return a type with the same bitwidth as the given type and which represents
3778 /// how SCEV will treat the given type, for which isSCEVable must return
3779 /// true. For pointer types, this is the pointer-sized integer type.
3780 Type
*ScalarEvolution::getEffectiveSCEVType(Type
*Ty
) const {
3781 assert(isSCEVable(Ty
) && "Type is not SCEVable!");
3783 if (Ty
->isIntegerTy())
3786 // The only other support type is pointer.
3787 assert(Ty
->isPointerTy() && "Unexpected non-pointer non-integer type!");
3788 return getDataLayout().getIntPtrType(Ty
);
3791 Type
*ScalarEvolution::getWiderType(Type
*T1
, Type
*T2
) const {
3792 return getTypeSizeInBits(T1
) >= getTypeSizeInBits(T2
) ? T1
: T2
;
3795 const SCEV
*ScalarEvolution::getCouldNotCompute() {
3796 return CouldNotCompute
.get();
3799 bool ScalarEvolution::checkValidity(const SCEV
*S
) const {
3800 bool ContainsNulls
= SCEVExprContains(S
, [](const SCEV
*S
) {
3801 auto *SU
= dyn_cast
<SCEVUnknown
>(S
);
3802 return SU
&& SU
->getValue() == nullptr;
3805 return !ContainsNulls
;
3808 bool ScalarEvolution::containsAddRecurrence(const SCEV
*S
) {
3809 HasRecMapType::iterator I
= HasRecMap
.find(S
);
3810 if (I
!= HasRecMap
.end())
3813 bool FoundAddRec
= SCEVExprContains(S
, isa
<SCEVAddRecExpr
, const SCEV
*>);
3814 HasRecMap
.insert({S
, FoundAddRec
});
3818 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3819 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3820 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3821 static std::pair
<const SCEV
*, ConstantInt
*> splitAddExpr(const SCEV
*S
) {
3822 const auto *Add
= dyn_cast
<SCEVAddExpr
>(S
);
3824 return {S
, nullptr};
3826 if (Add
->getNumOperands() != 2)
3827 return {S
, nullptr};
3829 auto *ConstOp
= dyn_cast
<SCEVConstant
>(Add
->getOperand(0));
3831 return {S
, nullptr};
3833 return {Add
->getOperand(1), ConstOp
->getValue()};
3836 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3837 /// by the value and offset from any ValueOffsetPair in the set.
3838 SetVector
<ScalarEvolution::ValueOffsetPair
> *
3839 ScalarEvolution::getSCEVValues(const SCEV
*S
) {
3840 ExprValueMapType::iterator SI
= ExprValueMap
.find_as(S
);
3841 if (SI
== ExprValueMap
.end())
3844 if (VerifySCEVMap
) {
3845 // Check there is no dangling Value in the set returned.
3846 for (const auto &VE
: SI
->second
)
3847 assert(ValueExprMap
.count(VE
.first
));
3853 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3854 /// cannot be used separately. eraseValueFromMap should be used to remove
3855 /// V from ValueExprMap and ExprValueMap at the same time.
3856 void ScalarEvolution::eraseValueFromMap(Value
*V
) {
3857 ValueExprMapType::iterator I
= ValueExprMap
.find_as(V
);
3858 if (I
!= ValueExprMap
.end()) {
3859 const SCEV
*S
= I
->second
;
3860 // Remove {V, 0} from the set of ExprValueMap[S]
3861 if (SetVector
<ValueOffsetPair
> *SV
= getSCEVValues(S
))
3862 SV
->remove({V
, nullptr});
3864 // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3865 const SCEV
*Stripped
;
3866 ConstantInt
*Offset
;
3867 std::tie(Stripped
, Offset
) = splitAddExpr(S
);
3868 if (Offset
!= nullptr) {
3869 if (SetVector
<ValueOffsetPair
> *SV
= getSCEVValues(Stripped
))
3870 SV
->remove({V
, Offset
});
3872 ValueExprMap
.erase(V
);
3876 /// Check whether value has nuw/nsw/exact set but SCEV does not.
3877 /// TODO: In reality it is better to check the poison recursively
3878 /// but this is better than nothing.
3879 static bool SCEVLostPoisonFlags(const SCEV
*S
, const Value
*V
) {
3880 if (auto *I
= dyn_cast
<Instruction
>(V
)) {
3881 if (isa
<OverflowingBinaryOperator
>(I
)) {
3882 if (auto *NS
= dyn_cast
<SCEVNAryExpr
>(S
)) {
3883 if (I
->hasNoSignedWrap() && !NS
->hasNoSignedWrap())
3885 if (I
->hasNoUnsignedWrap() && !NS
->hasNoUnsignedWrap())
3888 } else if (isa
<PossiblyExactOperator
>(I
) && I
->isExact())
3894 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3895 /// create a new one.
3896 const SCEV
*ScalarEvolution::getSCEV(Value
*V
) {
3897 assert(isSCEVable(V
->getType()) && "Value is not SCEVable!");
3899 const SCEV
*S
= getExistingSCEV(V
);
3902 // During PHI resolution, it is possible to create two SCEVs for the same
3903 // V, so it is needed to double check whether V->S is inserted into
3904 // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3905 std::pair
<ValueExprMapType::iterator
, bool> Pair
=
3906 ValueExprMap
.insert({SCEVCallbackVH(V
, this), S
});
3907 if (Pair
.second
&& !SCEVLostPoisonFlags(S
, V
)) {
3908 ExprValueMap
[S
].insert({V
, nullptr});
3910 // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3912 const SCEV
*Stripped
= S
;
3913 ConstantInt
*Offset
= nullptr;
3914 std::tie(Stripped
, Offset
) = splitAddExpr(S
);
3915 // If stripped is SCEVUnknown, don't bother to save
3916 // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3917 // increase the complexity of the expansion code.
3918 // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3919 // because it may generate add/sub instead of GEP in SCEV expansion.
3920 if (Offset
!= nullptr && !isa
<SCEVUnknown
>(Stripped
) &&
3921 !isa
<GetElementPtrInst
>(V
))
3922 ExprValueMap
[Stripped
].insert({V
, Offset
});
3928 const SCEV
*ScalarEvolution::getExistingSCEV(Value
*V
) {
3929 assert(isSCEVable(V
->getType()) && "Value is not SCEVable!");
3931 ValueExprMapType::iterator I
= ValueExprMap
.find_as(V
);
3932 if (I
!= ValueExprMap
.end()) {
3933 const SCEV
*S
= I
->second
;
3934 if (checkValidity(S
))
3936 eraseValueFromMap(V
);
3937 forgetMemoizedResults(S
);
3942 /// Return a SCEV corresponding to -V = -1*V
3943 const SCEV
*ScalarEvolution::getNegativeSCEV(const SCEV
*V
,
3944 SCEV::NoWrapFlags Flags
) {
3945 if (const SCEVConstant
*VC
= dyn_cast
<SCEVConstant
>(V
))
3947 cast
<ConstantInt
>(ConstantExpr::getNeg(VC
->getValue())));
3949 Type
*Ty
= V
->getType();
3950 Ty
= getEffectiveSCEVType(Ty
);
3952 V
, getConstant(cast
<ConstantInt
>(Constant::getAllOnesValue(Ty
))), Flags
);
3955 /// If Expr computes ~A, return A else return nullptr
3956 static const SCEV
*MatchNotExpr(const SCEV
*Expr
) {
3957 const SCEVAddExpr
*Add
= dyn_cast
<SCEVAddExpr
>(Expr
);
3958 if (!Add
|| Add
->getNumOperands() != 2 ||
3959 !Add
->getOperand(0)->isAllOnesValue())
3962 const SCEVMulExpr
*AddRHS
= dyn_cast
<SCEVMulExpr
>(Add
->getOperand(1));
3963 if (!AddRHS
|| AddRHS
->getNumOperands() != 2 ||
3964 !AddRHS
->getOperand(0)->isAllOnesValue())
3967 return AddRHS
->getOperand(1);
3970 /// Return a SCEV corresponding to ~V = -1-V
3971 const SCEV
*ScalarEvolution::getNotSCEV(const SCEV
*V
) {
3972 if (const SCEVConstant
*VC
= dyn_cast
<SCEVConstant
>(V
))
3974 cast
<ConstantInt
>(ConstantExpr::getNot(VC
->getValue())));
3976 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
3977 if (const SCEVMinMaxExpr
*MME
= dyn_cast
<SCEVMinMaxExpr
>(V
)) {
3978 auto MatchMinMaxNegation
= [&](const SCEVMinMaxExpr
*MME
) {
3979 SmallVector
<const SCEV
*, 2> MatchedOperands
;
3980 for (const SCEV
*Operand
: MME
->operands()) {
3981 const SCEV
*Matched
= MatchNotExpr(Operand
);
3983 return (const SCEV
*)nullptr;
3984 MatchedOperands
.push_back(Matched
);
3986 return getMinMaxExpr(
3987 SCEVMinMaxExpr::negate(static_cast<SCEVTypes
>(MME
->getSCEVType())),
3990 if (const SCEV
*Replaced
= MatchMinMaxNegation(MME
))
3994 Type
*Ty
= V
->getType();
3995 Ty
= getEffectiveSCEVType(Ty
);
3996 const SCEV
*AllOnes
=
3997 getConstant(cast
<ConstantInt
>(Constant::getAllOnesValue(Ty
)));
3998 return getMinusSCEV(AllOnes
, V
);
4001 const SCEV
*ScalarEvolution::getMinusSCEV(const SCEV
*LHS
, const SCEV
*RHS
,
4002 SCEV::NoWrapFlags Flags
,
4004 // Fast path: X - X --> 0.
4006 return getZero(LHS
->getType());
4008 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4009 // makes it so that we cannot make much use of NUW.
4010 auto AddFlags
= SCEV::FlagAnyWrap
;
4011 const bool RHSIsNotMinSigned
=
4012 !getSignedRangeMin(RHS
).isMinSignedValue();
4013 if (maskFlags(Flags
, SCEV::FlagNSW
) == SCEV::FlagNSW
) {
4014 // Let M be the minimum representable signed value. Then (-1)*RHS
4015 // signed-wraps if and only if RHS is M. That can happen even for
4016 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4017 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4018 // (-1)*RHS, we need to prove that RHS != M.
4020 // If LHS is non-negative and we know that LHS - RHS does not
4021 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4022 // either by proving that RHS > M or that LHS >= 0.
4023 if (RHSIsNotMinSigned
|| isKnownNonNegative(LHS
)) {
4024 AddFlags
= SCEV::FlagNSW
;
4028 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4029 // RHS is NSW and LHS >= 0.
4031 // The difficulty here is that the NSW flag may have been proven
4032 // relative to a loop that is to be found in a recurrence in LHS and
4033 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4034 // larger scope than intended.
4035 auto NegFlags
= RHSIsNotMinSigned
? SCEV::FlagNSW
: SCEV::FlagAnyWrap
;
4037 return getAddExpr(LHS
, getNegativeSCEV(RHS
, NegFlags
), AddFlags
, Depth
);
4040 const SCEV
*ScalarEvolution::getTruncateOrZeroExtend(const SCEV
*V
, Type
*Ty
,
4042 Type
*SrcTy
= V
->getType();
4043 assert(SrcTy
->isIntOrPtrTy() && Ty
->isIntOrPtrTy() &&
4044 "Cannot truncate or zero extend with non-integer arguments!");
4045 if (getTypeSizeInBits(SrcTy
) == getTypeSizeInBits(Ty
))
4046 return V
; // No conversion
4047 if (getTypeSizeInBits(SrcTy
) > getTypeSizeInBits(Ty
))
4048 return getTruncateExpr(V
, Ty
, Depth
);
4049 return getZeroExtendExpr(V
, Ty
, Depth
);
4052 const SCEV
*ScalarEvolution::getTruncateOrSignExtend(const SCEV
*V
, Type
*Ty
,
4054 Type
*SrcTy
= V
->getType();
4055 assert(SrcTy
->isIntOrPtrTy() && Ty
->isIntOrPtrTy() &&
4056 "Cannot truncate or zero extend with non-integer arguments!");
4057 if (getTypeSizeInBits(SrcTy
) == getTypeSizeInBits(Ty
))
4058 return V
; // No conversion
4059 if (getTypeSizeInBits(SrcTy
) > getTypeSizeInBits(Ty
))
4060 return getTruncateExpr(V
, Ty
, Depth
);
4061 return getSignExtendExpr(V
, Ty
, Depth
);
4065 ScalarEvolution::getNoopOrZeroExtend(const SCEV
*V
, Type
*Ty
) {
4066 Type
*SrcTy
= V
->getType();
4067 assert(SrcTy
->isIntOrPtrTy() && Ty
->isIntOrPtrTy() &&
4068 "Cannot noop or zero extend with non-integer arguments!");
4069 assert(getTypeSizeInBits(SrcTy
) <= getTypeSizeInBits(Ty
) &&
4070 "getNoopOrZeroExtend cannot truncate!");
4071 if (getTypeSizeInBits(SrcTy
) == getTypeSizeInBits(Ty
))
4072 return V
; // No conversion
4073 return getZeroExtendExpr(V
, Ty
);
4077 ScalarEvolution::getNoopOrSignExtend(const SCEV
*V
, Type
*Ty
) {
4078 Type
*SrcTy
= V
->getType();
4079 assert(SrcTy
->isIntOrPtrTy() && Ty
->isIntOrPtrTy() &&
4080 "Cannot noop or sign extend with non-integer arguments!");
4081 assert(getTypeSizeInBits(SrcTy
) <= getTypeSizeInBits(Ty
) &&
4082 "getNoopOrSignExtend cannot truncate!");
4083 if (getTypeSizeInBits(SrcTy
) == getTypeSizeInBits(Ty
))
4084 return V
; // No conversion
4085 return getSignExtendExpr(V
, Ty
);
4089 ScalarEvolution::getNoopOrAnyExtend(const SCEV
*V
, Type
*Ty
) {
4090 Type
*SrcTy
= V
->getType();
4091 assert(SrcTy
->isIntOrPtrTy() && Ty
->isIntOrPtrTy() &&
4092 "Cannot noop or any extend with non-integer arguments!");
4093 assert(getTypeSizeInBits(SrcTy
) <= getTypeSizeInBits(Ty
) &&
4094 "getNoopOrAnyExtend cannot truncate!");
4095 if (getTypeSizeInBits(SrcTy
) == getTypeSizeInBits(Ty
))
4096 return V
; // No conversion
4097 return getAnyExtendExpr(V
, Ty
);
4101 ScalarEvolution::getTruncateOrNoop(const SCEV
*V
, Type
*Ty
) {
4102 Type
*SrcTy
= V
->getType();
4103 assert(SrcTy
->isIntOrPtrTy() && Ty
->isIntOrPtrTy() &&
4104 "Cannot truncate or noop with non-integer arguments!");
4105 assert(getTypeSizeInBits(SrcTy
) >= getTypeSizeInBits(Ty
) &&
4106 "getTruncateOrNoop cannot extend!");
4107 if (getTypeSizeInBits(SrcTy
) == getTypeSizeInBits(Ty
))
4108 return V
; // No conversion
4109 return getTruncateExpr(V
, Ty
);
4112 const SCEV
*ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV
*LHS
,
4114 const SCEV
*PromotedLHS
= LHS
;
4115 const SCEV
*PromotedRHS
= RHS
;
4117 if (getTypeSizeInBits(LHS
->getType()) > getTypeSizeInBits(RHS
->getType()))
4118 PromotedRHS
= getZeroExtendExpr(RHS
, LHS
->getType());
4120 PromotedLHS
= getNoopOrZeroExtend(LHS
, RHS
->getType());
4122 return getUMaxExpr(PromotedLHS
, PromotedRHS
);
4125 const SCEV
*ScalarEvolution::getUMinFromMismatchedTypes(const SCEV
*LHS
,
4127 SmallVector
<const SCEV
*, 2> Ops
= { LHS
, RHS
};
4128 return getUMinFromMismatchedTypes(Ops
);
4131 const SCEV
*ScalarEvolution::getUMinFromMismatchedTypes(
4132 SmallVectorImpl
<const SCEV
*> &Ops
) {
4133 assert(!Ops
.empty() && "At least one operand must be!");
4135 if (Ops
.size() == 1)
4138 // Find the max type first.
4139 Type
*MaxType
= nullptr;
4142 MaxType
= getWiderType(MaxType
, S
->getType());
4144 MaxType
= S
->getType();
4146 // Extend all ops to max type.
4147 SmallVector
<const SCEV
*, 2> PromotedOps
;
4149 PromotedOps
.push_back(getNoopOrZeroExtend(S
, MaxType
));
4152 return getUMinExpr(PromotedOps
);
4155 const SCEV
*ScalarEvolution::getPointerBase(const SCEV
*V
) {
4156 // A pointer operand may evaluate to a nonpointer expression, such as null.
4157 if (!V
->getType()->isPointerTy())
4160 if (const SCEVCastExpr
*Cast
= dyn_cast
<SCEVCastExpr
>(V
)) {
4161 return getPointerBase(Cast
->getOperand());
4162 } else if (const SCEVNAryExpr
*NAry
= dyn_cast
<SCEVNAryExpr
>(V
)) {
4163 const SCEV
*PtrOp
= nullptr;
4164 for (const SCEV
*NAryOp
: NAry
->operands()) {
4165 if (NAryOp
->getType()->isPointerTy()) {
4166 // Cannot find the base of an expression with multiple pointer operands.
4174 return getPointerBase(PtrOp
);
4179 /// Push users of the given Instruction onto the given Worklist.
4181 PushDefUseChildren(Instruction
*I
,
4182 SmallVectorImpl
<Instruction
*> &Worklist
) {
4183 // Push the def-use children onto the Worklist stack.
4184 for (User
*U
: I
->users())
4185 Worklist
.push_back(cast
<Instruction
>(U
));
4188 void ScalarEvolution::forgetSymbolicName(Instruction
*PN
, const SCEV
*SymName
) {
4189 SmallVector
<Instruction
*, 16> Worklist
;
4190 PushDefUseChildren(PN
, Worklist
);
4192 SmallPtrSet
<Instruction
*, 8> Visited
;
4194 while (!Worklist
.empty()) {
4195 Instruction
*I
= Worklist
.pop_back_val();
4196 if (!Visited
.insert(I
).second
)
4199 auto It
= ValueExprMap
.find_as(static_cast<Value
*>(I
));
4200 if (It
!= ValueExprMap
.end()) {
4201 const SCEV
*Old
= It
->second
;
4203 // Short-circuit the def-use traversal if the symbolic name
4204 // ceases to appear in expressions.
4205 if (Old
!= SymName
&& !hasOperand(Old
, SymName
))
4208 // SCEVUnknown for a PHI either means that it has an unrecognized
4209 // structure, it's a PHI that's in the progress of being computed
4210 // by createNodeForPHI, or it's a single-value PHI. In the first case,
4211 // additional loop trip count information isn't going to change anything.
4212 // In the second case, createNodeForPHI will perform the necessary
4213 // updates on its own when it gets to that point. In the third, we do
4214 // want to forget the SCEVUnknown.
4215 if (!isa
<PHINode
>(I
) ||
4216 !isa
<SCEVUnknown
>(Old
) ||
4217 (I
!= PN
&& Old
== SymName
)) {
4218 eraseValueFromMap(It
->first
);
4219 forgetMemoizedResults(Old
);
4223 PushDefUseChildren(I
, Worklist
);
4229 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4230 /// expression in case its Loop is L. If it is not L then
4231 /// if IgnoreOtherLoops is true then use AddRec itself
4232 /// otherwise rewrite cannot be done.
4233 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4234 class SCEVInitRewriter
: public SCEVRewriteVisitor
<SCEVInitRewriter
> {
4236 static const SCEV
*rewrite(const SCEV
*S
, const Loop
*L
, ScalarEvolution
&SE
,
4237 bool IgnoreOtherLoops
= true) {
4238 SCEVInitRewriter
Rewriter(L
, SE
);
4239 const SCEV
*Result
= Rewriter
.visit(S
);
4240 if (Rewriter
.hasSeenLoopVariantSCEVUnknown())
4241 return SE
.getCouldNotCompute();
4242 return Rewriter
.hasSeenOtherLoops() && !IgnoreOtherLoops
4243 ? SE
.getCouldNotCompute()
4247 const SCEV
*visitUnknown(const SCEVUnknown
*Expr
) {
4248 if (!SE
.isLoopInvariant(Expr
, L
))
4249 SeenLoopVariantSCEVUnknown
= true;
4253 const SCEV
*visitAddRecExpr(const SCEVAddRecExpr
*Expr
) {
4254 // Only re-write AddRecExprs for this loop.
4255 if (Expr
->getLoop() == L
)
4256 return Expr
->getStart();
4257 SeenOtherLoops
= true;
4261 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown
; }
4263 bool hasSeenOtherLoops() { return SeenOtherLoops
; }
4266 explicit SCEVInitRewriter(const Loop
*L
, ScalarEvolution
&SE
)
4267 : SCEVRewriteVisitor(SE
), L(L
) {}
4270 bool SeenLoopVariantSCEVUnknown
= false;
4271 bool SeenOtherLoops
= false;
4274 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4275 /// increment expression in case its Loop is L. If it is not L then
4276 /// use AddRec itself.
4277 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4278 class SCEVPostIncRewriter
: public SCEVRewriteVisitor
<SCEVPostIncRewriter
> {
4280 static const SCEV
*rewrite(const SCEV
*S
, const Loop
*L
, ScalarEvolution
&SE
) {
4281 SCEVPostIncRewriter
Rewriter(L
, SE
);
4282 const SCEV
*Result
= Rewriter
.visit(S
);
4283 return Rewriter
.hasSeenLoopVariantSCEVUnknown()
4284 ? SE
.getCouldNotCompute()
4288 const SCEV
*visitUnknown(const SCEVUnknown
*Expr
) {
4289 if (!SE
.isLoopInvariant(Expr
, L
))
4290 SeenLoopVariantSCEVUnknown
= true;
4294 const SCEV
*visitAddRecExpr(const SCEVAddRecExpr
*Expr
) {
4295 // Only re-write AddRecExprs for this loop.
4296 if (Expr
->getLoop() == L
)
4297 return Expr
->getPostIncExpr(SE
);
4298 SeenOtherLoops
= true;
4302 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown
; }
4304 bool hasSeenOtherLoops() { return SeenOtherLoops
; }
4307 explicit SCEVPostIncRewriter(const Loop
*L
, ScalarEvolution
&SE
)
4308 : SCEVRewriteVisitor(SE
), L(L
) {}
4311 bool SeenLoopVariantSCEVUnknown
= false;
4312 bool SeenOtherLoops
= false;
4315 /// This class evaluates the compare condition by matching it against the
4316 /// condition of loop latch. If there is a match we assume a true value
4317 /// for the condition while building SCEV nodes.
4318 class SCEVBackedgeConditionFolder
4319 : public SCEVRewriteVisitor
<SCEVBackedgeConditionFolder
> {
4321 static const SCEV
*rewrite(const SCEV
*S
, const Loop
*L
,
4322 ScalarEvolution
&SE
) {
4323 bool IsPosBECond
= false;
4324 Value
*BECond
= nullptr;
4325 if (BasicBlock
*Latch
= L
->getLoopLatch()) {
4326 BranchInst
*BI
= dyn_cast
<BranchInst
>(Latch
->getTerminator());
4327 if (BI
&& BI
->isConditional()) {
4328 assert(BI
->getSuccessor(0) != BI
->getSuccessor(1) &&
4329 "Both outgoing branches should not target same header!");
4330 BECond
= BI
->getCondition();
4331 IsPosBECond
= BI
->getSuccessor(0) == L
->getHeader();
4336 SCEVBackedgeConditionFolder
Rewriter(L
, BECond
, IsPosBECond
, SE
);
4337 return Rewriter
.visit(S
);
4340 const SCEV
*visitUnknown(const SCEVUnknown
*Expr
) {
4341 const SCEV
*Result
= Expr
;
4342 bool InvariantF
= SE
.isLoopInvariant(Expr
, L
);
4345 Instruction
*I
= cast
<Instruction
>(Expr
->getValue());
4346 switch (I
->getOpcode()) {
4347 case Instruction::Select
: {
4348 SelectInst
*SI
= cast
<SelectInst
>(I
);
4349 Optional
<const SCEV
*> Res
=
4350 compareWithBackedgeCondition(SI
->getCondition());
4351 if (Res
.hasValue()) {
4352 bool IsOne
= cast
<SCEVConstant
>(Res
.getValue())->getValue()->isOne();
4353 Result
= SE
.getSCEV(IsOne
? SI
->getTrueValue() : SI
->getFalseValue());
4358 Optional
<const SCEV
*> Res
= compareWithBackedgeCondition(I
);
4360 Result
= Res
.getValue();
4369 explicit SCEVBackedgeConditionFolder(const Loop
*L
, Value
*BECond
,
4370 bool IsPosBECond
, ScalarEvolution
&SE
)
4371 : SCEVRewriteVisitor(SE
), L(L
), BackedgeCond(BECond
),
4372 IsPositiveBECond(IsPosBECond
) {}
4374 Optional
<const SCEV
*> compareWithBackedgeCondition(Value
*IC
);
4377 /// Loop back condition.
4378 Value
*BackedgeCond
= nullptr;
4379 /// Set to true if loop back is on positive branch condition.
4380 bool IsPositiveBECond
;
4383 Optional
<const SCEV
*>
4384 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value
*IC
) {
4386 // If value matches the backedge condition for loop latch,
4387 // then return a constant evolution node based on loopback
4389 if (BackedgeCond
== IC
)
4390 return IsPositiveBECond
? SE
.getOne(Type::getInt1Ty(SE
.getContext()))
4391 : SE
.getZero(Type::getInt1Ty(SE
.getContext()));
4395 class SCEVShiftRewriter
: public SCEVRewriteVisitor
<SCEVShiftRewriter
> {
4397 static const SCEV
*rewrite(const SCEV
*S
, const Loop
*L
,
4398 ScalarEvolution
&SE
) {
4399 SCEVShiftRewriter
Rewriter(L
, SE
);
4400 const SCEV
*Result
= Rewriter
.visit(S
);
4401 return Rewriter
.isValid() ? Result
: SE
.getCouldNotCompute();
4404 const SCEV
*visitUnknown(const SCEVUnknown
*Expr
) {
4405 // Only allow AddRecExprs for this loop.
4406 if (!SE
.isLoopInvariant(Expr
, L
))
4411 const SCEV
*visitAddRecExpr(const SCEVAddRecExpr
*Expr
) {
4412 if (Expr
->getLoop() == L
&& Expr
->isAffine())
4413 return SE
.getMinusSCEV(Expr
, Expr
->getStepRecurrence(SE
));
4418 bool isValid() { return Valid
; }
4421 explicit SCEVShiftRewriter(const Loop
*L
, ScalarEvolution
&SE
)
4422 : SCEVRewriteVisitor(SE
), L(L
) {}
4428 } // end anonymous namespace
4431 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr
*AR
) {
4432 if (!AR
->isAffine())
4433 return SCEV::FlagAnyWrap
;
4435 using OBO
= OverflowingBinaryOperator
;
4437 SCEV::NoWrapFlags Result
= SCEV::FlagAnyWrap
;
4439 if (!AR
->hasNoSignedWrap()) {
4440 ConstantRange AddRecRange
= getSignedRange(AR
);
4441 ConstantRange IncRange
= getSignedRange(AR
->getStepRecurrence(*this));
4443 auto NSWRegion
= ConstantRange::makeGuaranteedNoWrapRegion(
4444 Instruction::Add
, IncRange
, OBO::NoSignedWrap
);
4445 if (NSWRegion
.contains(AddRecRange
))
4446 Result
= ScalarEvolution::setFlags(Result
, SCEV::FlagNSW
);
4449 if (!AR
->hasNoUnsignedWrap()) {
4450 ConstantRange AddRecRange
= getUnsignedRange(AR
);
4451 ConstantRange IncRange
= getUnsignedRange(AR
->getStepRecurrence(*this));
4453 auto NUWRegion
= ConstantRange::makeGuaranteedNoWrapRegion(
4454 Instruction::Add
, IncRange
, OBO::NoUnsignedWrap
);
4455 if (NUWRegion
.contains(AddRecRange
))
4456 Result
= ScalarEvolution::setFlags(Result
, SCEV::FlagNUW
);
4464 /// Represents an abstract binary operation. This may exist as a
4465 /// normal instruction or constant expression, or may have been
4466 /// derived from an expression tree.
4474 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4475 /// constant expression.
4476 Operator
*Op
= nullptr;
4478 explicit BinaryOp(Operator
*Op
)
4479 : Opcode(Op
->getOpcode()), LHS(Op
->getOperand(0)), RHS(Op
->getOperand(1)),
4481 if (auto *OBO
= dyn_cast
<OverflowingBinaryOperator
>(Op
)) {
4482 IsNSW
= OBO
->hasNoSignedWrap();
4483 IsNUW
= OBO
->hasNoUnsignedWrap();
4487 explicit BinaryOp(unsigned Opcode
, Value
*LHS
, Value
*RHS
, bool IsNSW
= false,
4489 : Opcode(Opcode
), LHS(LHS
), RHS(RHS
), IsNSW(IsNSW
), IsNUW(IsNUW
) {}
4492 } // end anonymous namespace
4494 /// Try to map \p V into a BinaryOp, and return \c None on failure.
4495 static Optional
<BinaryOp
> MatchBinaryOp(Value
*V
, DominatorTree
&DT
) {
4496 auto *Op
= dyn_cast
<Operator
>(V
);
4500 // Implementation detail: all the cleverness here should happen without
4501 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4502 // SCEV expressions when possible, and we should not break that.
4504 switch (Op
->getOpcode()) {
4505 case Instruction::Add
:
4506 case Instruction::Sub
:
4507 case Instruction::Mul
:
4508 case Instruction::UDiv
:
4509 case Instruction::URem
:
4510 case Instruction::And
:
4511 case Instruction::Or
:
4512 case Instruction::AShr
:
4513 case Instruction::Shl
:
4514 return BinaryOp(Op
);
4516 case Instruction::Xor
:
4517 if (auto *RHSC
= dyn_cast
<ConstantInt
>(Op
->getOperand(1)))
4518 // If the RHS of the xor is a signmask, then this is just an add.
4519 // Instcombine turns add of signmask into xor as a strength reduction step.
4520 if (RHSC
->getValue().isSignMask())
4521 return BinaryOp(Instruction::Add
, Op
->getOperand(0), Op
->getOperand(1));
4522 return BinaryOp(Op
);
4524 case Instruction::LShr
:
4525 // Turn logical shift right of a constant into a unsigned divide.
4526 if (ConstantInt
*SA
= dyn_cast
<ConstantInt
>(Op
->getOperand(1))) {
4527 uint32_t BitWidth
= cast
<IntegerType
>(Op
->getType())->getBitWidth();
4529 // If the shift count is not less than the bitwidth, the result of
4530 // the shift is undefined. Don't try to analyze it, because the
4531 // resolution chosen here may differ from the resolution chosen in
4532 // other parts of the compiler.
4533 if (SA
->getValue().ult(BitWidth
)) {
4535 ConstantInt::get(SA
->getContext(),
4536 APInt::getOneBitSet(BitWidth
, SA
->getZExtValue()));
4537 return BinaryOp(Instruction::UDiv
, Op
->getOperand(0), X
);
4540 return BinaryOp(Op
);
4542 case Instruction::ExtractValue
: {
4543 auto *EVI
= cast
<ExtractValueInst
>(Op
);
4544 if (EVI
->getNumIndices() != 1 || EVI
->getIndices()[0] != 0)
4547 auto *WO
= dyn_cast
<WithOverflowInst
>(EVI
->getAggregateOperand());
4551 Instruction::BinaryOps BinOp
= WO
->getBinaryOp();
4552 bool Signed
= WO
->isSigned();
4553 // TODO: Should add nuw/nsw flags for mul as well.
4554 if (BinOp
== Instruction::Mul
|| !isOverflowIntrinsicNoWrap(WO
, DT
))
4555 return BinaryOp(BinOp
, WO
->getLHS(), WO
->getRHS());
4557 // Now that we know that all uses of the arithmetic-result component of
4558 // CI are guarded by the overflow check, we can go ahead and pretend
4559 // that the arithmetic is non-overflowing.
4560 return BinaryOp(BinOp
, WO
->getLHS(), WO
->getRHS(),
4561 /* IsNSW = */ Signed
, /* IsNUW = */ !Signed
);
4571 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4572 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4573 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4574 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4575 /// follows one of the following patterns:
4576 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4577 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4578 /// If the SCEV expression of \p Op conforms with one of the expected patterns
4579 /// we return the type of the truncation operation, and indicate whether the
4580 /// truncated type should be treated as signed/unsigned by setting
4581 /// \p Signed to true/false, respectively.
4582 static Type
*isSimpleCastedPHI(const SCEV
*Op
, const SCEVUnknown
*SymbolicPHI
,
4583 bool &Signed
, ScalarEvolution
&SE
) {
4584 // The case where Op == SymbolicPHI (that is, with no type conversions on
4585 // the way) is handled by the regular add recurrence creating logic and
4586 // would have already been triggered in createAddRecForPHI. Reaching it here
4587 // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4588 // because one of the other operands of the SCEVAddExpr updating this PHI is
4591 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4592 // this case predicates that allow us to prove that Op == SymbolicPHI will
4594 if (Op
== SymbolicPHI
)
4597 unsigned SourceBits
= SE
.getTypeSizeInBits(SymbolicPHI
->getType());
4598 unsigned NewBits
= SE
.getTypeSizeInBits(Op
->getType());
4599 if (SourceBits
!= NewBits
)
4602 const SCEVSignExtendExpr
*SExt
= dyn_cast
<SCEVSignExtendExpr
>(Op
);
4603 const SCEVZeroExtendExpr
*ZExt
= dyn_cast
<SCEVZeroExtendExpr
>(Op
);
4606 const SCEVTruncateExpr
*Trunc
=
4607 SExt
? dyn_cast
<SCEVTruncateExpr
>(SExt
->getOperand())
4608 : dyn_cast
<SCEVTruncateExpr
>(ZExt
->getOperand());
4611 const SCEV
*X
= Trunc
->getOperand();
4612 if (X
!= SymbolicPHI
)
4614 Signed
= SExt
!= nullptr;
4615 return Trunc
->getType();
4618 static const Loop
*isIntegerLoopHeaderPHI(const PHINode
*PN
, LoopInfo
&LI
) {
4619 if (!PN
->getType()->isIntegerTy())
4621 const Loop
*L
= LI
.getLoopFor(PN
->getParent());
4622 if (!L
|| L
->getHeader() != PN
->getParent())
4627 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4628 // computation that updates the phi follows the following pattern:
4629 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4630 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4631 // If so, try to see if it can be rewritten as an AddRecExpr under some
4632 // Predicates. If successful, return them as a pair. Also cache the results
4635 // Example usage scenario:
4636 // Say the Rewriter is called for the following SCEV:
4637 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4639 // %X = phi i64 (%Start, %BEValue)
4640 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4641 // and call this function with %SymbolicPHI = %X.
4643 // The analysis will find that the value coming around the backedge has
4644 // the following SCEV:
4645 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4646 // Upon concluding that this matches the desired pattern, the function
4647 // will return the pair {NewAddRec, SmallPredsVec} where:
4648 // NewAddRec = {%Start,+,%Step}
4649 // SmallPredsVec = {P1, P2, P3} as follows:
4650 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4651 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4652 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4653 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4654 // under the predicates {P1,P2,P3}.
4655 // This predicated rewrite will be cached in PredicatedSCEVRewrites:
4656 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4660 // 1) Extend the Induction descriptor to also support inductions that involve
4661 // casts: When needed (namely, when we are called in the context of the
4662 // vectorizer induction analysis), a Set of cast instructions will be
4663 // populated by this method, and provided back to isInductionPHI. This is
4664 // needed to allow the vectorizer to properly record them to be ignored by
4665 // the cost model and to avoid vectorizing them (otherwise these casts,
4666 // which are redundant under the runtime overflow checks, will be
4667 // vectorized, which can be costly).
4669 // 2) Support additional induction/PHISCEV patterns: We also want to support
4670 // inductions where the sext-trunc / zext-trunc operations (partly) occur
4671 // after the induction update operation (the induction increment):
4673 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4674 // which correspond to a phi->add->trunc->sext/zext->phi update chain.
4676 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4677 // which correspond to a phi->trunc->add->sext/zext->phi update chain.
4679 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
4680 Optional
<std::pair
<const SCEV
*, SmallVector
<const SCEVPredicate
*, 3>>>
4681 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown
*SymbolicPHI
) {
4682 SmallVector
<const SCEVPredicate
*, 3> Predicates
;
4684 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4685 // return an AddRec expression under some predicate.
4687 auto *PN
= cast
<PHINode
>(SymbolicPHI
->getValue());
4688 const Loop
*L
= isIntegerLoopHeaderPHI(PN
, LI
);
4689 assert(L
&& "Expecting an integer loop header phi");
4691 // The loop may have multiple entrances or multiple exits; we can analyze
4692 // this phi as an addrec if it has a unique entry value and a unique
4694 Value
*BEValueV
= nullptr, *StartValueV
= nullptr;
4695 for (unsigned i
= 0, e
= PN
->getNumIncomingValues(); i
!= e
; ++i
) {
4696 Value
*V
= PN
->getIncomingValue(i
);
4697 if (L
->contains(PN
->getIncomingBlock(i
))) {
4700 } else if (BEValueV
!= V
) {
4704 } else if (!StartValueV
) {
4706 } else if (StartValueV
!= V
) {
4707 StartValueV
= nullptr;
4711 if (!BEValueV
|| !StartValueV
)
4714 const SCEV
*BEValue
= getSCEV(BEValueV
);
4716 // If the value coming around the backedge is an add with the symbolic
4717 // value we just inserted, possibly with casts that we can ignore under
4718 // an appropriate runtime guard, then we found a simple induction variable!
4719 const auto *Add
= dyn_cast
<SCEVAddExpr
>(BEValue
);
4723 // If there is a single occurrence of the symbolic value, possibly
4724 // casted, replace it with a recurrence.
4725 unsigned FoundIndex
= Add
->getNumOperands();
4726 Type
*TruncTy
= nullptr;
4728 for (unsigned i
= 0, e
= Add
->getNumOperands(); i
!= e
; ++i
)
4730 isSimpleCastedPHI(Add
->getOperand(i
), SymbolicPHI
, Signed
, *this)))
4731 if (FoundIndex
== e
) {
4736 if (FoundIndex
== Add
->getNumOperands())
4739 // Create an add with everything but the specified operand.
4740 SmallVector
<const SCEV
*, 8> Ops
;
4741 for (unsigned i
= 0, e
= Add
->getNumOperands(); i
!= e
; ++i
)
4742 if (i
!= FoundIndex
)
4743 Ops
.push_back(Add
->getOperand(i
));
4744 const SCEV
*Accum
= getAddExpr(Ops
);
4746 // The runtime checks will not be valid if the step amount is
4747 // varying inside the loop.
4748 if (!isLoopInvariant(Accum
, L
))
4751 // *** Part2: Create the predicates
4753 // Analysis was successful: we have a phi-with-cast pattern for which we
4754 // can return an AddRec expression under the following predicates:
4756 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4757 // fits within the truncated type (does not overflow) for i = 0 to n-1.
4758 // P2: An Equal predicate that guarantees that
4759 // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4760 // P3: An Equal predicate that guarantees that
4761 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4763 // As we next prove, the above predicates guarantee that:
4764 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4767 // More formally, we want to prove that:
4768 // Expr(i+1) = Start + (i+1) * Accum
4769 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4772 // 1) Expr(0) = Start
4773 // 2) Expr(1) = Start + Accum
4774 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4775 // 3) Induction hypothesis (step i):
4776 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4780 // = Start + (i+1)*Accum
4781 // = (Start + i*Accum) + Accum
4782 // = Expr(i) + Accum
4783 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4786 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4788 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4789 // + (Ext ix (Trunc iy (Accum) to ix) to iy)
4790 // + Accum :: from P3
4792 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4793 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4795 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4796 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4798 // By induction, the same applies to all iterations 1<=i<n:
4801 // Create a truncated addrec for which we will add a no overflow check (P1).
4802 const SCEV
*StartVal
= getSCEV(StartValueV
);
4803 const SCEV
*PHISCEV
=
4804 getAddRecExpr(getTruncateExpr(StartVal
, TruncTy
),
4805 getTruncateExpr(Accum
, TruncTy
), L
, SCEV::FlagAnyWrap
);
4807 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
4808 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
4809 // will be constant.
4811 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
4813 if (const auto *AR
= dyn_cast
<SCEVAddRecExpr
>(PHISCEV
)) {
4814 SCEVWrapPredicate::IncrementWrapFlags AddedFlags
=
4815 Signed
? SCEVWrapPredicate::IncrementNSSW
4816 : SCEVWrapPredicate::IncrementNUSW
;
4817 const SCEVPredicate
*AddRecPred
= getWrapPredicate(AR
, AddedFlags
);
4818 Predicates
.push_back(AddRecPred
);
4821 // Create the Equal Predicates P2,P3:
4823 // It is possible that the predicates P2 and/or P3 are computable at
4824 // compile time due to StartVal and/or Accum being constants.
4825 // If either one is, then we can check that now and escape if either P2
4828 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
4829 // for each of StartVal and Accum
4830 auto getExtendedExpr
= [&](const SCEV
*Expr
,
4831 bool CreateSignExtend
) -> const SCEV
* {
4832 assert(isLoopInvariant(Expr
, L
) && "Expr is expected to be invariant");
4833 const SCEV
*TruncatedExpr
= getTruncateExpr(Expr
, TruncTy
);
4834 const SCEV
*ExtendedExpr
=
4835 CreateSignExtend
? getSignExtendExpr(TruncatedExpr
, Expr
->getType())
4836 : getZeroExtendExpr(TruncatedExpr
, Expr
->getType());
4837 return ExtendedExpr
;
4841 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
4842 // = getExtendedExpr(Expr)
4843 // Determine whether the predicate P: Expr == ExtendedExpr
4844 // is known to be false at compile time
4845 auto PredIsKnownFalse
= [&](const SCEV
*Expr
,
4846 const SCEV
*ExtendedExpr
) -> bool {
4847 return Expr
!= ExtendedExpr
&&
4848 isKnownPredicate(ICmpInst::ICMP_NE
, Expr
, ExtendedExpr
);
4851 const SCEV
*StartExtended
= getExtendedExpr(StartVal
, Signed
);
4852 if (PredIsKnownFalse(StartVal
, StartExtended
)) {
4853 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
4857 // The Step is always Signed (because the overflow checks are either
4859 const SCEV
*AccumExtended
= getExtendedExpr(Accum
, /*CreateSignExtend=*/true);
4860 if (PredIsKnownFalse(Accum
, AccumExtended
)) {
4861 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
4865 auto AppendPredicate
= [&](const SCEV
*Expr
,
4866 const SCEV
*ExtendedExpr
) -> void {
4867 if (Expr
!= ExtendedExpr
&&
4868 !isKnownPredicate(ICmpInst::ICMP_EQ
, Expr
, ExtendedExpr
)) {
4869 const SCEVPredicate
*Pred
= getEqualPredicate(Expr
, ExtendedExpr
);
4870 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred
);
4871 Predicates
.push_back(Pred
);
4875 AppendPredicate(StartVal
, StartExtended
);
4876 AppendPredicate(Accum
, AccumExtended
);
4878 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
4879 // which the casts had been folded away. The caller can rewrite SymbolicPHI
4880 // into NewAR if it will also add the runtime overflow checks specified in
4882 auto *NewAR
= getAddRecExpr(StartVal
, Accum
, L
, SCEV::FlagAnyWrap
);
4884 std::pair
<const SCEV
*, SmallVector
<const SCEVPredicate
*, 3>> PredRewrite
=
4885 std::make_pair(NewAR
, Predicates
);
4886 // Remember the result of the analysis for this SCEV at this locayyytion.
4887 PredicatedSCEVRewrites
[{SymbolicPHI
, L
}] = PredRewrite
;
4891 Optional
<std::pair
<const SCEV
*, SmallVector
<const SCEVPredicate
*, 3>>>
4892 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown
*SymbolicPHI
) {
4893 auto *PN
= cast
<PHINode
>(SymbolicPHI
->getValue());
4894 const Loop
*L
= isIntegerLoopHeaderPHI(PN
, LI
);
4898 // Check to see if we already analyzed this PHI.
4899 auto I
= PredicatedSCEVRewrites
.find({SymbolicPHI
, L
});
4900 if (I
!= PredicatedSCEVRewrites
.end()) {
4901 std::pair
<const SCEV
*, SmallVector
<const SCEVPredicate
*, 3>> Rewrite
=
4903 // Analysis was done before and failed to create an AddRec:
4904 if (Rewrite
.first
== SymbolicPHI
)
4906 // Analysis was done before and succeeded to create an AddRec under
4908 assert(isa
<SCEVAddRecExpr
>(Rewrite
.first
) && "Expected an AddRec");
4909 assert(!(Rewrite
.second
).empty() && "Expected to find Predicates");
4913 Optional
<std::pair
<const SCEV
*, SmallVector
<const SCEVPredicate
*, 3>>>
4914 Rewrite
= createAddRecFromPHIWithCastsImpl(SymbolicPHI
);
4916 // Record in the cache that the analysis failed
4918 SmallVector
<const SCEVPredicate
*, 3> Predicates
;
4919 PredicatedSCEVRewrites
[{SymbolicPHI
, L
}] = {SymbolicPHI
, Predicates
};
4926 // FIXME: This utility is currently required because the Rewriter currently
4927 // does not rewrite this expression:
4928 // {0, +, (sext ix (trunc iy to ix) to iy)}
4929 // into {0, +, %step},
4930 // even when the following Equal predicate exists:
4931 // "%step == (sext ix (trunc iy to ix) to iy)".
4932 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
4933 const SCEVAddRecExpr
*AR1
, const SCEVAddRecExpr
*AR2
) const {
4937 auto areExprsEqual
= [&](const SCEV
*Expr1
, const SCEV
*Expr2
) -> bool {
4938 if (Expr1
!= Expr2
&& !Preds
.implies(SE
.getEqualPredicate(Expr1
, Expr2
)) &&
4939 !Preds
.implies(SE
.getEqualPredicate(Expr2
, Expr1
)))
4944 if (!areExprsEqual(AR1
->getStart(), AR2
->getStart()) ||
4945 !areExprsEqual(AR1
->getStepRecurrence(SE
), AR2
->getStepRecurrence(SE
)))
4950 /// A helper function for createAddRecFromPHI to handle simple cases.
4952 /// This function tries to find an AddRec expression for the simplest (yet most
4953 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
4954 /// If it fails, createAddRecFromPHI will use a more general, but slow,
4955 /// technique for finding the AddRec expression.
4956 const SCEV
*ScalarEvolution::createSimpleAffineAddRec(PHINode
*PN
,
4958 Value
*StartValueV
) {
4959 const Loop
*L
= LI
.getLoopFor(PN
->getParent());
4960 assert(L
&& L
->getHeader() == PN
->getParent());
4961 assert(BEValueV
&& StartValueV
);
4963 auto BO
= MatchBinaryOp(BEValueV
, DT
);
4967 if (BO
->Opcode
!= Instruction::Add
)
4970 const SCEV
*Accum
= nullptr;
4971 if (BO
->LHS
== PN
&& L
->isLoopInvariant(BO
->RHS
))
4972 Accum
= getSCEV(BO
->RHS
);
4973 else if (BO
->RHS
== PN
&& L
->isLoopInvariant(BO
->LHS
))
4974 Accum
= getSCEV(BO
->LHS
);
4979 SCEV::NoWrapFlags Flags
= SCEV::FlagAnyWrap
;
4981 Flags
= setFlags(Flags
, SCEV::FlagNUW
);
4983 Flags
= setFlags(Flags
, SCEV::FlagNSW
);
4985 const SCEV
*StartVal
= getSCEV(StartValueV
);
4986 const SCEV
*PHISCEV
= getAddRecExpr(StartVal
, Accum
, L
, Flags
);
4988 ValueExprMap
[SCEVCallbackVH(PN
, this)] = PHISCEV
;
4990 // We can add Flags to the post-inc expression only if we
4991 // know that it is *undefined behavior* for BEValueV to
4993 if (auto *BEInst
= dyn_cast
<Instruction
>(BEValueV
))
4994 if (isLoopInvariant(Accum
, L
) && isAddRecNeverPoison(BEInst
, L
))
4995 (void)getAddRecExpr(getAddExpr(StartVal
, Accum
, Flags
), Accum
, L
, Flags
);
5000 const SCEV
*ScalarEvolution::createAddRecFromPHI(PHINode
*PN
) {
5001 const Loop
*L
= LI
.getLoopFor(PN
->getParent());
5002 if (!L
|| L
->getHeader() != PN
->getParent())
5005 // The loop may have multiple entrances or multiple exits; we can analyze
5006 // this phi as an addrec if it has a unique entry value and a unique
5008 Value
*BEValueV
= nullptr, *StartValueV
= nullptr;
5009 for (unsigned i
= 0, e
= PN
->getNumIncomingValues(); i
!= e
; ++i
) {
5010 Value
*V
= PN
->getIncomingValue(i
);
5011 if (L
->contains(PN
->getIncomingBlock(i
))) {
5014 } else if (BEValueV
!= V
) {
5018 } else if (!StartValueV
) {
5020 } else if (StartValueV
!= V
) {
5021 StartValueV
= nullptr;
5025 if (!BEValueV
|| !StartValueV
)
5028 assert(ValueExprMap
.find_as(PN
) == ValueExprMap
.end() &&
5029 "PHI node already processed?");
5031 // First, try to find AddRec expression without creating a fictituos symbolic
5033 if (auto *S
= createSimpleAffineAddRec(PN
, BEValueV
, StartValueV
))
5036 // Handle PHI node value symbolically.
5037 const SCEV
*SymbolicName
= getUnknown(PN
);
5038 ValueExprMap
.insert({SCEVCallbackVH(PN
, this), SymbolicName
});
5040 // Using this symbolic name for the PHI, analyze the value coming around
5042 const SCEV
*BEValue
= getSCEV(BEValueV
);
5044 // NOTE: If BEValue is loop invariant, we know that the PHI node just
5045 // has a special value for the first iteration of the loop.
5047 // If the value coming around the backedge is an add with the symbolic
5048 // value we just inserted, then we found a simple induction variable!
5049 if (const SCEVAddExpr
*Add
= dyn_cast
<SCEVAddExpr
>(BEValue
)) {
5050 // If there is a single occurrence of the symbolic value, replace it
5051 // with a recurrence.
5052 unsigned FoundIndex
= Add
->getNumOperands();
5053 for (unsigned i
= 0, e
= Add
->getNumOperands(); i
!= e
; ++i
)
5054 if (Add
->getOperand(i
) == SymbolicName
)
5055 if (FoundIndex
== e
) {
5060 if (FoundIndex
!= Add
->getNumOperands()) {
5061 // Create an add with everything but the specified operand.
5062 SmallVector
<const SCEV
*, 8> Ops
;
5063 for (unsigned i
= 0, e
= Add
->getNumOperands(); i
!= e
; ++i
)
5064 if (i
!= FoundIndex
)
5065 Ops
.push_back(SCEVBackedgeConditionFolder::rewrite(Add
->getOperand(i
),
5067 const SCEV
*Accum
= getAddExpr(Ops
);
5069 // This is not a valid addrec if the step amount is varying each
5070 // loop iteration, but is not itself an addrec in this loop.
5071 if (isLoopInvariant(Accum
, L
) ||
5072 (isa
<SCEVAddRecExpr
>(Accum
) &&
5073 cast
<SCEVAddRecExpr
>(Accum
)->getLoop() == L
)) {
5074 SCEV::NoWrapFlags Flags
= SCEV::FlagAnyWrap
;
5076 if (auto BO
= MatchBinaryOp(BEValueV
, DT
)) {
5077 if (BO
->Opcode
== Instruction::Add
&& BO
->LHS
== PN
) {
5079 Flags
= setFlags(Flags
, SCEV::FlagNUW
);
5081 Flags
= setFlags(Flags
, SCEV::FlagNSW
);
5083 } else if (GEPOperator
*GEP
= dyn_cast
<GEPOperator
>(BEValueV
)) {
5084 // If the increment is an inbounds GEP, then we know the address
5085 // space cannot be wrapped around. We cannot make any guarantee
5086 // about signed or unsigned overflow because pointers are
5087 // unsigned but we may have a negative index from the base
5088 // pointer. We can guarantee that no unsigned wrap occurs if the
5089 // indices form a positive value.
5090 if (GEP
->isInBounds() && GEP
->getOperand(0) == PN
) {
5091 Flags
= setFlags(Flags
, SCEV::FlagNW
);
5093 const SCEV
*Ptr
= getSCEV(GEP
->getPointerOperand());
5094 if (isKnownPositive(getMinusSCEV(getSCEV(GEP
), Ptr
)))
5095 Flags
= setFlags(Flags
, SCEV::FlagNUW
);
5098 // We cannot transfer nuw and nsw flags from subtraction
5099 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5103 const SCEV
*StartVal
= getSCEV(StartValueV
);
5104 const SCEV
*PHISCEV
= getAddRecExpr(StartVal
, Accum
, L
, Flags
);
5106 // Okay, for the entire analysis of this edge we assumed the PHI
5107 // to be symbolic. We now need to go back and purge all of the
5108 // entries for the scalars that use the symbolic expression.
5109 forgetSymbolicName(PN
, SymbolicName
);
5110 ValueExprMap
[SCEVCallbackVH(PN
, this)] = PHISCEV
;
5112 // We can add Flags to the post-inc expression only if we
5113 // know that it is *undefined behavior* for BEValueV to
5115 if (auto *BEInst
= dyn_cast
<Instruction
>(BEValueV
))
5116 if (isLoopInvariant(Accum
, L
) && isAddRecNeverPoison(BEInst
, L
))
5117 (void)getAddRecExpr(getAddExpr(StartVal
, Accum
), Accum
, L
, Flags
);
5123 // Otherwise, this could be a loop like this:
5124 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
5125 // In this case, j = {1,+,1} and BEValue is j.
5126 // Because the other in-value of i (0) fits the evolution of BEValue
5127 // i really is an addrec evolution.
5129 // We can generalize this saying that i is the shifted value of BEValue
5130 // by one iteration:
5131 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
5132 const SCEV
*Shifted
= SCEVShiftRewriter::rewrite(BEValue
, L
, *this);
5133 const SCEV
*Start
= SCEVInitRewriter::rewrite(Shifted
, L
, *this, false);
5134 if (Shifted
!= getCouldNotCompute() &&
5135 Start
!= getCouldNotCompute()) {
5136 const SCEV
*StartVal
= getSCEV(StartValueV
);
5137 if (Start
== StartVal
) {
5138 // Okay, for the entire analysis of this edge we assumed the PHI
5139 // to be symbolic. We now need to go back and purge all of the
5140 // entries for the scalars that use the symbolic expression.
5141 forgetSymbolicName(PN
, SymbolicName
);
5142 ValueExprMap
[SCEVCallbackVH(PN
, this)] = Shifted
;
5148 // Remove the temporary PHI node SCEV that has been inserted while intending
5149 // to create an AddRecExpr for this PHI node. We can not keep this temporary
5150 // as it will prevent later (possibly simpler) SCEV expressions to be added
5151 // to the ValueExprMap.
5152 eraseValueFromMap(PN
);
5157 // Checks if the SCEV S is available at BB. S is considered available at BB
5158 // if S can be materialized at BB without introducing a fault.
5159 static bool IsAvailableOnEntry(const Loop
*L
, DominatorTree
&DT
, const SCEV
*S
,
5161 struct CheckAvailable
{
5162 bool TraversalDone
= false;
5163 bool Available
= true;
5165 const Loop
*L
= nullptr; // The loop BB is in (can be nullptr)
5166 BasicBlock
*BB
= nullptr;
5169 CheckAvailable(const Loop
*L
, BasicBlock
*BB
, DominatorTree
&DT
)
5170 : L(L
), BB(BB
), DT(DT
) {}
5172 bool setUnavailable() {
5173 TraversalDone
= true;
5178 bool follow(const SCEV
*S
) {
5179 switch (S
->getSCEVType()) {
5180 case scConstant
: case scTruncate
: case scZeroExtend
: case scSignExtend
:
5181 case scAddExpr
: case scMulExpr
: case scUMaxExpr
: case scSMaxExpr
:
5184 // These expressions are available if their operand(s) is/are.
5187 case scAddRecExpr
: {
5188 // We allow add recurrences that are on the loop BB is in, or some
5189 // outer loop. This guarantees availability because the value of the
5190 // add recurrence at BB is simply the "current" value of the induction
5191 // variable. We can relax this in the future; for instance an add
5192 // recurrence on a sibling dominating loop is also available at BB.
5193 const auto *ARLoop
= cast
<SCEVAddRecExpr
>(S
)->getLoop();
5194 if (L
&& (ARLoop
== L
|| ARLoop
->contains(L
)))
5197 return setUnavailable();
5201 // For SCEVUnknown, we check for simple dominance.
5202 const auto *SU
= cast
<SCEVUnknown
>(S
);
5203 Value
*V
= SU
->getValue();
5205 if (isa
<Argument
>(V
))
5208 if (isa
<Instruction
>(V
) && DT
.dominates(cast
<Instruction
>(V
), BB
))
5211 return setUnavailable();
5215 case scCouldNotCompute
:
5216 // We do not try to smart about these at all.
5217 return setUnavailable();
5219 llvm_unreachable("switch should be fully covered!");
5222 bool isDone() { return TraversalDone
; }
5225 CheckAvailable
CA(L
, BB
, DT
);
5226 SCEVTraversal
<CheckAvailable
> ST(CA
);
5229 return CA
.Available
;
5232 // Try to match a control flow sequence that branches out at BI and merges back
5233 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
5235 static bool BrPHIToSelect(DominatorTree
&DT
, BranchInst
*BI
, PHINode
*Merge
,
5236 Value
*&C
, Value
*&LHS
, Value
*&RHS
) {
5237 C
= BI
->getCondition();
5239 BasicBlockEdge
LeftEdge(BI
->getParent(), BI
->getSuccessor(0));
5240 BasicBlockEdge
RightEdge(BI
->getParent(), BI
->getSuccessor(1));
5242 if (!LeftEdge
.isSingleEdge())
5245 assert(RightEdge
.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5247 Use
&LeftUse
= Merge
->getOperandUse(0);
5248 Use
&RightUse
= Merge
->getOperandUse(1);
5250 if (DT
.dominates(LeftEdge
, LeftUse
) && DT
.dominates(RightEdge
, RightUse
)) {
5256 if (DT
.dominates(LeftEdge
, RightUse
) && DT
.dominates(RightEdge
, LeftUse
)) {
5265 const SCEV
*ScalarEvolution::createNodeFromSelectLikePHI(PHINode
*PN
) {
5267 [&](BasicBlock
*BB
) { return DT
.isReachableFromEntry(BB
); };
5268 if (PN
->getNumIncomingValues() == 2 && all_of(PN
->blocks(), IsReachable
)) {
5269 const Loop
*L
= LI
.getLoopFor(PN
->getParent());
5271 // We don't want to break LCSSA, even in a SCEV expression tree.
5272 for (unsigned i
= 0, e
= PN
->getNumIncomingValues(); i
!= e
; ++i
)
5273 if (LI
.getLoopFor(PN
->getIncomingBlock(i
)) != L
)
5278 // br %cond, label %left, label %right
5284 // V = phi [ %x, %left ], [ %y, %right ]
5286 // as "select %cond, %x, %y"
5288 BasicBlock
*IDom
= DT
[PN
->getParent()]->getIDom()->getBlock();
5289 assert(IDom
&& "At least the entry block should dominate PN");
5291 auto *BI
= dyn_cast
<BranchInst
>(IDom
->getTerminator());
5292 Value
*Cond
= nullptr, *LHS
= nullptr, *RHS
= nullptr;
5294 if (BI
&& BI
->isConditional() &&
5295 BrPHIToSelect(DT
, BI
, PN
, Cond
, LHS
, RHS
) &&
5296 IsAvailableOnEntry(L
, DT
, getSCEV(LHS
), PN
->getParent()) &&
5297 IsAvailableOnEntry(L
, DT
, getSCEV(RHS
), PN
->getParent()))
5298 return createNodeForSelectOrPHI(PN
, Cond
, LHS
, RHS
);
5304 const SCEV
*ScalarEvolution::createNodeForPHI(PHINode
*PN
) {
5305 if (const SCEV
*S
= createAddRecFromPHI(PN
))
5308 if (const SCEV
*S
= createNodeFromSelectLikePHI(PN
))
5311 // If the PHI has a single incoming value, follow that value, unless the
5312 // PHI's incoming blocks are in a different loop, in which case doing so
5313 // risks breaking LCSSA form. Instcombine would normally zap these, but
5314 // it doesn't have DominatorTree information, so it may miss cases.
5315 if (Value
*V
= SimplifyInstruction(PN
, {getDataLayout(), &TLI
, &DT
, &AC
}))
5316 if (LI
.replacementPreservesLCSSAForm(PN
, V
))
5319 // If it's not a loop phi, we can't handle it yet.
5320 return getUnknown(PN
);
5323 const SCEV
*ScalarEvolution::createNodeForSelectOrPHI(Instruction
*I
,
5327 // Handle "constant" branch or select. This can occur for instance when a
5328 // loop pass transforms an inner loop and moves on to process the outer loop.
5329 if (auto *CI
= dyn_cast
<ConstantInt
>(Cond
))
5330 return getSCEV(CI
->isOne() ? TrueVal
: FalseVal
);
5332 // Try to match some simple smax or umax patterns.
5333 auto *ICI
= dyn_cast
<ICmpInst
>(Cond
);
5335 return getUnknown(I
);
5337 Value
*LHS
= ICI
->getOperand(0);
5338 Value
*RHS
= ICI
->getOperand(1);
5340 switch (ICI
->getPredicate()) {
5341 case ICmpInst::ICMP_SLT
:
5342 case ICmpInst::ICMP_SLE
:
5343 std::swap(LHS
, RHS
);
5345 case ICmpInst::ICMP_SGT
:
5346 case ICmpInst::ICMP_SGE
:
5347 // a >s b ? a+x : b+x -> smax(a, b)+x
5348 // a >s b ? b+x : a+x -> smin(a, b)+x
5349 if (getTypeSizeInBits(LHS
->getType()) <= getTypeSizeInBits(I
->getType())) {
5350 const SCEV
*LS
= getNoopOrSignExtend(getSCEV(LHS
), I
->getType());
5351 const SCEV
*RS
= getNoopOrSignExtend(getSCEV(RHS
), I
->getType());
5352 const SCEV
*LA
= getSCEV(TrueVal
);
5353 const SCEV
*RA
= getSCEV(FalseVal
);
5354 const SCEV
*LDiff
= getMinusSCEV(LA
, LS
);
5355 const SCEV
*RDiff
= getMinusSCEV(RA
, RS
);
5357 return getAddExpr(getSMaxExpr(LS
, RS
), LDiff
);
5358 LDiff
= getMinusSCEV(LA
, RS
);
5359 RDiff
= getMinusSCEV(RA
, LS
);
5361 return getAddExpr(getSMinExpr(LS
, RS
), LDiff
);
5364 case ICmpInst::ICMP_ULT
:
5365 case ICmpInst::ICMP_ULE
:
5366 std::swap(LHS
, RHS
);
5368 case ICmpInst::ICMP_UGT
:
5369 case ICmpInst::ICMP_UGE
:
5370 // a >u b ? a+x : b+x -> umax(a, b)+x
5371 // a >u b ? b+x : a+x -> umin(a, b)+x
5372 if (getTypeSizeInBits(LHS
->getType()) <= getTypeSizeInBits(I
->getType())) {
5373 const SCEV
*LS
= getNoopOrZeroExtend(getSCEV(LHS
), I
->getType());
5374 const SCEV
*RS
= getNoopOrZeroExtend(getSCEV(RHS
), I
->getType());
5375 const SCEV
*LA
= getSCEV(TrueVal
);
5376 const SCEV
*RA
= getSCEV(FalseVal
);
5377 const SCEV
*LDiff
= getMinusSCEV(LA
, LS
);
5378 const SCEV
*RDiff
= getMinusSCEV(RA
, RS
);
5380 return getAddExpr(getUMaxExpr(LS
, RS
), LDiff
);
5381 LDiff
= getMinusSCEV(LA
, RS
);
5382 RDiff
= getMinusSCEV(RA
, LS
);
5384 return getAddExpr(getUMinExpr(LS
, RS
), LDiff
);
5387 case ICmpInst::ICMP_NE
:
5388 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
5389 if (getTypeSizeInBits(LHS
->getType()) <= getTypeSizeInBits(I
->getType()) &&
5390 isa
<ConstantInt
>(RHS
) && cast
<ConstantInt
>(RHS
)->isZero()) {
5391 const SCEV
*One
= getOne(I
->getType());
5392 const SCEV
*LS
= getNoopOrZeroExtend(getSCEV(LHS
), I
->getType());
5393 const SCEV
*LA
= getSCEV(TrueVal
);
5394 const SCEV
*RA
= getSCEV(FalseVal
);
5395 const SCEV
*LDiff
= getMinusSCEV(LA
, LS
);
5396 const SCEV
*RDiff
= getMinusSCEV(RA
, One
);
5398 return getAddExpr(getUMaxExpr(One
, LS
), LDiff
);
5401 case ICmpInst::ICMP_EQ
:
5402 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
5403 if (getTypeSizeInBits(LHS
->getType()) <= getTypeSizeInBits(I
->getType()) &&
5404 isa
<ConstantInt
>(RHS
) && cast
<ConstantInt
>(RHS
)->isZero()) {
5405 const SCEV
*One
= getOne(I
->getType());
5406 const SCEV
*LS
= getNoopOrZeroExtend(getSCEV(LHS
), I
->getType());
5407 const SCEV
*LA
= getSCEV(TrueVal
);
5408 const SCEV
*RA
= getSCEV(FalseVal
);
5409 const SCEV
*LDiff
= getMinusSCEV(LA
, One
);
5410 const SCEV
*RDiff
= getMinusSCEV(RA
, LS
);
5412 return getAddExpr(getUMaxExpr(One
, LS
), LDiff
);
5419 return getUnknown(I
);
5422 /// Expand GEP instructions into add and multiply operations. This allows them
5423 /// to be analyzed by regular SCEV code.
5424 const SCEV
*ScalarEvolution::createNodeForGEP(GEPOperator
*GEP
) {
5425 // Don't attempt to analyze GEPs over unsized objects.
5426 if (!GEP
->getSourceElementType()->isSized())
5427 return getUnknown(GEP
);
5429 SmallVector
<const SCEV
*, 4> IndexExprs
;
5430 for (auto Index
= GEP
->idx_begin(); Index
!= GEP
->idx_end(); ++Index
)
5431 IndexExprs
.push_back(getSCEV(*Index
));
5432 return getGEPExpr(GEP
, IndexExprs
);
5435 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV
*S
) {
5436 if (const SCEVConstant
*C
= dyn_cast
<SCEVConstant
>(S
))
5437 return C
->getAPInt().countTrailingZeros();
5439 if (const SCEVTruncateExpr
*T
= dyn_cast
<SCEVTruncateExpr
>(S
))
5440 return std::min(GetMinTrailingZeros(T
->getOperand()),
5441 (uint32_t)getTypeSizeInBits(T
->getType()));
5443 if (const SCEVZeroExtendExpr
*E
= dyn_cast
<SCEVZeroExtendExpr
>(S
)) {
5444 uint32_t OpRes
= GetMinTrailingZeros(E
->getOperand());
5445 return OpRes
== getTypeSizeInBits(E
->getOperand()->getType())
5446 ? getTypeSizeInBits(E
->getType())
5450 if (const SCEVSignExtendExpr
*E
= dyn_cast
<SCEVSignExtendExpr
>(S
)) {
5451 uint32_t OpRes
= GetMinTrailingZeros(E
->getOperand());
5452 return OpRes
== getTypeSizeInBits(E
->getOperand()->getType())
5453 ? getTypeSizeInBits(E
->getType())
5457 if (const SCEVAddExpr
*A
= dyn_cast
<SCEVAddExpr
>(S
)) {
5458 // The result is the min of all operands results.
5459 uint32_t MinOpRes
= GetMinTrailingZeros(A
->getOperand(0));
5460 for (unsigned i
= 1, e
= A
->getNumOperands(); MinOpRes
&& i
!= e
; ++i
)
5461 MinOpRes
= std::min(MinOpRes
, GetMinTrailingZeros(A
->getOperand(i
)));
5465 if (const SCEVMulExpr
*M
= dyn_cast
<SCEVMulExpr
>(S
)) {
5466 // The result is the sum of all operands results.
5467 uint32_t SumOpRes
= GetMinTrailingZeros(M
->getOperand(0));
5468 uint32_t BitWidth
= getTypeSizeInBits(M
->getType());
5469 for (unsigned i
= 1, e
= M
->getNumOperands();
5470 SumOpRes
!= BitWidth
&& i
!= e
; ++i
)
5472 std::min(SumOpRes
+ GetMinTrailingZeros(M
->getOperand(i
)), BitWidth
);
5476 if (const SCEVAddRecExpr
*A
= dyn_cast
<SCEVAddRecExpr
>(S
)) {
5477 // The result is the min of all operands results.
5478 uint32_t MinOpRes
= GetMinTrailingZeros(A
->getOperand(0));
5479 for (unsigned i
= 1, e
= A
->getNumOperands(); MinOpRes
&& i
!= e
; ++i
)
5480 MinOpRes
= std::min(MinOpRes
, GetMinTrailingZeros(A
->getOperand(i
)));
5484 if (const SCEVSMaxExpr
*M
= dyn_cast
<SCEVSMaxExpr
>(S
)) {
5485 // The result is the min of all operands results.
5486 uint32_t MinOpRes
= GetMinTrailingZeros(M
->getOperand(0));
5487 for (unsigned i
= 1, e
= M
->getNumOperands(); MinOpRes
&& i
!= e
; ++i
)
5488 MinOpRes
= std::min(MinOpRes
, GetMinTrailingZeros(M
->getOperand(i
)));
5492 if (const SCEVUMaxExpr
*M
= dyn_cast
<SCEVUMaxExpr
>(S
)) {
5493 // The result is the min of all operands results.
5494 uint32_t MinOpRes
= GetMinTrailingZeros(M
->getOperand(0));
5495 for (unsigned i
= 1, e
= M
->getNumOperands(); MinOpRes
&& i
!= e
; ++i
)
5496 MinOpRes
= std::min(MinOpRes
, GetMinTrailingZeros(M
->getOperand(i
)));
5500 if (const SCEVUnknown
*U
= dyn_cast
<SCEVUnknown
>(S
)) {
5501 // For a SCEVUnknown, ask ValueTracking.
5502 KnownBits Known
= computeKnownBits(U
->getValue(), getDataLayout(), 0, &AC
, nullptr, &DT
);
5503 return Known
.countMinTrailingZeros();
5510 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV
*S
) {
5511 auto I
= MinTrailingZerosCache
.find(S
);
5512 if (I
!= MinTrailingZerosCache
.end())
5515 uint32_t Result
= GetMinTrailingZerosImpl(S
);
5516 auto InsertPair
= MinTrailingZerosCache
.insert({S
, Result
});
5517 assert(InsertPair
.second
&& "Should insert a new key");
5518 return InsertPair
.first
->second
;
5521 /// Helper method to assign a range to V from metadata present in the IR.
5522 static Optional
<ConstantRange
> GetRangeFromMetadata(Value
*V
) {
5523 if (Instruction
*I
= dyn_cast
<Instruction
>(V
))
5524 if (MDNode
*MD
= I
->getMetadata(LLVMContext::MD_range
))
5525 return getConstantRangeFromMetadata(*MD
);
5530 /// Determine the range for a particular SCEV. If SignHint is
5531 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5532 /// with a "cleaner" unsigned (resp. signed) representation.
5533 const ConstantRange
&
5534 ScalarEvolution::getRangeRef(const SCEV
*S
,
5535 ScalarEvolution::RangeSignHint SignHint
) {
5536 DenseMap
<const SCEV
*, ConstantRange
> &Cache
=
5537 SignHint
== ScalarEvolution::HINT_RANGE_UNSIGNED
? UnsignedRanges
5539 ConstantRange::PreferredRangeType RangeType
=
5540 SignHint
== ScalarEvolution::HINT_RANGE_UNSIGNED
5541 ? ConstantRange::Unsigned
: ConstantRange::Signed
;
5543 // See if we've computed this range already.
5544 DenseMap
<const SCEV
*, ConstantRange
>::iterator I
= Cache
.find(S
);
5545 if (I
!= Cache
.end())
5548 if (const SCEVConstant
*C
= dyn_cast
<SCEVConstant
>(S
))
5549 return setRange(C
, SignHint
, ConstantRange(C
->getAPInt()));
5551 unsigned BitWidth
= getTypeSizeInBits(S
->getType());
5552 ConstantRange
ConservativeResult(BitWidth
, /*isFullSet=*/true);
5554 // If the value has known zeros, the maximum value will have those known zeros
5556 uint32_t TZ
= GetMinTrailingZeros(S
);
5558 if (SignHint
== ScalarEvolution::HINT_RANGE_UNSIGNED
)
5559 ConservativeResult
=
5560 ConstantRange(APInt::getMinValue(BitWidth
),
5561 APInt::getMaxValue(BitWidth
).lshr(TZ
).shl(TZ
) + 1);
5563 ConservativeResult
= ConstantRange(
5564 APInt::getSignedMinValue(BitWidth
),
5565 APInt::getSignedMaxValue(BitWidth
).ashr(TZ
).shl(TZ
) + 1);
5568 if (const SCEVAddExpr
*Add
= dyn_cast
<SCEVAddExpr
>(S
)) {
5569 ConstantRange X
= getRangeRef(Add
->getOperand(0), SignHint
);
5570 for (unsigned i
= 1, e
= Add
->getNumOperands(); i
!= e
; ++i
)
5571 X
= X
.add(getRangeRef(Add
->getOperand(i
), SignHint
));
5572 return setRange(Add
, SignHint
,
5573 ConservativeResult
.intersectWith(X
, RangeType
));
5576 if (const SCEVMulExpr
*Mul
= dyn_cast
<SCEVMulExpr
>(S
)) {
5577 ConstantRange X
= getRangeRef(Mul
->getOperand(0), SignHint
);
5578 for (unsigned i
= 1, e
= Mul
->getNumOperands(); i
!= e
; ++i
)
5579 X
= X
.multiply(getRangeRef(Mul
->getOperand(i
), SignHint
));
5580 return setRange(Mul
, SignHint
,
5581 ConservativeResult
.intersectWith(X
, RangeType
));
5584 if (const SCEVSMaxExpr
*SMax
= dyn_cast
<SCEVSMaxExpr
>(S
)) {
5585 ConstantRange X
= getRangeRef(SMax
->getOperand(0), SignHint
);
5586 for (unsigned i
= 1, e
= SMax
->getNumOperands(); i
!= e
; ++i
)
5587 X
= X
.smax(getRangeRef(SMax
->getOperand(i
), SignHint
));
5588 return setRange(SMax
, SignHint
,
5589 ConservativeResult
.intersectWith(X
, RangeType
));
5592 if (const SCEVUMaxExpr
*UMax
= dyn_cast
<SCEVUMaxExpr
>(S
)) {
5593 ConstantRange X
= getRangeRef(UMax
->getOperand(0), SignHint
);
5594 for (unsigned i
= 1, e
= UMax
->getNumOperands(); i
!= e
; ++i
)
5595 X
= X
.umax(getRangeRef(UMax
->getOperand(i
), SignHint
));
5596 return setRange(UMax
, SignHint
,
5597 ConservativeResult
.intersectWith(X
, RangeType
));
5600 if (const SCEVSMinExpr
*SMin
= dyn_cast
<SCEVSMinExpr
>(S
)) {
5601 ConstantRange X
= getRangeRef(SMin
->getOperand(0), SignHint
);
5602 for (unsigned i
= 1, e
= SMin
->getNumOperands(); i
!= e
; ++i
)
5603 X
= X
.smin(getRangeRef(SMin
->getOperand(i
), SignHint
));
5604 return setRange(SMin
, SignHint
,
5605 ConservativeResult
.intersectWith(X
, RangeType
));
5608 if (const SCEVUMinExpr
*UMin
= dyn_cast
<SCEVUMinExpr
>(S
)) {
5609 ConstantRange X
= getRangeRef(UMin
->getOperand(0), SignHint
);
5610 for (unsigned i
= 1, e
= UMin
->getNumOperands(); i
!= e
; ++i
)
5611 X
= X
.umin(getRangeRef(UMin
->getOperand(i
), SignHint
));
5612 return setRange(UMin
, SignHint
,
5613 ConservativeResult
.intersectWith(X
, RangeType
));
5616 if (const SCEVUDivExpr
*UDiv
= dyn_cast
<SCEVUDivExpr
>(S
)) {
5617 ConstantRange X
= getRangeRef(UDiv
->getLHS(), SignHint
);
5618 ConstantRange Y
= getRangeRef(UDiv
->getRHS(), SignHint
);
5619 return setRange(UDiv
, SignHint
,
5620 ConservativeResult
.intersectWith(X
.udiv(Y
), RangeType
));
5623 if (const SCEVZeroExtendExpr
*ZExt
= dyn_cast
<SCEVZeroExtendExpr
>(S
)) {
5624 ConstantRange X
= getRangeRef(ZExt
->getOperand(), SignHint
);
5625 return setRange(ZExt
, SignHint
,
5626 ConservativeResult
.intersectWith(X
.zeroExtend(BitWidth
),
5630 if (const SCEVSignExtendExpr
*SExt
= dyn_cast
<SCEVSignExtendExpr
>(S
)) {
5631 ConstantRange X
= getRangeRef(SExt
->getOperand(), SignHint
);
5632 return setRange(SExt
, SignHint
,
5633 ConservativeResult
.intersectWith(X
.signExtend(BitWidth
),
5637 if (const SCEVTruncateExpr
*Trunc
= dyn_cast
<SCEVTruncateExpr
>(S
)) {
5638 ConstantRange X
= getRangeRef(Trunc
->getOperand(), SignHint
);
5639 return setRange(Trunc
, SignHint
,
5640 ConservativeResult
.intersectWith(X
.truncate(BitWidth
),
5644 if (const SCEVAddRecExpr
*AddRec
= dyn_cast
<SCEVAddRecExpr
>(S
)) {
5645 // If there's no unsigned wrap, the value will never be less than its
5647 if (AddRec
->hasNoUnsignedWrap())
5648 if (const SCEVConstant
*C
= dyn_cast
<SCEVConstant
>(AddRec
->getStart()))
5649 if (!C
->getValue()->isZero())
5650 ConservativeResult
= ConservativeResult
.intersectWith(
5651 ConstantRange(C
->getAPInt(), APInt(BitWidth
, 0)), RangeType
);
5653 // If there's no signed wrap, and all the operands have the same sign or
5654 // zero, the value won't ever change sign.
5655 if (AddRec
->hasNoSignedWrap()) {
5656 bool AllNonNeg
= true;
5657 bool AllNonPos
= true;
5658 for (unsigned i
= 0, e
= AddRec
->getNumOperands(); i
!= e
; ++i
) {
5659 if (!isKnownNonNegative(AddRec
->getOperand(i
))) AllNonNeg
= false;
5660 if (!isKnownNonPositive(AddRec
->getOperand(i
))) AllNonPos
= false;
5663 ConservativeResult
= ConservativeResult
.intersectWith(
5664 ConstantRange(APInt(BitWidth
, 0),
5665 APInt::getSignedMinValue(BitWidth
)), RangeType
);
5667 ConservativeResult
= ConservativeResult
.intersectWith(
5668 ConstantRange(APInt::getSignedMinValue(BitWidth
),
5669 APInt(BitWidth
, 1)), RangeType
);
5672 // TODO: non-affine addrec
5673 if (AddRec
->isAffine()) {
5674 const SCEV
*MaxBECount
= getConstantMaxBackedgeTakenCount(AddRec
->getLoop());
5675 if (!isa
<SCEVCouldNotCompute
>(MaxBECount
) &&
5676 getTypeSizeInBits(MaxBECount
->getType()) <= BitWidth
) {
5677 auto RangeFromAffine
= getRangeForAffineAR(
5678 AddRec
->getStart(), AddRec
->getStepRecurrence(*this), MaxBECount
,
5680 if (!RangeFromAffine
.isFullSet())
5681 ConservativeResult
=
5682 ConservativeResult
.intersectWith(RangeFromAffine
, RangeType
);
5684 auto RangeFromFactoring
= getRangeViaFactoring(
5685 AddRec
->getStart(), AddRec
->getStepRecurrence(*this), MaxBECount
,
5687 if (!RangeFromFactoring
.isFullSet())
5688 ConservativeResult
=
5689 ConservativeResult
.intersectWith(RangeFromFactoring
, RangeType
);
5693 return setRange(AddRec
, SignHint
, std::move(ConservativeResult
));
5696 if (const SCEVUnknown
*U
= dyn_cast
<SCEVUnknown
>(S
)) {
5697 // Check if the IR explicitly contains !range metadata.
5698 Optional
<ConstantRange
> MDRange
= GetRangeFromMetadata(U
->getValue());
5699 if (MDRange
.hasValue())
5700 ConservativeResult
= ConservativeResult
.intersectWith(MDRange
.getValue(),
5703 // Split here to avoid paying the compile-time cost of calling both
5704 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted
5706 const DataLayout
&DL
= getDataLayout();
5707 if (SignHint
== ScalarEvolution::HINT_RANGE_UNSIGNED
) {
5708 // For a SCEVUnknown, ask ValueTracking.
5709 KnownBits Known
= computeKnownBits(U
->getValue(), DL
, 0, &AC
, nullptr, &DT
);
5710 if (Known
.One
!= ~Known
.Zero
+ 1)
5711 ConservativeResult
=
5712 ConservativeResult
.intersectWith(
5713 ConstantRange(Known
.One
, ~Known
.Zero
+ 1), RangeType
);
5715 assert(SignHint
== ScalarEvolution::HINT_RANGE_SIGNED
&&
5716 "generalize as needed!");
5717 unsigned NS
= ComputeNumSignBits(U
->getValue(), DL
, 0, &AC
, nullptr, &DT
);
5719 ConservativeResult
= ConservativeResult
.intersectWith(
5720 ConstantRange(APInt::getSignedMinValue(BitWidth
).ashr(NS
- 1),
5721 APInt::getSignedMaxValue(BitWidth
).ashr(NS
- 1) + 1),
5725 // A range of Phi is a subset of union of all ranges of its input.
5726 if (const PHINode
*Phi
= dyn_cast
<PHINode
>(U
->getValue())) {
5727 // Make sure that we do not run over cycled Phis.
5728 if (PendingPhiRanges
.insert(Phi
).second
) {
5729 ConstantRange
RangeFromOps(BitWidth
, /*isFullSet=*/false);
5730 for (auto &Op
: Phi
->operands()) {
5731 auto OpRange
= getRangeRef(getSCEV(Op
), SignHint
);
5732 RangeFromOps
= RangeFromOps
.unionWith(OpRange
);
5733 // No point to continue if we already have a full set.
5734 if (RangeFromOps
.isFullSet())
5737 ConservativeResult
=
5738 ConservativeResult
.intersectWith(RangeFromOps
, RangeType
);
5739 bool Erased
= PendingPhiRanges
.erase(Phi
);
5740 assert(Erased
&& "Failed to erase Phi properly?");
5745 return setRange(U
, SignHint
, std::move(ConservativeResult
));
5748 return setRange(S
, SignHint
, std::move(ConservativeResult
));
5751 // Given a StartRange, Step and MaxBECount for an expression compute a range of
5752 // values that the expression can take. Initially, the expression has a value
5753 // from StartRange and then is changed by Step up to MaxBECount times. Signed
5754 // argument defines if we treat Step as signed or unsigned.
5755 static ConstantRange
getRangeForAffineARHelper(APInt Step
,
5756 const ConstantRange
&StartRange
,
5757 const APInt
&MaxBECount
,
5758 unsigned BitWidth
, bool Signed
) {
5759 // If either Step or MaxBECount is 0, then the expression won't change, and we
5760 // just need to return the initial range.
5761 if (Step
== 0 || MaxBECount
== 0)
5764 // If we don't know anything about the initial value (i.e. StartRange is
5765 // FullRange), then we don't know anything about the final range either.
5766 // Return FullRange.
5767 if (StartRange
.isFullSet())
5768 return ConstantRange::getFull(BitWidth
);
5770 // If Step is signed and negative, then we use its absolute value, but we also
5771 // note that we're moving in the opposite direction.
5772 bool Descending
= Signed
&& Step
.isNegative();
5775 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
5776 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
5777 // This equations hold true due to the well-defined wrap-around behavior of
5781 // Check if Offset is more than full span of BitWidth. If it is, the
5782 // expression is guaranteed to overflow.
5783 if (APInt::getMaxValue(StartRange
.getBitWidth()).udiv(Step
).ult(MaxBECount
))
5784 return ConstantRange::getFull(BitWidth
);
5786 // Offset is by how much the expression can change. Checks above guarantee no
5788 APInt Offset
= Step
* MaxBECount
;
5790 // Minimum value of the final range will match the minimal value of StartRange
5791 // if the expression is increasing and will be decreased by Offset otherwise.
5792 // Maximum value of the final range will match the maximal value of StartRange
5793 // if the expression is decreasing and will be increased by Offset otherwise.
5794 APInt StartLower
= StartRange
.getLower();
5795 APInt StartUpper
= StartRange
.getUpper() - 1;
5796 APInt MovedBoundary
= Descending
? (StartLower
- std::move(Offset
))
5797 : (StartUpper
+ std::move(Offset
));
5799 // It's possible that the new minimum/maximum value will fall into the initial
5800 // range (due to wrap around). This means that the expression can take any
5801 // value in this bitwidth, and we have to return full range.
5802 if (StartRange
.contains(MovedBoundary
))
5803 return ConstantRange::getFull(BitWidth
);
5806 Descending
? std::move(MovedBoundary
) : std::move(StartLower
);
5808 Descending
? std::move(StartUpper
) : std::move(MovedBoundary
);
5811 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
5812 return ConstantRange::getNonEmpty(std::move(NewLower
), std::move(NewUpper
));
5815 ConstantRange
ScalarEvolution::getRangeForAffineAR(const SCEV
*Start
,
5817 const SCEV
*MaxBECount
,
5818 unsigned BitWidth
) {
5819 assert(!isa
<SCEVCouldNotCompute
>(MaxBECount
) &&
5820 getTypeSizeInBits(MaxBECount
->getType()) <= BitWidth
&&
5823 MaxBECount
= getNoopOrZeroExtend(MaxBECount
, Start
->getType());
5824 APInt MaxBECountValue
= getUnsignedRangeMax(MaxBECount
);
5826 // First, consider step signed.
5827 ConstantRange StartSRange
= getSignedRange(Start
);
5828 ConstantRange StepSRange
= getSignedRange(Step
);
5830 // If Step can be both positive and negative, we need to find ranges for the
5831 // maximum absolute step values in both directions and union them.
5833 getRangeForAffineARHelper(StepSRange
.getSignedMin(), StartSRange
,
5834 MaxBECountValue
, BitWidth
, /* Signed = */ true);
5835 SR
= SR
.unionWith(getRangeForAffineARHelper(StepSRange
.getSignedMax(),
5836 StartSRange
, MaxBECountValue
,
5837 BitWidth
, /* Signed = */ true));
5839 // Next, consider step unsigned.
5840 ConstantRange UR
= getRangeForAffineARHelper(
5841 getUnsignedRangeMax(Step
), getUnsignedRange(Start
),
5842 MaxBECountValue
, BitWidth
, /* Signed = */ false);
5844 // Finally, intersect signed and unsigned ranges.
5845 return SR
.intersectWith(UR
, ConstantRange::Smallest
);
5848 ConstantRange
ScalarEvolution::getRangeViaFactoring(const SCEV
*Start
,
5850 const SCEV
*MaxBECount
,
5851 unsigned BitWidth
) {
5852 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
5853 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
5855 struct SelectPattern
{
5856 Value
*Condition
= nullptr;
5860 explicit SelectPattern(ScalarEvolution
&SE
, unsigned BitWidth
,
5862 Optional
<unsigned> CastOp
;
5863 APInt
Offset(BitWidth
, 0);
5865 assert(SE
.getTypeSizeInBits(S
->getType()) == BitWidth
&&
5868 // Peel off a constant offset:
5869 if (auto *SA
= dyn_cast
<SCEVAddExpr
>(S
)) {
5870 // In the future we could consider being smarter here and handle
5871 // {Start+Step,+,Step} too.
5872 if (SA
->getNumOperands() != 2 || !isa
<SCEVConstant
>(SA
->getOperand(0)))
5875 Offset
= cast
<SCEVConstant
>(SA
->getOperand(0))->getAPInt();
5876 S
= SA
->getOperand(1);
5879 // Peel off a cast operation
5880 if (auto *SCast
= dyn_cast
<SCEVCastExpr
>(S
)) {
5881 CastOp
= SCast
->getSCEVType();
5882 S
= SCast
->getOperand();
5885 using namespace llvm::PatternMatch
;
5887 auto *SU
= dyn_cast
<SCEVUnknown
>(S
);
5888 const APInt
*TrueVal
, *FalseVal
;
5890 !match(SU
->getValue(), m_Select(m_Value(Condition
), m_APInt(TrueVal
),
5891 m_APInt(FalseVal
)))) {
5892 Condition
= nullptr;
5896 TrueValue
= *TrueVal
;
5897 FalseValue
= *FalseVal
;
5899 // Re-apply the cast we peeled off earlier
5900 if (CastOp
.hasValue())
5903 llvm_unreachable("Unknown SCEV cast type!");
5906 TrueValue
= TrueValue
.trunc(BitWidth
);
5907 FalseValue
= FalseValue
.trunc(BitWidth
);
5910 TrueValue
= TrueValue
.zext(BitWidth
);
5911 FalseValue
= FalseValue
.zext(BitWidth
);
5914 TrueValue
= TrueValue
.sext(BitWidth
);
5915 FalseValue
= FalseValue
.sext(BitWidth
);
5919 // Re-apply the constant offset we peeled off earlier
5920 TrueValue
+= Offset
;
5921 FalseValue
+= Offset
;
5924 bool isRecognized() { return Condition
!= nullptr; }
5927 SelectPattern
StartPattern(*this, BitWidth
, Start
);
5928 if (!StartPattern
.isRecognized())
5929 return ConstantRange::getFull(BitWidth
);
5931 SelectPattern
StepPattern(*this, BitWidth
, Step
);
5932 if (!StepPattern
.isRecognized())
5933 return ConstantRange::getFull(BitWidth
);
5935 if (StartPattern
.Condition
!= StepPattern
.Condition
) {
5936 // We don't handle this case today; but we could, by considering four
5937 // possibilities below instead of two. I'm not sure if there are cases where
5938 // that will help over what getRange already does, though.
5939 return ConstantRange::getFull(BitWidth
);
5942 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
5943 // construct arbitrary general SCEV expressions here. This function is called
5944 // from deep in the call stack, and calling getSCEV (on a sext instruction,
5945 // say) can end up caching a suboptimal value.
5947 // FIXME: without the explicit `this` receiver below, MSVC errors out with
5948 // C2352 and C2512 (otherwise it isn't needed).
5950 const SCEV
*TrueStart
= this->getConstant(StartPattern
.TrueValue
);
5951 const SCEV
*TrueStep
= this->getConstant(StepPattern
.TrueValue
);
5952 const SCEV
*FalseStart
= this->getConstant(StartPattern
.FalseValue
);
5953 const SCEV
*FalseStep
= this->getConstant(StepPattern
.FalseValue
);
5955 ConstantRange TrueRange
=
5956 this->getRangeForAffineAR(TrueStart
, TrueStep
, MaxBECount
, BitWidth
);
5957 ConstantRange FalseRange
=
5958 this->getRangeForAffineAR(FalseStart
, FalseStep
, MaxBECount
, BitWidth
);
5960 return TrueRange
.unionWith(FalseRange
);
5963 SCEV::NoWrapFlags
ScalarEvolution::getNoWrapFlagsFromUB(const Value
*V
) {
5964 if (isa
<ConstantExpr
>(V
)) return SCEV::FlagAnyWrap
;
5965 const BinaryOperator
*BinOp
= cast
<BinaryOperator
>(V
);
5967 // Return early if there are no flags to propagate to the SCEV.
5968 SCEV::NoWrapFlags Flags
= SCEV::FlagAnyWrap
;
5969 if (BinOp
->hasNoUnsignedWrap())
5970 Flags
= ScalarEvolution::setFlags(Flags
, SCEV::FlagNUW
);
5971 if (BinOp
->hasNoSignedWrap())
5972 Flags
= ScalarEvolution::setFlags(Flags
, SCEV::FlagNSW
);
5973 if (Flags
== SCEV::FlagAnyWrap
)
5974 return SCEV::FlagAnyWrap
;
5976 return isSCEVExprNeverPoison(BinOp
) ? Flags
: SCEV::FlagAnyWrap
;
5979 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction
*I
) {
5980 // Here we check that I is in the header of the innermost loop containing I,
5981 // since we only deal with instructions in the loop header. The actual loop we
5982 // need to check later will come from an add recurrence, but getting that
5983 // requires computing the SCEV of the operands, which can be expensive. This
5984 // check we can do cheaply to rule out some cases early.
5985 Loop
*InnermostContainingLoop
= LI
.getLoopFor(I
->getParent());
5986 if (InnermostContainingLoop
== nullptr ||
5987 InnermostContainingLoop
->getHeader() != I
->getParent())
5990 // Only proceed if we can prove that I does not yield poison.
5991 if (!programUndefinedIfFullPoison(I
))
5994 // At this point we know that if I is executed, then it does not wrap
5995 // according to at least one of NSW or NUW. If I is not executed, then we do
5996 // not know if the calculation that I represents would wrap. Multiple
5997 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
5998 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
5999 // derived from other instructions that map to the same SCEV. We cannot make
6000 // that guarantee for cases where I is not executed. So we need to find the
6001 // loop that I is considered in relation to and prove that I is executed for
6002 // every iteration of that loop. That implies that the value that I
6003 // calculates does not wrap anywhere in the loop, so then we can apply the
6004 // flags to the SCEV.
6006 // We check isLoopInvariant to disambiguate in case we are adding recurrences
6007 // from different loops, so that we know which loop to prove that I is
6009 for (unsigned OpIndex
= 0; OpIndex
< I
->getNumOperands(); ++OpIndex
) {
6010 // I could be an extractvalue from a call to an overflow intrinsic.
6011 // TODO: We can do better here in some cases.
6012 if (!isSCEVable(I
->getOperand(OpIndex
)->getType()))
6014 const SCEV
*Op
= getSCEV(I
->getOperand(OpIndex
));
6015 if (auto *AddRec
= dyn_cast
<SCEVAddRecExpr
>(Op
)) {
6016 bool AllOtherOpsLoopInvariant
= true;
6017 for (unsigned OtherOpIndex
= 0; OtherOpIndex
< I
->getNumOperands();
6019 if (OtherOpIndex
!= OpIndex
) {
6020 const SCEV
*OtherOp
= getSCEV(I
->getOperand(OtherOpIndex
));
6021 if (!isLoopInvariant(OtherOp
, AddRec
->getLoop())) {
6022 AllOtherOpsLoopInvariant
= false;
6027 if (AllOtherOpsLoopInvariant
&&
6028 isGuaranteedToExecuteForEveryIteration(I
, AddRec
->getLoop()))
6035 bool ScalarEvolution::isAddRecNeverPoison(const Instruction
*I
, const Loop
*L
) {
6036 // If we know that \c I can never be poison period, then that's enough.
6037 if (isSCEVExprNeverPoison(I
))
6040 // For an add recurrence specifically, we assume that infinite loops without
6041 // side effects are undefined behavior, and then reason as follows:
6043 // If the add recurrence is poison in any iteration, it is poison on all
6044 // future iterations (since incrementing poison yields poison). If the result
6045 // of the add recurrence is fed into the loop latch condition and the loop
6046 // does not contain any throws or exiting blocks other than the latch, we now
6047 // have the ability to "choose" whether the backedge is taken or not (by
6048 // choosing a sufficiently evil value for the poison feeding into the branch)
6049 // for every iteration including and after the one in which \p I first became
6050 // poison. There are two possibilities (let's call the iteration in which \p
6051 // I first became poison as K):
6053 // 1. In the set of iterations including and after K, the loop body executes
6054 // no side effects. In this case executing the backege an infinte number
6055 // of times will yield undefined behavior.
6057 // 2. In the set of iterations including and after K, the loop body executes
6058 // at least one side effect. In this case, that specific instance of side
6059 // effect is control dependent on poison, which also yields undefined
6062 auto *ExitingBB
= L
->getExitingBlock();
6063 auto *LatchBB
= L
->getLoopLatch();
6064 if (!ExitingBB
|| !LatchBB
|| ExitingBB
!= LatchBB
)
6067 SmallPtrSet
<const Instruction
*, 16> Pushed
;
6068 SmallVector
<const Instruction
*, 8> PoisonStack
;
6070 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
6071 // things that are known to be fully poison under that assumption go on the
6074 PoisonStack
.push_back(I
);
6076 bool LatchControlDependentOnPoison
= false;
6077 while (!PoisonStack
.empty() && !LatchControlDependentOnPoison
) {
6078 const Instruction
*Poison
= PoisonStack
.pop_back_val();
6080 for (auto *PoisonUser
: Poison
->users()) {
6081 if (propagatesFullPoison(cast
<Instruction
>(PoisonUser
))) {
6082 if (Pushed
.insert(cast
<Instruction
>(PoisonUser
)).second
)
6083 PoisonStack
.push_back(cast
<Instruction
>(PoisonUser
));
6084 } else if (auto *BI
= dyn_cast
<BranchInst
>(PoisonUser
)) {
6085 assert(BI
->isConditional() && "Only possibility!");
6086 if (BI
->getParent() == LatchBB
) {
6087 LatchControlDependentOnPoison
= true;
6094 return LatchControlDependentOnPoison
&& loopHasNoAbnormalExits(L
);
6097 ScalarEvolution::LoopProperties
6098 ScalarEvolution::getLoopProperties(const Loop
*L
) {
6099 using LoopProperties
= ScalarEvolution::LoopProperties
;
6101 auto Itr
= LoopPropertiesCache
.find(L
);
6102 if (Itr
== LoopPropertiesCache
.end()) {
6103 auto HasSideEffects
= [](Instruction
*I
) {
6104 if (auto *SI
= dyn_cast
<StoreInst
>(I
))
6105 return !SI
->isSimple();
6107 return I
->mayHaveSideEffects();
6110 LoopProperties LP
= {/* HasNoAbnormalExits */ true,
6111 /*HasNoSideEffects*/ true};
6113 for (auto *BB
: L
->getBlocks())
6114 for (auto &I
: *BB
) {
6115 if (!isGuaranteedToTransferExecutionToSuccessor(&I
))
6116 LP
.HasNoAbnormalExits
= false;
6117 if (HasSideEffects(&I
))
6118 LP
.HasNoSideEffects
= false;
6119 if (!LP
.HasNoAbnormalExits
&& !LP
.HasNoSideEffects
)
6120 break; // We're already as pessimistic as we can get.
6123 auto InsertPair
= LoopPropertiesCache
.insert({L
, LP
});
6124 assert(InsertPair
.second
&& "We just checked!");
6125 Itr
= InsertPair
.first
;
6131 const SCEV
*ScalarEvolution::createSCEV(Value
*V
) {
6132 if (!isSCEVable(V
->getType()))
6133 return getUnknown(V
);
6135 if (Instruction
*I
= dyn_cast
<Instruction
>(V
)) {
6136 // Don't attempt to analyze instructions in blocks that aren't
6137 // reachable. Such instructions don't matter, and they aren't required
6138 // to obey basic rules for definitions dominating uses which this
6139 // analysis depends on.
6140 if (!DT
.isReachableFromEntry(I
->getParent()))
6141 return getUnknown(UndefValue::get(V
->getType()));
6142 } else if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(V
))
6143 return getConstant(CI
);
6144 else if (isa
<ConstantPointerNull
>(V
))
6145 return getZero(V
->getType());
6146 else if (GlobalAlias
*GA
= dyn_cast
<GlobalAlias
>(V
))
6147 return GA
->isInterposable() ? getUnknown(V
) : getSCEV(GA
->getAliasee());
6148 else if (!isa
<ConstantExpr
>(V
))
6149 return getUnknown(V
);
6151 Operator
*U
= cast
<Operator
>(V
);
6152 if (auto BO
= MatchBinaryOp(U
, DT
)) {
6153 switch (BO
->Opcode
) {
6154 case Instruction::Add
: {
6155 // The simple thing to do would be to just call getSCEV on both operands
6156 // and call getAddExpr with the result. However if we're looking at a
6157 // bunch of things all added together, this can be quite inefficient,
6158 // because it leads to N-1 getAddExpr calls for N ultimate operands.
6159 // Instead, gather up all the operands and make a single getAddExpr call.
6160 // LLVM IR canonical form means we need only traverse the left operands.
6161 SmallVector
<const SCEV
*, 4> AddOps
;
6164 if (auto *OpSCEV
= getExistingSCEV(BO
->Op
)) {
6165 AddOps
.push_back(OpSCEV
);
6169 // If a NUW or NSW flag can be applied to the SCEV for this
6170 // addition, then compute the SCEV for this addition by itself
6171 // with a separate call to getAddExpr. We need to do that
6172 // instead of pushing the operands of the addition onto AddOps,
6173 // since the flags are only known to apply to this particular
6174 // addition - they may not apply to other additions that can be
6175 // formed with operands from AddOps.
6176 const SCEV
*RHS
= getSCEV(BO
->RHS
);
6177 SCEV::NoWrapFlags Flags
= getNoWrapFlagsFromUB(BO
->Op
);
6178 if (Flags
!= SCEV::FlagAnyWrap
) {
6179 const SCEV
*LHS
= getSCEV(BO
->LHS
);
6180 if (BO
->Opcode
== Instruction::Sub
)
6181 AddOps
.push_back(getMinusSCEV(LHS
, RHS
, Flags
));
6183 AddOps
.push_back(getAddExpr(LHS
, RHS
, Flags
));
6188 if (BO
->Opcode
== Instruction::Sub
)
6189 AddOps
.push_back(getNegativeSCEV(getSCEV(BO
->RHS
)));
6191 AddOps
.push_back(getSCEV(BO
->RHS
));
6193 auto NewBO
= MatchBinaryOp(BO
->LHS
, DT
);
6194 if (!NewBO
|| (NewBO
->Opcode
!= Instruction::Add
&&
6195 NewBO
->Opcode
!= Instruction::Sub
)) {
6196 AddOps
.push_back(getSCEV(BO
->LHS
));
6202 return getAddExpr(AddOps
);
6205 case Instruction::Mul
: {
6206 SmallVector
<const SCEV
*, 4> MulOps
;
6209 if (auto *OpSCEV
= getExistingSCEV(BO
->Op
)) {
6210 MulOps
.push_back(OpSCEV
);
6214 SCEV::NoWrapFlags Flags
= getNoWrapFlagsFromUB(BO
->Op
);
6215 if (Flags
!= SCEV::FlagAnyWrap
) {
6217 getMulExpr(getSCEV(BO
->LHS
), getSCEV(BO
->RHS
), Flags
));
6222 MulOps
.push_back(getSCEV(BO
->RHS
));
6223 auto NewBO
= MatchBinaryOp(BO
->LHS
, DT
);
6224 if (!NewBO
|| NewBO
->Opcode
!= Instruction::Mul
) {
6225 MulOps
.push_back(getSCEV(BO
->LHS
));
6231 return getMulExpr(MulOps
);
6233 case Instruction::UDiv
:
6234 return getUDivExpr(getSCEV(BO
->LHS
), getSCEV(BO
->RHS
));
6235 case Instruction::URem
:
6236 return getURemExpr(getSCEV(BO
->LHS
), getSCEV(BO
->RHS
));
6237 case Instruction::Sub
: {
6238 SCEV::NoWrapFlags Flags
= SCEV::FlagAnyWrap
;
6240 Flags
= getNoWrapFlagsFromUB(BO
->Op
);
6241 return getMinusSCEV(getSCEV(BO
->LHS
), getSCEV(BO
->RHS
), Flags
);
6243 case Instruction::And
:
6244 // For an expression like x&255 that merely masks off the high bits,
6245 // use zext(trunc(x)) as the SCEV expression.
6246 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(BO
->RHS
)) {
6248 return getSCEV(BO
->RHS
);
6249 if (CI
->isMinusOne())
6250 return getSCEV(BO
->LHS
);
6251 const APInt
&A
= CI
->getValue();
6253 // Instcombine's ShrinkDemandedConstant may strip bits out of
6254 // constants, obscuring what would otherwise be a low-bits mask.
6255 // Use computeKnownBits to compute what ShrinkDemandedConstant
6256 // knew about to reconstruct a low-bits mask value.
6257 unsigned LZ
= A
.countLeadingZeros();
6258 unsigned TZ
= A
.countTrailingZeros();
6259 unsigned BitWidth
= A
.getBitWidth();
6260 KnownBits
Known(BitWidth
);
6261 computeKnownBits(BO
->LHS
, Known
, getDataLayout(),
6262 0, &AC
, nullptr, &DT
);
6264 APInt EffectiveMask
=
6265 APInt::getLowBitsSet(BitWidth
, BitWidth
- LZ
- TZ
).shl(TZ
);
6266 if ((LZ
!= 0 || TZ
!= 0) && !((~A
& ~Known
.Zero
) & EffectiveMask
)) {
6267 const SCEV
*MulCount
= getConstant(APInt::getOneBitSet(BitWidth
, TZ
));
6268 const SCEV
*LHS
= getSCEV(BO
->LHS
);
6269 const SCEV
*ShiftedLHS
= nullptr;
6270 if (auto *LHSMul
= dyn_cast
<SCEVMulExpr
>(LHS
)) {
6271 if (auto *OpC
= dyn_cast
<SCEVConstant
>(LHSMul
->getOperand(0))) {
6272 // For an expression like (x * 8) & 8, simplify the multiply.
6273 unsigned MulZeros
= OpC
->getAPInt().countTrailingZeros();
6274 unsigned GCD
= std::min(MulZeros
, TZ
);
6275 APInt DivAmt
= APInt::getOneBitSet(BitWidth
, TZ
- GCD
);
6276 SmallVector
<const SCEV
*, 4> MulOps
;
6277 MulOps
.push_back(getConstant(OpC
->getAPInt().lshr(GCD
)));
6278 MulOps
.append(LHSMul
->op_begin() + 1, LHSMul
->op_end());
6279 auto *NewMul
= getMulExpr(MulOps
, LHSMul
->getNoWrapFlags());
6280 ShiftedLHS
= getUDivExpr(NewMul
, getConstant(DivAmt
));
6284 ShiftedLHS
= getUDivExpr(LHS
, MulCount
);
6287 getTruncateExpr(ShiftedLHS
,
6288 IntegerType::get(getContext(), BitWidth
- LZ
- TZ
)),
6289 BO
->LHS
->getType()),
6295 case Instruction::Or
:
6296 // If the RHS of the Or is a constant, we may have something like:
6297 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
6298 // optimizations will transparently handle this case.
6300 // In order for this transformation to be safe, the LHS must be of the
6301 // form X*(2^n) and the Or constant must be less than 2^n.
6302 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(BO
->RHS
)) {
6303 const SCEV
*LHS
= getSCEV(BO
->LHS
);
6304 const APInt
&CIVal
= CI
->getValue();
6305 if (GetMinTrailingZeros(LHS
) >=
6306 (CIVal
.getBitWidth() - CIVal
.countLeadingZeros())) {
6307 // Build a plain add SCEV.
6308 const SCEV
*S
= getAddExpr(LHS
, getSCEV(CI
));
6309 // If the LHS of the add was an addrec and it has no-wrap flags,
6310 // transfer the no-wrap flags, since an or won't introduce a wrap.
6311 if (const SCEVAddRecExpr
*NewAR
= dyn_cast
<SCEVAddRecExpr
>(S
)) {
6312 const SCEVAddRecExpr
*OldAR
= cast
<SCEVAddRecExpr
>(LHS
);
6313 const_cast<SCEVAddRecExpr
*>(NewAR
)->setNoWrapFlags(
6314 OldAR
->getNoWrapFlags());
6321 case Instruction::Xor
:
6322 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(BO
->RHS
)) {
6323 // If the RHS of xor is -1, then this is a not operation.
6324 if (CI
->isMinusOne())
6325 return getNotSCEV(getSCEV(BO
->LHS
));
6327 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
6328 // This is a variant of the check for xor with -1, and it handles
6329 // the case where instcombine has trimmed non-demanded bits out
6330 // of an xor with -1.
6331 if (auto *LBO
= dyn_cast
<BinaryOperator
>(BO
->LHS
))
6332 if (ConstantInt
*LCI
= dyn_cast
<ConstantInt
>(LBO
->getOperand(1)))
6333 if (LBO
->getOpcode() == Instruction::And
&&
6334 LCI
->getValue() == CI
->getValue())
6335 if (const SCEVZeroExtendExpr
*Z
=
6336 dyn_cast
<SCEVZeroExtendExpr
>(getSCEV(BO
->LHS
))) {
6337 Type
*UTy
= BO
->LHS
->getType();
6338 const SCEV
*Z0
= Z
->getOperand();
6339 Type
*Z0Ty
= Z0
->getType();
6340 unsigned Z0TySize
= getTypeSizeInBits(Z0Ty
);
6342 // If C is a low-bits mask, the zero extend is serving to
6343 // mask off the high bits. Complement the operand and
6344 // re-apply the zext.
6345 if (CI
->getValue().isMask(Z0TySize
))
6346 return getZeroExtendExpr(getNotSCEV(Z0
), UTy
);
6348 // If C is a single bit, it may be in the sign-bit position
6349 // before the zero-extend. In this case, represent the xor
6350 // using an add, which is equivalent, and re-apply the zext.
6351 APInt Trunc
= CI
->getValue().trunc(Z0TySize
);
6352 if (Trunc
.zext(getTypeSizeInBits(UTy
)) == CI
->getValue() &&
6354 return getZeroExtendExpr(getAddExpr(Z0
, getConstant(Trunc
)),
6360 case Instruction::Shl
:
6361 // Turn shift left of a constant amount into a multiply.
6362 if (ConstantInt
*SA
= dyn_cast
<ConstantInt
>(BO
->RHS
)) {
6363 uint32_t BitWidth
= cast
<IntegerType
>(SA
->getType())->getBitWidth();
6365 // If the shift count is not less than the bitwidth, the result of
6366 // the shift is undefined. Don't try to analyze it, because the
6367 // resolution chosen here may differ from the resolution chosen in
6368 // other parts of the compiler.
6369 if (SA
->getValue().uge(BitWidth
))
6372 // It is currently not resolved how to interpret NSW for left
6373 // shift by BitWidth - 1, so we avoid applying flags in that
6374 // case. Remove this check (or this comment) once the situation
6376 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
6377 // and http://reviews.llvm.org/D8890 .
6378 auto Flags
= SCEV::FlagAnyWrap
;
6379 if (BO
->Op
&& SA
->getValue().ult(BitWidth
- 1))
6380 Flags
= getNoWrapFlagsFromUB(BO
->Op
);
6382 Constant
*X
= ConstantInt::get(
6383 getContext(), APInt::getOneBitSet(BitWidth
, SA
->getZExtValue()));
6384 return getMulExpr(getSCEV(BO
->LHS
), getSCEV(X
), Flags
);
6388 case Instruction::AShr
: {
6389 // AShr X, C, where C is a constant.
6390 ConstantInt
*CI
= dyn_cast
<ConstantInt
>(BO
->RHS
);
6394 Type
*OuterTy
= BO
->LHS
->getType();
6395 uint64_t BitWidth
= getTypeSizeInBits(OuterTy
);
6396 // If the shift count is not less than the bitwidth, the result of
6397 // the shift is undefined. Don't try to analyze it, because the
6398 // resolution chosen here may differ from the resolution chosen in
6399 // other parts of the compiler.
6400 if (CI
->getValue().uge(BitWidth
))
6404 return getSCEV(BO
->LHS
); // shift by zero --> noop
6406 uint64_t AShrAmt
= CI
->getZExtValue();
6407 Type
*TruncTy
= IntegerType::get(getContext(), BitWidth
- AShrAmt
);
6409 Operator
*L
= dyn_cast
<Operator
>(BO
->LHS
);
6410 if (L
&& L
->getOpcode() == Instruction::Shl
) {
6413 // Both n and m are constant.
6415 const SCEV
*ShlOp0SCEV
= getSCEV(L
->getOperand(0));
6416 if (L
->getOperand(1) == BO
->RHS
)
6417 // For a two-shift sext-inreg, i.e. n = m,
6418 // use sext(trunc(x)) as the SCEV expression.
6419 return getSignExtendExpr(
6420 getTruncateExpr(ShlOp0SCEV
, TruncTy
), OuterTy
);
6422 ConstantInt
*ShlAmtCI
= dyn_cast
<ConstantInt
>(L
->getOperand(1));
6423 if (ShlAmtCI
&& ShlAmtCI
->getValue().ult(BitWidth
)) {
6424 uint64_t ShlAmt
= ShlAmtCI
->getZExtValue();
6425 if (ShlAmt
> AShrAmt
) {
6426 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
6427 // expression. We already checked that ShlAmt < BitWidth, so
6428 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
6429 // ShlAmt - AShrAmt < Amt.
6430 APInt Mul
= APInt::getOneBitSet(BitWidth
- AShrAmt
,
6432 return getSignExtendExpr(
6433 getMulExpr(getTruncateExpr(ShlOp0SCEV
, TruncTy
),
6434 getConstant(Mul
)), OuterTy
);
6443 switch (U
->getOpcode()) {
6444 case Instruction::Trunc
:
6445 return getTruncateExpr(getSCEV(U
->getOperand(0)), U
->getType());
6447 case Instruction::ZExt
:
6448 return getZeroExtendExpr(getSCEV(U
->getOperand(0)), U
->getType());
6450 case Instruction::SExt
:
6451 if (auto BO
= MatchBinaryOp(U
->getOperand(0), DT
)) {
6452 // The NSW flag of a subtract does not always survive the conversion to
6453 // A + (-1)*B. By pushing sign extension onto its operands we are much
6454 // more likely to preserve NSW and allow later AddRec optimisations.
6456 // NOTE: This is effectively duplicating this logic from getSignExtend:
6457 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
6458 // but by that point the NSW information has potentially been lost.
6459 if (BO
->Opcode
== Instruction::Sub
&& BO
->IsNSW
) {
6460 Type
*Ty
= U
->getType();
6461 auto *V1
= getSignExtendExpr(getSCEV(BO
->LHS
), Ty
);
6462 auto *V2
= getSignExtendExpr(getSCEV(BO
->RHS
), Ty
);
6463 return getMinusSCEV(V1
, V2
, SCEV::FlagNSW
);
6466 return getSignExtendExpr(getSCEV(U
->getOperand(0)), U
->getType());
6468 case Instruction::BitCast
:
6469 // BitCasts are no-op casts so we just eliminate the cast.
6470 if (isSCEVable(U
->getType()) && isSCEVable(U
->getOperand(0)->getType()))
6471 return getSCEV(U
->getOperand(0));
6474 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
6475 // lead to pointer expressions which cannot safely be expanded to GEPs,
6476 // because ScalarEvolution doesn't respect the GEP aliasing rules when
6477 // simplifying integer expressions.
6479 case Instruction::GetElementPtr
:
6480 return createNodeForGEP(cast
<GEPOperator
>(U
));
6482 case Instruction::PHI
:
6483 return createNodeForPHI(cast
<PHINode
>(U
));
6485 case Instruction::Select
:
6486 // U can also be a select constant expr, which let fall through. Since
6487 // createNodeForSelect only works for a condition that is an `ICmpInst`, and
6488 // constant expressions cannot have instructions as operands, we'd have
6489 // returned getUnknown for a select constant expressions anyway.
6490 if (isa
<Instruction
>(U
))
6491 return createNodeForSelectOrPHI(cast
<Instruction
>(U
), U
->getOperand(0),
6492 U
->getOperand(1), U
->getOperand(2));
6495 case Instruction::Call
:
6496 case Instruction::Invoke
:
6497 if (Value
*RV
= CallSite(U
).getReturnedArgOperand())
6502 return getUnknown(V
);
6505 //===----------------------------------------------------------------------===//
6506 // Iteration Count Computation Code
6509 static unsigned getConstantTripCount(const SCEVConstant
*ExitCount
) {
6513 ConstantInt
*ExitConst
= ExitCount
->getValue();
6515 // Guard against huge trip counts.
6516 if (ExitConst
->getValue().getActiveBits() > 32)
6519 // In case of integer overflow, this returns 0, which is correct.
6520 return ((unsigned)ExitConst
->getZExtValue()) + 1;
6523 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop
*L
) {
6524 if (BasicBlock
*ExitingBB
= L
->getExitingBlock())
6525 return getSmallConstantTripCount(L
, ExitingBB
);
6527 // No trip count information for multiple exits.
6531 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop
*L
,
6532 BasicBlock
*ExitingBlock
) {
6533 assert(ExitingBlock
&& "Must pass a non-null exiting block!");
6534 assert(L
->isLoopExiting(ExitingBlock
) &&
6535 "Exiting block must actually branch out of the loop!");
6536 const SCEVConstant
*ExitCount
=
6537 dyn_cast
<SCEVConstant
>(getExitCount(L
, ExitingBlock
));
6538 return getConstantTripCount(ExitCount
);
6541 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop
*L
) {
6542 const auto *MaxExitCount
=
6543 dyn_cast
<SCEVConstant
>(getConstantMaxBackedgeTakenCount(L
));
6544 return getConstantTripCount(MaxExitCount
);
6547 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop
*L
) {
6548 if (BasicBlock
*ExitingBB
= L
->getExitingBlock())
6549 return getSmallConstantTripMultiple(L
, ExitingBB
);
6551 // No trip multiple information for multiple exits.
6555 /// Returns the largest constant divisor of the trip count of this loop as a
6556 /// normal unsigned value, if possible. This means that the actual trip count is
6557 /// always a multiple of the returned value (don't forget the trip count could
6558 /// very well be zero as well!).
6560 /// Returns 1 if the trip count is unknown or not guaranteed to be the
6561 /// multiple of a constant (which is also the case if the trip count is simply
6562 /// constant, use getSmallConstantTripCount for that case), Will also return 1
6563 /// if the trip count is very large (>= 2^32).
6565 /// As explained in the comments for getSmallConstantTripCount, this assumes
6566 /// that control exits the loop via ExitingBlock.
6568 ScalarEvolution::getSmallConstantTripMultiple(const Loop
*L
,
6569 BasicBlock
*ExitingBlock
) {
6570 assert(ExitingBlock
&& "Must pass a non-null exiting block!");
6571 assert(L
->isLoopExiting(ExitingBlock
) &&
6572 "Exiting block must actually branch out of the loop!");
6573 const SCEV
*ExitCount
= getExitCount(L
, ExitingBlock
);
6574 if (ExitCount
== getCouldNotCompute())
6577 // Get the trip count from the BE count by adding 1.
6578 const SCEV
*TCExpr
= getAddExpr(ExitCount
, getOne(ExitCount
->getType()));
6580 const SCEVConstant
*TC
= dyn_cast
<SCEVConstant
>(TCExpr
);
6582 // Attempt to factor more general cases. Returns the greatest power of
6583 // two divisor. If overflow happens, the trip count expression is still
6584 // divisible by the greatest power of 2 divisor returned.
6585 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr
));
6587 ConstantInt
*Result
= TC
->getValue();
6589 // Guard against huge trip counts (this requires checking
6590 // for zero to handle the case where the trip count == -1 and the
6592 if (!Result
|| Result
->getValue().getActiveBits() > 32 ||
6593 Result
->getValue().getActiveBits() == 0)
6596 return (unsigned)Result
->getZExtValue();
6599 /// Get the expression for the number of loop iterations for which this loop is
6600 /// guaranteed not to exit via ExitingBlock. Otherwise return
6601 /// SCEVCouldNotCompute.
6602 const SCEV
*ScalarEvolution::getExitCount(const Loop
*L
,
6603 BasicBlock
*ExitingBlock
) {
6604 return getBackedgeTakenInfo(L
).getExact(ExitingBlock
, this);
6608 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop
*L
,
6609 SCEVUnionPredicate
&Preds
) {
6610 return getPredicatedBackedgeTakenInfo(L
).getExact(L
, this, &Preds
);
6613 const SCEV
*ScalarEvolution::getBackedgeTakenCount(const Loop
*L
) {
6614 return getBackedgeTakenInfo(L
).getExact(L
, this);
6617 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is
6618 /// known never to be less than the actual backedge taken count.
6619 const SCEV
*ScalarEvolution::getConstantMaxBackedgeTakenCount(const Loop
*L
) {
6620 return getBackedgeTakenInfo(L
).getMax(this);
6623 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop
*L
) {
6624 return getBackedgeTakenInfo(L
).isMaxOrZero(this);
6627 /// Push PHI nodes in the header of the given loop onto the given Worklist.
6629 PushLoopPHIs(const Loop
*L
, SmallVectorImpl
<Instruction
*> &Worklist
) {
6630 BasicBlock
*Header
= L
->getHeader();
6632 // Push all Loop-header PHIs onto the Worklist stack.
6633 for (PHINode
&PN
: Header
->phis())
6634 Worklist
.push_back(&PN
);
6637 const ScalarEvolution::BackedgeTakenInfo
&
6638 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop
*L
) {
6639 auto &BTI
= getBackedgeTakenInfo(L
);
6640 if (BTI
.hasFullInfo())
6643 auto Pair
= PredicatedBackedgeTakenCounts
.insert({L
, BackedgeTakenInfo()});
6646 return Pair
.first
->second
;
6648 BackedgeTakenInfo Result
=
6649 computeBackedgeTakenCount(L
, /*AllowPredicates=*/true);
6651 return PredicatedBackedgeTakenCounts
.find(L
)->second
= std::move(Result
);
6654 const ScalarEvolution::BackedgeTakenInfo
&
6655 ScalarEvolution::getBackedgeTakenInfo(const Loop
*L
) {
6656 // Initially insert an invalid entry for this loop. If the insertion
6657 // succeeds, proceed to actually compute a backedge-taken count and
6658 // update the value. The temporary CouldNotCompute value tells SCEV
6659 // code elsewhere that it shouldn't attempt to request a new
6660 // backedge-taken count, which could result in infinite recursion.
6661 std::pair
<DenseMap
<const Loop
*, BackedgeTakenInfo
>::iterator
, bool> Pair
=
6662 BackedgeTakenCounts
.insert({L
, BackedgeTakenInfo()});
6664 return Pair
.first
->second
;
6666 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
6667 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
6668 // must be cleared in this scope.
6669 BackedgeTakenInfo Result
= computeBackedgeTakenCount(L
);
6671 // In product build, there are no usage of statistic.
6672 (void)NumTripCountsComputed
;
6673 (void)NumTripCountsNotComputed
;
6674 #if LLVM_ENABLE_STATS || !defined(NDEBUG)
6675 const SCEV
*BEExact
= Result
.getExact(L
, this);
6676 if (BEExact
!= getCouldNotCompute()) {
6677 assert(isLoopInvariant(BEExact
, L
) &&
6678 isLoopInvariant(Result
.getMax(this), L
) &&
6679 "Computed backedge-taken count isn't loop invariant for loop!");
6680 ++NumTripCountsComputed
;
6682 else if (Result
.getMax(this) == getCouldNotCompute() &&
6683 isa
<PHINode
>(L
->getHeader()->begin())) {
6684 // Only count loops that have phi nodes as not being computable.
6685 ++NumTripCountsNotComputed
;
6687 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
6689 // Now that we know more about the trip count for this loop, forget any
6690 // existing SCEV values for PHI nodes in this loop since they are only
6691 // conservative estimates made without the benefit of trip count
6692 // information. This is similar to the code in forgetLoop, except that
6693 // it handles SCEVUnknown PHI nodes specially.
6694 if (Result
.hasAnyInfo()) {
6695 SmallVector
<Instruction
*, 16> Worklist
;
6696 PushLoopPHIs(L
, Worklist
);
6698 SmallPtrSet
<Instruction
*, 8> Discovered
;
6699 while (!Worklist
.empty()) {
6700 Instruction
*I
= Worklist
.pop_back_val();
6702 ValueExprMapType::iterator It
=
6703 ValueExprMap
.find_as(static_cast<Value
*>(I
));
6704 if (It
!= ValueExprMap
.end()) {
6705 const SCEV
*Old
= It
->second
;
6707 // SCEVUnknown for a PHI either means that it has an unrecognized
6708 // structure, or it's a PHI that's in the progress of being computed
6709 // by createNodeForPHI. In the former case, additional loop trip
6710 // count information isn't going to change anything. In the later
6711 // case, createNodeForPHI will perform the necessary updates on its
6712 // own when it gets to that point.
6713 if (!isa
<PHINode
>(I
) || !isa
<SCEVUnknown
>(Old
)) {
6714 eraseValueFromMap(It
->first
);
6715 forgetMemoizedResults(Old
);
6717 if (PHINode
*PN
= dyn_cast
<PHINode
>(I
))
6718 ConstantEvolutionLoopExitValue
.erase(PN
);
6721 // Since we don't need to invalidate anything for correctness and we're
6722 // only invalidating to make SCEV's results more precise, we get to stop
6723 // early to avoid invalidating too much. This is especially important in
6726 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node
6734 // where both loop0 and loop1's backedge taken count uses the SCEV
6735 // expression for %v. If we don't have the early stop below then in cases
6736 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip
6737 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip
6738 // count for loop1, effectively nullifying SCEV's trip count cache.
6739 for (auto *U
: I
->users())
6740 if (auto *I
= dyn_cast
<Instruction
>(U
)) {
6741 auto *LoopForUser
= LI
.getLoopFor(I
->getParent());
6742 if (LoopForUser
&& L
->contains(LoopForUser
) &&
6743 Discovered
.insert(I
).second
)
6744 Worklist
.push_back(I
);
6749 // Re-lookup the insert position, since the call to
6750 // computeBackedgeTakenCount above could result in a
6751 // recusive call to getBackedgeTakenInfo (on a different
6752 // loop), which would invalidate the iterator computed
6754 return BackedgeTakenCounts
.find(L
)->second
= std::move(Result
);
6757 void ScalarEvolution::forgetAllLoops() {
6758 // This method is intended to forget all info about loops. It should
6759 // invalidate caches as if the following happened:
6760 // - The trip counts of all loops have changed arbitrarily
6761 // - Every llvm::Value has been updated in place to produce a different
6763 BackedgeTakenCounts
.clear();
6764 PredicatedBackedgeTakenCounts
.clear();
6765 LoopPropertiesCache
.clear();
6766 ConstantEvolutionLoopExitValue
.clear();
6767 ValueExprMap
.clear();
6768 ValuesAtScopes
.clear();
6769 LoopDispositions
.clear();
6770 BlockDispositions
.clear();
6771 UnsignedRanges
.clear();
6772 SignedRanges
.clear();
6773 ExprValueMap
.clear();
6775 MinTrailingZerosCache
.clear();
6776 PredicatedSCEVRewrites
.clear();
6779 void ScalarEvolution::forgetLoop(const Loop
*L
) {
6780 // Drop any stored trip count value.
6781 auto RemoveLoopFromBackedgeMap
=
6782 [](DenseMap
<const Loop
*, BackedgeTakenInfo
> &Map
, const Loop
*L
) {
6783 auto BTCPos
= Map
.find(L
);
6784 if (BTCPos
!= Map
.end()) {
6785 BTCPos
->second
.clear();
6790 SmallVector
<const Loop
*, 16> LoopWorklist(1, L
);
6791 SmallVector
<Instruction
*, 32> Worklist
;
6792 SmallPtrSet
<Instruction
*, 16> Visited
;
6794 // Iterate over all the loops and sub-loops to drop SCEV information.
6795 while (!LoopWorklist
.empty()) {
6796 auto *CurrL
= LoopWorklist
.pop_back_val();
6798 RemoveLoopFromBackedgeMap(BackedgeTakenCounts
, CurrL
);
6799 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts
, CurrL
);
6801 // Drop information about predicated SCEV rewrites for this loop.
6802 for (auto I
= PredicatedSCEVRewrites
.begin();
6803 I
!= PredicatedSCEVRewrites
.end();) {
6804 std::pair
<const SCEV
*, const Loop
*> Entry
= I
->first
;
6805 if (Entry
.second
== CurrL
)
6806 PredicatedSCEVRewrites
.erase(I
++);
6811 auto LoopUsersItr
= LoopUsers
.find(CurrL
);
6812 if (LoopUsersItr
!= LoopUsers
.end()) {
6813 for (auto *S
: LoopUsersItr
->second
)
6814 forgetMemoizedResults(S
);
6815 LoopUsers
.erase(LoopUsersItr
);
6818 // Drop information about expressions based on loop-header PHIs.
6819 PushLoopPHIs(CurrL
, Worklist
);
6821 while (!Worklist
.empty()) {
6822 Instruction
*I
= Worklist
.pop_back_val();
6823 if (!Visited
.insert(I
).second
)
6826 ValueExprMapType::iterator It
=
6827 ValueExprMap
.find_as(static_cast<Value
*>(I
));
6828 if (It
!= ValueExprMap
.end()) {
6829 eraseValueFromMap(It
->first
);
6830 forgetMemoizedResults(It
->second
);
6831 if (PHINode
*PN
= dyn_cast
<PHINode
>(I
))
6832 ConstantEvolutionLoopExitValue
.erase(PN
);
6835 PushDefUseChildren(I
, Worklist
);
6838 LoopPropertiesCache
.erase(CurrL
);
6839 // Forget all contained loops too, to avoid dangling entries in the
6840 // ValuesAtScopes map.
6841 LoopWorklist
.append(CurrL
->begin(), CurrL
->end());
6845 void ScalarEvolution::forgetTopmostLoop(const Loop
*L
) {
6846 while (Loop
*Parent
= L
->getParentLoop())
6851 void ScalarEvolution::forgetValue(Value
*V
) {
6852 Instruction
*I
= dyn_cast
<Instruction
>(V
);
6855 // Drop information about expressions based on loop-header PHIs.
6856 SmallVector
<Instruction
*, 16> Worklist
;
6857 Worklist
.push_back(I
);
6859 SmallPtrSet
<Instruction
*, 8> Visited
;
6860 while (!Worklist
.empty()) {
6861 I
= Worklist
.pop_back_val();
6862 if (!Visited
.insert(I
).second
)
6865 ValueExprMapType::iterator It
=
6866 ValueExprMap
.find_as(static_cast<Value
*>(I
));
6867 if (It
!= ValueExprMap
.end()) {
6868 eraseValueFromMap(It
->first
);
6869 forgetMemoizedResults(It
->second
);
6870 if (PHINode
*PN
= dyn_cast
<PHINode
>(I
))
6871 ConstantEvolutionLoopExitValue
.erase(PN
);
6874 PushDefUseChildren(I
, Worklist
);
6878 /// Get the exact loop backedge taken count considering all loop exits. A
6879 /// computable result can only be returned for loops with all exiting blocks
6880 /// dominating the latch. howFarToZero assumes that the limit of each loop test
6881 /// is never skipped. This is a valid assumption as long as the loop exits via
6882 /// that test. For precise results, it is the caller's responsibility to specify
6883 /// the relevant loop exiting block using getExact(ExitingBlock, SE).
6885 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop
*L
, ScalarEvolution
*SE
,
6886 SCEVUnionPredicate
*Preds
) const {
6887 // If any exits were not computable, the loop is not computable.
6888 if (!isComplete() || ExitNotTaken
.empty())
6889 return SE
->getCouldNotCompute();
6891 const BasicBlock
*Latch
= L
->getLoopLatch();
6892 // All exiting blocks we have collected must dominate the only backedge.
6894 return SE
->getCouldNotCompute();
6896 // All exiting blocks we have gathered dominate loop's latch, so exact trip
6897 // count is simply a minimum out of all these calculated exit counts.
6898 SmallVector
<const SCEV
*, 2> Ops
;
6899 for (auto &ENT
: ExitNotTaken
) {
6900 const SCEV
*BECount
= ENT
.ExactNotTaken
;
6901 assert(BECount
!= SE
->getCouldNotCompute() && "Bad exit SCEV!");
6902 assert(SE
->DT
.dominates(ENT
.ExitingBlock
, Latch
) &&
6903 "We should only have known counts for exiting blocks that dominate "
6906 Ops
.push_back(BECount
);
6908 if (Preds
&& !ENT
.hasAlwaysTruePredicate())
6909 Preds
->add(ENT
.Predicate
.get());
6911 assert((Preds
|| ENT
.hasAlwaysTruePredicate()) &&
6912 "Predicate should be always true!");
6915 return SE
->getUMinFromMismatchedTypes(Ops
);
6918 /// Get the exact not taken count for this loop exit.
6920 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock
*ExitingBlock
,
6921 ScalarEvolution
*SE
) const {
6922 for (auto &ENT
: ExitNotTaken
)
6923 if (ENT
.ExitingBlock
== ExitingBlock
&& ENT
.hasAlwaysTruePredicate())
6924 return ENT
.ExactNotTaken
;
6926 return SE
->getCouldNotCompute();
6929 /// getMax - Get the max backedge taken count for the loop.
6931 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution
*SE
) const {
6932 auto PredicateNotAlwaysTrue
= [](const ExitNotTakenInfo
&ENT
) {
6933 return !ENT
.hasAlwaysTruePredicate();
6936 if (any_of(ExitNotTaken
, PredicateNotAlwaysTrue
) || !getMax())
6937 return SE
->getCouldNotCompute();
6939 assert((isa
<SCEVCouldNotCompute
>(getMax()) || isa
<SCEVConstant
>(getMax())) &&
6940 "No point in having a non-constant max backedge taken count!");
6944 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution
*SE
) const {
6945 auto PredicateNotAlwaysTrue
= [](const ExitNotTakenInfo
&ENT
) {
6946 return !ENT
.hasAlwaysTruePredicate();
6948 return MaxOrZero
&& !any_of(ExitNotTaken
, PredicateNotAlwaysTrue
);
6951 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV
*S
,
6952 ScalarEvolution
*SE
) const {
6953 if (getMax() && getMax() != SE
->getCouldNotCompute() &&
6954 SE
->hasOperand(getMax(), S
))
6957 for (auto &ENT
: ExitNotTaken
)
6958 if (ENT
.ExactNotTaken
!= SE
->getCouldNotCompute() &&
6959 SE
->hasOperand(ENT
.ExactNotTaken
, S
))
6965 ScalarEvolution::ExitLimit::ExitLimit(const SCEV
*E
)
6966 : ExactNotTaken(E
), MaxNotTaken(E
) {
6967 assert((isa
<SCEVCouldNotCompute
>(MaxNotTaken
) ||
6968 isa
<SCEVConstant
>(MaxNotTaken
)) &&
6969 "No point in having a non-constant max backedge taken count!");
6972 ScalarEvolution::ExitLimit::ExitLimit(
6973 const SCEV
*E
, const SCEV
*M
, bool MaxOrZero
,
6974 ArrayRef
<const SmallPtrSetImpl
<const SCEVPredicate
*> *> PredSetList
)
6975 : ExactNotTaken(E
), MaxNotTaken(M
), MaxOrZero(MaxOrZero
) {
6976 assert((isa
<SCEVCouldNotCompute
>(ExactNotTaken
) ||
6977 !isa
<SCEVCouldNotCompute
>(MaxNotTaken
)) &&
6978 "Exact is not allowed to be less precise than Max");
6979 assert((isa
<SCEVCouldNotCompute
>(MaxNotTaken
) ||
6980 isa
<SCEVConstant
>(MaxNotTaken
)) &&
6981 "No point in having a non-constant max backedge taken count!");
6982 for (auto *PredSet
: PredSetList
)
6983 for (auto *P
: *PredSet
)
6987 ScalarEvolution::ExitLimit::ExitLimit(
6988 const SCEV
*E
, const SCEV
*M
, bool MaxOrZero
,
6989 const SmallPtrSetImpl
<const SCEVPredicate
*> &PredSet
)
6990 : ExitLimit(E
, M
, MaxOrZero
, {&PredSet
}) {
6991 assert((isa
<SCEVCouldNotCompute
>(MaxNotTaken
) ||
6992 isa
<SCEVConstant
>(MaxNotTaken
)) &&
6993 "No point in having a non-constant max backedge taken count!");
6996 ScalarEvolution::ExitLimit::ExitLimit(const SCEV
*E
, const SCEV
*M
,
6998 : ExitLimit(E
, M
, MaxOrZero
, None
) {
6999 assert((isa
<SCEVCouldNotCompute
>(MaxNotTaken
) ||
7000 isa
<SCEVConstant
>(MaxNotTaken
)) &&
7001 "No point in having a non-constant max backedge taken count!");
7004 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
7005 /// computable exit into a persistent ExitNotTakenInfo array.
7006 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
7007 ArrayRef
<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo
>
7009 bool Complete
, const SCEV
*MaxCount
, bool MaxOrZero
)
7010 : MaxAndComplete(MaxCount
, Complete
), MaxOrZero(MaxOrZero
) {
7011 using EdgeExitInfo
= ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo
;
7013 ExitNotTaken
.reserve(ExitCounts
.size());
7015 ExitCounts
.begin(), ExitCounts
.end(), std::back_inserter(ExitNotTaken
),
7016 [&](const EdgeExitInfo
&EEI
) {
7017 BasicBlock
*ExitBB
= EEI
.first
;
7018 const ExitLimit
&EL
= EEI
.second
;
7019 if (EL
.Predicates
.empty())
7020 return ExitNotTakenInfo(ExitBB
, EL
.ExactNotTaken
, nullptr);
7022 std::unique_ptr
<SCEVUnionPredicate
> Predicate(new SCEVUnionPredicate
);
7023 for (auto *Pred
: EL
.Predicates
)
7024 Predicate
->add(Pred
);
7026 return ExitNotTakenInfo(ExitBB
, EL
.ExactNotTaken
, std::move(Predicate
));
7028 assert((isa
<SCEVCouldNotCompute
>(MaxCount
) || isa
<SCEVConstant
>(MaxCount
)) &&
7029 "No point in having a non-constant max backedge taken count!");
7032 /// Invalidate this result and free the ExitNotTakenInfo array.
7033 void ScalarEvolution::BackedgeTakenInfo::clear() {
7034 ExitNotTaken
.clear();
7037 /// Compute the number of times the backedge of the specified loop will execute.
7038 ScalarEvolution::BackedgeTakenInfo
7039 ScalarEvolution::computeBackedgeTakenCount(const Loop
*L
,
7040 bool AllowPredicates
) {
7041 SmallVector
<BasicBlock
*, 8> ExitingBlocks
;
7042 L
->getExitingBlocks(ExitingBlocks
);
7044 using EdgeExitInfo
= ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo
;
7046 SmallVector
<EdgeExitInfo
, 4> ExitCounts
;
7047 bool CouldComputeBECount
= true;
7048 BasicBlock
*Latch
= L
->getLoopLatch(); // may be NULL.
7049 const SCEV
*MustExitMaxBECount
= nullptr;
7050 const SCEV
*MayExitMaxBECount
= nullptr;
7051 bool MustExitMaxOrZero
= false;
7053 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
7054 // and compute maxBECount.
7055 // Do a union of all the predicates here.
7056 for (unsigned i
= 0, e
= ExitingBlocks
.size(); i
!= e
; ++i
) {
7057 BasicBlock
*ExitBB
= ExitingBlocks
[i
];
7058 ExitLimit EL
= computeExitLimit(L
, ExitBB
, AllowPredicates
);
7060 assert((AllowPredicates
|| EL
.Predicates
.empty()) &&
7061 "Predicated exit limit when predicates are not allowed!");
7063 // 1. For each exit that can be computed, add an entry to ExitCounts.
7064 // CouldComputeBECount is true only if all exits can be computed.
7065 if (EL
.ExactNotTaken
== getCouldNotCompute())
7066 // We couldn't compute an exact value for this exit, so
7067 // we won't be able to compute an exact value for the loop.
7068 CouldComputeBECount
= false;
7070 ExitCounts
.emplace_back(ExitBB
, EL
);
7072 // 2. Derive the loop's MaxBECount from each exit's max number of
7073 // non-exiting iterations. Partition the loop exits into two kinds:
7074 // LoopMustExits and LoopMayExits.
7076 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
7077 // is a LoopMayExit. If any computable LoopMustExit is found, then
7078 // MaxBECount is the minimum EL.MaxNotTaken of computable
7079 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
7080 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
7081 // computable EL.MaxNotTaken.
7082 if (EL
.MaxNotTaken
!= getCouldNotCompute() && Latch
&&
7083 DT
.dominates(ExitBB
, Latch
)) {
7084 if (!MustExitMaxBECount
) {
7085 MustExitMaxBECount
= EL
.MaxNotTaken
;
7086 MustExitMaxOrZero
= EL
.MaxOrZero
;
7088 MustExitMaxBECount
=
7089 getUMinFromMismatchedTypes(MustExitMaxBECount
, EL
.MaxNotTaken
);
7091 } else if (MayExitMaxBECount
!= getCouldNotCompute()) {
7092 if (!MayExitMaxBECount
|| EL
.MaxNotTaken
== getCouldNotCompute())
7093 MayExitMaxBECount
= EL
.MaxNotTaken
;
7096 getUMaxFromMismatchedTypes(MayExitMaxBECount
, EL
.MaxNotTaken
);
7100 const SCEV
*MaxBECount
= MustExitMaxBECount
? MustExitMaxBECount
:
7101 (MayExitMaxBECount
? MayExitMaxBECount
: getCouldNotCompute());
7102 // The loop backedge will be taken the maximum or zero times if there's
7103 // a single exit that must be taken the maximum or zero times.
7104 bool MaxOrZero
= (MustExitMaxOrZero
&& ExitingBlocks
.size() == 1);
7105 return BackedgeTakenInfo(std::move(ExitCounts
), CouldComputeBECount
,
7106 MaxBECount
, MaxOrZero
);
7109 ScalarEvolution::ExitLimit
7110 ScalarEvolution::computeExitLimit(const Loop
*L
, BasicBlock
*ExitingBlock
,
7111 bool AllowPredicates
) {
7112 assert(L
->contains(ExitingBlock
) && "Exit count for non-loop block?");
7113 // If our exiting block does not dominate the latch, then its connection with
7114 // loop's exit limit may be far from trivial.
7115 const BasicBlock
*Latch
= L
->getLoopLatch();
7116 if (!Latch
|| !DT
.dominates(ExitingBlock
, Latch
))
7117 return getCouldNotCompute();
7119 bool IsOnlyExit
= (L
->getExitingBlock() != nullptr);
7120 Instruction
*Term
= ExitingBlock
->getTerminator();
7121 if (BranchInst
*BI
= dyn_cast
<BranchInst
>(Term
)) {
7122 assert(BI
->isConditional() && "If unconditional, it can't be in loop!");
7123 bool ExitIfTrue
= !L
->contains(BI
->getSuccessor(0));
7124 assert(ExitIfTrue
== L
->contains(BI
->getSuccessor(1)) &&
7125 "It should have one successor in loop and one exit block!");
7126 // Proceed to the next level to examine the exit condition expression.
7127 return computeExitLimitFromCond(
7128 L
, BI
->getCondition(), ExitIfTrue
,
7129 /*ControlsExit=*/IsOnlyExit
, AllowPredicates
);
7132 if (SwitchInst
*SI
= dyn_cast
<SwitchInst
>(Term
)) {
7133 // For switch, make sure that there is a single exit from the loop.
7134 BasicBlock
*Exit
= nullptr;
7135 for (auto *SBB
: successors(ExitingBlock
))
7136 if (!L
->contains(SBB
)) {
7137 if (Exit
) // Multiple exit successors.
7138 return getCouldNotCompute();
7141 assert(Exit
&& "Exiting block must have at least one exit");
7142 return computeExitLimitFromSingleExitSwitch(L
, SI
, Exit
,
7143 /*ControlsExit=*/IsOnlyExit
);
7146 return getCouldNotCompute();
7149 ScalarEvolution::ExitLimit
ScalarEvolution::computeExitLimitFromCond(
7150 const Loop
*L
, Value
*ExitCond
, bool ExitIfTrue
,
7151 bool ControlsExit
, bool AllowPredicates
) {
7152 ScalarEvolution::ExitLimitCacheTy
Cache(L
, ExitIfTrue
, AllowPredicates
);
7153 return computeExitLimitFromCondCached(Cache
, L
, ExitCond
, ExitIfTrue
,
7154 ControlsExit
, AllowPredicates
);
7157 Optional
<ScalarEvolution::ExitLimit
>
7158 ScalarEvolution::ExitLimitCache::find(const Loop
*L
, Value
*ExitCond
,
7159 bool ExitIfTrue
, bool ControlsExit
,
7160 bool AllowPredicates
) {
7162 (void)this->ExitIfTrue
;
7163 (void)this->AllowPredicates
;
7165 assert(this->L
== L
&& this->ExitIfTrue
== ExitIfTrue
&&
7166 this->AllowPredicates
== AllowPredicates
&&
7167 "Variance in assumed invariant key components!");
7168 auto Itr
= TripCountMap
.find({ExitCond
, ControlsExit
});
7169 if (Itr
== TripCountMap
.end())
7174 void ScalarEvolution::ExitLimitCache::insert(const Loop
*L
, Value
*ExitCond
,
7177 bool AllowPredicates
,
7178 const ExitLimit
&EL
) {
7179 assert(this->L
== L
&& this->ExitIfTrue
== ExitIfTrue
&&
7180 this->AllowPredicates
== AllowPredicates
&&
7181 "Variance in assumed invariant key components!");
7183 auto InsertResult
= TripCountMap
.insert({{ExitCond
, ControlsExit
}, EL
});
7184 assert(InsertResult
.second
&& "Expected successful insertion!");
7189 ScalarEvolution::ExitLimit
ScalarEvolution::computeExitLimitFromCondCached(
7190 ExitLimitCacheTy
&Cache
, const Loop
*L
, Value
*ExitCond
, bool ExitIfTrue
,
7191 bool ControlsExit
, bool AllowPredicates
) {
7194 Cache
.find(L
, ExitCond
, ExitIfTrue
, ControlsExit
, AllowPredicates
))
7197 ExitLimit EL
= computeExitLimitFromCondImpl(Cache
, L
, ExitCond
, ExitIfTrue
,
7198 ControlsExit
, AllowPredicates
);
7199 Cache
.insert(L
, ExitCond
, ExitIfTrue
, ControlsExit
, AllowPredicates
, EL
);
7203 ScalarEvolution::ExitLimit
ScalarEvolution::computeExitLimitFromCondImpl(
7204 ExitLimitCacheTy
&Cache
, const Loop
*L
, Value
*ExitCond
, bool ExitIfTrue
,
7205 bool ControlsExit
, bool AllowPredicates
) {
7206 // Check if the controlling expression for this loop is an And or Or.
7207 if (BinaryOperator
*BO
= dyn_cast
<BinaryOperator
>(ExitCond
)) {
7208 if (BO
->getOpcode() == Instruction::And
) {
7209 // Recurse on the operands of the and.
7210 bool EitherMayExit
= !ExitIfTrue
;
7211 ExitLimit EL0
= computeExitLimitFromCondCached(
7212 Cache
, L
, BO
->getOperand(0), ExitIfTrue
,
7213 ControlsExit
&& !EitherMayExit
, AllowPredicates
);
7214 ExitLimit EL1
= computeExitLimitFromCondCached(
7215 Cache
, L
, BO
->getOperand(1), ExitIfTrue
,
7216 ControlsExit
&& !EitherMayExit
, AllowPredicates
);
7217 const SCEV
*BECount
= getCouldNotCompute();
7218 const SCEV
*MaxBECount
= getCouldNotCompute();
7219 if (EitherMayExit
) {
7220 // Both conditions must be true for the loop to continue executing.
7221 // Choose the less conservative count.
7222 if (EL0
.ExactNotTaken
== getCouldNotCompute() ||
7223 EL1
.ExactNotTaken
== getCouldNotCompute())
7224 BECount
= getCouldNotCompute();
7227 getUMinFromMismatchedTypes(EL0
.ExactNotTaken
, EL1
.ExactNotTaken
);
7228 if (EL0
.MaxNotTaken
== getCouldNotCompute())
7229 MaxBECount
= EL1
.MaxNotTaken
;
7230 else if (EL1
.MaxNotTaken
== getCouldNotCompute())
7231 MaxBECount
= EL0
.MaxNotTaken
;
7234 getUMinFromMismatchedTypes(EL0
.MaxNotTaken
, EL1
.MaxNotTaken
);
7236 // Both conditions must be true at the same time for the loop to exit.
7237 // For now, be conservative.
7238 if (EL0
.MaxNotTaken
== EL1
.MaxNotTaken
)
7239 MaxBECount
= EL0
.MaxNotTaken
;
7240 if (EL0
.ExactNotTaken
== EL1
.ExactNotTaken
)
7241 BECount
= EL0
.ExactNotTaken
;
7244 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7245 // to be more aggressive when computing BECount than when computing
7246 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and
7247 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7249 if (isa
<SCEVCouldNotCompute
>(MaxBECount
) &&
7250 !isa
<SCEVCouldNotCompute
>(BECount
))
7251 MaxBECount
= getConstant(getUnsignedRangeMax(BECount
));
7253 return ExitLimit(BECount
, MaxBECount
, false,
7254 {&EL0
.Predicates
, &EL1
.Predicates
});
7256 if (BO
->getOpcode() == Instruction::Or
) {
7257 // Recurse on the operands of the or.
7258 bool EitherMayExit
= ExitIfTrue
;
7259 ExitLimit EL0
= computeExitLimitFromCondCached(
7260 Cache
, L
, BO
->getOperand(0), ExitIfTrue
,
7261 ControlsExit
&& !EitherMayExit
, AllowPredicates
);
7262 ExitLimit EL1
= computeExitLimitFromCondCached(
7263 Cache
, L
, BO
->getOperand(1), ExitIfTrue
,
7264 ControlsExit
&& !EitherMayExit
, AllowPredicates
);
7265 const SCEV
*BECount
= getCouldNotCompute();
7266 const SCEV
*MaxBECount
= getCouldNotCompute();
7267 if (EitherMayExit
) {
7268 // Both conditions must be false for the loop to continue executing.
7269 // Choose the less conservative count.
7270 if (EL0
.ExactNotTaken
== getCouldNotCompute() ||
7271 EL1
.ExactNotTaken
== getCouldNotCompute())
7272 BECount
= getCouldNotCompute();
7275 getUMinFromMismatchedTypes(EL0
.ExactNotTaken
, EL1
.ExactNotTaken
);
7276 if (EL0
.MaxNotTaken
== getCouldNotCompute())
7277 MaxBECount
= EL1
.MaxNotTaken
;
7278 else if (EL1
.MaxNotTaken
== getCouldNotCompute())
7279 MaxBECount
= EL0
.MaxNotTaken
;
7282 getUMinFromMismatchedTypes(EL0
.MaxNotTaken
, EL1
.MaxNotTaken
);
7284 // Both conditions must be false at the same time for the loop to exit.
7285 // For now, be conservative.
7286 if (EL0
.MaxNotTaken
== EL1
.MaxNotTaken
)
7287 MaxBECount
= EL0
.MaxNotTaken
;
7288 if (EL0
.ExactNotTaken
== EL1
.ExactNotTaken
)
7289 BECount
= EL0
.ExactNotTaken
;
7291 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7292 // to be more aggressive when computing BECount than when computing
7293 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and
7294 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7296 if (isa
<SCEVCouldNotCompute
>(MaxBECount
) &&
7297 !isa
<SCEVCouldNotCompute
>(BECount
))
7298 MaxBECount
= getConstant(getUnsignedRangeMax(BECount
));
7300 return ExitLimit(BECount
, MaxBECount
, false,
7301 {&EL0
.Predicates
, &EL1
.Predicates
});
7305 // With an icmp, it may be feasible to compute an exact backedge-taken count.
7306 // Proceed to the next level to examine the icmp.
7307 if (ICmpInst
*ExitCondICmp
= dyn_cast
<ICmpInst
>(ExitCond
)) {
7309 computeExitLimitFromICmp(L
, ExitCondICmp
, ExitIfTrue
, ControlsExit
);
7310 if (EL
.hasFullInfo() || !AllowPredicates
)
7313 // Try again, but use SCEV predicates this time.
7314 return computeExitLimitFromICmp(L
, ExitCondICmp
, ExitIfTrue
, ControlsExit
,
7315 /*AllowPredicates=*/true);
7318 // Check for a constant condition. These are normally stripped out by
7319 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
7320 // preserve the CFG and is temporarily leaving constant conditions
7322 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(ExitCond
)) {
7323 if (ExitIfTrue
== !CI
->getZExtValue())
7324 // The backedge is always taken.
7325 return getCouldNotCompute();
7327 // The backedge is never taken.
7328 return getZero(CI
->getType());
7331 // If it's not an integer or pointer comparison then compute it the hard way.
7332 return computeExitCountExhaustively(L
, ExitCond
, ExitIfTrue
);
7335 ScalarEvolution::ExitLimit
7336 ScalarEvolution::computeExitLimitFromICmp(const Loop
*L
,
7340 bool AllowPredicates
) {
7341 // If the condition was exit on true, convert the condition to exit on false
7342 ICmpInst::Predicate Pred
;
7344 Pred
= ExitCond
->getPredicate();
7346 Pred
= ExitCond
->getInversePredicate();
7347 const ICmpInst::Predicate OriginalPred
= Pred
;
7349 // Handle common loops like: for (X = "string"; *X; ++X)
7350 if (LoadInst
*LI
= dyn_cast
<LoadInst
>(ExitCond
->getOperand(0)))
7351 if (Constant
*RHS
= dyn_cast
<Constant
>(ExitCond
->getOperand(1))) {
7353 computeLoadConstantCompareExitLimit(LI
, RHS
, L
, Pred
);
7354 if (ItCnt
.hasAnyInfo())
7358 const SCEV
*LHS
= getSCEV(ExitCond
->getOperand(0));
7359 const SCEV
*RHS
= getSCEV(ExitCond
->getOperand(1));
7361 // Try to evaluate any dependencies out of the loop.
7362 LHS
= getSCEVAtScope(LHS
, L
);
7363 RHS
= getSCEVAtScope(RHS
, L
);
7365 // At this point, we would like to compute how many iterations of the
7366 // loop the predicate will return true for these inputs.
7367 if (isLoopInvariant(LHS
, L
) && !isLoopInvariant(RHS
, L
)) {
7368 // If there is a loop-invariant, force it into the RHS.
7369 std::swap(LHS
, RHS
);
7370 Pred
= ICmpInst::getSwappedPredicate(Pred
);
7373 // Simplify the operands before analyzing them.
7374 (void)SimplifyICmpOperands(Pred
, LHS
, RHS
);
7376 // If we have a comparison of a chrec against a constant, try to use value
7377 // ranges to answer this query.
7378 if (const SCEVConstant
*RHSC
= dyn_cast
<SCEVConstant
>(RHS
))
7379 if (const SCEVAddRecExpr
*AddRec
= dyn_cast
<SCEVAddRecExpr
>(LHS
))
7380 if (AddRec
->getLoop() == L
) {
7381 // Form the constant range.
7382 ConstantRange CompRange
=
7383 ConstantRange::makeExactICmpRegion(Pred
, RHSC
->getAPInt());
7385 const SCEV
*Ret
= AddRec
->getNumIterationsInRange(CompRange
, *this);
7386 if (!isa
<SCEVCouldNotCompute
>(Ret
)) return Ret
;
7390 case ICmpInst::ICMP_NE
: { // while (X != Y)
7391 // Convert to: while (X-Y != 0)
7392 ExitLimit EL
= howFarToZero(getMinusSCEV(LHS
, RHS
), L
, ControlsExit
,
7394 if (EL
.hasAnyInfo()) return EL
;
7397 case ICmpInst::ICMP_EQ
: { // while (X == Y)
7398 // Convert to: while (X-Y == 0)
7399 ExitLimit EL
= howFarToNonZero(getMinusSCEV(LHS
, RHS
), L
);
7400 if (EL
.hasAnyInfo()) return EL
;
7403 case ICmpInst::ICMP_SLT
:
7404 case ICmpInst::ICMP_ULT
: { // while (X < Y)
7405 bool IsSigned
= Pred
== ICmpInst::ICMP_SLT
;
7406 ExitLimit EL
= howManyLessThans(LHS
, RHS
, L
, IsSigned
, ControlsExit
,
7408 if (EL
.hasAnyInfo()) return EL
;
7411 case ICmpInst::ICMP_SGT
:
7412 case ICmpInst::ICMP_UGT
: { // while (X > Y)
7413 bool IsSigned
= Pred
== ICmpInst::ICMP_SGT
;
7415 howManyGreaterThans(LHS
, RHS
, L
, IsSigned
, ControlsExit
,
7417 if (EL
.hasAnyInfo()) return EL
;
7424 auto *ExhaustiveCount
=
7425 computeExitCountExhaustively(L
, ExitCond
, ExitIfTrue
);
7427 if (!isa
<SCEVCouldNotCompute
>(ExhaustiveCount
))
7428 return ExhaustiveCount
;
7430 return computeShiftCompareExitLimit(ExitCond
->getOperand(0),
7431 ExitCond
->getOperand(1), L
, OriginalPred
);
7434 ScalarEvolution::ExitLimit
7435 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop
*L
,
7437 BasicBlock
*ExitingBlock
,
7438 bool ControlsExit
) {
7439 assert(!L
->contains(ExitingBlock
) && "Not an exiting block!");
7441 // Give up if the exit is the default dest of a switch.
7442 if (Switch
->getDefaultDest() == ExitingBlock
)
7443 return getCouldNotCompute();
7445 assert(L
->contains(Switch
->getDefaultDest()) &&
7446 "Default case must not exit the loop!");
7447 const SCEV
*LHS
= getSCEVAtScope(Switch
->getCondition(), L
);
7448 const SCEV
*RHS
= getConstant(Switch
->findCaseDest(ExitingBlock
));
7450 // while (X != Y) --> while (X-Y != 0)
7451 ExitLimit EL
= howFarToZero(getMinusSCEV(LHS
, RHS
), L
, ControlsExit
);
7452 if (EL
.hasAnyInfo())
7455 return getCouldNotCompute();
7458 static ConstantInt
*
7459 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr
*AddRec
, ConstantInt
*C
,
7460 ScalarEvolution
&SE
) {
7461 const SCEV
*InVal
= SE
.getConstant(C
);
7462 const SCEV
*Val
= AddRec
->evaluateAtIteration(InVal
, SE
);
7463 assert(isa
<SCEVConstant
>(Val
) &&
7464 "Evaluation of SCEV at constant didn't fold correctly?");
7465 return cast
<SCEVConstant
>(Val
)->getValue();
7468 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
7469 /// compute the backedge execution count.
7470 ScalarEvolution::ExitLimit
7471 ScalarEvolution::computeLoadConstantCompareExitLimit(
7475 ICmpInst::Predicate predicate
) {
7476 if (LI
->isVolatile()) return getCouldNotCompute();
7478 // Check to see if the loaded pointer is a getelementptr of a global.
7479 // TODO: Use SCEV instead of manually grubbing with GEPs.
7480 GetElementPtrInst
*GEP
= dyn_cast
<GetElementPtrInst
>(LI
->getOperand(0));
7481 if (!GEP
) return getCouldNotCompute();
7483 // Make sure that it is really a constant global we are gepping, with an
7484 // initializer, and make sure the first IDX is really 0.
7485 GlobalVariable
*GV
= dyn_cast
<GlobalVariable
>(GEP
->getOperand(0));
7486 if (!GV
|| !GV
->isConstant() || !GV
->hasDefinitiveInitializer() ||
7487 GEP
->getNumOperands() < 3 || !isa
<Constant
>(GEP
->getOperand(1)) ||
7488 !cast
<Constant
>(GEP
->getOperand(1))->isNullValue())
7489 return getCouldNotCompute();
7491 // Okay, we allow one non-constant index into the GEP instruction.
7492 Value
*VarIdx
= nullptr;
7493 std::vector
<Constant
*> Indexes
;
7494 unsigned VarIdxNum
= 0;
7495 for (unsigned i
= 2, e
= GEP
->getNumOperands(); i
!= e
; ++i
)
7496 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(GEP
->getOperand(i
))) {
7497 Indexes
.push_back(CI
);
7498 } else if (!isa
<ConstantInt
>(GEP
->getOperand(i
))) {
7499 if (VarIdx
) return getCouldNotCompute(); // Multiple non-constant idx's.
7500 VarIdx
= GEP
->getOperand(i
);
7502 Indexes
.push_back(nullptr);
7505 // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
7507 return getCouldNotCompute();
7509 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
7510 // Check to see if X is a loop variant variable value now.
7511 const SCEV
*Idx
= getSCEV(VarIdx
);
7512 Idx
= getSCEVAtScope(Idx
, L
);
7514 // We can only recognize very limited forms of loop index expressions, in
7515 // particular, only affine AddRec's like {C1,+,C2}.
7516 const SCEVAddRecExpr
*IdxExpr
= dyn_cast
<SCEVAddRecExpr
>(Idx
);
7517 if (!IdxExpr
|| !IdxExpr
->isAffine() || isLoopInvariant(IdxExpr
, L
) ||
7518 !isa
<SCEVConstant
>(IdxExpr
->getOperand(0)) ||
7519 !isa
<SCEVConstant
>(IdxExpr
->getOperand(1)))
7520 return getCouldNotCompute();
7522 unsigned MaxSteps
= MaxBruteForceIterations
;
7523 for (unsigned IterationNum
= 0; IterationNum
!= MaxSteps
; ++IterationNum
) {
7524 ConstantInt
*ItCst
= ConstantInt::get(
7525 cast
<IntegerType
>(IdxExpr
->getType()), IterationNum
);
7526 ConstantInt
*Val
= EvaluateConstantChrecAtConstant(IdxExpr
, ItCst
, *this);
7528 // Form the GEP offset.
7529 Indexes
[VarIdxNum
] = Val
;
7531 Constant
*Result
= ConstantFoldLoadThroughGEPIndices(GV
->getInitializer(),
7533 if (!Result
) break; // Cannot compute!
7535 // Evaluate the condition for this iteration.
7536 Result
= ConstantExpr::getICmp(predicate
, Result
, RHS
);
7537 if (!isa
<ConstantInt
>(Result
)) break; // Couldn't decide for sure
7538 if (cast
<ConstantInt
>(Result
)->getValue().isMinValue()) {
7539 ++NumArrayLenItCounts
;
7540 return getConstant(ItCst
); // Found terminating iteration!
7543 return getCouldNotCompute();
7546 ScalarEvolution::ExitLimit
ScalarEvolution::computeShiftCompareExitLimit(
7547 Value
*LHS
, Value
*RHSV
, const Loop
*L
, ICmpInst::Predicate Pred
) {
7548 ConstantInt
*RHS
= dyn_cast
<ConstantInt
>(RHSV
);
7550 return getCouldNotCompute();
7552 const BasicBlock
*Latch
= L
->getLoopLatch();
7554 return getCouldNotCompute();
7556 const BasicBlock
*Predecessor
= L
->getLoopPredecessor();
7558 return getCouldNotCompute();
7560 // Return true if V is of the form "LHS `shift_op` <positive constant>".
7561 // Return LHS in OutLHS and shift_opt in OutOpCode.
7562 auto MatchPositiveShift
=
7563 [](Value
*V
, Value
*&OutLHS
, Instruction::BinaryOps
&OutOpCode
) {
7565 using namespace PatternMatch
;
7567 ConstantInt
*ShiftAmt
;
7568 if (match(V
, m_LShr(m_Value(OutLHS
), m_ConstantInt(ShiftAmt
))))
7569 OutOpCode
= Instruction::LShr
;
7570 else if (match(V
, m_AShr(m_Value(OutLHS
), m_ConstantInt(ShiftAmt
))))
7571 OutOpCode
= Instruction::AShr
;
7572 else if (match(V
, m_Shl(m_Value(OutLHS
), m_ConstantInt(ShiftAmt
))))
7573 OutOpCode
= Instruction::Shl
;
7577 return ShiftAmt
->getValue().isStrictlyPositive();
7580 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
7583 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
7584 // %iv.shifted = lshr i32 %iv, <positive constant>
7586 // Return true on a successful match. Return the corresponding PHI node (%iv
7587 // above) in PNOut and the opcode of the shift operation in OpCodeOut.
7588 auto MatchShiftRecurrence
=
7589 [&](Value
*V
, PHINode
*&PNOut
, Instruction::BinaryOps
&OpCodeOut
) {
7590 Optional
<Instruction::BinaryOps
> PostShiftOpCode
;
7593 Instruction::BinaryOps OpC
;
7596 // If we encounter a shift instruction, "peel off" the shift operation,
7597 // and remember that we did so. Later when we inspect %iv's backedge
7598 // value, we will make sure that the backedge value uses the same
7601 // Note: the peeled shift operation does not have to be the same
7602 // instruction as the one feeding into the PHI's backedge value. We only
7603 // really care about it being the same *kind* of shift instruction --
7604 // that's all that is required for our later inferences to hold.
7605 if (MatchPositiveShift(LHS
, V
, OpC
)) {
7606 PostShiftOpCode
= OpC
;
7611 PNOut
= dyn_cast
<PHINode
>(LHS
);
7612 if (!PNOut
|| PNOut
->getParent() != L
->getHeader())
7615 Value
*BEValue
= PNOut
->getIncomingValueForBlock(Latch
);
7619 // The backedge value for the PHI node must be a shift by a positive
7621 MatchPositiveShift(BEValue
, OpLHS
, OpCodeOut
) &&
7623 // of the PHI node itself
7626 // and the kind of shift should be match the kind of shift we peeled
7628 (!PostShiftOpCode
.hasValue() || *PostShiftOpCode
== OpCodeOut
);
7632 Instruction::BinaryOps OpCode
;
7633 if (!MatchShiftRecurrence(LHS
, PN
, OpCode
))
7634 return getCouldNotCompute();
7636 const DataLayout
&DL
= getDataLayout();
7638 // The key rationale for this optimization is that for some kinds of shift
7639 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
7640 // within a finite number of iterations. If the condition guarding the
7641 // backedge (in the sense that the backedge is taken if the condition is true)
7642 // is false for the value the shift recurrence stabilizes to, then we know
7643 // that the backedge is taken only a finite number of times.
7645 ConstantInt
*StableValue
= nullptr;
7648 llvm_unreachable("Impossible case!");
7650 case Instruction::AShr
: {
7651 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
7652 // bitwidth(K) iterations.
7653 Value
*FirstValue
= PN
->getIncomingValueForBlock(Predecessor
);
7654 KnownBits Known
= computeKnownBits(FirstValue
, DL
, 0, nullptr,
7655 Predecessor
->getTerminator(), &DT
);
7656 auto *Ty
= cast
<IntegerType
>(RHS
->getType());
7657 if (Known
.isNonNegative())
7658 StableValue
= ConstantInt::get(Ty
, 0);
7659 else if (Known
.isNegative())
7660 StableValue
= ConstantInt::get(Ty
, -1, true);
7662 return getCouldNotCompute();
7666 case Instruction::LShr
:
7667 case Instruction::Shl
:
7668 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
7669 // stabilize to 0 in at most bitwidth(K) iterations.
7670 StableValue
= ConstantInt::get(cast
<IntegerType
>(RHS
->getType()), 0);
7675 ConstantFoldCompareInstOperands(Pred
, StableValue
, RHS
, DL
, &TLI
);
7676 assert(Result
->getType()->isIntegerTy(1) &&
7677 "Otherwise cannot be an operand to a branch instruction");
7679 if (Result
->isZeroValue()) {
7680 unsigned BitWidth
= getTypeSizeInBits(RHS
->getType());
7681 const SCEV
*UpperBound
=
7682 getConstant(getEffectiveSCEVType(RHS
->getType()), BitWidth
);
7683 return ExitLimit(getCouldNotCompute(), UpperBound
, false);
7686 return getCouldNotCompute();
7689 /// Return true if we can constant fold an instruction of the specified type,
7690 /// assuming that all operands were constants.
7691 static bool CanConstantFold(const Instruction
*I
) {
7692 if (isa
<BinaryOperator
>(I
) || isa
<CmpInst
>(I
) ||
7693 isa
<SelectInst
>(I
) || isa
<CastInst
>(I
) || isa
<GetElementPtrInst
>(I
) ||
7694 isa
<LoadInst
>(I
) || isa
<ExtractValueInst
>(I
))
7697 if (const CallInst
*CI
= dyn_cast
<CallInst
>(I
))
7698 if (const Function
*F
= CI
->getCalledFunction())
7699 return canConstantFoldCallTo(CI
, F
);
7703 /// Determine whether this instruction can constant evolve within this loop
7704 /// assuming its operands can all constant evolve.
7705 static bool canConstantEvolve(Instruction
*I
, const Loop
*L
) {
7706 // An instruction outside of the loop can't be derived from a loop PHI.
7707 if (!L
->contains(I
)) return false;
7709 if (isa
<PHINode
>(I
)) {
7710 // We don't currently keep track of the control flow needed to evaluate
7711 // PHIs, so we cannot handle PHIs inside of loops.
7712 return L
->getHeader() == I
->getParent();
7715 // If we won't be able to constant fold this expression even if the operands
7716 // are constants, bail early.
7717 return CanConstantFold(I
);
7720 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
7721 /// recursing through each instruction operand until reaching a loop header phi.
7723 getConstantEvolvingPHIOperands(Instruction
*UseInst
, const Loop
*L
,
7724 DenseMap
<Instruction
*, PHINode
*> &PHIMap
,
7726 if (Depth
> MaxConstantEvolvingDepth
)
7729 // Otherwise, we can evaluate this instruction if all of its operands are
7730 // constant or derived from a PHI node themselves.
7731 PHINode
*PHI
= nullptr;
7732 for (Value
*Op
: UseInst
->operands()) {
7733 if (isa
<Constant
>(Op
)) continue;
7735 Instruction
*OpInst
= dyn_cast
<Instruction
>(Op
);
7736 if (!OpInst
|| !canConstantEvolve(OpInst
, L
)) return nullptr;
7738 PHINode
*P
= dyn_cast
<PHINode
>(OpInst
);
7740 // If this operand is already visited, reuse the prior result.
7741 // We may have P != PHI if this is the deepest point at which the
7742 // inconsistent paths meet.
7743 P
= PHIMap
.lookup(OpInst
);
7745 // Recurse and memoize the results, whether a phi is found or not.
7746 // This recursive call invalidates pointers into PHIMap.
7747 P
= getConstantEvolvingPHIOperands(OpInst
, L
, PHIMap
, Depth
+ 1);
7751 return nullptr; // Not evolving from PHI
7752 if (PHI
&& PHI
!= P
)
7753 return nullptr; // Evolving from multiple different PHIs.
7756 // This is a expression evolving from a constant PHI!
7760 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
7761 /// in the loop that V is derived from. We allow arbitrary operations along the
7762 /// way, but the operands of an operation must either be constants or a value
7763 /// derived from a constant PHI. If this expression does not fit with these
7764 /// constraints, return null.
7765 static PHINode
*getConstantEvolvingPHI(Value
*V
, const Loop
*L
) {
7766 Instruction
*I
= dyn_cast
<Instruction
>(V
);
7767 if (!I
|| !canConstantEvolve(I
, L
)) return nullptr;
7769 if (PHINode
*PN
= dyn_cast
<PHINode
>(I
))
7772 // Record non-constant instructions contained by the loop.
7773 DenseMap
<Instruction
*, PHINode
*> PHIMap
;
7774 return getConstantEvolvingPHIOperands(I
, L
, PHIMap
, 0);
7777 /// EvaluateExpression - Given an expression that passes the
7778 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
7779 /// in the loop has the value PHIVal. If we can't fold this expression for some
7780 /// reason, return null.
7781 static Constant
*EvaluateExpression(Value
*V
, const Loop
*L
,
7782 DenseMap
<Instruction
*, Constant
*> &Vals
,
7783 const DataLayout
&DL
,
7784 const TargetLibraryInfo
*TLI
) {
7785 // Convenient constant check, but redundant for recursive calls.
7786 if (Constant
*C
= dyn_cast
<Constant
>(V
)) return C
;
7787 Instruction
*I
= dyn_cast
<Instruction
>(V
);
7788 if (!I
) return nullptr;
7790 if (Constant
*C
= Vals
.lookup(I
)) return C
;
7792 // An instruction inside the loop depends on a value outside the loop that we
7793 // weren't given a mapping for, or a value such as a call inside the loop.
7794 if (!canConstantEvolve(I
, L
)) return nullptr;
7796 // An unmapped PHI can be due to a branch or another loop inside this loop,
7797 // or due to this not being the initial iteration through a loop where we
7798 // couldn't compute the evolution of this particular PHI last time.
7799 if (isa
<PHINode
>(I
)) return nullptr;
7801 std::vector
<Constant
*> Operands(I
->getNumOperands());
7803 for (unsigned i
= 0, e
= I
->getNumOperands(); i
!= e
; ++i
) {
7804 Instruction
*Operand
= dyn_cast
<Instruction
>(I
->getOperand(i
));
7806 Operands
[i
] = dyn_cast
<Constant
>(I
->getOperand(i
));
7807 if (!Operands
[i
]) return nullptr;
7810 Constant
*C
= EvaluateExpression(Operand
, L
, Vals
, DL
, TLI
);
7812 if (!C
) return nullptr;
7816 if (CmpInst
*CI
= dyn_cast
<CmpInst
>(I
))
7817 return ConstantFoldCompareInstOperands(CI
->getPredicate(), Operands
[0],
7818 Operands
[1], DL
, TLI
);
7819 if (LoadInst
*LI
= dyn_cast
<LoadInst
>(I
)) {
7820 if (!LI
->isVolatile())
7821 return ConstantFoldLoadFromConstPtr(Operands
[0], LI
->getType(), DL
);
7823 return ConstantFoldInstOperands(I
, Operands
, DL
, TLI
);
7827 // If every incoming value to PN except the one for BB is a specific Constant,
7828 // return that, else return nullptr.
7829 static Constant
*getOtherIncomingValue(PHINode
*PN
, BasicBlock
*BB
) {
7830 Constant
*IncomingVal
= nullptr;
7832 for (unsigned i
= 0, e
= PN
->getNumIncomingValues(); i
!= e
; ++i
) {
7833 if (PN
->getIncomingBlock(i
) == BB
)
7836 auto *CurrentVal
= dyn_cast
<Constant
>(PN
->getIncomingValue(i
));
7840 if (IncomingVal
!= CurrentVal
) {
7843 IncomingVal
= CurrentVal
;
7850 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
7851 /// in the header of its containing loop, we know the loop executes a
7852 /// constant number of times, and the PHI node is just a recurrence
7853 /// involving constants, fold it.
7855 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode
*PN
,
7858 auto I
= ConstantEvolutionLoopExitValue
.find(PN
);
7859 if (I
!= ConstantEvolutionLoopExitValue
.end())
7862 if (BEs
.ugt(MaxBruteForceIterations
))
7863 return ConstantEvolutionLoopExitValue
[PN
] = nullptr; // Not going to evaluate it.
7865 Constant
*&RetVal
= ConstantEvolutionLoopExitValue
[PN
];
7867 DenseMap
<Instruction
*, Constant
*> CurrentIterVals
;
7868 BasicBlock
*Header
= L
->getHeader();
7869 assert(PN
->getParent() == Header
&& "Can't evaluate PHI not in loop header!");
7871 BasicBlock
*Latch
= L
->getLoopLatch();
7875 for (PHINode
&PHI
: Header
->phis()) {
7876 if (auto *StartCST
= getOtherIncomingValue(&PHI
, Latch
))
7877 CurrentIterVals
[&PHI
] = StartCST
;
7879 if (!CurrentIterVals
.count(PN
))
7880 return RetVal
= nullptr;
7882 Value
*BEValue
= PN
->getIncomingValueForBlock(Latch
);
7884 // Execute the loop symbolically to determine the exit value.
7885 assert(BEs
.getActiveBits() < CHAR_BIT
* sizeof(unsigned) &&
7886 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
7888 unsigned NumIterations
= BEs
.getZExtValue(); // must be in range
7889 unsigned IterationNum
= 0;
7890 const DataLayout
&DL
= getDataLayout();
7891 for (; ; ++IterationNum
) {
7892 if (IterationNum
== NumIterations
)
7893 return RetVal
= CurrentIterVals
[PN
]; // Got exit value!
7895 // Compute the value of the PHIs for the next iteration.
7896 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
7897 DenseMap
<Instruction
*, Constant
*> NextIterVals
;
7899 EvaluateExpression(BEValue
, L
, CurrentIterVals
, DL
, &TLI
);
7901 return nullptr; // Couldn't evaluate!
7902 NextIterVals
[PN
] = NextPHI
;
7904 bool StoppedEvolving
= NextPHI
== CurrentIterVals
[PN
];
7906 // Also evaluate the other PHI nodes. However, we don't get to stop if we
7907 // cease to be able to evaluate one of them or if they stop evolving,
7908 // because that doesn't necessarily prevent us from computing PN.
7909 SmallVector
<std::pair
<PHINode
*, Constant
*>, 8> PHIsToCompute
;
7910 for (const auto &I
: CurrentIterVals
) {
7911 PHINode
*PHI
= dyn_cast
<PHINode
>(I
.first
);
7912 if (!PHI
|| PHI
== PN
|| PHI
->getParent() != Header
) continue;
7913 PHIsToCompute
.emplace_back(PHI
, I
.second
);
7915 // We use two distinct loops because EvaluateExpression may invalidate any
7916 // iterators into CurrentIterVals.
7917 for (const auto &I
: PHIsToCompute
) {
7918 PHINode
*PHI
= I
.first
;
7919 Constant
*&NextPHI
= NextIterVals
[PHI
];
7920 if (!NextPHI
) { // Not already computed.
7921 Value
*BEValue
= PHI
->getIncomingValueForBlock(Latch
);
7922 NextPHI
= EvaluateExpression(BEValue
, L
, CurrentIterVals
, DL
, &TLI
);
7924 if (NextPHI
!= I
.second
)
7925 StoppedEvolving
= false;
7928 // If all entries in CurrentIterVals == NextIterVals then we can stop
7929 // iterating, the loop can't continue to change.
7930 if (StoppedEvolving
)
7931 return RetVal
= CurrentIterVals
[PN
];
7933 CurrentIterVals
.swap(NextIterVals
);
7937 const SCEV
*ScalarEvolution::computeExitCountExhaustively(const Loop
*L
,
7940 PHINode
*PN
= getConstantEvolvingPHI(Cond
, L
);
7941 if (!PN
) return getCouldNotCompute();
7943 // If the loop is canonicalized, the PHI will have exactly two entries.
7944 // That's the only form we support here.
7945 if (PN
->getNumIncomingValues() != 2) return getCouldNotCompute();
7947 DenseMap
<Instruction
*, Constant
*> CurrentIterVals
;
7948 BasicBlock
*Header
= L
->getHeader();
7949 assert(PN
->getParent() == Header
&& "Can't evaluate PHI not in loop header!");
7951 BasicBlock
*Latch
= L
->getLoopLatch();
7952 assert(Latch
&& "Should follow from NumIncomingValues == 2!");
7954 for (PHINode
&PHI
: Header
->phis()) {
7955 if (auto *StartCST
= getOtherIncomingValue(&PHI
, Latch
))
7956 CurrentIterVals
[&PHI
] = StartCST
;
7958 if (!CurrentIterVals
.count(PN
))
7959 return getCouldNotCompute();
7961 // Okay, we find a PHI node that defines the trip count of this loop. Execute
7962 // the loop symbolically to determine when the condition gets a value of
7964 unsigned MaxIterations
= MaxBruteForceIterations
; // Limit analysis.
7965 const DataLayout
&DL
= getDataLayout();
7966 for (unsigned IterationNum
= 0; IterationNum
!= MaxIterations
;++IterationNum
){
7967 auto *CondVal
= dyn_cast_or_null
<ConstantInt
>(
7968 EvaluateExpression(Cond
, L
, CurrentIterVals
, DL
, &TLI
));
7970 // Couldn't symbolically evaluate.
7971 if (!CondVal
) return getCouldNotCompute();
7973 if (CondVal
->getValue() == uint64_t(ExitWhen
)) {
7974 ++NumBruteForceTripCountsComputed
;
7975 return getConstant(Type::getInt32Ty(getContext()), IterationNum
);
7978 // Update all the PHI nodes for the next iteration.
7979 DenseMap
<Instruction
*, Constant
*> NextIterVals
;
7981 // Create a list of which PHIs we need to compute. We want to do this before
7982 // calling EvaluateExpression on them because that may invalidate iterators
7983 // into CurrentIterVals.
7984 SmallVector
<PHINode
*, 8> PHIsToCompute
;
7985 for (const auto &I
: CurrentIterVals
) {
7986 PHINode
*PHI
= dyn_cast
<PHINode
>(I
.first
);
7987 if (!PHI
|| PHI
->getParent() != Header
) continue;
7988 PHIsToCompute
.push_back(PHI
);
7990 for (PHINode
*PHI
: PHIsToCompute
) {
7991 Constant
*&NextPHI
= NextIterVals
[PHI
];
7992 if (NextPHI
) continue; // Already computed!
7994 Value
*BEValue
= PHI
->getIncomingValueForBlock(Latch
);
7995 NextPHI
= EvaluateExpression(BEValue
, L
, CurrentIterVals
, DL
, &TLI
);
7997 CurrentIterVals
.swap(NextIterVals
);
8000 // Too many iterations were needed to evaluate.
8001 return getCouldNotCompute();
8004 const SCEV
*ScalarEvolution::getSCEVAtScope(const SCEV
*V
, const Loop
*L
) {
8005 SmallVector
<std::pair
<const Loop
*, const SCEV
*>, 2> &Values
=
8007 // Check to see if we've folded this expression at this loop before.
8008 for (auto &LS
: Values
)
8010 return LS
.second
? LS
.second
: V
;
8012 Values
.emplace_back(L
, nullptr);
8014 // Otherwise compute it.
8015 const SCEV
*C
= computeSCEVAtScope(V
, L
);
8016 for (auto &LS
: reverse(ValuesAtScopes
[V
]))
8017 if (LS
.first
== L
) {
8024 /// This builds up a Constant using the ConstantExpr interface. That way, we
8025 /// will return Constants for objects which aren't represented by a
8026 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
8027 /// Returns NULL if the SCEV isn't representable as a Constant.
8028 static Constant
*BuildConstantFromSCEV(const SCEV
*V
) {
8029 switch (static_cast<SCEVTypes
>(V
->getSCEVType())) {
8030 case scCouldNotCompute
:
8034 return cast
<SCEVConstant
>(V
)->getValue();
8036 return dyn_cast
<Constant
>(cast
<SCEVUnknown
>(V
)->getValue());
8037 case scSignExtend
: {
8038 const SCEVSignExtendExpr
*SS
= cast
<SCEVSignExtendExpr
>(V
);
8039 if (Constant
*CastOp
= BuildConstantFromSCEV(SS
->getOperand()))
8040 return ConstantExpr::getSExt(CastOp
, SS
->getType());
8043 case scZeroExtend
: {
8044 const SCEVZeroExtendExpr
*SZ
= cast
<SCEVZeroExtendExpr
>(V
);
8045 if (Constant
*CastOp
= BuildConstantFromSCEV(SZ
->getOperand()))
8046 return ConstantExpr::getZExt(CastOp
, SZ
->getType());
8050 const SCEVTruncateExpr
*ST
= cast
<SCEVTruncateExpr
>(V
);
8051 if (Constant
*CastOp
= BuildConstantFromSCEV(ST
->getOperand()))
8052 return ConstantExpr::getTrunc(CastOp
, ST
->getType());
8056 const SCEVAddExpr
*SA
= cast
<SCEVAddExpr
>(V
);
8057 if (Constant
*C
= BuildConstantFromSCEV(SA
->getOperand(0))) {
8058 if (PointerType
*PTy
= dyn_cast
<PointerType
>(C
->getType())) {
8059 unsigned AS
= PTy
->getAddressSpace();
8060 Type
*DestPtrTy
= Type::getInt8PtrTy(C
->getContext(), AS
);
8061 C
= ConstantExpr::getBitCast(C
, DestPtrTy
);
8063 for (unsigned i
= 1, e
= SA
->getNumOperands(); i
!= e
; ++i
) {
8064 Constant
*C2
= BuildConstantFromSCEV(SA
->getOperand(i
));
8065 if (!C2
) return nullptr;
8068 if (!C
->getType()->isPointerTy() && C2
->getType()->isPointerTy()) {
8069 unsigned AS
= C2
->getType()->getPointerAddressSpace();
8071 Type
*DestPtrTy
= Type::getInt8PtrTy(C
->getContext(), AS
);
8072 // The offsets have been converted to bytes. We can add bytes to an
8073 // i8* by GEP with the byte count in the first index.
8074 C
= ConstantExpr::getBitCast(C
, DestPtrTy
);
8077 // Don't bother trying to sum two pointers. We probably can't
8078 // statically compute a load that results from it anyway.
8079 if (C2
->getType()->isPointerTy())
8082 if (PointerType
*PTy
= dyn_cast
<PointerType
>(C
->getType())) {
8083 if (PTy
->getElementType()->isStructTy())
8084 C2
= ConstantExpr::getIntegerCast(
8085 C2
, Type::getInt32Ty(C
->getContext()), true);
8086 C
= ConstantExpr::getGetElementPtr(PTy
->getElementType(), C
, C2
);
8088 C
= ConstantExpr::getAdd(C
, C2
);
8095 const SCEVMulExpr
*SM
= cast
<SCEVMulExpr
>(V
);
8096 if (Constant
*C
= BuildConstantFromSCEV(SM
->getOperand(0))) {
8097 // Don't bother with pointers at all.
8098 if (C
->getType()->isPointerTy()) return nullptr;
8099 for (unsigned i
= 1, e
= SM
->getNumOperands(); i
!= e
; ++i
) {
8100 Constant
*C2
= BuildConstantFromSCEV(SM
->getOperand(i
));
8101 if (!C2
|| C2
->getType()->isPointerTy()) return nullptr;
8102 C
= ConstantExpr::getMul(C
, C2
);
8109 const SCEVUDivExpr
*SU
= cast
<SCEVUDivExpr
>(V
);
8110 if (Constant
*LHS
= BuildConstantFromSCEV(SU
->getLHS()))
8111 if (Constant
*RHS
= BuildConstantFromSCEV(SU
->getRHS()))
8112 if (LHS
->getType() == RHS
->getType())
8113 return ConstantExpr::getUDiv(LHS
, RHS
);
8120 break; // TODO: smax, umax, smin, umax.
8125 const SCEV
*ScalarEvolution::computeSCEVAtScope(const SCEV
*V
, const Loop
*L
) {
8126 if (isa
<SCEVConstant
>(V
)) return V
;
8128 // If this instruction is evolved from a constant-evolving PHI, compute the
8129 // exit value from the loop without using SCEVs.
8130 if (const SCEVUnknown
*SU
= dyn_cast
<SCEVUnknown
>(V
)) {
8131 if (Instruction
*I
= dyn_cast
<Instruction
>(SU
->getValue())) {
8132 if (PHINode
*PN
= dyn_cast
<PHINode
>(I
)) {
8133 const Loop
*LI
= this->LI
[I
->getParent()];
8134 // Looking for loop exit value.
8135 if (LI
&& LI
->getParentLoop() == L
&&
8136 PN
->getParent() == LI
->getHeader()) {
8137 // Okay, there is no closed form solution for the PHI node. Check
8138 // to see if the loop that contains it has a known backedge-taken
8139 // count. If so, we may be able to force computation of the exit
8141 const SCEV
*BackedgeTakenCount
= getBackedgeTakenCount(LI
);
8142 // This trivial case can show up in some degenerate cases where
8143 // the incoming IR has not yet been fully simplified.
8144 if (BackedgeTakenCount
->isZero()) {
8145 Value
*InitValue
= nullptr;
8146 bool MultipleInitValues
= false;
8147 for (unsigned i
= 0; i
< PN
->getNumIncomingValues(); i
++) {
8148 if (!LI
->contains(PN
->getIncomingBlock(i
))) {
8150 InitValue
= PN
->getIncomingValue(i
);
8151 else if (InitValue
!= PN
->getIncomingValue(i
)) {
8152 MultipleInitValues
= true;
8157 if (!MultipleInitValues
&& InitValue
)
8158 return getSCEV(InitValue
);
8160 // Do we have a loop invariant value flowing around the backedge
8161 // for a loop which must execute the backedge?
8162 if (!isa
<SCEVCouldNotCompute
>(BackedgeTakenCount
) &&
8163 isKnownPositive(BackedgeTakenCount
) &&
8164 PN
->getNumIncomingValues() == 2) {
8165 unsigned InLoopPred
= LI
->contains(PN
->getIncomingBlock(0)) ? 0 : 1;
8166 const SCEV
*OnBackedge
= getSCEV(PN
->getIncomingValue(InLoopPred
));
8167 if (IsAvailableOnEntry(LI
, DT
, OnBackedge
, PN
->getParent()))
8170 if (auto *BTCC
= dyn_cast
<SCEVConstant
>(BackedgeTakenCount
)) {
8171 // Okay, we know how many times the containing loop executes. If
8172 // this is a constant evolving PHI node, get the final value at
8173 // the specified iteration number.
8175 getConstantEvolutionLoopExitValue(PN
, BTCC
->getAPInt(), LI
);
8176 if (RV
) return getSCEV(RV
);
8180 // If there is a single-input Phi, evaluate it at our scope. If we can
8181 // prove that this replacement does not break LCSSA form, use new value.
8182 if (PN
->getNumOperands() == 1) {
8183 const SCEV
*Input
= getSCEV(PN
->getOperand(0));
8184 const SCEV
*InputAtScope
= getSCEVAtScope(Input
, L
);
8185 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm,
8186 // for the simplest case just support constants.
8187 if (isa
<SCEVConstant
>(InputAtScope
)) return InputAtScope
;
8191 // Okay, this is an expression that we cannot symbolically evaluate
8192 // into a SCEV. Check to see if it's possible to symbolically evaluate
8193 // the arguments into constants, and if so, try to constant propagate the
8194 // result. This is particularly useful for computing loop exit values.
8195 if (CanConstantFold(I
)) {
8196 SmallVector
<Constant
*, 4> Operands
;
8197 bool MadeImprovement
= false;
8198 for (Value
*Op
: I
->operands()) {
8199 if (Constant
*C
= dyn_cast
<Constant
>(Op
)) {
8200 Operands
.push_back(C
);
8204 // If any of the operands is non-constant and if they are
8205 // non-integer and non-pointer, don't even try to analyze them
8206 // with scev techniques.
8207 if (!isSCEVable(Op
->getType()))
8210 const SCEV
*OrigV
= getSCEV(Op
);
8211 const SCEV
*OpV
= getSCEVAtScope(OrigV
, L
);
8212 MadeImprovement
|= OrigV
!= OpV
;
8214 Constant
*C
= BuildConstantFromSCEV(OpV
);
8216 if (C
->getType() != Op
->getType())
8217 C
= ConstantExpr::getCast(CastInst::getCastOpcode(C
, false,
8221 Operands
.push_back(C
);
8224 // Check to see if getSCEVAtScope actually made an improvement.
8225 if (MadeImprovement
) {
8226 Constant
*C
= nullptr;
8227 const DataLayout
&DL
= getDataLayout();
8228 if (const CmpInst
*CI
= dyn_cast
<CmpInst
>(I
))
8229 C
= ConstantFoldCompareInstOperands(CI
->getPredicate(), Operands
[0],
8230 Operands
[1], DL
, &TLI
);
8231 else if (const LoadInst
*LI
= dyn_cast
<LoadInst
>(I
)) {
8232 if (!LI
->isVolatile())
8233 C
= ConstantFoldLoadFromConstPtr(Operands
[0], LI
->getType(), DL
);
8235 C
= ConstantFoldInstOperands(I
, Operands
, DL
, &TLI
);
8242 // This is some other type of SCEVUnknown, just return it.
8246 if (const SCEVCommutativeExpr
*Comm
= dyn_cast
<SCEVCommutativeExpr
>(V
)) {
8247 // Avoid performing the look-up in the common case where the specified
8248 // expression has no loop-variant portions.
8249 for (unsigned i
= 0, e
= Comm
->getNumOperands(); i
!= e
; ++i
) {
8250 const SCEV
*OpAtScope
= getSCEVAtScope(Comm
->getOperand(i
), L
);
8251 if (OpAtScope
!= Comm
->getOperand(i
)) {
8252 // Okay, at least one of these operands is loop variant but might be
8253 // foldable. Build a new instance of the folded commutative expression.
8254 SmallVector
<const SCEV
*, 8> NewOps(Comm
->op_begin(),
8255 Comm
->op_begin()+i
);
8256 NewOps
.push_back(OpAtScope
);
8258 for (++i
; i
!= e
; ++i
) {
8259 OpAtScope
= getSCEVAtScope(Comm
->getOperand(i
), L
);
8260 NewOps
.push_back(OpAtScope
);
8262 if (isa
<SCEVAddExpr
>(Comm
))
8263 return getAddExpr(NewOps
, Comm
->getNoWrapFlags());
8264 if (isa
<SCEVMulExpr
>(Comm
))
8265 return getMulExpr(NewOps
, Comm
->getNoWrapFlags());
8266 if (isa
<SCEVMinMaxExpr
>(Comm
))
8267 return getMinMaxExpr(Comm
->getSCEVType(), NewOps
);
8268 llvm_unreachable("Unknown commutative SCEV type!");
8271 // If we got here, all operands are loop invariant.
8275 if (const SCEVUDivExpr
*Div
= dyn_cast
<SCEVUDivExpr
>(V
)) {
8276 const SCEV
*LHS
= getSCEVAtScope(Div
->getLHS(), L
);
8277 const SCEV
*RHS
= getSCEVAtScope(Div
->getRHS(), L
);
8278 if (LHS
== Div
->getLHS() && RHS
== Div
->getRHS())
8279 return Div
; // must be loop invariant
8280 return getUDivExpr(LHS
, RHS
);
8283 // If this is a loop recurrence for a loop that does not contain L, then we
8284 // are dealing with the final value computed by the loop.
8285 if (const SCEVAddRecExpr
*AddRec
= dyn_cast
<SCEVAddRecExpr
>(V
)) {
8286 // First, attempt to evaluate each operand.
8287 // Avoid performing the look-up in the common case where the specified
8288 // expression has no loop-variant portions.
8289 for (unsigned i
= 0, e
= AddRec
->getNumOperands(); i
!= e
; ++i
) {
8290 const SCEV
*OpAtScope
= getSCEVAtScope(AddRec
->getOperand(i
), L
);
8291 if (OpAtScope
== AddRec
->getOperand(i
))
8294 // Okay, at least one of these operands is loop variant but might be
8295 // foldable. Build a new instance of the folded commutative expression.
8296 SmallVector
<const SCEV
*, 8> NewOps(AddRec
->op_begin(),
8297 AddRec
->op_begin()+i
);
8298 NewOps
.push_back(OpAtScope
);
8299 for (++i
; i
!= e
; ++i
)
8300 NewOps
.push_back(getSCEVAtScope(AddRec
->getOperand(i
), L
));
8302 const SCEV
*FoldedRec
=
8303 getAddRecExpr(NewOps
, AddRec
->getLoop(),
8304 AddRec
->getNoWrapFlags(SCEV::FlagNW
));
8305 AddRec
= dyn_cast
<SCEVAddRecExpr
>(FoldedRec
);
8306 // The addrec may be folded to a nonrecurrence, for example, if the
8307 // induction variable is multiplied by zero after constant folding. Go
8308 // ahead and return the folded value.
8314 // If the scope is outside the addrec's loop, evaluate it by using the
8315 // loop exit value of the addrec.
8316 if (!AddRec
->getLoop()->contains(L
)) {
8317 // To evaluate this recurrence, we need to know how many times the AddRec
8318 // loop iterates. Compute this now.
8319 const SCEV
*BackedgeTakenCount
= getBackedgeTakenCount(AddRec
->getLoop());
8320 if (BackedgeTakenCount
== getCouldNotCompute()) return AddRec
;
8322 // Then, evaluate the AddRec.
8323 return AddRec
->evaluateAtIteration(BackedgeTakenCount
, *this);
8329 if (const SCEVZeroExtendExpr
*Cast
= dyn_cast
<SCEVZeroExtendExpr
>(V
)) {
8330 const SCEV
*Op
= getSCEVAtScope(Cast
->getOperand(), L
);
8331 if (Op
== Cast
->getOperand())
8332 return Cast
; // must be loop invariant
8333 return getZeroExtendExpr(Op
, Cast
->getType());
8336 if (const SCEVSignExtendExpr
*Cast
= dyn_cast
<SCEVSignExtendExpr
>(V
)) {
8337 const SCEV
*Op
= getSCEVAtScope(Cast
->getOperand(), L
);
8338 if (Op
== Cast
->getOperand())
8339 return Cast
; // must be loop invariant
8340 return getSignExtendExpr(Op
, Cast
->getType());
8343 if (const SCEVTruncateExpr
*Cast
= dyn_cast
<SCEVTruncateExpr
>(V
)) {
8344 const SCEV
*Op
= getSCEVAtScope(Cast
->getOperand(), L
);
8345 if (Op
== Cast
->getOperand())
8346 return Cast
; // must be loop invariant
8347 return getTruncateExpr(Op
, Cast
->getType());
8350 llvm_unreachable("Unknown SCEV type!");
8353 const SCEV
*ScalarEvolution::getSCEVAtScope(Value
*V
, const Loop
*L
) {
8354 return getSCEVAtScope(getSCEV(V
), L
);
8357 const SCEV
*ScalarEvolution::stripInjectiveFunctions(const SCEV
*S
) const {
8358 if (const SCEVZeroExtendExpr
*ZExt
= dyn_cast
<SCEVZeroExtendExpr
>(S
))
8359 return stripInjectiveFunctions(ZExt
->getOperand());
8360 if (const SCEVSignExtendExpr
*SExt
= dyn_cast
<SCEVSignExtendExpr
>(S
))
8361 return stripInjectiveFunctions(SExt
->getOperand());
8365 /// Finds the minimum unsigned root of the following equation:
8367 /// A * X = B (mod N)
8369 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
8370 /// A and B isn't important.
8372 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
8373 static const SCEV
*SolveLinEquationWithOverflow(const APInt
&A
, const SCEV
*B
,
8374 ScalarEvolution
&SE
) {
8375 uint32_t BW
= A
.getBitWidth();
8376 assert(BW
== SE
.getTypeSizeInBits(B
->getType()));
8377 assert(A
!= 0 && "A must be non-zero.");
8381 // The gcd of A and N may have only one prime factor: 2. The number of
8382 // trailing zeros in A is its multiplicity
8383 uint32_t Mult2
= A
.countTrailingZeros();
8386 // 2. Check if B is divisible by D.
8388 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
8389 // is not less than multiplicity of this prime factor for D.
8390 if (SE
.GetMinTrailingZeros(B
) < Mult2
)
8391 return SE
.getCouldNotCompute();
8393 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
8396 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
8397 // (N / D) in general. The inverse itself always fits into BW bits, though,
8398 // so we immediately truncate it.
8399 APInt AD
= A
.lshr(Mult2
).zext(BW
+ 1); // AD = A / D
8400 APInt
Mod(BW
+ 1, 0);
8401 Mod
.setBit(BW
- Mult2
); // Mod = N / D
8402 APInt I
= AD
.multiplicativeInverse(Mod
).trunc(BW
);
8404 // 4. Compute the minimum unsigned root of the equation:
8405 // I * (B / D) mod (N / D)
8406 // To simplify the computation, we factor out the divide by D:
8407 // (I * B mod N) / D
8408 const SCEV
*D
= SE
.getConstant(APInt::getOneBitSet(BW
, Mult2
));
8409 return SE
.getUDivExactExpr(SE
.getMulExpr(B
, SE
.getConstant(I
)), D
);
8412 /// For a given quadratic addrec, generate coefficients of the corresponding
8413 /// quadratic equation, multiplied by a common value to ensure that they are
8415 /// The returned value is a tuple { A, B, C, M, BitWidth }, where
8416 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
8417 /// were multiplied by, and BitWidth is the bit width of the original addrec
8419 /// This function returns None if the addrec coefficients are not compile-
8421 static Optional
<std::tuple
<APInt
, APInt
, APInt
, APInt
, unsigned>>
8422 GetQuadraticEquation(const SCEVAddRecExpr
*AddRec
) {
8423 assert(AddRec
->getNumOperands() == 3 && "This is not a quadratic chrec!");
8424 const SCEVConstant
*LC
= dyn_cast
<SCEVConstant
>(AddRec
->getOperand(0));
8425 const SCEVConstant
*MC
= dyn_cast
<SCEVConstant
>(AddRec
->getOperand(1));
8426 const SCEVConstant
*NC
= dyn_cast
<SCEVConstant
>(AddRec
->getOperand(2));
8427 LLVM_DEBUG(dbgs() << __func__
<< ": analyzing quadratic addrec: "
8428 << *AddRec
<< '\n');
8430 // We currently can only solve this if the coefficients are constants.
8431 if (!LC
|| !MC
|| !NC
) {
8432 LLVM_DEBUG(dbgs() << __func__
<< ": coefficients are not constant\n");
8436 APInt L
= LC
->getAPInt();
8437 APInt M
= MC
->getAPInt();
8438 APInt N
= NC
->getAPInt();
8439 assert(!N
.isNullValue() && "This is not a quadratic addrec");
8441 unsigned BitWidth
= LC
->getAPInt().getBitWidth();
8442 unsigned NewWidth
= BitWidth
+ 1;
8443 LLVM_DEBUG(dbgs() << __func__
<< ": addrec coeff bw: "
8444 << BitWidth
<< '\n');
8445 // The sign-extension (as opposed to a zero-extension) here matches the
8446 // extension used in SolveQuadraticEquationWrap (with the same motivation).
8447 N
= N
.sext(NewWidth
);
8448 M
= M
.sext(NewWidth
);
8449 L
= L
.sext(NewWidth
);
8451 // The increments are M, M+N, M+2N, ..., so the accumulated values are
8452 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
8453 // L+M, L+2M+N, L+3M+3N, ...
8454 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
8456 // The equation Acc = 0 is then
8457 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0.
8458 // In a quadratic form it becomes:
8459 // N n^2 + (2M-N) n + 2L = 0.
8462 APInt B
= 2 * M
- A
;
8464 APInt T
= APInt(NewWidth
, 2);
8465 LLVM_DEBUG(dbgs() << __func__
<< ": equation " << A
<< "x^2 + " << B
8466 << "x + " << C
<< ", coeff bw: " << NewWidth
8467 << ", multiplied by " << T
<< '\n');
8468 return std::make_tuple(A
, B
, C
, T
, BitWidth
);
8471 /// Helper function to compare optional APInts:
8472 /// (a) if X and Y both exist, return min(X, Y),
8473 /// (b) if neither X nor Y exist, return None,
8474 /// (c) if exactly one of X and Y exists, return that value.
8475 static Optional
<APInt
> MinOptional(Optional
<APInt
> X
, Optional
<APInt
> Y
) {
8476 if (X
.hasValue() && Y
.hasValue()) {
8477 unsigned W
= std::max(X
->getBitWidth(), Y
->getBitWidth());
8478 APInt XW
= X
->sextOrSelf(W
);
8479 APInt YW
= Y
->sextOrSelf(W
);
8480 return XW
.slt(YW
) ? *X
: *Y
;
8482 if (!X
.hasValue() && !Y
.hasValue())
8484 return X
.hasValue() ? *X
: *Y
;
8487 /// Helper function to truncate an optional APInt to a given BitWidth.
8488 /// When solving addrec-related equations, it is preferable to return a value
8489 /// that has the same bit width as the original addrec's coefficients. If the
8490 /// solution fits in the original bit width, truncate it (except for i1).
8491 /// Returning a value of a different bit width may inhibit some optimizations.
8493 /// In general, a solution to a quadratic equation generated from an addrec
8494 /// may require BW+1 bits, where BW is the bit width of the addrec's
8495 /// coefficients. The reason is that the coefficients of the quadratic
8496 /// equation are BW+1 bits wide (to avoid truncation when converting from
8497 /// the addrec to the equation).
8498 static Optional
<APInt
> TruncIfPossible(Optional
<APInt
> X
, unsigned BitWidth
) {
8501 unsigned W
= X
->getBitWidth();
8502 if (BitWidth
> 1 && BitWidth
< W
&& X
->isIntN(BitWidth
))
8503 return X
->trunc(BitWidth
);
8507 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
8508 /// iterations. The values L, M, N are assumed to be signed, and they
8509 /// should all have the same bit widths.
8510 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
8511 /// where BW is the bit width of the addrec's coefficients.
8512 /// If the calculated value is a BW-bit integer (for BW > 1), it will be
8513 /// returned as such, otherwise the bit width of the returned value may
8514 /// be greater than BW.
8516 /// This function returns None if
8517 /// (a) the addrec coefficients are not constant, or
8518 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
8519 /// like x^2 = 5, no integer solutions exist, in other cases an integer
8520 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it.
8521 static Optional
<APInt
>
8522 SolveQuadraticAddRecExact(const SCEVAddRecExpr
*AddRec
, ScalarEvolution
&SE
) {
8525 auto T
= GetQuadraticEquation(AddRec
);
8529 std::tie(A
, B
, C
, M
, BitWidth
) = *T
;
8530 LLVM_DEBUG(dbgs() << __func__
<< ": solving for unsigned overflow\n");
8531 Optional
<APInt
> X
= APIntOps::SolveQuadraticEquationWrap(A
, B
, C
, BitWidth
+1);
8535 ConstantInt
*CX
= ConstantInt::get(SE
.getContext(), *X
);
8536 ConstantInt
*V
= EvaluateConstantChrecAtConstant(AddRec
, CX
, SE
);
8540 return TruncIfPossible(X
, BitWidth
);
8543 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
8544 /// iterations. The values M, N are assumed to be signed, and they
8545 /// should all have the same bit widths.
8546 /// Find the least n such that c(n) does not belong to the given range,
8547 /// while c(n-1) does.
8549 /// This function returns None if
8550 /// (a) the addrec coefficients are not constant, or
8551 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the
8552 /// bounds of the range.
8553 static Optional
<APInt
>
8554 SolveQuadraticAddRecRange(const SCEVAddRecExpr
*AddRec
,
8555 const ConstantRange
&Range
, ScalarEvolution
&SE
) {
8556 assert(AddRec
->getOperand(0)->isZero() &&
8557 "Starting value of addrec should be 0");
8558 LLVM_DEBUG(dbgs() << __func__
<< ": solving boundary crossing for range "
8559 << Range
<< ", addrec " << *AddRec
<< '\n');
8560 // This case is handled in getNumIterationsInRange. Here we can assume that
8561 // we start in the range.
8562 assert(Range
.contains(APInt(SE
.getTypeSizeInBits(AddRec
->getType()), 0)) &&
8563 "Addrec's initial value should be in range");
8567 auto T
= GetQuadraticEquation(AddRec
);
8571 // Be careful about the return value: there can be two reasons for not
8572 // returning an actual number. First, if no solutions to the equations
8573 // were found, and second, if the solutions don't leave the given range.
8574 // The first case means that the actual solution is "unknown", the second
8575 // means that it's known, but not valid. If the solution is unknown, we
8576 // cannot make any conclusions.
8577 // Return a pair: the optional solution and a flag indicating if the
8578 // solution was found.
8579 auto SolveForBoundary
= [&](APInt Bound
) -> std::pair
<Optional
<APInt
>,bool> {
8580 // Solve for signed overflow and unsigned overflow, pick the lower
8582 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
8583 << Bound
<< " (before multiplying by " << M
<< ")\n");
8584 Bound
*= M
; // The quadratic equation multiplier.
8586 Optional
<APInt
> SO
= None
;
8588 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
8589 "signed overflow\n");
8590 SO
= APIntOps::SolveQuadraticEquationWrap(A
, B
, -Bound
, BitWidth
);
8592 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
8593 "unsigned overflow\n");
8594 Optional
<APInt
> UO
= APIntOps::SolveQuadraticEquationWrap(A
, B
, -Bound
,
8597 auto LeavesRange
= [&] (const APInt
&X
) {
8598 ConstantInt
*C0
= ConstantInt::get(SE
.getContext(), X
);
8599 ConstantInt
*V0
= EvaluateConstantChrecAtConstant(AddRec
, C0
, SE
);
8600 if (Range
.contains(V0
->getValue()))
8602 // X should be at least 1, so X-1 is non-negative.
8603 ConstantInt
*C1
= ConstantInt::get(SE
.getContext(), X
-1);
8604 ConstantInt
*V1
= EvaluateConstantChrecAtConstant(AddRec
, C1
, SE
);
8605 if (Range
.contains(V1
->getValue()))
8610 // If SolveQuadraticEquationWrap returns None, it means that there can
8611 // be a solution, but the function failed to find it. We cannot treat it
8612 // as "no solution".
8613 if (!SO
.hasValue() || !UO
.hasValue())
8614 return { None
, false };
8616 // Check the smaller value first to see if it leaves the range.
8617 // At this point, both SO and UO must have values.
8618 Optional
<APInt
> Min
= MinOptional(SO
, UO
);
8619 if (LeavesRange(*Min
))
8620 return { Min
, true };
8621 Optional
<APInt
> Max
= Min
== SO
? UO
: SO
;
8622 if (LeavesRange(*Max
))
8623 return { Max
, true };
8625 // Solutions were found, but were eliminated, hence the "true".
8626 return { None
, true };
8629 std::tie(A
, B
, C
, M
, BitWidth
) = *T
;
8630 // Lower bound is inclusive, subtract 1 to represent the exiting value.
8631 APInt Lower
= Range
.getLower().sextOrSelf(A
.getBitWidth()) - 1;
8632 APInt Upper
= Range
.getUpper().sextOrSelf(A
.getBitWidth());
8633 auto SL
= SolveForBoundary(Lower
);
8634 auto SU
= SolveForBoundary(Upper
);
8635 // If any of the solutions was unknown, no meaninigful conclusions can
8637 if (!SL
.second
|| !SU
.second
)
8640 // Claim: The correct solution is not some value between Min and Max.
8642 // Justification: Assuming that Min and Max are different values, one of
8643 // them is when the first signed overflow happens, the other is when the
8644 // first unsigned overflow happens. Crossing the range boundary is only
8645 // possible via an overflow (treating 0 as a special case of it, modeling
8646 // an overflow as crossing k*2^W for some k).
8648 // The interesting case here is when Min was eliminated as an invalid
8649 // solution, but Max was not. The argument is that if there was another
8650 // overflow between Min and Max, it would also have been eliminated if
8651 // it was considered.
8653 // For a given boundary, it is possible to have two overflows of the same
8654 // type (signed/unsigned) without having the other type in between: this
8655 // can happen when the vertex of the parabola is between the iterations
8656 // corresponding to the overflows. This is only possible when the two
8657 // overflows cross k*2^W for the same k. In such case, if the second one
8658 // left the range (and was the first one to do so), the first overflow
8659 // would have to enter the range, which would mean that either we had left
8660 // the range before or that we started outside of it. Both of these cases
8661 // are contradictions.
8663 // Claim: In the case where SolveForBoundary returns None, the correct
8664 // solution is not some value between the Max for this boundary and the
8665 // Min of the other boundary.
8667 // Justification: Assume that we had such Max_A and Min_B corresponding
8668 // to range boundaries A and B and such that Max_A < Min_B. If there was
8669 // a solution between Max_A and Min_B, it would have to be caused by an
8670 // overflow corresponding to either A or B. It cannot correspond to B,
8671 // since Min_B is the first occurrence of such an overflow. If it
8672 // corresponded to A, it would have to be either a signed or an unsigned
8673 // overflow that is larger than both eliminated overflows for A. But
8674 // between the eliminated overflows and this overflow, the values would
8675 // cover the entire value space, thus crossing the other boundary, which
8676 // is a contradiction.
8678 return TruncIfPossible(MinOptional(SL
.first
, SU
.first
), BitWidth
);
8681 ScalarEvolution::ExitLimit
8682 ScalarEvolution::howFarToZero(const SCEV
*V
, const Loop
*L
, bool ControlsExit
,
8683 bool AllowPredicates
) {
8685 // This is only used for loops with a "x != y" exit test. The exit condition
8686 // is now expressed as a single expression, V = x-y. So the exit test is
8687 // effectively V != 0. We know and take advantage of the fact that this
8688 // expression only being used in a comparison by zero context.
8690 SmallPtrSet
<const SCEVPredicate
*, 4> Predicates
;
8691 // If the value is a constant
8692 if (const SCEVConstant
*C
= dyn_cast
<SCEVConstant
>(V
)) {
8693 // If the value is already zero, the branch will execute zero times.
8694 if (C
->getValue()->isZero()) return C
;
8695 return getCouldNotCompute(); // Otherwise it will loop infinitely.
8698 const SCEVAddRecExpr
*AddRec
=
8699 dyn_cast
<SCEVAddRecExpr
>(stripInjectiveFunctions(V
));
8701 if (!AddRec
&& AllowPredicates
)
8702 // Try to make this an AddRec using runtime tests, in the first X
8703 // iterations of this loop, where X is the SCEV expression found by the
8705 AddRec
= convertSCEVToAddRecWithPredicates(V
, L
, Predicates
);
8707 if (!AddRec
|| AddRec
->getLoop() != L
)
8708 return getCouldNotCompute();
8710 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
8711 // the quadratic equation to solve it.
8712 if (AddRec
->isQuadratic() && AddRec
->getType()->isIntegerTy()) {
8713 // We can only use this value if the chrec ends up with an exact zero
8714 // value at this index. When solving for "X*X != 5", for example, we
8715 // should not accept a root of 2.
8716 if (auto S
= SolveQuadraticAddRecExact(AddRec
, *this)) {
8717 const auto *R
= cast
<SCEVConstant
>(getConstant(S
.getValue()));
8718 return ExitLimit(R
, R
, false, Predicates
);
8720 return getCouldNotCompute();
8723 // Otherwise we can only handle this if it is affine.
8724 if (!AddRec
->isAffine())
8725 return getCouldNotCompute();
8727 // If this is an affine expression, the execution count of this branch is
8728 // the minimum unsigned root of the following equation:
8730 // Start + Step*N = 0 (mod 2^BW)
8734 // Step*N = -Start (mod 2^BW)
8736 // where BW is the common bit width of Start and Step.
8738 // Get the initial value for the loop.
8739 const SCEV
*Start
= getSCEVAtScope(AddRec
->getStart(), L
->getParentLoop());
8740 const SCEV
*Step
= getSCEVAtScope(AddRec
->getOperand(1), L
->getParentLoop());
8742 // For now we handle only constant steps.
8744 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
8745 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
8746 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
8747 // We have not yet seen any such cases.
8748 const SCEVConstant
*StepC
= dyn_cast
<SCEVConstant
>(Step
);
8749 if (!StepC
|| StepC
->getValue()->isZero())
8750 return getCouldNotCompute();
8752 // For positive steps (counting up until unsigned overflow):
8753 // N = -Start/Step (as unsigned)
8754 // For negative steps (counting down to zero):
8756 // First compute the unsigned distance from zero in the direction of Step.
8757 bool CountDown
= StepC
->getAPInt().isNegative();
8758 const SCEV
*Distance
= CountDown
? Start
: getNegativeSCEV(Start
);
8760 // Handle unitary steps, which cannot wraparound.
8761 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
8762 // N = Distance (as unsigned)
8763 if (StepC
->getValue()->isOne() || StepC
->getValue()->isMinusOne()) {
8764 APInt MaxBECount
= getUnsignedRangeMax(Distance
);
8766 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
8767 // we end up with a loop whose backedge-taken count is n - 1. Detect this
8768 // case, and see if we can improve the bound.
8770 // Explicitly handling this here is necessary because getUnsignedRange
8771 // isn't context-sensitive; it doesn't know that we only care about the
8772 // range inside the loop.
8773 const SCEV
*Zero
= getZero(Distance
->getType());
8774 const SCEV
*One
= getOne(Distance
->getType());
8775 const SCEV
*DistancePlusOne
= getAddExpr(Distance
, One
);
8776 if (isLoopEntryGuardedByCond(L
, ICmpInst::ICMP_NE
, DistancePlusOne
, Zero
)) {
8777 // If Distance + 1 doesn't overflow, we can compute the maximum distance
8778 // as "unsigned_max(Distance + 1) - 1".
8779 ConstantRange CR
= getUnsignedRange(DistancePlusOne
);
8780 MaxBECount
= APIntOps::umin(MaxBECount
, CR
.getUnsignedMax() - 1);
8782 return ExitLimit(Distance
, getConstant(MaxBECount
), false, Predicates
);
8785 // If the condition controls loop exit (the loop exits only if the expression
8786 // is true) and the addition is no-wrap we can use unsigned divide to
8787 // compute the backedge count. In this case, the step may not divide the
8788 // distance, but we don't care because if the condition is "missed" the loop
8789 // will have undefined behavior due to wrapping.
8790 if (ControlsExit
&& AddRec
->hasNoSelfWrap() &&
8791 loopHasNoAbnormalExits(AddRec
->getLoop())) {
8793 getUDivExpr(Distance
, CountDown
? getNegativeSCEV(Step
) : Step
);
8795 Exact
== getCouldNotCompute()
8797 : getConstant(getUnsignedRangeMax(Exact
));
8798 return ExitLimit(Exact
, Max
, false, Predicates
);
8801 // Solve the general equation.
8802 const SCEV
*E
= SolveLinEquationWithOverflow(StepC
->getAPInt(),
8803 getNegativeSCEV(Start
), *this);
8804 const SCEV
*M
= E
== getCouldNotCompute()
8806 : getConstant(getUnsignedRangeMax(E
));
8807 return ExitLimit(E
, M
, false, Predicates
);
8810 ScalarEvolution::ExitLimit
8811 ScalarEvolution::howFarToNonZero(const SCEV
*V
, const Loop
*L
) {
8812 // Loops that look like: while (X == 0) are very strange indeed. We don't
8813 // handle them yet except for the trivial case. This could be expanded in the
8814 // future as needed.
8816 // If the value is a constant, check to see if it is known to be non-zero
8817 // already. If so, the backedge will execute zero times.
8818 if (const SCEVConstant
*C
= dyn_cast
<SCEVConstant
>(V
)) {
8819 if (!C
->getValue()->isZero())
8820 return getZero(C
->getType());
8821 return getCouldNotCompute(); // Otherwise it will loop infinitely.
8824 // We could implement others, but I really doubt anyone writes loops like
8825 // this, and if they did, they would already be constant folded.
8826 return getCouldNotCompute();
8829 std::pair
<BasicBlock
*, BasicBlock
*>
8830 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock
*BB
) {
8831 // If the block has a unique predecessor, then there is no path from the
8832 // predecessor to the block that does not go through the direct edge
8833 // from the predecessor to the block.
8834 if (BasicBlock
*Pred
= BB
->getSinglePredecessor())
8837 // A loop's header is defined to be a block that dominates the loop.
8838 // If the header has a unique predecessor outside the loop, it must be
8839 // a block that has exactly one successor that can reach the loop.
8840 if (Loop
*L
= LI
.getLoopFor(BB
))
8841 return {L
->getLoopPredecessor(), L
->getHeader()};
8843 return {nullptr, nullptr};
8846 /// SCEV structural equivalence is usually sufficient for testing whether two
8847 /// expressions are equal, however for the purposes of looking for a condition
8848 /// guarding a loop, it can be useful to be a little more general, since a
8849 /// front-end may have replicated the controlling expression.
8850 static bool HasSameValue(const SCEV
*A
, const SCEV
*B
) {
8851 // Quick check to see if they are the same SCEV.
8852 if (A
== B
) return true;
8854 auto ComputesEqualValues
= [](const Instruction
*A
, const Instruction
*B
) {
8855 // Not all instructions that are "identical" compute the same value. For
8856 // instance, two distinct alloca instructions allocating the same type are
8857 // identical and do not read memory; but compute distinct values.
8858 return A
->isIdenticalTo(B
) && (isa
<BinaryOperator
>(A
) || isa
<GetElementPtrInst
>(A
));
8861 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
8862 // two different instructions with the same value. Check for this case.
8863 if (const SCEVUnknown
*AU
= dyn_cast
<SCEVUnknown
>(A
))
8864 if (const SCEVUnknown
*BU
= dyn_cast
<SCEVUnknown
>(B
))
8865 if (const Instruction
*AI
= dyn_cast
<Instruction
>(AU
->getValue()))
8866 if (const Instruction
*BI
= dyn_cast
<Instruction
>(BU
->getValue()))
8867 if (ComputesEqualValues(AI
, BI
))
8870 // Otherwise assume they may have a different value.
8874 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate
&Pred
,
8875 const SCEV
*&LHS
, const SCEV
*&RHS
,
8877 bool Changed
= false;
8878 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
8880 auto TrivialCase
= [&](bool TriviallyTrue
) {
8881 LHS
= RHS
= getConstant(ConstantInt::getFalse(getContext()));
8882 Pred
= TriviallyTrue
? ICmpInst::ICMP_EQ
: ICmpInst::ICMP_NE
;
8885 // If we hit the max recursion limit bail out.
8889 // Canonicalize a constant to the right side.
8890 if (const SCEVConstant
*LHSC
= dyn_cast
<SCEVConstant
>(LHS
)) {
8891 // Check for both operands constant.
8892 if (const SCEVConstant
*RHSC
= dyn_cast
<SCEVConstant
>(RHS
)) {
8893 if (ConstantExpr::getICmp(Pred
,
8895 RHSC
->getValue())->isNullValue())
8896 return TrivialCase(false);
8898 return TrivialCase(true);
8900 // Otherwise swap the operands to put the constant on the right.
8901 std::swap(LHS
, RHS
);
8902 Pred
= ICmpInst::getSwappedPredicate(Pred
);
8906 // If we're comparing an addrec with a value which is loop-invariant in the
8907 // addrec's loop, put the addrec on the left. Also make a dominance check,
8908 // as both operands could be addrecs loop-invariant in each other's loop.
8909 if (const SCEVAddRecExpr
*AR
= dyn_cast
<SCEVAddRecExpr
>(RHS
)) {
8910 const Loop
*L
= AR
->getLoop();
8911 if (isLoopInvariant(LHS
, L
) && properlyDominates(LHS
, L
->getHeader())) {
8912 std::swap(LHS
, RHS
);
8913 Pred
= ICmpInst::getSwappedPredicate(Pred
);
8918 // If there's a constant operand, canonicalize comparisons with boundary
8919 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
8920 if (const SCEVConstant
*RC
= dyn_cast
<SCEVConstant
>(RHS
)) {
8921 const APInt
&RA
= RC
->getAPInt();
8923 bool SimplifiedByConstantRange
= false;
8925 if (!ICmpInst::isEquality(Pred
)) {
8926 ConstantRange ExactCR
= ConstantRange::makeExactICmpRegion(Pred
, RA
);
8927 if (ExactCR
.isFullSet())
8928 return TrivialCase(true);
8929 else if (ExactCR
.isEmptySet())
8930 return TrivialCase(false);
8933 CmpInst::Predicate NewPred
;
8934 if (ExactCR
.getEquivalentICmp(NewPred
, NewRHS
) &&
8935 ICmpInst::isEquality(NewPred
)) {
8936 // We were able to convert an inequality to an equality.
8938 RHS
= getConstant(NewRHS
);
8939 Changed
= SimplifiedByConstantRange
= true;
8943 if (!SimplifiedByConstantRange
) {
8947 case ICmpInst::ICMP_EQ
:
8948 case ICmpInst::ICMP_NE
:
8949 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
8951 if (const SCEVAddExpr
*AE
= dyn_cast
<SCEVAddExpr
>(LHS
))
8952 if (const SCEVMulExpr
*ME
=
8953 dyn_cast
<SCEVMulExpr
>(AE
->getOperand(0)))
8954 if (AE
->getNumOperands() == 2 && ME
->getNumOperands() == 2 &&
8955 ME
->getOperand(0)->isAllOnesValue()) {
8956 RHS
= AE
->getOperand(1);
8957 LHS
= ME
->getOperand(1);
8963 // The "Should have been caught earlier!" messages refer to the fact
8964 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
8965 // should have fired on the corresponding cases, and canonicalized the
8966 // check to trivial case.
8968 case ICmpInst::ICMP_UGE
:
8969 assert(!RA
.isMinValue() && "Should have been caught earlier!");
8970 Pred
= ICmpInst::ICMP_UGT
;
8971 RHS
= getConstant(RA
- 1);
8974 case ICmpInst::ICMP_ULE
:
8975 assert(!RA
.isMaxValue() && "Should have been caught earlier!");
8976 Pred
= ICmpInst::ICMP_ULT
;
8977 RHS
= getConstant(RA
+ 1);
8980 case ICmpInst::ICMP_SGE
:
8981 assert(!RA
.isMinSignedValue() && "Should have been caught earlier!");
8982 Pred
= ICmpInst::ICMP_SGT
;
8983 RHS
= getConstant(RA
- 1);
8986 case ICmpInst::ICMP_SLE
:
8987 assert(!RA
.isMaxSignedValue() && "Should have been caught earlier!");
8988 Pred
= ICmpInst::ICMP_SLT
;
8989 RHS
= getConstant(RA
+ 1);
8996 // Check for obvious equality.
8997 if (HasSameValue(LHS
, RHS
)) {
8998 if (ICmpInst::isTrueWhenEqual(Pred
))
8999 return TrivialCase(true);
9000 if (ICmpInst::isFalseWhenEqual(Pred
))
9001 return TrivialCase(false);
9004 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
9005 // adding or subtracting 1 from one of the operands.
9007 case ICmpInst::ICMP_SLE
:
9008 if (!getSignedRangeMax(RHS
).isMaxSignedValue()) {
9009 RHS
= getAddExpr(getConstant(RHS
->getType(), 1, true), RHS
,
9011 Pred
= ICmpInst::ICMP_SLT
;
9013 } else if (!getSignedRangeMin(LHS
).isMinSignedValue()) {
9014 LHS
= getAddExpr(getConstant(RHS
->getType(), (uint64_t)-1, true), LHS
,
9016 Pred
= ICmpInst::ICMP_SLT
;
9020 case ICmpInst::ICMP_SGE
:
9021 if (!getSignedRangeMin(RHS
).isMinSignedValue()) {
9022 RHS
= getAddExpr(getConstant(RHS
->getType(), (uint64_t)-1, true), RHS
,
9024 Pred
= ICmpInst::ICMP_SGT
;
9026 } else if (!getSignedRangeMax(LHS
).isMaxSignedValue()) {
9027 LHS
= getAddExpr(getConstant(RHS
->getType(), 1, true), LHS
,
9029 Pred
= ICmpInst::ICMP_SGT
;
9033 case ICmpInst::ICMP_ULE
:
9034 if (!getUnsignedRangeMax(RHS
).isMaxValue()) {
9035 RHS
= getAddExpr(getConstant(RHS
->getType(), 1, true), RHS
,
9037 Pred
= ICmpInst::ICMP_ULT
;
9039 } else if (!getUnsignedRangeMin(LHS
).isMinValue()) {
9040 LHS
= getAddExpr(getConstant(RHS
->getType(), (uint64_t)-1, true), LHS
);
9041 Pred
= ICmpInst::ICMP_ULT
;
9045 case ICmpInst::ICMP_UGE
:
9046 if (!getUnsignedRangeMin(RHS
).isMinValue()) {
9047 RHS
= getAddExpr(getConstant(RHS
->getType(), (uint64_t)-1, true), RHS
);
9048 Pred
= ICmpInst::ICMP_UGT
;
9050 } else if (!getUnsignedRangeMax(LHS
).isMaxValue()) {
9051 LHS
= getAddExpr(getConstant(RHS
->getType(), 1, true), LHS
,
9053 Pred
= ICmpInst::ICMP_UGT
;
9061 // TODO: More simplifications are possible here.
9063 // Recursively simplify until we either hit a recursion limit or nothing
9066 return SimplifyICmpOperands(Pred
, LHS
, RHS
, Depth
+1);
9071 bool ScalarEvolution::isKnownNegative(const SCEV
*S
) {
9072 return getSignedRangeMax(S
).isNegative();
9075 bool ScalarEvolution::isKnownPositive(const SCEV
*S
) {
9076 return getSignedRangeMin(S
).isStrictlyPositive();
9079 bool ScalarEvolution::isKnownNonNegative(const SCEV
*S
) {
9080 return !getSignedRangeMin(S
).isNegative();
9083 bool ScalarEvolution::isKnownNonPositive(const SCEV
*S
) {
9084 return !getSignedRangeMax(S
).isStrictlyPositive();
9087 bool ScalarEvolution::isKnownNonZero(const SCEV
*S
) {
9088 return isKnownNegative(S
) || isKnownPositive(S
);
9091 std::pair
<const SCEV
*, const SCEV
*>
9092 ScalarEvolution::SplitIntoInitAndPostInc(const Loop
*L
, const SCEV
*S
) {
9093 // Compute SCEV on entry of loop L.
9094 const SCEV
*Start
= SCEVInitRewriter::rewrite(S
, L
, *this);
9095 if (Start
== getCouldNotCompute())
9096 return { Start
, Start
};
9097 // Compute post increment SCEV for loop L.
9098 const SCEV
*PostInc
= SCEVPostIncRewriter::rewrite(S
, L
, *this);
9099 assert(PostInc
!= getCouldNotCompute() && "Unexpected could not compute");
9100 return { Start
, PostInc
};
9103 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred
,
9104 const SCEV
*LHS
, const SCEV
*RHS
) {
9105 // First collect all loops.
9106 SmallPtrSet
<const Loop
*, 8> LoopsUsed
;
9107 getUsedLoops(LHS
, LoopsUsed
);
9108 getUsedLoops(RHS
, LoopsUsed
);
9110 if (LoopsUsed
.empty())
9113 // Domination relationship must be a linear order on collected loops.
9115 for (auto *L1
: LoopsUsed
)
9116 for (auto *L2
: LoopsUsed
)
9117 assert((DT
.dominates(L1
->getHeader(), L2
->getHeader()) ||
9118 DT
.dominates(L2
->getHeader(), L1
->getHeader())) &&
9119 "Domination relationship is not a linear order");
9123 *std::max_element(LoopsUsed
.begin(), LoopsUsed
.end(),
9124 [&](const Loop
*L1
, const Loop
*L2
) {
9125 return DT
.properlyDominates(L1
->getHeader(), L2
->getHeader());
9128 // Get init and post increment value for LHS.
9129 auto SplitLHS
= SplitIntoInitAndPostInc(MDL
, LHS
);
9130 // if LHS contains unknown non-invariant SCEV then bail out.
9131 if (SplitLHS
.first
== getCouldNotCompute())
9133 assert (SplitLHS
.second
!= getCouldNotCompute() && "Unexpected CNC");
9134 // Get init and post increment value for RHS.
9135 auto SplitRHS
= SplitIntoInitAndPostInc(MDL
, RHS
);
9136 // if RHS contains unknown non-invariant SCEV then bail out.
9137 if (SplitRHS
.first
== getCouldNotCompute())
9139 assert (SplitRHS
.second
!= getCouldNotCompute() && "Unexpected CNC");
9140 // It is possible that init SCEV contains an invariant load but it does
9141 // not dominate MDL and is not available at MDL loop entry, so we should
9143 if (!isAvailableAtLoopEntry(SplitLHS
.first
, MDL
) ||
9144 !isAvailableAtLoopEntry(SplitRHS
.first
, MDL
))
9147 return isLoopEntryGuardedByCond(MDL
, Pred
, SplitLHS
.first
, SplitRHS
.first
) &&
9148 isLoopBackedgeGuardedByCond(MDL
, Pred
, SplitLHS
.second
,
9152 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred
,
9153 const SCEV
*LHS
, const SCEV
*RHS
) {
9154 // Canonicalize the inputs first.
9155 (void)SimplifyICmpOperands(Pred
, LHS
, RHS
);
9157 if (isKnownViaInduction(Pred
, LHS
, RHS
))
9160 if (isKnownPredicateViaSplitting(Pred
, LHS
, RHS
))
9163 // Otherwise see what can be done with some simple reasoning.
9164 return isKnownViaNonRecursiveReasoning(Pred
, LHS
, RHS
);
9167 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred
,
9168 const SCEVAddRecExpr
*LHS
,
9170 const Loop
*L
= LHS
->getLoop();
9171 return isLoopEntryGuardedByCond(L
, Pred
, LHS
->getStart(), RHS
) &&
9172 isLoopBackedgeGuardedByCond(L
, Pred
, LHS
->getPostIncExpr(*this), RHS
);
9175 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr
*LHS
,
9176 ICmpInst::Predicate Pred
,
9178 bool Result
= isMonotonicPredicateImpl(LHS
, Pred
, Increasing
);
9181 // Verify an invariant: inverting the predicate should turn a monotonically
9182 // increasing change to a monotonically decreasing one, and vice versa.
9183 bool IncreasingSwapped
;
9184 bool ResultSwapped
= isMonotonicPredicateImpl(
9185 LHS
, ICmpInst::getSwappedPredicate(Pred
), IncreasingSwapped
);
9187 assert(Result
== ResultSwapped
&& "should be able to analyze both!");
9189 assert(Increasing
== !IncreasingSwapped
&&
9190 "monotonicity should flip as we flip the predicate");
9196 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr
*LHS
,
9197 ICmpInst::Predicate Pred
,
9200 // A zero step value for LHS means the induction variable is essentially a
9201 // loop invariant value. We don't really depend on the predicate actually
9202 // flipping from false to true (for increasing predicates, and the other way
9203 // around for decreasing predicates), all we care about is that *if* the
9204 // predicate changes then it only changes from false to true.
9206 // A zero step value in itself is not very useful, but there may be places
9207 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
9208 // as general as possible.
9212 return false; // Conservative answer
9214 case ICmpInst::ICMP_UGT
:
9215 case ICmpInst::ICMP_UGE
:
9216 case ICmpInst::ICMP_ULT
:
9217 case ICmpInst::ICMP_ULE
:
9218 if (!LHS
->hasNoUnsignedWrap())
9221 Increasing
= Pred
== ICmpInst::ICMP_UGT
|| Pred
== ICmpInst::ICMP_UGE
;
9224 case ICmpInst::ICMP_SGT
:
9225 case ICmpInst::ICMP_SGE
:
9226 case ICmpInst::ICMP_SLT
:
9227 case ICmpInst::ICMP_SLE
: {
9228 if (!LHS
->hasNoSignedWrap())
9231 const SCEV
*Step
= LHS
->getStepRecurrence(*this);
9233 if (isKnownNonNegative(Step
)) {
9234 Increasing
= Pred
== ICmpInst::ICMP_SGT
|| Pred
== ICmpInst::ICMP_SGE
;
9238 if (isKnownNonPositive(Step
)) {
9239 Increasing
= Pred
== ICmpInst::ICMP_SLT
|| Pred
== ICmpInst::ICMP_SLE
;
9248 llvm_unreachable("switch has default clause!");
9251 bool ScalarEvolution::isLoopInvariantPredicate(
9252 ICmpInst::Predicate Pred
, const SCEV
*LHS
, const SCEV
*RHS
, const Loop
*L
,
9253 ICmpInst::Predicate
&InvariantPred
, const SCEV
*&InvariantLHS
,
9254 const SCEV
*&InvariantRHS
) {
9256 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
9257 if (!isLoopInvariant(RHS
, L
)) {
9258 if (!isLoopInvariant(LHS
, L
))
9261 std::swap(LHS
, RHS
);
9262 Pred
= ICmpInst::getSwappedPredicate(Pred
);
9265 const SCEVAddRecExpr
*ArLHS
= dyn_cast
<SCEVAddRecExpr
>(LHS
);
9266 if (!ArLHS
|| ArLHS
->getLoop() != L
)
9270 if (!isMonotonicPredicate(ArLHS
, Pred
, Increasing
))
9273 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
9274 // true as the loop iterates, and the backedge is control dependent on
9275 // "ArLHS `Pred` RHS" == true then we can reason as follows:
9277 // * if the predicate was false in the first iteration then the predicate
9278 // is never evaluated again, since the loop exits without taking the
9280 // * if the predicate was true in the first iteration then it will
9281 // continue to be true for all future iterations since it is
9282 // monotonically increasing.
9284 // For both the above possibilities, we can replace the loop varying
9285 // predicate with its value on the first iteration of the loop (which is
9288 // A similar reasoning applies for a monotonically decreasing predicate, by
9289 // replacing true with false and false with true in the above two bullets.
9291 auto P
= Increasing
? Pred
: ICmpInst::getInversePredicate(Pred
);
9293 if (!isLoopBackedgeGuardedByCond(L
, P
, LHS
, RHS
))
9296 InvariantPred
= Pred
;
9297 InvariantLHS
= ArLHS
->getStart();
9302 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
9303 ICmpInst::Predicate Pred
, const SCEV
*LHS
, const SCEV
*RHS
) {
9304 if (HasSameValue(LHS
, RHS
))
9305 return ICmpInst::isTrueWhenEqual(Pred
);
9307 // This code is split out from isKnownPredicate because it is called from
9308 // within isLoopEntryGuardedByCond.
9311 [&](const ConstantRange
&RangeLHS
, const ConstantRange
&RangeRHS
) {
9312 return ConstantRange::makeSatisfyingICmpRegion(Pred
, RangeRHS
)
9313 .contains(RangeLHS
);
9316 // The check at the top of the function catches the case where the values are
9317 // known to be equal.
9318 if (Pred
== CmpInst::ICMP_EQ
)
9321 if (Pred
== CmpInst::ICMP_NE
)
9322 return CheckRanges(getSignedRange(LHS
), getSignedRange(RHS
)) ||
9323 CheckRanges(getUnsignedRange(LHS
), getUnsignedRange(RHS
)) ||
9324 isKnownNonZero(getMinusSCEV(LHS
, RHS
));
9326 if (CmpInst::isSigned(Pred
))
9327 return CheckRanges(getSignedRange(LHS
), getSignedRange(RHS
));
9329 return CheckRanges(getUnsignedRange(LHS
), getUnsignedRange(RHS
));
9332 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred
,
9335 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
9336 // Return Y via OutY.
9337 auto MatchBinaryAddToConst
=
9338 [this](const SCEV
*Result
, const SCEV
*X
, APInt
&OutY
,
9339 SCEV::NoWrapFlags ExpectedFlags
) {
9340 const SCEV
*NonConstOp
, *ConstOp
;
9341 SCEV::NoWrapFlags FlagsPresent
;
9343 if (!splitBinaryAdd(Result
, ConstOp
, NonConstOp
, FlagsPresent
) ||
9344 !isa
<SCEVConstant
>(ConstOp
) || NonConstOp
!= X
)
9347 OutY
= cast
<SCEVConstant
>(ConstOp
)->getAPInt();
9348 return (FlagsPresent
& ExpectedFlags
) == ExpectedFlags
;
9357 case ICmpInst::ICMP_SGE
:
9358 std::swap(LHS
, RHS
);
9360 case ICmpInst::ICMP_SLE
:
9361 // X s<= (X + C)<nsw> if C >= 0
9362 if (MatchBinaryAddToConst(RHS
, LHS
, C
, SCEV::FlagNSW
) && C
.isNonNegative())
9365 // (X + C)<nsw> s<= X if C <= 0
9366 if (MatchBinaryAddToConst(LHS
, RHS
, C
, SCEV::FlagNSW
) &&
9367 !C
.isStrictlyPositive())
9371 case ICmpInst::ICMP_SGT
:
9372 std::swap(LHS
, RHS
);
9374 case ICmpInst::ICMP_SLT
:
9375 // X s< (X + C)<nsw> if C > 0
9376 if (MatchBinaryAddToConst(RHS
, LHS
, C
, SCEV::FlagNSW
) &&
9377 C
.isStrictlyPositive())
9380 // (X + C)<nsw> s< X if C < 0
9381 if (MatchBinaryAddToConst(LHS
, RHS
, C
, SCEV::FlagNSW
) && C
.isNegative())
9389 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred
,
9392 if (Pred
!= ICmpInst::ICMP_ULT
|| ProvingSplitPredicate
)
9395 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
9396 // the stack can result in exponential time complexity.
9397 SaveAndRestore
<bool> Restore(ProvingSplitPredicate
, true);
9399 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
9401 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
9402 // isKnownPredicate. isKnownPredicate is more powerful, but also more
9403 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
9404 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
9405 // use isKnownPredicate later if needed.
9406 return isKnownNonNegative(RHS
) &&
9407 isKnownPredicate(CmpInst::ICMP_SGE
, LHS
, getZero(LHS
->getType())) &&
9408 isKnownPredicate(CmpInst::ICMP_SLT
, LHS
, RHS
);
9411 bool ScalarEvolution::isImpliedViaGuard(BasicBlock
*BB
,
9412 ICmpInst::Predicate Pred
,
9413 const SCEV
*LHS
, const SCEV
*RHS
) {
9414 // No need to even try if we know the module has no guards.
9418 return any_of(*BB
, [&](Instruction
&I
) {
9419 using namespace llvm::PatternMatch
;
9422 return match(&I
, m_Intrinsic
<Intrinsic::experimental_guard
>(
9423 m_Value(Condition
))) &&
9424 isImpliedCond(Pred
, LHS
, RHS
, Condition
, false);
9428 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
9429 /// protected by a conditional between LHS and RHS. This is used to
9430 /// to eliminate casts.
9432 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop
*L
,
9433 ICmpInst::Predicate Pred
,
9434 const SCEV
*LHS
, const SCEV
*RHS
) {
9435 // Interpret a null as meaning no loop, where there is obviously no guard
9436 // (interprocedural conditions notwithstanding).
9437 if (!L
) return true;
9440 assert(!verifyFunction(*L
->getHeader()->getParent(), &dbgs()) &&
9441 "This cannot be done on broken IR!");
9444 if (isKnownViaNonRecursiveReasoning(Pred
, LHS
, RHS
))
9447 BasicBlock
*Latch
= L
->getLoopLatch();
9451 BranchInst
*LoopContinuePredicate
=
9452 dyn_cast
<BranchInst
>(Latch
->getTerminator());
9453 if (LoopContinuePredicate
&& LoopContinuePredicate
->isConditional() &&
9454 isImpliedCond(Pred
, LHS
, RHS
,
9455 LoopContinuePredicate
->getCondition(),
9456 LoopContinuePredicate
->getSuccessor(0) != L
->getHeader()))
9459 // We don't want more than one activation of the following loops on the stack
9460 // -- that can lead to O(n!) time complexity.
9461 if (WalkingBEDominatingConds
)
9464 SaveAndRestore
<bool> ClearOnExit(WalkingBEDominatingConds
, true);
9466 // See if we can exploit a trip count to prove the predicate.
9467 const auto &BETakenInfo
= getBackedgeTakenInfo(L
);
9468 const SCEV
*LatchBECount
= BETakenInfo
.getExact(Latch
, this);
9469 if (LatchBECount
!= getCouldNotCompute()) {
9470 // We know that Latch branches back to the loop header exactly
9471 // LatchBECount times. This means the backdege condition at Latch is
9472 // equivalent to "{0,+,1} u< LatchBECount".
9473 Type
*Ty
= LatchBECount
->getType();
9474 auto NoWrapFlags
= SCEV::NoWrapFlags(SCEV::FlagNUW
| SCEV::FlagNW
);
9475 const SCEV
*LoopCounter
=
9476 getAddRecExpr(getZero(Ty
), getOne(Ty
), L
, NoWrapFlags
);
9477 if (isImpliedCond(Pred
, LHS
, RHS
, ICmpInst::ICMP_ULT
, LoopCounter
,
9482 // Check conditions due to any @llvm.assume intrinsics.
9483 for (auto &AssumeVH
: AC
.assumptions()) {
9486 auto *CI
= cast
<CallInst
>(AssumeVH
);
9487 if (!DT
.dominates(CI
, Latch
->getTerminator()))
9490 if (isImpliedCond(Pred
, LHS
, RHS
, CI
->getArgOperand(0), false))
9494 // If the loop is not reachable from the entry block, we risk running into an
9495 // infinite loop as we walk up into the dom tree. These loops do not matter
9496 // anyway, so we just return a conservative answer when we see them.
9497 if (!DT
.isReachableFromEntry(L
->getHeader()))
9500 if (isImpliedViaGuard(Latch
, Pred
, LHS
, RHS
))
9503 for (DomTreeNode
*DTN
= DT
[Latch
], *HeaderDTN
= DT
[L
->getHeader()];
9504 DTN
!= HeaderDTN
; DTN
= DTN
->getIDom()) {
9505 assert(DTN
&& "should reach the loop header before reaching the root!");
9507 BasicBlock
*BB
= DTN
->getBlock();
9508 if (isImpliedViaGuard(BB
, Pred
, LHS
, RHS
))
9511 BasicBlock
*PBB
= BB
->getSinglePredecessor();
9515 BranchInst
*ContinuePredicate
= dyn_cast
<BranchInst
>(PBB
->getTerminator());
9516 if (!ContinuePredicate
|| !ContinuePredicate
->isConditional())
9519 Value
*Condition
= ContinuePredicate
->getCondition();
9521 // If we have an edge `E` within the loop body that dominates the only
9522 // latch, the condition guarding `E` also guards the backedge. This
9523 // reasoning works only for loops with a single latch.
9525 BasicBlockEdge
DominatingEdge(PBB
, BB
);
9526 if (DominatingEdge
.isSingleEdge()) {
9527 // We're constructively (and conservatively) enumerating edges within the
9528 // loop body that dominate the latch. The dominator tree better agree
9530 assert(DT
.dominates(DominatingEdge
, Latch
) && "should be!");
9532 if (isImpliedCond(Pred
, LHS
, RHS
, Condition
,
9533 BB
!= ContinuePredicate
->getSuccessor(0)))
9542 ScalarEvolution::isLoopEntryGuardedByCond(const Loop
*L
,
9543 ICmpInst::Predicate Pred
,
9544 const SCEV
*LHS
, const SCEV
*RHS
) {
9545 // Interpret a null as meaning no loop, where there is obviously no guard
9546 // (interprocedural conditions notwithstanding).
9547 if (!L
) return false;
9550 assert(!verifyFunction(*L
->getHeader()->getParent(), &dbgs()) &&
9551 "This cannot be done on broken IR!");
9553 // Both LHS and RHS must be available at loop entry.
9554 assert(isAvailableAtLoopEntry(LHS
, L
) &&
9555 "LHS is not available at Loop Entry");
9556 assert(isAvailableAtLoopEntry(RHS
, L
) &&
9557 "RHS is not available at Loop Entry");
9559 if (isKnownViaNonRecursiveReasoning(Pred
, LHS
, RHS
))
9562 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
9563 // the facts (a >= b && a != b) separately. A typical situation is when the
9564 // non-strict comparison is known from ranges and non-equality is known from
9565 // dominating predicates. If we are proving strict comparison, we always try
9566 // to prove non-equality and non-strict comparison separately.
9567 auto NonStrictPredicate
= ICmpInst::getNonStrictPredicate(Pred
);
9568 const bool ProvingStrictComparison
= (Pred
!= NonStrictPredicate
);
9569 bool ProvedNonStrictComparison
= false;
9570 bool ProvedNonEquality
= false;
9572 if (ProvingStrictComparison
) {
9573 ProvedNonStrictComparison
=
9574 isKnownViaNonRecursiveReasoning(NonStrictPredicate
, LHS
, RHS
);
9576 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE
, LHS
, RHS
);
9577 if (ProvedNonStrictComparison
&& ProvedNonEquality
)
9581 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
9582 auto ProveViaGuard
= [&](BasicBlock
*Block
) {
9583 if (isImpliedViaGuard(Block
, Pred
, LHS
, RHS
))
9585 if (ProvingStrictComparison
) {
9586 if (!ProvedNonStrictComparison
)
9587 ProvedNonStrictComparison
=
9588 isImpliedViaGuard(Block
, NonStrictPredicate
, LHS
, RHS
);
9589 if (!ProvedNonEquality
)
9591 isImpliedViaGuard(Block
, ICmpInst::ICMP_NE
, LHS
, RHS
);
9592 if (ProvedNonStrictComparison
&& ProvedNonEquality
)
9598 // Try to prove (Pred, LHS, RHS) using isImpliedCond.
9599 auto ProveViaCond
= [&](Value
*Condition
, bool Inverse
) {
9600 if (isImpliedCond(Pred
, LHS
, RHS
, Condition
, Inverse
))
9602 if (ProvingStrictComparison
) {
9603 if (!ProvedNonStrictComparison
)
9604 ProvedNonStrictComparison
=
9605 isImpliedCond(NonStrictPredicate
, LHS
, RHS
, Condition
, Inverse
);
9606 if (!ProvedNonEquality
)
9608 isImpliedCond(ICmpInst::ICMP_NE
, LHS
, RHS
, Condition
, Inverse
);
9609 if (ProvedNonStrictComparison
&& ProvedNonEquality
)
9615 // Starting at the loop predecessor, climb up the predecessor chain, as long
9616 // as there are predecessors that can be found that have unique successors
9617 // leading to the original header.
9618 for (std::pair
<BasicBlock
*, BasicBlock
*>
9619 Pair(L
->getLoopPredecessor(), L
->getHeader());
9621 Pair
= getPredecessorWithUniqueSuccessorForBB(Pair
.first
)) {
9623 if (ProveViaGuard(Pair
.first
))
9626 BranchInst
*LoopEntryPredicate
=
9627 dyn_cast
<BranchInst
>(Pair
.first
->getTerminator());
9628 if (!LoopEntryPredicate
||
9629 LoopEntryPredicate
->isUnconditional())
9632 if (ProveViaCond(LoopEntryPredicate
->getCondition(),
9633 LoopEntryPredicate
->getSuccessor(0) != Pair
.second
))
9637 // Check conditions due to any @llvm.assume intrinsics.
9638 for (auto &AssumeVH
: AC
.assumptions()) {
9641 auto *CI
= cast
<CallInst
>(AssumeVH
);
9642 if (!DT
.dominates(CI
, L
->getHeader()))
9645 if (ProveViaCond(CI
->getArgOperand(0), false))
9652 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred
,
9653 const SCEV
*LHS
, const SCEV
*RHS
,
9654 Value
*FoundCondValue
,
9656 if (!PendingLoopPredicates
.insert(FoundCondValue
).second
)
9660 make_scope_exit([&]() { PendingLoopPredicates
.erase(FoundCondValue
); });
9662 // Recursively handle And and Or conditions.
9663 if (BinaryOperator
*BO
= dyn_cast
<BinaryOperator
>(FoundCondValue
)) {
9664 if (BO
->getOpcode() == Instruction::And
) {
9666 return isImpliedCond(Pred
, LHS
, RHS
, BO
->getOperand(0), Inverse
) ||
9667 isImpliedCond(Pred
, LHS
, RHS
, BO
->getOperand(1), Inverse
);
9668 } else if (BO
->getOpcode() == Instruction::Or
) {
9670 return isImpliedCond(Pred
, LHS
, RHS
, BO
->getOperand(0), Inverse
) ||
9671 isImpliedCond(Pred
, LHS
, RHS
, BO
->getOperand(1), Inverse
);
9675 ICmpInst
*ICI
= dyn_cast
<ICmpInst
>(FoundCondValue
);
9676 if (!ICI
) return false;
9678 // Now that we found a conditional branch that dominates the loop or controls
9679 // the loop latch. Check to see if it is the comparison we are looking for.
9680 ICmpInst::Predicate FoundPred
;
9682 FoundPred
= ICI
->getInversePredicate();
9684 FoundPred
= ICI
->getPredicate();
9686 const SCEV
*FoundLHS
= getSCEV(ICI
->getOperand(0));
9687 const SCEV
*FoundRHS
= getSCEV(ICI
->getOperand(1));
9689 return isImpliedCond(Pred
, LHS
, RHS
, FoundPred
, FoundLHS
, FoundRHS
);
9692 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred
, const SCEV
*LHS
,
9694 ICmpInst::Predicate FoundPred
,
9695 const SCEV
*FoundLHS
,
9696 const SCEV
*FoundRHS
) {
9697 // Balance the types.
9698 if (getTypeSizeInBits(LHS
->getType()) <
9699 getTypeSizeInBits(FoundLHS
->getType())) {
9700 if (CmpInst::isSigned(Pred
)) {
9701 LHS
= getSignExtendExpr(LHS
, FoundLHS
->getType());
9702 RHS
= getSignExtendExpr(RHS
, FoundLHS
->getType());
9704 LHS
= getZeroExtendExpr(LHS
, FoundLHS
->getType());
9705 RHS
= getZeroExtendExpr(RHS
, FoundLHS
->getType());
9707 } else if (getTypeSizeInBits(LHS
->getType()) >
9708 getTypeSizeInBits(FoundLHS
->getType())) {
9709 if (CmpInst::isSigned(FoundPred
)) {
9710 FoundLHS
= getSignExtendExpr(FoundLHS
, LHS
->getType());
9711 FoundRHS
= getSignExtendExpr(FoundRHS
, LHS
->getType());
9713 FoundLHS
= getZeroExtendExpr(FoundLHS
, LHS
->getType());
9714 FoundRHS
= getZeroExtendExpr(FoundRHS
, LHS
->getType());
9718 // Canonicalize the query to match the way instcombine will have
9719 // canonicalized the comparison.
9720 if (SimplifyICmpOperands(Pred
, LHS
, RHS
))
9722 return CmpInst::isTrueWhenEqual(Pred
);
9723 if (SimplifyICmpOperands(FoundPred
, FoundLHS
, FoundRHS
))
9724 if (FoundLHS
== FoundRHS
)
9725 return CmpInst::isFalseWhenEqual(FoundPred
);
9727 // Check to see if we can make the LHS or RHS match.
9728 if (LHS
== FoundRHS
|| RHS
== FoundLHS
) {
9729 if (isa
<SCEVConstant
>(RHS
)) {
9730 std::swap(FoundLHS
, FoundRHS
);
9731 FoundPred
= ICmpInst::getSwappedPredicate(FoundPred
);
9733 std::swap(LHS
, RHS
);
9734 Pred
= ICmpInst::getSwappedPredicate(Pred
);
9738 // Check whether the found predicate is the same as the desired predicate.
9739 if (FoundPred
== Pred
)
9740 return isImpliedCondOperands(Pred
, LHS
, RHS
, FoundLHS
, FoundRHS
);
9742 // Check whether swapping the found predicate makes it the same as the
9743 // desired predicate.
9744 if (ICmpInst::getSwappedPredicate(FoundPred
) == Pred
) {
9745 if (isa
<SCEVConstant
>(RHS
))
9746 return isImpliedCondOperands(Pred
, LHS
, RHS
, FoundRHS
, FoundLHS
);
9748 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred
),
9749 RHS
, LHS
, FoundLHS
, FoundRHS
);
9752 // Unsigned comparison is the same as signed comparison when both the operands
9753 // are non-negative.
9754 if (CmpInst::isUnsigned(FoundPred
) &&
9755 CmpInst::getSignedPredicate(FoundPred
) == Pred
&&
9756 isKnownNonNegative(FoundLHS
) && isKnownNonNegative(FoundRHS
))
9757 return isImpliedCondOperands(Pred
, LHS
, RHS
, FoundLHS
, FoundRHS
);
9759 // Check if we can make progress by sharpening ranges.
9760 if (FoundPred
== ICmpInst::ICMP_NE
&&
9761 (isa
<SCEVConstant
>(FoundLHS
) || isa
<SCEVConstant
>(FoundRHS
))) {
9763 const SCEVConstant
*C
= nullptr;
9764 const SCEV
*V
= nullptr;
9766 if (isa
<SCEVConstant
>(FoundLHS
)) {
9767 C
= cast
<SCEVConstant
>(FoundLHS
);
9770 C
= cast
<SCEVConstant
>(FoundRHS
);
9774 // The guarding predicate tells us that C != V. If the known range
9775 // of V is [C, t), we can sharpen the range to [C + 1, t). The
9776 // range we consider has to correspond to same signedness as the
9777 // predicate we're interested in folding.
9779 APInt Min
= ICmpInst::isSigned(Pred
) ?
9780 getSignedRangeMin(V
) : getUnsignedRangeMin(V
);
9782 if (Min
== C
->getAPInt()) {
9783 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
9784 // This is true even if (Min + 1) wraps around -- in case of
9785 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
9787 APInt SharperMin
= Min
+ 1;
9790 case ICmpInst::ICMP_SGE
:
9791 case ICmpInst::ICMP_UGE
:
9792 // We know V `Pred` SharperMin. If this implies LHS `Pred`
9794 if (isImpliedCondOperands(Pred
, LHS
, RHS
, V
,
9795 getConstant(SharperMin
)))
9799 case ICmpInst::ICMP_SGT
:
9800 case ICmpInst::ICMP_UGT
:
9801 // We know from the range information that (V `Pred` Min ||
9802 // V == Min). We know from the guarding condition that !(V
9803 // == Min). This gives us
9805 // V `Pred` Min || V == Min && !(V == Min)
9808 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
9810 if (isImpliedCondOperands(Pred
, LHS
, RHS
, V
, getConstant(Min
)))
9821 // Check whether the actual condition is beyond sufficient.
9822 if (FoundPred
== ICmpInst::ICMP_EQ
)
9823 if (ICmpInst::isTrueWhenEqual(Pred
))
9824 if (isImpliedCondOperands(Pred
, LHS
, RHS
, FoundLHS
, FoundRHS
))
9826 if (Pred
== ICmpInst::ICMP_NE
)
9827 if (!ICmpInst::isTrueWhenEqual(FoundPred
))
9828 if (isImpliedCondOperands(FoundPred
, LHS
, RHS
, FoundLHS
, FoundRHS
))
9831 // Otherwise assume the worst.
9835 bool ScalarEvolution::splitBinaryAdd(const SCEV
*Expr
,
9836 const SCEV
*&L
, const SCEV
*&R
,
9837 SCEV::NoWrapFlags
&Flags
) {
9838 const auto *AE
= dyn_cast
<SCEVAddExpr
>(Expr
);
9839 if (!AE
|| AE
->getNumOperands() != 2)
9842 L
= AE
->getOperand(0);
9843 R
= AE
->getOperand(1);
9844 Flags
= AE
->getNoWrapFlags();
9848 Optional
<APInt
> ScalarEvolution::computeConstantDifference(const SCEV
*More
,
9850 // We avoid subtracting expressions here because this function is usually
9851 // fairly deep in the call stack (i.e. is called many times).
9855 return APInt(getTypeSizeInBits(More
->getType()), 0);
9857 if (isa
<SCEVAddRecExpr
>(Less
) && isa
<SCEVAddRecExpr
>(More
)) {
9858 const auto *LAR
= cast
<SCEVAddRecExpr
>(Less
);
9859 const auto *MAR
= cast
<SCEVAddRecExpr
>(More
);
9861 if (LAR
->getLoop() != MAR
->getLoop())
9864 // We look at affine expressions only; not for correctness but to keep
9865 // getStepRecurrence cheap.
9866 if (!LAR
->isAffine() || !MAR
->isAffine())
9869 if (LAR
->getStepRecurrence(*this) != MAR
->getStepRecurrence(*this))
9872 Less
= LAR
->getStart();
9873 More
= MAR
->getStart();
9878 if (isa
<SCEVConstant
>(Less
) && isa
<SCEVConstant
>(More
)) {
9879 const auto &M
= cast
<SCEVConstant
>(More
)->getAPInt();
9880 const auto &L
= cast
<SCEVConstant
>(Less
)->getAPInt();
9884 SCEV::NoWrapFlags Flags
;
9885 const SCEV
*LLess
= nullptr, *RLess
= nullptr;
9886 const SCEV
*LMore
= nullptr, *RMore
= nullptr;
9887 const SCEVConstant
*C1
= nullptr, *C2
= nullptr;
9888 // Compare (X + C1) vs X.
9889 if (splitBinaryAdd(Less
, LLess
, RLess
, Flags
))
9890 if ((C1
= dyn_cast
<SCEVConstant
>(LLess
)))
9892 return -(C1
->getAPInt());
9894 // Compare X vs (X + C2).
9895 if (splitBinaryAdd(More
, LMore
, RMore
, Flags
))
9896 if ((C2
= dyn_cast
<SCEVConstant
>(LMore
)))
9898 return C2
->getAPInt();
9900 // Compare (X + C1) vs (X + C2).
9901 if (C1
&& C2
&& RLess
== RMore
)
9902 return C2
->getAPInt() - C1
->getAPInt();
9907 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
9908 ICmpInst::Predicate Pred
, const SCEV
*LHS
, const SCEV
*RHS
,
9909 const SCEV
*FoundLHS
, const SCEV
*FoundRHS
) {
9910 if (Pred
!= CmpInst::ICMP_SLT
&& Pred
!= CmpInst::ICMP_ULT
)
9913 const auto *AddRecLHS
= dyn_cast
<SCEVAddRecExpr
>(LHS
);
9917 const auto *AddRecFoundLHS
= dyn_cast
<SCEVAddRecExpr
>(FoundLHS
);
9918 if (!AddRecFoundLHS
)
9921 // We'd like to let SCEV reason about control dependencies, so we constrain
9922 // both the inequalities to be about add recurrences on the same loop. This
9923 // way we can use isLoopEntryGuardedByCond later.
9925 const Loop
*L
= AddRecFoundLHS
->getLoop();
9926 if (L
!= AddRecLHS
->getLoop())
9929 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
9931 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
9934 // Informal proof for (2), assuming (1) [*]:
9936 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
9940 // FoundLHS s< FoundRHS s< INT_MIN - C
9941 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
9942 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
9943 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
9944 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
9945 // <=> FoundLHS + C s< FoundRHS + C
9947 // [*]: (1) can be proved by ruling out overflow.
9949 // [**]: This can be proved by analyzing all the four possibilities:
9950 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
9951 // (A s>= 0, B s>= 0).
9954 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
9955 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
9956 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
9957 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
9958 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
9961 Optional
<APInt
> LDiff
= computeConstantDifference(LHS
, FoundLHS
);
9962 Optional
<APInt
> RDiff
= computeConstantDifference(RHS
, FoundRHS
);
9963 if (!LDiff
|| !RDiff
|| *LDiff
!= *RDiff
)
9966 if (LDiff
->isMinValue())
9969 APInt FoundRHSLimit
;
9971 if (Pred
== CmpInst::ICMP_ULT
) {
9972 FoundRHSLimit
= -(*RDiff
);
9974 assert(Pred
== CmpInst::ICMP_SLT
&& "Checked above!");
9975 FoundRHSLimit
= APInt::getSignedMinValue(getTypeSizeInBits(RHS
->getType())) - *RDiff
;
9978 // Try to prove (1) or (2), as needed.
9979 return isAvailableAtLoopEntry(FoundRHS
, L
) &&
9980 isLoopEntryGuardedByCond(L
, Pred
, FoundRHS
,
9981 getConstant(FoundRHSLimit
));
9984 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred
,
9985 const SCEV
*LHS
, const SCEV
*RHS
,
9986 const SCEV
*FoundLHS
,
9987 const SCEV
*FoundRHS
, unsigned Depth
) {
9988 const PHINode
*LPhi
= nullptr, *RPhi
= nullptr;
9990 auto ClearOnExit
= make_scope_exit([&]() {
9992 bool Erased
= PendingMerges
.erase(LPhi
);
9993 assert(Erased
&& "Failed to erase LPhi!");
9997 bool Erased
= PendingMerges
.erase(RPhi
);
9998 assert(Erased
&& "Failed to erase RPhi!");
10003 // Find respective Phis and check that they are not being pending.
10004 if (const SCEVUnknown
*LU
= dyn_cast
<SCEVUnknown
>(LHS
))
10005 if (auto *Phi
= dyn_cast
<PHINode
>(LU
->getValue())) {
10006 if (!PendingMerges
.insert(Phi
).second
)
10010 if (const SCEVUnknown
*RU
= dyn_cast
<SCEVUnknown
>(RHS
))
10011 if (auto *Phi
= dyn_cast
<PHINode
>(RU
->getValue())) {
10012 // If we detect a loop of Phi nodes being processed by this method, for
10015 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
10016 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
10018 // we don't want to deal with a case that complex, so return conservative
10020 if (!PendingMerges
.insert(Phi
).second
)
10025 // If none of LHS, RHS is a Phi, nothing to do here.
10026 if (!LPhi
&& !RPhi
)
10029 // If there is a SCEVUnknown Phi we are interested in, make it left.
10031 std::swap(LHS
, RHS
);
10032 std::swap(FoundLHS
, FoundRHS
);
10033 std::swap(LPhi
, RPhi
);
10034 Pred
= ICmpInst::getSwappedPredicate(Pred
);
10037 assert(LPhi
&& "LPhi should definitely be a SCEVUnknown Phi!");
10038 const BasicBlock
*LBB
= LPhi
->getParent();
10039 const SCEVAddRecExpr
*RAR
= dyn_cast
<SCEVAddRecExpr
>(RHS
);
10041 auto ProvedEasily
= [&](const SCEV
*S1
, const SCEV
*S2
) {
10042 return isKnownViaNonRecursiveReasoning(Pred
, S1
, S2
) ||
10043 isImpliedCondOperandsViaRanges(Pred
, S1
, S2
, FoundLHS
, FoundRHS
) ||
10044 isImpliedViaOperations(Pred
, S1
, S2
, FoundLHS
, FoundRHS
, Depth
);
10047 if (RPhi
&& RPhi
->getParent() == LBB
) {
10048 // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
10049 // If we compare two Phis from the same block, and for each entry block
10050 // the predicate is true for incoming values from this block, then the
10051 // predicate is also true for the Phis.
10052 for (const BasicBlock
*IncBB
: predecessors(LBB
)) {
10053 const SCEV
*L
= getSCEV(LPhi
->getIncomingValueForBlock(IncBB
));
10054 const SCEV
*R
= getSCEV(RPhi
->getIncomingValueForBlock(IncBB
));
10055 if (!ProvedEasily(L
, R
))
10058 } else if (RAR
&& RAR
->getLoop()->getHeader() == LBB
) {
10059 // Case two: RHS is also a Phi from the same basic block, and it is an
10060 // AddRec. It means that there is a loop which has both AddRec and Unknown
10061 // PHIs, for it we can compare incoming values of AddRec from above the loop
10062 // and latch with their respective incoming values of LPhi.
10063 // TODO: Generalize to handle loops with many inputs in a header.
10064 if (LPhi
->getNumIncomingValues() != 2) return false;
10066 auto *RLoop
= RAR
->getLoop();
10067 auto *Predecessor
= RLoop
->getLoopPredecessor();
10068 assert(Predecessor
&& "Loop with AddRec with no predecessor?");
10069 const SCEV
*L1
= getSCEV(LPhi
->getIncomingValueForBlock(Predecessor
));
10070 if (!ProvedEasily(L1
, RAR
->getStart()))
10072 auto *Latch
= RLoop
->getLoopLatch();
10073 assert(Latch
&& "Loop with AddRec with no latch?");
10074 const SCEV
*L2
= getSCEV(LPhi
->getIncomingValueForBlock(Latch
));
10075 if (!ProvedEasily(L2
, RAR
->getPostIncExpr(*this)))
10078 // In all other cases go over inputs of LHS and compare each of them to RHS,
10079 // the predicate is true for (LHS, RHS) if it is true for all such pairs.
10080 // At this point RHS is either a non-Phi, or it is a Phi from some block
10081 // different from LBB.
10082 for (const BasicBlock
*IncBB
: predecessors(LBB
)) {
10083 // Check that RHS is available in this block.
10084 if (!dominates(RHS
, IncBB
))
10086 const SCEV
*L
= getSCEV(LPhi
->getIncomingValueForBlock(IncBB
));
10087 if (!ProvedEasily(L
, RHS
))
10094 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred
,
10095 const SCEV
*LHS
, const SCEV
*RHS
,
10096 const SCEV
*FoundLHS
,
10097 const SCEV
*FoundRHS
) {
10098 if (isImpliedCondOperandsViaRanges(Pred
, LHS
, RHS
, FoundLHS
, FoundRHS
))
10101 if (isImpliedCondOperandsViaNoOverflow(Pred
, LHS
, RHS
, FoundLHS
, FoundRHS
))
10104 return isImpliedCondOperandsHelper(Pred
, LHS
, RHS
,
10105 FoundLHS
, FoundRHS
) ||
10106 // ~x < ~y --> x > y
10107 isImpliedCondOperandsHelper(Pred
, LHS
, RHS
,
10108 getNotSCEV(FoundRHS
),
10109 getNotSCEV(FoundLHS
));
10112 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
10113 template <typename MinMaxExprType
>
10114 static bool IsMinMaxConsistingOf(const SCEV
*MaybeMinMaxExpr
,
10115 const SCEV
*Candidate
) {
10116 const MinMaxExprType
*MinMaxExpr
= dyn_cast
<MinMaxExprType
>(MaybeMinMaxExpr
);
10120 return find(MinMaxExpr
->operands(), Candidate
) != MinMaxExpr
->op_end();
10123 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution
&SE
,
10124 ICmpInst::Predicate Pred
,
10125 const SCEV
*LHS
, const SCEV
*RHS
) {
10126 // If both sides are affine addrecs for the same loop, with equal
10127 // steps, and we know the recurrences don't wrap, then we only
10128 // need to check the predicate on the starting values.
10130 if (!ICmpInst::isRelational(Pred
))
10133 const SCEVAddRecExpr
*LAR
= dyn_cast
<SCEVAddRecExpr
>(LHS
);
10136 const SCEVAddRecExpr
*RAR
= dyn_cast
<SCEVAddRecExpr
>(RHS
);
10139 if (LAR
->getLoop() != RAR
->getLoop())
10141 if (!LAR
->isAffine() || !RAR
->isAffine())
10144 if (LAR
->getStepRecurrence(SE
) != RAR
->getStepRecurrence(SE
))
10147 SCEV::NoWrapFlags NW
= ICmpInst::isSigned(Pred
) ?
10148 SCEV::FlagNSW
: SCEV::FlagNUW
;
10149 if (!LAR
->getNoWrapFlags(NW
) || !RAR
->getNoWrapFlags(NW
))
10152 return SE
.isKnownPredicate(Pred
, LAR
->getStart(), RAR
->getStart());
10155 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
10157 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution
&SE
,
10158 ICmpInst::Predicate Pred
,
10159 const SCEV
*LHS
, const SCEV
*RHS
) {
10164 case ICmpInst::ICMP_SGE
:
10165 std::swap(LHS
, RHS
);
10167 case ICmpInst::ICMP_SLE
:
10169 // min(A, ...) <= A
10170 IsMinMaxConsistingOf
<SCEVSMinExpr
>(LHS
, RHS
) ||
10171 // A <= max(A, ...)
10172 IsMinMaxConsistingOf
<SCEVSMaxExpr
>(RHS
, LHS
);
10174 case ICmpInst::ICMP_UGE
:
10175 std::swap(LHS
, RHS
);
10177 case ICmpInst::ICMP_ULE
:
10179 // min(A, ...) <= A
10180 IsMinMaxConsistingOf
<SCEVUMinExpr
>(LHS
, RHS
) ||
10181 // A <= max(A, ...)
10182 IsMinMaxConsistingOf
<SCEVUMaxExpr
>(RHS
, LHS
);
10185 llvm_unreachable("covered switch fell through?!");
10188 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred
,
10189 const SCEV
*LHS
, const SCEV
*RHS
,
10190 const SCEV
*FoundLHS
,
10191 const SCEV
*FoundRHS
,
10193 assert(getTypeSizeInBits(LHS
->getType()) ==
10194 getTypeSizeInBits(RHS
->getType()) &&
10195 "LHS and RHS have different sizes?");
10196 assert(getTypeSizeInBits(FoundLHS
->getType()) ==
10197 getTypeSizeInBits(FoundRHS
->getType()) &&
10198 "FoundLHS and FoundRHS have different sizes?");
10199 // We want to avoid hurting the compile time with analysis of too big trees.
10200 if (Depth
> MaxSCEVOperationsImplicationDepth
)
10202 // We only want to work with ICMP_SGT comparison so far.
10203 // TODO: Extend to ICMP_UGT?
10204 if (Pred
== ICmpInst::ICMP_SLT
) {
10205 Pred
= ICmpInst::ICMP_SGT
;
10206 std::swap(LHS
, RHS
);
10207 std::swap(FoundLHS
, FoundRHS
);
10209 if (Pred
!= ICmpInst::ICMP_SGT
)
10212 auto GetOpFromSExt
= [&](const SCEV
*S
) {
10213 if (auto *Ext
= dyn_cast
<SCEVSignExtendExpr
>(S
))
10214 return Ext
->getOperand();
10215 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
10216 // the constant in some cases.
10220 // Acquire values from extensions.
10221 auto *OrigLHS
= LHS
;
10222 auto *OrigFoundLHS
= FoundLHS
;
10223 LHS
= GetOpFromSExt(LHS
);
10224 FoundLHS
= GetOpFromSExt(FoundLHS
);
10226 // Is the SGT predicate can be proved trivially or using the found context.
10227 auto IsSGTViaContext
= [&](const SCEV
*S1
, const SCEV
*S2
) {
10228 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT
, S1
, S2
) ||
10229 isImpliedViaOperations(ICmpInst::ICMP_SGT
, S1
, S2
, OrigFoundLHS
,
10230 FoundRHS
, Depth
+ 1);
10233 if (auto *LHSAddExpr
= dyn_cast
<SCEVAddExpr
>(LHS
)) {
10234 // We want to avoid creation of any new non-constant SCEV. Since we are
10235 // going to compare the operands to RHS, we should be certain that we don't
10236 // need any size extensions for this. So let's decline all cases when the
10237 // sizes of types of LHS and RHS do not match.
10238 // TODO: Maybe try to get RHS from sext to catch more cases?
10239 if (getTypeSizeInBits(LHS
->getType()) != getTypeSizeInBits(RHS
->getType()))
10242 // Should not overflow.
10243 if (!LHSAddExpr
->hasNoSignedWrap())
10246 auto *LL
= LHSAddExpr
->getOperand(0);
10247 auto *LR
= LHSAddExpr
->getOperand(1);
10248 auto *MinusOne
= getNegativeSCEV(getOne(RHS
->getType()));
10250 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
10251 auto IsSumGreaterThanRHS
= [&](const SCEV
*S1
, const SCEV
*S2
) {
10252 return IsSGTViaContext(S1
, MinusOne
) && IsSGTViaContext(S2
, RHS
);
10254 // Try to prove the following rule:
10255 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
10256 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
10257 if (IsSumGreaterThanRHS(LL
, LR
) || IsSumGreaterThanRHS(LR
, LL
))
10259 } else if (auto *LHSUnknownExpr
= dyn_cast
<SCEVUnknown
>(LHS
)) {
10261 // FIXME: Once we have SDiv implemented, we can get rid of this matching.
10263 using namespace llvm::PatternMatch
;
10265 if (match(LHSUnknownExpr
->getValue(), m_SDiv(m_Value(LL
), m_Value(LR
)))) {
10266 // Rules for division.
10267 // We are going to perform some comparisons with Denominator and its
10268 // derivative expressions. In general case, creating a SCEV for it may
10269 // lead to a complex analysis of the entire graph, and in particular it
10270 // can request trip count recalculation for the same loop. This would
10271 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
10272 // this, we only want to create SCEVs that are constants in this section.
10273 // So we bail if Denominator is not a constant.
10274 if (!isa
<ConstantInt
>(LR
))
10277 auto *Denominator
= cast
<SCEVConstant
>(getSCEV(LR
));
10279 // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
10280 // then a SCEV for the numerator already exists and matches with FoundLHS.
10281 auto *Numerator
= getExistingSCEV(LL
);
10282 if (!Numerator
|| Numerator
->getType() != FoundLHS
->getType())
10285 // Make sure that the numerator matches with FoundLHS and the denominator
10287 if (!HasSameValue(Numerator
, FoundLHS
) || !isKnownPositive(Denominator
))
10290 auto *DTy
= Denominator
->getType();
10291 auto *FRHSTy
= FoundRHS
->getType();
10292 if (DTy
->isPointerTy() != FRHSTy
->isPointerTy())
10293 // One of types is a pointer and another one is not. We cannot extend
10294 // them properly to a wider type, so let us just reject this case.
10295 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
10296 // to avoid this check.
10300 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
10301 auto *WTy
= getWiderType(DTy
, FRHSTy
);
10302 auto *DenominatorExt
= getNoopOrSignExtend(Denominator
, WTy
);
10303 auto *FoundRHSExt
= getNoopOrSignExtend(FoundRHS
, WTy
);
10305 // Try to prove the following rule:
10306 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
10307 // For example, given that FoundLHS > 2. It means that FoundLHS is at
10308 // least 3. If we divide it by Denominator < 4, we will have at least 1.
10309 auto *DenomMinusTwo
= getMinusSCEV(DenominatorExt
, getConstant(WTy
, 2));
10310 if (isKnownNonPositive(RHS
) &&
10311 IsSGTViaContext(FoundRHSExt
, DenomMinusTwo
))
10314 // Try to prove the following rule:
10315 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
10316 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
10317 // If we divide it by Denominator > 2, then:
10318 // 1. If FoundLHS is negative, then the result is 0.
10319 // 2. If FoundLHS is non-negative, then the result is non-negative.
10320 // Anyways, the result is non-negative.
10321 auto *MinusOne
= getNegativeSCEV(getOne(WTy
));
10322 auto *NegDenomMinusOne
= getMinusSCEV(MinusOne
, DenominatorExt
);
10323 if (isKnownNegative(RHS
) &&
10324 IsSGTViaContext(FoundRHSExt
, NegDenomMinusOne
))
10329 // If our expression contained SCEVUnknown Phis, and we split it down and now
10330 // need to prove something for them, try to prove the predicate for every
10331 // possible incoming values of those Phis.
10332 if (isImpliedViaMerge(Pred
, OrigLHS
, RHS
, OrigFoundLHS
, FoundRHS
, Depth
+ 1))
10339 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred
,
10340 const SCEV
*LHS
, const SCEV
*RHS
) {
10341 return isKnownPredicateViaConstantRanges(Pred
, LHS
, RHS
) ||
10342 IsKnownPredicateViaMinOrMax(*this, Pred
, LHS
, RHS
) ||
10343 IsKnownPredicateViaAddRecStart(*this, Pred
, LHS
, RHS
) ||
10344 isKnownPredicateViaNoOverflow(Pred
, LHS
, RHS
);
10348 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred
,
10349 const SCEV
*LHS
, const SCEV
*RHS
,
10350 const SCEV
*FoundLHS
,
10351 const SCEV
*FoundRHS
) {
10353 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
10354 case ICmpInst::ICMP_EQ
:
10355 case ICmpInst::ICMP_NE
:
10356 if (HasSameValue(LHS
, FoundLHS
) && HasSameValue(RHS
, FoundRHS
))
10359 case ICmpInst::ICMP_SLT
:
10360 case ICmpInst::ICMP_SLE
:
10361 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE
, LHS
, FoundLHS
) &&
10362 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE
, RHS
, FoundRHS
))
10365 case ICmpInst::ICMP_SGT
:
10366 case ICmpInst::ICMP_SGE
:
10367 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE
, LHS
, FoundLHS
) &&
10368 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE
, RHS
, FoundRHS
))
10371 case ICmpInst::ICMP_ULT
:
10372 case ICmpInst::ICMP_ULE
:
10373 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE
, LHS
, FoundLHS
) &&
10374 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE
, RHS
, FoundRHS
))
10377 case ICmpInst::ICMP_UGT
:
10378 case ICmpInst::ICMP_UGE
:
10379 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE
, LHS
, FoundLHS
) &&
10380 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE
, RHS
, FoundRHS
))
10385 // Maybe it can be proved via operations?
10386 if (isImpliedViaOperations(Pred
, LHS
, RHS
, FoundLHS
, FoundRHS
))
10392 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred
,
10395 const SCEV
*FoundLHS
,
10396 const SCEV
*FoundRHS
) {
10397 if (!isa
<SCEVConstant
>(RHS
) || !isa
<SCEVConstant
>(FoundRHS
))
10398 // The restriction on `FoundRHS` be lifted easily -- it exists only to
10399 // reduce the compile time impact of this optimization.
10402 Optional
<APInt
> Addend
= computeConstantDifference(LHS
, FoundLHS
);
10406 const APInt
&ConstFoundRHS
= cast
<SCEVConstant
>(FoundRHS
)->getAPInt();
10408 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
10409 // antecedent "`FoundLHS` `Pred` `FoundRHS`".
10410 ConstantRange FoundLHSRange
=
10411 ConstantRange::makeAllowedICmpRegion(Pred
, ConstFoundRHS
);
10413 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
10414 ConstantRange LHSRange
= FoundLHSRange
.add(ConstantRange(*Addend
));
10416 // We can also compute the range of values for `LHS` that satisfy the
10417 // consequent, "`LHS` `Pred` `RHS`":
10418 const APInt
&ConstRHS
= cast
<SCEVConstant
>(RHS
)->getAPInt();
10419 ConstantRange SatisfyingLHSRange
=
10420 ConstantRange::makeSatisfyingICmpRegion(Pred
, ConstRHS
);
10422 // The antecedent implies the consequent if every value of `LHS` that
10423 // satisfies the antecedent also satisfies the consequent.
10424 return SatisfyingLHSRange
.contains(LHSRange
);
10427 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV
*RHS
, const SCEV
*Stride
,
10428 bool IsSigned
, bool NoWrap
) {
10429 assert(isKnownPositive(Stride
) && "Positive stride expected!");
10431 if (NoWrap
) return false;
10433 unsigned BitWidth
= getTypeSizeInBits(RHS
->getType());
10434 const SCEV
*One
= getOne(Stride
->getType());
10437 APInt MaxRHS
= getSignedRangeMax(RHS
);
10438 APInt MaxValue
= APInt::getSignedMaxValue(BitWidth
);
10439 APInt MaxStrideMinusOne
= getSignedRangeMax(getMinusSCEV(Stride
, One
));
10441 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
10442 return (std::move(MaxValue
) - MaxStrideMinusOne
).slt(MaxRHS
);
10445 APInt MaxRHS
= getUnsignedRangeMax(RHS
);
10446 APInt MaxValue
= APInt::getMaxValue(BitWidth
);
10447 APInt MaxStrideMinusOne
= getUnsignedRangeMax(getMinusSCEV(Stride
, One
));
10449 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
10450 return (std::move(MaxValue
) - MaxStrideMinusOne
).ult(MaxRHS
);
10453 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV
*RHS
, const SCEV
*Stride
,
10454 bool IsSigned
, bool NoWrap
) {
10455 if (NoWrap
) return false;
10457 unsigned BitWidth
= getTypeSizeInBits(RHS
->getType());
10458 const SCEV
*One
= getOne(Stride
->getType());
10461 APInt MinRHS
= getSignedRangeMin(RHS
);
10462 APInt MinValue
= APInt::getSignedMinValue(BitWidth
);
10463 APInt MaxStrideMinusOne
= getSignedRangeMax(getMinusSCEV(Stride
, One
));
10465 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
10466 return (std::move(MinValue
) + MaxStrideMinusOne
).sgt(MinRHS
);
10469 APInt MinRHS
= getUnsignedRangeMin(RHS
);
10470 APInt MinValue
= APInt::getMinValue(BitWidth
);
10471 APInt MaxStrideMinusOne
= getUnsignedRangeMax(getMinusSCEV(Stride
, One
));
10473 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
10474 return (std::move(MinValue
) + MaxStrideMinusOne
).ugt(MinRHS
);
10477 const SCEV
*ScalarEvolution::computeBECount(const SCEV
*Delta
, const SCEV
*Step
,
10479 const SCEV
*One
= getOne(Step
->getType());
10480 Delta
= Equality
? getAddExpr(Delta
, Step
)
10481 : getAddExpr(Delta
, getMinusSCEV(Step
, One
));
10482 return getUDivExpr(Delta
, Step
);
10485 const SCEV
*ScalarEvolution::computeMaxBECountForLT(const SCEV
*Start
,
10486 const SCEV
*Stride
,
10491 assert(!isKnownNonPositive(Stride
) &&
10492 "Stride is expected strictly positive!");
10493 // Calculate the maximum backedge count based on the range of values
10494 // permitted by Start, End, and Stride.
10495 const SCEV
*MaxBECount
;
10497 IsSigned
? getSignedRangeMin(Start
) : getUnsignedRangeMin(Start
);
10499 APInt StrideForMaxBECount
=
10500 IsSigned
? getSignedRangeMin(Stride
) : getUnsignedRangeMin(Stride
);
10502 // We already know that the stride is positive, so we paper over conservatism
10503 // in our range computation by forcing StrideForMaxBECount to be at least one.
10504 // In theory this is unnecessary, but we expect MaxBECount to be a
10505 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there
10506 // is nothing to constant fold it to).
10507 APInt
One(BitWidth
, 1, IsSigned
);
10508 StrideForMaxBECount
= APIntOps::smax(One
, StrideForMaxBECount
);
10510 APInt MaxValue
= IsSigned
? APInt::getSignedMaxValue(BitWidth
)
10511 : APInt::getMaxValue(BitWidth
);
10512 APInt Limit
= MaxValue
- (StrideForMaxBECount
- 1);
10514 // Although End can be a MAX expression we estimate MaxEnd considering only
10515 // the case End = RHS of the loop termination condition. This is safe because
10516 // in the other case (End - Start) is zero, leading to a zero maximum backedge
10518 APInt MaxEnd
= IsSigned
? APIntOps::smin(getSignedRangeMax(End
), Limit
)
10519 : APIntOps::umin(getUnsignedRangeMax(End
), Limit
);
10521 MaxBECount
= computeBECount(getConstant(MaxEnd
- MinStart
) /* Delta */,
10522 getConstant(StrideForMaxBECount
) /* Step */,
10523 false /* Equality */);
10528 ScalarEvolution::ExitLimit
10529 ScalarEvolution::howManyLessThans(const SCEV
*LHS
, const SCEV
*RHS
,
10530 const Loop
*L
, bool IsSigned
,
10531 bool ControlsExit
, bool AllowPredicates
) {
10532 SmallPtrSet
<const SCEVPredicate
*, 4> Predicates
;
10534 const SCEVAddRecExpr
*IV
= dyn_cast
<SCEVAddRecExpr
>(LHS
);
10535 bool PredicatedIV
= false;
10537 if (!IV
&& AllowPredicates
) {
10538 // Try to make this an AddRec using runtime tests, in the first X
10539 // iterations of this loop, where X is the SCEV expression found by the
10540 // algorithm below.
10541 IV
= convertSCEVToAddRecWithPredicates(LHS
, L
, Predicates
);
10542 PredicatedIV
= true;
10545 // Avoid weird loops
10546 if (!IV
|| IV
->getLoop() != L
|| !IV
->isAffine())
10547 return getCouldNotCompute();
10549 bool NoWrap
= ControlsExit
&&
10550 IV
->getNoWrapFlags(IsSigned
? SCEV::FlagNSW
: SCEV::FlagNUW
);
10552 const SCEV
*Stride
= IV
->getStepRecurrence(*this);
10554 bool PositiveStride
= isKnownPositive(Stride
);
10556 // Avoid negative or zero stride values.
10557 if (!PositiveStride
) {
10558 // We can compute the correct backedge taken count for loops with unknown
10559 // strides if we can prove that the loop is not an infinite loop with side
10560 // effects. Here's the loop structure we are trying to handle -
10566 // } while (i < end);
10568 // The backedge taken count for such loops is evaluated as -
10569 // (max(end, start + stride) - start - 1) /u stride
10571 // The additional preconditions that we need to check to prove correctness
10572 // of the above formula is as follows -
10574 // a) IV is either nuw or nsw depending upon signedness (indicated by the
10576 // b) loop is single exit with no side effects.
10579 // Precondition a) implies that if the stride is negative, this is a single
10580 // trip loop. The backedge taken count formula reduces to zero in this case.
10582 // Precondition b) implies that the unknown stride cannot be zero otherwise
10585 // The positive stride case is the same as isKnownPositive(Stride) returning
10586 // true (original behavior of the function).
10588 // We want to make sure that the stride is truly unknown as there are edge
10589 // cases where ScalarEvolution propagates no wrap flags to the
10590 // post-increment/decrement IV even though the increment/decrement operation
10591 // itself is wrapping. The computed backedge taken count may be wrong in
10592 // such cases. This is prevented by checking that the stride is not known to
10593 // be either positive or non-positive. For example, no wrap flags are
10594 // propagated to the post-increment IV of this loop with a trip count of 2 -
10596 // unsigned char i;
10597 // for(i=127; i<128; i+=129)
10600 if (PredicatedIV
|| !NoWrap
|| isKnownNonPositive(Stride
) ||
10601 !loopHasNoSideEffects(L
))
10602 return getCouldNotCompute();
10603 } else if (!Stride
->isOne() &&
10604 doesIVOverflowOnLT(RHS
, Stride
, IsSigned
, NoWrap
))
10605 // Avoid proven overflow cases: this will ensure that the backedge taken
10606 // count will not generate any unsigned overflow. Relaxed no-overflow
10607 // conditions exploit NoWrapFlags, allowing to optimize in presence of
10608 // undefined behaviors like the case of C language.
10609 return getCouldNotCompute();
10611 ICmpInst::Predicate Cond
= IsSigned
? ICmpInst::ICMP_SLT
10612 : ICmpInst::ICMP_ULT
;
10613 const SCEV
*Start
= IV
->getStart();
10614 const SCEV
*End
= RHS
;
10615 // When the RHS is not invariant, we do not know the end bound of the loop and
10616 // cannot calculate the ExactBECount needed by ExitLimit. However, we can
10617 // calculate the MaxBECount, given the start, stride and max value for the end
10618 // bound of the loop (RHS), and the fact that IV does not overflow (which is
10620 if (!isLoopInvariant(RHS
, L
)) {
10621 const SCEV
*MaxBECount
= computeMaxBECountForLT(
10622 Start
, Stride
, RHS
, getTypeSizeInBits(LHS
->getType()), IsSigned
);
10623 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount
,
10624 false /*MaxOrZero*/, Predicates
);
10626 // If the backedge is taken at least once, then it will be taken
10627 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
10628 // is the LHS value of the less-than comparison the first time it is evaluated
10629 // and End is the RHS.
10630 const SCEV
*BECountIfBackedgeTaken
=
10631 computeBECount(getMinusSCEV(End
, Start
), Stride
, false);
10632 // If the loop entry is guarded by the result of the backedge test of the
10633 // first loop iteration, then we know the backedge will be taken at least
10634 // once and so the backedge taken count is as above. If not then we use the
10635 // expression (max(End,Start)-Start)/Stride to describe the backedge count,
10636 // as if the backedge is taken at least once max(End,Start) is End and so the
10637 // result is as above, and if not max(End,Start) is Start so we get a backedge
10639 const SCEV
*BECount
;
10640 if (isLoopEntryGuardedByCond(L
, Cond
, getMinusSCEV(Start
, Stride
), RHS
))
10641 BECount
= BECountIfBackedgeTaken
;
10643 End
= IsSigned
? getSMaxExpr(RHS
, Start
) : getUMaxExpr(RHS
, Start
);
10644 BECount
= computeBECount(getMinusSCEV(End
, Start
), Stride
, false);
10647 const SCEV
*MaxBECount
;
10648 bool MaxOrZero
= false;
10649 if (isa
<SCEVConstant
>(BECount
))
10650 MaxBECount
= BECount
;
10651 else if (isa
<SCEVConstant
>(BECountIfBackedgeTaken
)) {
10652 // If we know exactly how many times the backedge will be taken if it's
10653 // taken at least once, then the backedge count will either be that or
10655 MaxBECount
= BECountIfBackedgeTaken
;
10658 MaxBECount
= computeMaxBECountForLT(
10659 Start
, Stride
, RHS
, getTypeSizeInBits(LHS
->getType()), IsSigned
);
10662 if (isa
<SCEVCouldNotCompute
>(MaxBECount
) &&
10663 !isa
<SCEVCouldNotCompute
>(BECount
))
10664 MaxBECount
= getConstant(getUnsignedRangeMax(BECount
));
10666 return ExitLimit(BECount
, MaxBECount
, MaxOrZero
, Predicates
);
10669 ScalarEvolution::ExitLimit
10670 ScalarEvolution::howManyGreaterThans(const SCEV
*LHS
, const SCEV
*RHS
,
10671 const Loop
*L
, bool IsSigned
,
10672 bool ControlsExit
, bool AllowPredicates
) {
10673 SmallPtrSet
<const SCEVPredicate
*, 4> Predicates
;
10674 // We handle only IV > Invariant
10675 if (!isLoopInvariant(RHS
, L
))
10676 return getCouldNotCompute();
10678 const SCEVAddRecExpr
*IV
= dyn_cast
<SCEVAddRecExpr
>(LHS
);
10679 if (!IV
&& AllowPredicates
)
10680 // Try to make this an AddRec using runtime tests, in the first X
10681 // iterations of this loop, where X is the SCEV expression found by the
10682 // algorithm below.
10683 IV
= convertSCEVToAddRecWithPredicates(LHS
, L
, Predicates
);
10685 // Avoid weird loops
10686 if (!IV
|| IV
->getLoop() != L
|| !IV
->isAffine())
10687 return getCouldNotCompute();
10689 bool NoWrap
= ControlsExit
&&
10690 IV
->getNoWrapFlags(IsSigned
? SCEV::FlagNSW
: SCEV::FlagNUW
);
10692 const SCEV
*Stride
= getNegativeSCEV(IV
->getStepRecurrence(*this));
10694 // Avoid negative or zero stride values
10695 if (!isKnownPositive(Stride
))
10696 return getCouldNotCompute();
10698 // Avoid proven overflow cases: this will ensure that the backedge taken count
10699 // will not generate any unsigned overflow. Relaxed no-overflow conditions
10700 // exploit NoWrapFlags, allowing to optimize in presence of undefined
10701 // behaviors like the case of C language.
10702 if (!Stride
->isOne() && doesIVOverflowOnGT(RHS
, Stride
, IsSigned
, NoWrap
))
10703 return getCouldNotCompute();
10705 ICmpInst::Predicate Cond
= IsSigned
? ICmpInst::ICMP_SGT
10706 : ICmpInst::ICMP_UGT
;
10708 const SCEV
*Start
= IV
->getStart();
10709 const SCEV
*End
= RHS
;
10710 if (!isLoopEntryGuardedByCond(L
, Cond
, getAddExpr(Start
, Stride
), RHS
))
10711 End
= IsSigned
? getSMinExpr(RHS
, Start
) : getUMinExpr(RHS
, Start
);
10713 const SCEV
*BECount
= computeBECount(getMinusSCEV(Start
, End
), Stride
, false);
10715 APInt MaxStart
= IsSigned
? getSignedRangeMax(Start
)
10716 : getUnsignedRangeMax(Start
);
10718 APInt MinStride
= IsSigned
? getSignedRangeMin(Stride
)
10719 : getUnsignedRangeMin(Stride
);
10721 unsigned BitWidth
= getTypeSizeInBits(LHS
->getType());
10722 APInt Limit
= IsSigned
? APInt::getSignedMinValue(BitWidth
) + (MinStride
- 1)
10723 : APInt::getMinValue(BitWidth
) + (MinStride
- 1);
10725 // Although End can be a MIN expression we estimate MinEnd considering only
10726 // the case End = RHS. This is safe because in the other case (Start - End)
10727 // is zero, leading to a zero maximum backedge taken count.
10729 IsSigned
? APIntOps::smax(getSignedRangeMin(RHS
), Limit
)
10730 : APIntOps::umax(getUnsignedRangeMin(RHS
), Limit
);
10732 const SCEV
*MaxBECount
= isa
<SCEVConstant
>(BECount
)
10734 : computeBECount(getConstant(MaxStart
- MinEnd
),
10735 getConstant(MinStride
), false);
10737 if (isa
<SCEVCouldNotCompute
>(MaxBECount
))
10738 MaxBECount
= BECount
;
10740 return ExitLimit(BECount
, MaxBECount
, false, Predicates
);
10743 const SCEV
*SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange
&Range
,
10744 ScalarEvolution
&SE
) const {
10745 if (Range
.isFullSet()) // Infinite loop.
10746 return SE
.getCouldNotCompute();
10748 // If the start is a non-zero constant, shift the range to simplify things.
10749 if (const SCEVConstant
*SC
= dyn_cast
<SCEVConstant
>(getStart()))
10750 if (!SC
->getValue()->isZero()) {
10751 SmallVector
<const SCEV
*, 4> Operands(op_begin(), op_end());
10752 Operands
[0] = SE
.getZero(SC
->getType());
10753 const SCEV
*Shifted
= SE
.getAddRecExpr(Operands
, getLoop(),
10754 getNoWrapFlags(FlagNW
));
10755 if (const auto *ShiftedAddRec
= dyn_cast
<SCEVAddRecExpr
>(Shifted
))
10756 return ShiftedAddRec
->getNumIterationsInRange(
10757 Range
.subtract(SC
->getAPInt()), SE
);
10758 // This is strange and shouldn't happen.
10759 return SE
.getCouldNotCompute();
10762 // The only time we can solve this is when we have all constant indices.
10763 // Otherwise, we cannot determine the overflow conditions.
10764 if (any_of(operands(), [](const SCEV
*Op
) { return !isa
<SCEVConstant
>(Op
); }))
10765 return SE
.getCouldNotCompute();
10767 // Okay at this point we know that all elements of the chrec are constants and
10768 // that the start element is zero.
10770 // First check to see if the range contains zero. If not, the first
10771 // iteration exits.
10772 unsigned BitWidth
= SE
.getTypeSizeInBits(getType());
10773 if (!Range
.contains(APInt(BitWidth
, 0)))
10774 return SE
.getZero(getType());
10777 // If this is an affine expression then we have this situation:
10778 // Solve {0,+,A} in Range === Ax in Range
10780 // We know that zero is in the range. If A is positive then we know that
10781 // the upper value of the range must be the first possible exit value.
10782 // If A is negative then the lower of the range is the last possible loop
10783 // value. Also note that we already checked for a full range.
10784 APInt A
= cast
<SCEVConstant
>(getOperand(1))->getAPInt();
10785 APInt End
= A
.sge(1) ? (Range
.getUpper() - 1) : Range
.getLower();
10787 // The exit value should be (End+A)/A.
10788 APInt ExitVal
= (End
+ A
).udiv(A
);
10789 ConstantInt
*ExitValue
= ConstantInt::get(SE
.getContext(), ExitVal
);
10791 // Evaluate at the exit value. If we really did fall out of the valid
10792 // range, then we computed our trip count, otherwise wrap around or other
10793 // things must have happened.
10794 ConstantInt
*Val
= EvaluateConstantChrecAtConstant(this, ExitValue
, SE
);
10795 if (Range
.contains(Val
->getValue()))
10796 return SE
.getCouldNotCompute(); // Something strange happened
10798 // Ensure that the previous value is in the range. This is a sanity check.
10799 assert(Range
.contains(
10800 EvaluateConstantChrecAtConstant(this,
10801 ConstantInt::get(SE
.getContext(), ExitVal
- 1), SE
)->getValue()) &&
10802 "Linear scev computation is off in a bad way!");
10803 return SE
.getConstant(ExitValue
);
10806 if (isQuadratic()) {
10807 if (auto S
= SolveQuadraticAddRecRange(this, Range
, SE
))
10808 return SE
.getConstant(S
.getValue());
10811 return SE
.getCouldNotCompute();
10814 const SCEVAddRecExpr
*
10815 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution
&SE
) const {
10816 assert(getNumOperands() > 1 && "AddRec with zero step?");
10817 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
10818 // but in this case we cannot guarantee that the value returned will be an
10819 // AddRec because SCEV does not have a fixed point where it stops
10820 // simplification: it is legal to return ({rec1} + {rec2}). For example, it
10821 // may happen if we reach arithmetic depth limit while simplifying. So we
10822 // construct the returned value explicitly.
10823 SmallVector
<const SCEV
*, 3> Ops
;
10824 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
10825 // (this + Step) is {A+B,+,B+C,+...,+,N}.
10826 for (unsigned i
= 0, e
= getNumOperands() - 1; i
< e
; ++i
)
10827 Ops
.push_back(SE
.getAddExpr(getOperand(i
), getOperand(i
+ 1)));
10828 // We know that the last operand is not a constant zero (otherwise it would
10829 // have been popped out earlier). This guarantees us that if the result has
10830 // the same last operand, then it will also not be popped out, meaning that
10831 // the returned value will be an AddRec.
10832 const SCEV
*Last
= getOperand(getNumOperands() - 1);
10833 assert(!Last
->isZero() && "Recurrency with zero step?");
10834 Ops
.push_back(Last
);
10835 return cast
<SCEVAddRecExpr
>(SE
.getAddRecExpr(Ops
, getLoop(),
10836 SCEV::FlagAnyWrap
));
10839 // Return true when S contains at least an undef value.
10840 static inline bool containsUndefs(const SCEV
*S
) {
10841 return SCEVExprContains(S
, [](const SCEV
*S
) {
10842 if (const auto *SU
= dyn_cast
<SCEVUnknown
>(S
))
10843 return isa
<UndefValue
>(SU
->getValue());
10850 // Collect all steps of SCEV expressions.
10851 struct SCEVCollectStrides
{
10852 ScalarEvolution
&SE
;
10853 SmallVectorImpl
<const SCEV
*> &Strides
;
10855 SCEVCollectStrides(ScalarEvolution
&SE
, SmallVectorImpl
<const SCEV
*> &S
)
10856 : SE(SE
), Strides(S
) {}
10858 bool follow(const SCEV
*S
) {
10859 if (const SCEVAddRecExpr
*AR
= dyn_cast
<SCEVAddRecExpr
>(S
))
10860 Strides
.push_back(AR
->getStepRecurrence(SE
));
10864 bool isDone() const { return false; }
10867 // Collect all SCEVUnknown and SCEVMulExpr expressions.
10868 struct SCEVCollectTerms
{
10869 SmallVectorImpl
<const SCEV
*> &Terms
;
10871 SCEVCollectTerms(SmallVectorImpl
<const SCEV
*> &T
) : Terms(T
) {}
10873 bool follow(const SCEV
*S
) {
10874 if (isa
<SCEVUnknown
>(S
) || isa
<SCEVMulExpr
>(S
) ||
10875 isa
<SCEVSignExtendExpr
>(S
)) {
10876 if (!containsUndefs(S
))
10877 Terms
.push_back(S
);
10879 // Stop recursion: once we collected a term, do not walk its operands.
10887 bool isDone() const { return false; }
10890 // Check if a SCEV contains an AddRecExpr.
10891 struct SCEVHasAddRec
{
10892 bool &ContainsAddRec
;
10894 SCEVHasAddRec(bool &ContainsAddRec
) : ContainsAddRec(ContainsAddRec
) {
10895 ContainsAddRec
= false;
10898 bool follow(const SCEV
*S
) {
10899 if (isa
<SCEVAddRecExpr
>(S
)) {
10900 ContainsAddRec
= true;
10902 // Stop recursion: once we collected a term, do not walk its operands.
10910 bool isDone() const { return false; }
10913 // Find factors that are multiplied with an expression that (possibly as a
10914 // subexpression) contains an AddRecExpr. In the expression:
10916 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop))
10918 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
10919 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
10920 // parameters as they form a product with an induction variable.
10922 // This collector expects all array size parameters to be in the same MulExpr.
10923 // It might be necessary to later add support for collecting parameters that are
10924 // spread over different nested MulExpr.
10925 struct SCEVCollectAddRecMultiplies
{
10926 SmallVectorImpl
<const SCEV
*> &Terms
;
10927 ScalarEvolution
&SE
;
10929 SCEVCollectAddRecMultiplies(SmallVectorImpl
<const SCEV
*> &T
, ScalarEvolution
&SE
)
10930 : Terms(T
), SE(SE
) {}
10932 bool follow(const SCEV
*S
) {
10933 if (auto *Mul
= dyn_cast
<SCEVMulExpr
>(S
)) {
10934 bool HasAddRec
= false;
10935 SmallVector
<const SCEV
*, 0> Operands
;
10936 for (auto Op
: Mul
->operands()) {
10937 const SCEVUnknown
*Unknown
= dyn_cast
<SCEVUnknown
>(Op
);
10938 if (Unknown
&& !isa
<CallInst
>(Unknown
->getValue())) {
10939 Operands
.push_back(Op
);
10940 } else if (Unknown
) {
10943 bool ContainsAddRec
;
10944 SCEVHasAddRec
ContiansAddRec(ContainsAddRec
);
10945 visitAll(Op
, ContiansAddRec
);
10946 HasAddRec
|= ContainsAddRec
;
10949 if (Operands
.size() == 0)
10955 Terms
.push_back(SE
.getMulExpr(Operands
));
10956 // Stop recursion: once we collected a term, do not walk its operands.
10964 bool isDone() const { return false; }
10967 } // end anonymous namespace
10969 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
10971 /// 1) The strides of AddRec expressions.
10972 /// 2) Unknowns that are multiplied with AddRec expressions.
10973 void ScalarEvolution::collectParametricTerms(const SCEV
*Expr
,
10974 SmallVectorImpl
<const SCEV
*> &Terms
) {
10975 SmallVector
<const SCEV
*, 4> Strides
;
10976 SCEVCollectStrides
StrideCollector(*this, Strides
);
10977 visitAll(Expr
, StrideCollector
);
10980 dbgs() << "Strides:\n";
10981 for (const SCEV
*S
: Strides
)
10982 dbgs() << *S
<< "\n";
10985 for (const SCEV
*S
: Strides
) {
10986 SCEVCollectTerms
TermCollector(Terms
);
10987 visitAll(S
, TermCollector
);
10991 dbgs() << "Terms:\n";
10992 for (const SCEV
*T
: Terms
)
10993 dbgs() << *T
<< "\n";
10996 SCEVCollectAddRecMultiplies
MulCollector(Terms
, *this);
10997 visitAll(Expr
, MulCollector
);
11000 static bool findArrayDimensionsRec(ScalarEvolution
&SE
,
11001 SmallVectorImpl
<const SCEV
*> &Terms
,
11002 SmallVectorImpl
<const SCEV
*> &Sizes
) {
11003 int Last
= Terms
.size() - 1;
11004 const SCEV
*Step
= Terms
[Last
];
11006 // End of recursion.
11008 if (const SCEVMulExpr
*M
= dyn_cast
<SCEVMulExpr
>(Step
)) {
11009 SmallVector
<const SCEV
*, 2> Qs
;
11010 for (const SCEV
*Op
: M
->operands())
11011 if (!isa
<SCEVConstant
>(Op
))
11014 Step
= SE
.getMulExpr(Qs
);
11017 Sizes
.push_back(Step
);
11021 for (const SCEV
*&Term
: Terms
) {
11022 // Normalize the terms before the next call to findArrayDimensionsRec.
11024 SCEVDivision::divide(SE
, Term
, Step
, &Q
, &R
);
11026 // Bail out when GCD does not evenly divide one of the terms.
11033 // Remove all SCEVConstants.
11035 remove_if(Terms
, [](const SCEV
*E
) { return isa
<SCEVConstant
>(E
); }),
11038 if (Terms
.size() > 0)
11039 if (!findArrayDimensionsRec(SE
, Terms
, Sizes
))
11042 Sizes
.push_back(Step
);
11046 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
11047 static inline bool containsParameters(SmallVectorImpl
<const SCEV
*> &Terms
) {
11048 for (const SCEV
*T
: Terms
)
11049 if (SCEVExprContains(T
, isa
<SCEVUnknown
, const SCEV
*>))
11054 // Return the number of product terms in S.
11055 static inline int numberOfTerms(const SCEV
*S
) {
11056 if (const SCEVMulExpr
*Expr
= dyn_cast
<SCEVMulExpr
>(S
))
11057 return Expr
->getNumOperands();
11061 static const SCEV
*removeConstantFactors(ScalarEvolution
&SE
, const SCEV
*T
) {
11062 if (isa
<SCEVConstant
>(T
))
11065 if (isa
<SCEVUnknown
>(T
))
11068 if (const SCEVMulExpr
*M
= dyn_cast
<SCEVMulExpr
>(T
)) {
11069 SmallVector
<const SCEV
*, 2> Factors
;
11070 for (const SCEV
*Op
: M
->operands())
11071 if (!isa
<SCEVConstant
>(Op
))
11072 Factors
.push_back(Op
);
11074 return SE
.getMulExpr(Factors
);
11080 /// Return the size of an element read or written by Inst.
11081 const SCEV
*ScalarEvolution::getElementSize(Instruction
*Inst
) {
11083 if (StoreInst
*Store
= dyn_cast
<StoreInst
>(Inst
))
11084 Ty
= Store
->getValueOperand()->getType();
11085 else if (LoadInst
*Load
= dyn_cast
<LoadInst
>(Inst
))
11086 Ty
= Load
->getType();
11090 Type
*ETy
= getEffectiveSCEVType(PointerType::getUnqual(Ty
));
11091 return getSizeOfExpr(ETy
, Ty
);
11094 void ScalarEvolution::findArrayDimensions(SmallVectorImpl
<const SCEV
*> &Terms
,
11095 SmallVectorImpl
<const SCEV
*> &Sizes
,
11096 const SCEV
*ElementSize
) {
11097 if (Terms
.size() < 1 || !ElementSize
)
11100 // Early return when Terms do not contain parameters: we do not delinearize
11101 // non parametric SCEVs.
11102 if (!containsParameters(Terms
))
11106 dbgs() << "Terms:\n";
11107 for (const SCEV
*T
: Terms
)
11108 dbgs() << *T
<< "\n";
11111 // Remove duplicates.
11112 array_pod_sort(Terms
.begin(), Terms
.end());
11113 Terms
.erase(std::unique(Terms
.begin(), Terms
.end()), Terms
.end());
11115 // Put larger terms first.
11116 llvm::sort(Terms
, [](const SCEV
*LHS
, const SCEV
*RHS
) {
11117 return numberOfTerms(LHS
) > numberOfTerms(RHS
);
11120 // Try to divide all terms by the element size. If term is not divisible by
11121 // element size, proceed with the original term.
11122 for (const SCEV
*&Term
: Terms
) {
11124 SCEVDivision::divide(*this, Term
, ElementSize
, &Q
, &R
);
11129 SmallVector
<const SCEV
*, 4> NewTerms
;
11131 // Remove constant factors.
11132 for (const SCEV
*T
: Terms
)
11133 if (const SCEV
*NewT
= removeConstantFactors(*this, T
))
11134 NewTerms
.push_back(NewT
);
11137 dbgs() << "Terms after sorting:\n";
11138 for (const SCEV
*T
: NewTerms
)
11139 dbgs() << *T
<< "\n";
11142 if (NewTerms
.empty() || !findArrayDimensionsRec(*this, NewTerms
, Sizes
)) {
11147 // The last element to be pushed into Sizes is the size of an element.
11148 Sizes
.push_back(ElementSize
);
11151 dbgs() << "Sizes:\n";
11152 for (const SCEV
*S
: Sizes
)
11153 dbgs() << *S
<< "\n";
11157 void ScalarEvolution::computeAccessFunctions(
11158 const SCEV
*Expr
, SmallVectorImpl
<const SCEV
*> &Subscripts
,
11159 SmallVectorImpl
<const SCEV
*> &Sizes
) {
11160 // Early exit in case this SCEV is not an affine multivariate function.
11164 if (auto *AR
= dyn_cast
<SCEVAddRecExpr
>(Expr
))
11165 if (!AR
->isAffine())
11168 const SCEV
*Res
= Expr
;
11169 int Last
= Sizes
.size() - 1;
11170 for (int i
= Last
; i
>= 0; i
--) {
11172 SCEVDivision::divide(*this, Res
, Sizes
[i
], &Q
, &R
);
11175 dbgs() << "Res: " << *Res
<< "\n";
11176 dbgs() << "Sizes[i]: " << *Sizes
[i
] << "\n";
11177 dbgs() << "Res divided by Sizes[i]:\n";
11178 dbgs() << "Quotient: " << *Q
<< "\n";
11179 dbgs() << "Remainder: " << *R
<< "\n";
11184 // Do not record the last subscript corresponding to the size of elements in
11188 // Bail out if the remainder is too complex.
11189 if (isa
<SCEVAddRecExpr
>(R
)) {
11190 Subscripts
.clear();
11198 // Record the access function for the current subscript.
11199 Subscripts
.push_back(R
);
11202 // Also push in last position the remainder of the last division: it will be
11203 // the access function of the innermost dimension.
11204 Subscripts
.push_back(Res
);
11206 std::reverse(Subscripts
.begin(), Subscripts
.end());
11209 dbgs() << "Subscripts:\n";
11210 for (const SCEV
*S
: Subscripts
)
11211 dbgs() << *S
<< "\n";
11215 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
11216 /// sizes of an array access. Returns the remainder of the delinearization that
11217 /// is the offset start of the array. The SCEV->delinearize algorithm computes
11218 /// the multiples of SCEV coefficients: that is a pattern matching of sub
11219 /// expressions in the stride and base of a SCEV corresponding to the
11220 /// computation of a GCD (greatest common divisor) of base and stride. When
11221 /// SCEV->delinearize fails, it returns the SCEV unchanged.
11223 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
11225 /// void foo(long n, long m, long o, double A[n][m][o]) {
11227 /// for (long i = 0; i < n; i++)
11228 /// for (long j = 0; j < m; j++)
11229 /// for (long k = 0; k < o; k++)
11230 /// A[i][j][k] = 1.0;
11233 /// the delinearization input is the following AddRec SCEV:
11235 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
11237 /// From this SCEV, we are able to say that the base offset of the access is %A
11238 /// because it appears as an offset that does not divide any of the strides in
11241 /// CHECK: Base offset: %A
11243 /// and then SCEV->delinearize determines the size of some of the dimensions of
11244 /// the array as these are the multiples by which the strides are happening:
11246 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
11248 /// Note that the outermost dimension remains of UnknownSize because there are
11249 /// no strides that would help identifying the size of the last dimension: when
11250 /// the array has been statically allocated, one could compute the size of that
11251 /// dimension by dividing the overall size of the array by the size of the known
11252 /// dimensions: %m * %o * 8.
11254 /// Finally delinearize provides the access functions for the array reference
11255 /// that does correspond to A[i][j][k] of the above C testcase:
11257 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
11259 /// The testcases are checking the output of a function pass:
11260 /// DelinearizationPass that walks through all loads and stores of a function
11261 /// asking for the SCEV of the memory access with respect to all enclosing
11262 /// loops, calling SCEV->delinearize on that and printing the results.
11263 void ScalarEvolution::delinearize(const SCEV
*Expr
,
11264 SmallVectorImpl
<const SCEV
*> &Subscripts
,
11265 SmallVectorImpl
<const SCEV
*> &Sizes
,
11266 const SCEV
*ElementSize
) {
11267 // First step: collect parametric terms.
11268 SmallVector
<const SCEV
*, 4> Terms
;
11269 collectParametricTerms(Expr
, Terms
);
11274 // Second step: find subscript sizes.
11275 findArrayDimensions(Terms
, Sizes
, ElementSize
);
11280 // Third step: compute the access functions for each subscript.
11281 computeAccessFunctions(Expr
, Subscripts
, Sizes
);
11283 if (Subscripts
.empty())
11287 dbgs() << "succeeded to delinearize " << *Expr
<< "\n";
11288 dbgs() << "ArrayDecl[UnknownSize]";
11289 for (const SCEV
*S
: Sizes
)
11290 dbgs() << "[" << *S
<< "]";
11292 dbgs() << "\nArrayRef";
11293 for (const SCEV
*S
: Subscripts
)
11294 dbgs() << "[" << *S
<< "]";
11299 //===----------------------------------------------------------------------===//
11300 // SCEVCallbackVH Class Implementation
11301 //===----------------------------------------------------------------------===//
11303 void ScalarEvolution::SCEVCallbackVH::deleted() {
11304 assert(SE
&& "SCEVCallbackVH called with a null ScalarEvolution!");
11305 if (PHINode
*PN
= dyn_cast
<PHINode
>(getValPtr()))
11306 SE
->ConstantEvolutionLoopExitValue
.erase(PN
);
11307 SE
->eraseValueFromMap(getValPtr());
11308 // this now dangles!
11311 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value
*V
) {
11312 assert(SE
&& "SCEVCallbackVH called with a null ScalarEvolution!");
11314 // Forget all the expressions associated with users of the old value,
11315 // so that future queries will recompute the expressions using the new
11317 Value
*Old
= getValPtr();
11318 SmallVector
<User
*, 16> Worklist(Old
->user_begin(), Old
->user_end());
11319 SmallPtrSet
<User
*, 8> Visited
;
11320 while (!Worklist
.empty()) {
11321 User
*U
= Worklist
.pop_back_val();
11322 // Deleting the Old value will cause this to dangle. Postpone
11323 // that until everything else is done.
11326 if (!Visited
.insert(U
).second
)
11328 if (PHINode
*PN
= dyn_cast
<PHINode
>(U
))
11329 SE
->ConstantEvolutionLoopExitValue
.erase(PN
);
11330 SE
->eraseValueFromMap(U
);
11331 Worklist
.insert(Worklist
.end(), U
->user_begin(), U
->user_end());
11333 // Delete the Old value.
11334 if (PHINode
*PN
= dyn_cast
<PHINode
>(Old
))
11335 SE
->ConstantEvolutionLoopExitValue
.erase(PN
);
11336 SE
->eraseValueFromMap(Old
);
11337 // this now dangles!
11340 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value
*V
, ScalarEvolution
*se
)
11341 : CallbackVH(V
), SE(se
) {}
11343 //===----------------------------------------------------------------------===//
11344 // ScalarEvolution Class Implementation
11345 //===----------------------------------------------------------------------===//
11347 ScalarEvolution::ScalarEvolution(Function
&F
, TargetLibraryInfo
&TLI
,
11348 AssumptionCache
&AC
, DominatorTree
&DT
,
11350 : F(F
), TLI(TLI
), AC(AC
), DT(DT
), LI(LI
),
11351 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
11352 LoopDispositions(64), BlockDispositions(64) {
11353 // To use guards for proving predicates, we need to scan every instruction in
11354 // relevant basic blocks, and not just terminators. Doing this is a waste of
11355 // time if the IR does not actually contain any calls to
11356 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
11358 // This pessimizes the case where a pass that preserves ScalarEvolution wants
11359 // to _add_ guards to the module when there weren't any before, and wants
11360 // ScalarEvolution to optimize based on those guards. For now we prefer to be
11361 // efficient in lieu of being smart in that rather obscure case.
11363 auto *GuardDecl
= F
.getParent()->getFunction(
11364 Intrinsic::getName(Intrinsic::experimental_guard
));
11365 HasGuards
= GuardDecl
&& !GuardDecl
->use_empty();
11368 ScalarEvolution::ScalarEvolution(ScalarEvolution
&&Arg
)
11369 : F(Arg
.F
), HasGuards(Arg
.HasGuards
), TLI(Arg
.TLI
), AC(Arg
.AC
), DT(Arg
.DT
),
11370 LI(Arg
.LI
), CouldNotCompute(std::move(Arg
.CouldNotCompute
)),
11371 ValueExprMap(std::move(Arg
.ValueExprMap
)),
11372 PendingLoopPredicates(std::move(Arg
.PendingLoopPredicates
)),
11373 PendingPhiRanges(std::move(Arg
.PendingPhiRanges
)),
11374 PendingMerges(std::move(Arg
.PendingMerges
)),
11375 MinTrailingZerosCache(std::move(Arg
.MinTrailingZerosCache
)),
11376 BackedgeTakenCounts(std::move(Arg
.BackedgeTakenCounts
)),
11377 PredicatedBackedgeTakenCounts(
11378 std::move(Arg
.PredicatedBackedgeTakenCounts
)),
11379 ConstantEvolutionLoopExitValue(
11380 std::move(Arg
.ConstantEvolutionLoopExitValue
)),
11381 ValuesAtScopes(std::move(Arg
.ValuesAtScopes
)),
11382 LoopDispositions(std::move(Arg
.LoopDispositions
)),
11383 LoopPropertiesCache(std::move(Arg
.LoopPropertiesCache
)),
11384 BlockDispositions(std::move(Arg
.BlockDispositions
)),
11385 UnsignedRanges(std::move(Arg
.UnsignedRanges
)),
11386 SignedRanges(std::move(Arg
.SignedRanges
)),
11387 UniqueSCEVs(std::move(Arg
.UniqueSCEVs
)),
11388 UniquePreds(std::move(Arg
.UniquePreds
)),
11389 SCEVAllocator(std::move(Arg
.SCEVAllocator
)),
11390 LoopUsers(std::move(Arg
.LoopUsers
)),
11391 PredicatedSCEVRewrites(std::move(Arg
.PredicatedSCEVRewrites
)),
11392 FirstUnknown(Arg
.FirstUnknown
) {
11393 Arg
.FirstUnknown
= nullptr;
11396 ScalarEvolution::~ScalarEvolution() {
11397 // Iterate through all the SCEVUnknown instances and call their
11398 // destructors, so that they release their references to their values.
11399 for (SCEVUnknown
*U
= FirstUnknown
; U
;) {
11400 SCEVUnknown
*Tmp
= U
;
11402 Tmp
->~SCEVUnknown();
11404 FirstUnknown
= nullptr;
11406 ExprValueMap
.clear();
11407 ValueExprMap
.clear();
11410 // Free any extra memory created for ExitNotTakenInfo in the unlikely event
11411 // that a loop had multiple computable exits.
11412 for (auto &BTCI
: BackedgeTakenCounts
)
11413 BTCI
.second
.clear();
11414 for (auto &BTCI
: PredicatedBackedgeTakenCounts
)
11415 BTCI
.second
.clear();
11417 assert(PendingLoopPredicates
.empty() && "isImpliedCond garbage");
11418 assert(PendingPhiRanges
.empty() && "getRangeRef garbage");
11419 assert(PendingMerges
.empty() && "isImpliedViaMerge garbage");
11420 assert(!WalkingBEDominatingConds
&& "isLoopBackedgeGuardedByCond garbage!");
11421 assert(!ProvingSplitPredicate
&& "ProvingSplitPredicate garbage!");
11424 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop
*L
) {
11425 return !isa
<SCEVCouldNotCompute
>(getBackedgeTakenCount(L
));
11428 static void PrintLoopInfo(raw_ostream
&OS
, ScalarEvolution
*SE
,
11430 // Print all inner loops first
11432 PrintLoopInfo(OS
, SE
, I
);
11435 L
->getHeader()->printAsOperand(OS
, /*PrintType=*/false);
11438 SmallVector
<BasicBlock
*, 8> ExitingBlocks
;
11439 L
->getExitingBlocks(ExitingBlocks
);
11440 if (ExitingBlocks
.size() != 1)
11441 OS
<< "<multiple exits> ";
11443 if (SE
->hasLoopInvariantBackedgeTakenCount(L
))
11444 OS
<< "backedge-taken count is " << *SE
->getBackedgeTakenCount(L
) << "\n";
11446 OS
<< "Unpredictable backedge-taken count.\n";
11448 if (ExitingBlocks
.size() > 1)
11449 for (BasicBlock
*ExitingBlock
: ExitingBlocks
) {
11450 OS
<< " exit count for " << ExitingBlock
->getName() << ": "
11451 << *SE
->getExitCount(L
, ExitingBlock
) << "\n";
11455 L
->getHeader()->printAsOperand(OS
, /*PrintType=*/false);
11458 if (!isa
<SCEVCouldNotCompute
>(SE
->getConstantMaxBackedgeTakenCount(L
))) {
11459 OS
<< "max backedge-taken count is " << *SE
->getConstantMaxBackedgeTakenCount(L
);
11460 if (SE
->isBackedgeTakenCountMaxOrZero(L
))
11461 OS
<< ", actual taken count either this or zero.";
11463 OS
<< "Unpredictable max backedge-taken count. ";
11468 L
->getHeader()->printAsOperand(OS
, /*PrintType=*/false);
11471 SCEVUnionPredicate Pred
;
11472 auto PBT
= SE
->getPredicatedBackedgeTakenCount(L
, Pred
);
11473 if (!isa
<SCEVCouldNotCompute
>(PBT
)) {
11474 OS
<< "Predicated backedge-taken count is " << *PBT
<< "\n";
11475 OS
<< " Predicates:\n";
11478 OS
<< "Unpredictable predicated backedge-taken count. ";
11482 if (SE
->hasLoopInvariantBackedgeTakenCount(L
)) {
11484 L
->getHeader()->printAsOperand(OS
, /*PrintType=*/false);
11486 OS
<< "Trip multiple is " << SE
->getSmallConstantTripMultiple(L
) << "\n";
11490 static StringRef
loopDispositionToStr(ScalarEvolution::LoopDisposition LD
) {
11492 case ScalarEvolution::LoopVariant
:
11494 case ScalarEvolution::LoopInvariant
:
11495 return "Invariant";
11496 case ScalarEvolution::LoopComputable
:
11497 return "Computable";
11499 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
11502 void ScalarEvolution::print(raw_ostream
&OS
) const {
11503 // ScalarEvolution's implementation of the print method is to print
11504 // out SCEV values of all instructions that are interesting. Doing
11505 // this potentially causes it to create new SCEV objects though,
11506 // which technically conflicts with the const qualifier. This isn't
11507 // observable from outside the class though, so casting away the
11508 // const isn't dangerous.
11509 ScalarEvolution
&SE
= *const_cast<ScalarEvolution
*>(this);
11511 OS
<< "Classifying expressions for: ";
11512 F
.printAsOperand(OS
, /*PrintType=*/false);
11514 for (Instruction
&I
: instructions(F
))
11515 if (isSCEVable(I
.getType()) && !isa
<CmpInst
>(I
)) {
11518 const SCEV
*SV
= SE
.getSCEV(&I
);
11520 if (!isa
<SCEVCouldNotCompute
>(SV
)) {
11522 SE
.getUnsignedRange(SV
).print(OS
);
11524 SE
.getSignedRange(SV
).print(OS
);
11527 const Loop
*L
= LI
.getLoopFor(I
.getParent());
11529 const SCEV
*AtUse
= SE
.getSCEVAtScope(SV
, L
);
11533 if (!isa
<SCEVCouldNotCompute
>(AtUse
)) {
11535 SE
.getUnsignedRange(AtUse
).print(OS
);
11537 SE
.getSignedRange(AtUse
).print(OS
);
11542 OS
<< "\t\t" "Exits: ";
11543 const SCEV
*ExitValue
= SE
.getSCEVAtScope(SV
, L
->getParentLoop());
11544 if (!SE
.isLoopInvariant(ExitValue
, L
)) {
11545 OS
<< "<<Unknown>>";
11551 for (auto *Iter
= L
; Iter
; Iter
= Iter
->getParentLoop()) {
11553 OS
<< "\t\t" "LoopDispositions: { ";
11559 Iter
->getHeader()->printAsOperand(OS
, /*PrintType=*/false);
11560 OS
<< ": " << loopDispositionToStr(SE
.getLoopDisposition(SV
, Iter
));
11563 for (auto *InnerL
: depth_first(L
)) {
11567 OS
<< "\t\t" "LoopDispositions: { ";
11573 InnerL
->getHeader()->printAsOperand(OS
, /*PrintType=*/false);
11574 OS
<< ": " << loopDispositionToStr(SE
.getLoopDisposition(SV
, InnerL
));
11583 OS
<< "Determining loop execution counts for: ";
11584 F
.printAsOperand(OS
, /*PrintType=*/false);
11587 PrintLoopInfo(OS
, &SE
, I
);
11590 ScalarEvolution::LoopDisposition
11591 ScalarEvolution::getLoopDisposition(const SCEV
*S
, const Loop
*L
) {
11592 auto &Values
= LoopDispositions
[S
];
11593 for (auto &V
: Values
) {
11594 if (V
.getPointer() == L
)
11597 Values
.emplace_back(L
, LoopVariant
);
11598 LoopDisposition D
= computeLoopDisposition(S
, L
);
11599 auto &Values2
= LoopDispositions
[S
];
11600 for (auto &V
: make_range(Values2
.rbegin(), Values2
.rend())) {
11601 if (V
.getPointer() == L
) {
11609 ScalarEvolution::LoopDisposition
11610 ScalarEvolution::computeLoopDisposition(const SCEV
*S
, const Loop
*L
) {
11611 switch (static_cast<SCEVTypes
>(S
->getSCEVType())) {
11613 return LoopInvariant
;
11617 return getLoopDisposition(cast
<SCEVCastExpr
>(S
)->getOperand(), L
);
11618 case scAddRecExpr
: {
11619 const SCEVAddRecExpr
*AR
= cast
<SCEVAddRecExpr
>(S
);
11621 // If L is the addrec's loop, it's computable.
11622 if (AR
->getLoop() == L
)
11623 return LoopComputable
;
11625 // Add recurrences are never invariant in the function-body (null loop).
11627 return LoopVariant
;
11629 // Everything that is not defined at loop entry is variant.
11630 if (DT
.dominates(L
->getHeader(), AR
->getLoop()->getHeader()))
11631 return LoopVariant
;
11632 assert(!L
->contains(AR
->getLoop()) && "Containing loop's header does not"
11633 " dominate the contained loop's header?");
11635 // This recurrence is invariant w.r.t. L if AR's loop contains L.
11636 if (AR
->getLoop()->contains(L
))
11637 return LoopInvariant
;
11639 // This recurrence is variant w.r.t. L if any of its operands
11641 for (auto *Op
: AR
->operands())
11642 if (!isLoopInvariant(Op
, L
))
11643 return LoopVariant
;
11645 // Otherwise it's loop-invariant.
11646 return LoopInvariant
;
11654 bool HasVarying
= false;
11655 for (auto *Op
: cast
<SCEVNAryExpr
>(S
)->operands()) {
11656 LoopDisposition D
= getLoopDisposition(Op
, L
);
11657 if (D
== LoopVariant
)
11658 return LoopVariant
;
11659 if (D
== LoopComputable
)
11662 return HasVarying
? LoopComputable
: LoopInvariant
;
11665 const SCEVUDivExpr
*UDiv
= cast
<SCEVUDivExpr
>(S
);
11666 LoopDisposition LD
= getLoopDisposition(UDiv
->getLHS(), L
);
11667 if (LD
== LoopVariant
)
11668 return LoopVariant
;
11669 LoopDisposition RD
= getLoopDisposition(UDiv
->getRHS(), L
);
11670 if (RD
== LoopVariant
)
11671 return LoopVariant
;
11672 return (LD
== LoopInvariant
&& RD
== LoopInvariant
) ?
11673 LoopInvariant
: LoopComputable
;
11676 // All non-instruction values are loop invariant. All instructions are loop
11677 // invariant if they are not contained in the specified loop.
11678 // Instructions are never considered invariant in the function body
11679 // (null loop) because they are defined within the "loop".
11680 if (auto *I
= dyn_cast
<Instruction
>(cast
<SCEVUnknown
>(S
)->getValue()))
11681 return (L
&& !L
->contains(I
)) ? LoopInvariant
: LoopVariant
;
11682 return LoopInvariant
;
11683 case scCouldNotCompute
:
11684 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
11686 llvm_unreachable("Unknown SCEV kind!");
11689 bool ScalarEvolution::isLoopInvariant(const SCEV
*S
, const Loop
*L
) {
11690 return getLoopDisposition(S
, L
) == LoopInvariant
;
11693 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV
*S
, const Loop
*L
) {
11694 return getLoopDisposition(S
, L
) == LoopComputable
;
11697 ScalarEvolution::BlockDisposition
11698 ScalarEvolution::getBlockDisposition(const SCEV
*S
, const BasicBlock
*BB
) {
11699 auto &Values
= BlockDispositions
[S
];
11700 for (auto &V
: Values
) {
11701 if (V
.getPointer() == BB
)
11704 Values
.emplace_back(BB
, DoesNotDominateBlock
);
11705 BlockDisposition D
= computeBlockDisposition(S
, BB
);
11706 auto &Values2
= BlockDispositions
[S
];
11707 for (auto &V
: make_range(Values2
.rbegin(), Values2
.rend())) {
11708 if (V
.getPointer() == BB
) {
11716 ScalarEvolution::BlockDisposition
11717 ScalarEvolution::computeBlockDisposition(const SCEV
*S
, const BasicBlock
*BB
) {
11718 switch (static_cast<SCEVTypes
>(S
->getSCEVType())) {
11720 return ProperlyDominatesBlock
;
11724 return getBlockDisposition(cast
<SCEVCastExpr
>(S
)->getOperand(), BB
);
11725 case scAddRecExpr
: {
11726 // This uses a "dominates" query instead of "properly dominates" query
11727 // to test for proper dominance too, because the instruction which
11728 // produces the addrec's value is a PHI, and a PHI effectively properly
11729 // dominates its entire containing block.
11730 const SCEVAddRecExpr
*AR
= cast
<SCEVAddRecExpr
>(S
);
11731 if (!DT
.dominates(AR
->getLoop()->getHeader(), BB
))
11732 return DoesNotDominateBlock
;
11734 // Fall through into SCEVNAryExpr handling.
11743 const SCEVNAryExpr
*NAry
= cast
<SCEVNAryExpr
>(S
);
11744 bool Proper
= true;
11745 for (const SCEV
*NAryOp
: NAry
->operands()) {
11746 BlockDisposition D
= getBlockDisposition(NAryOp
, BB
);
11747 if (D
== DoesNotDominateBlock
)
11748 return DoesNotDominateBlock
;
11749 if (D
== DominatesBlock
)
11752 return Proper
? ProperlyDominatesBlock
: DominatesBlock
;
11755 const SCEVUDivExpr
*UDiv
= cast
<SCEVUDivExpr
>(S
);
11756 const SCEV
*LHS
= UDiv
->getLHS(), *RHS
= UDiv
->getRHS();
11757 BlockDisposition LD
= getBlockDisposition(LHS
, BB
);
11758 if (LD
== DoesNotDominateBlock
)
11759 return DoesNotDominateBlock
;
11760 BlockDisposition RD
= getBlockDisposition(RHS
, BB
);
11761 if (RD
== DoesNotDominateBlock
)
11762 return DoesNotDominateBlock
;
11763 return (LD
== ProperlyDominatesBlock
&& RD
== ProperlyDominatesBlock
) ?
11764 ProperlyDominatesBlock
: DominatesBlock
;
11767 if (Instruction
*I
=
11768 dyn_cast
<Instruction
>(cast
<SCEVUnknown
>(S
)->getValue())) {
11769 if (I
->getParent() == BB
)
11770 return DominatesBlock
;
11771 if (DT
.properlyDominates(I
->getParent(), BB
))
11772 return ProperlyDominatesBlock
;
11773 return DoesNotDominateBlock
;
11775 return ProperlyDominatesBlock
;
11776 case scCouldNotCompute
:
11777 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
11779 llvm_unreachable("Unknown SCEV kind!");
11782 bool ScalarEvolution::dominates(const SCEV
*S
, const BasicBlock
*BB
) {
11783 return getBlockDisposition(S
, BB
) >= DominatesBlock
;
11786 bool ScalarEvolution::properlyDominates(const SCEV
*S
, const BasicBlock
*BB
) {
11787 return getBlockDisposition(S
, BB
) == ProperlyDominatesBlock
;
11790 bool ScalarEvolution::hasOperand(const SCEV
*S
, const SCEV
*Op
) const {
11791 return SCEVExprContains(S
, [&](const SCEV
*Expr
) { return Expr
== Op
; });
11794 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV
*S
) const {
11795 auto IsS
= [&](const SCEV
*X
) { return S
== X
; };
11796 auto ContainsS
= [&](const SCEV
*X
) {
11797 return !isa
<SCEVCouldNotCompute
>(X
) && SCEVExprContains(X
, IsS
);
11799 return ContainsS(ExactNotTaken
) || ContainsS(MaxNotTaken
);
11803 ScalarEvolution::forgetMemoizedResults(const SCEV
*S
) {
11804 ValuesAtScopes
.erase(S
);
11805 LoopDispositions
.erase(S
);
11806 BlockDispositions
.erase(S
);
11807 UnsignedRanges
.erase(S
);
11808 SignedRanges
.erase(S
);
11809 ExprValueMap
.erase(S
);
11810 HasRecMap
.erase(S
);
11811 MinTrailingZerosCache
.erase(S
);
11813 for (auto I
= PredicatedSCEVRewrites
.begin();
11814 I
!= PredicatedSCEVRewrites
.end();) {
11815 std::pair
<const SCEV
*, const Loop
*> Entry
= I
->first
;
11816 if (Entry
.first
== S
)
11817 PredicatedSCEVRewrites
.erase(I
++);
11822 auto RemoveSCEVFromBackedgeMap
=
11823 [S
, this](DenseMap
<const Loop
*, BackedgeTakenInfo
> &Map
) {
11824 for (auto I
= Map
.begin(), E
= Map
.end(); I
!= E
;) {
11825 BackedgeTakenInfo
&BEInfo
= I
->second
;
11826 if (BEInfo
.hasOperand(S
, this)) {
11834 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts
);
11835 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts
);
11839 ScalarEvolution::getUsedLoops(const SCEV
*S
,
11840 SmallPtrSetImpl
<const Loop
*> &LoopsUsed
) {
11841 struct FindUsedLoops
{
11842 FindUsedLoops(SmallPtrSetImpl
<const Loop
*> &LoopsUsed
)
11843 : LoopsUsed(LoopsUsed
) {}
11844 SmallPtrSetImpl
<const Loop
*> &LoopsUsed
;
11845 bool follow(const SCEV
*S
) {
11846 if (auto *AR
= dyn_cast
<SCEVAddRecExpr
>(S
))
11847 LoopsUsed
.insert(AR
->getLoop());
11851 bool isDone() const { return false; }
11854 FindUsedLoops
F(LoopsUsed
);
11855 SCEVTraversal
<FindUsedLoops
>(F
).visitAll(S
);
11858 void ScalarEvolution::addToLoopUseLists(const SCEV
*S
) {
11859 SmallPtrSet
<const Loop
*, 8> LoopsUsed
;
11860 getUsedLoops(S
, LoopsUsed
);
11861 for (auto *L
: LoopsUsed
)
11862 LoopUsers
[L
].push_back(S
);
11865 void ScalarEvolution::verify() const {
11866 ScalarEvolution
&SE
= *const_cast<ScalarEvolution
*>(this);
11867 ScalarEvolution
SE2(F
, TLI
, AC
, DT
, LI
);
11869 SmallVector
<Loop
*, 8> LoopStack(LI
.begin(), LI
.end());
11871 // Map's SCEV expressions from one ScalarEvolution "universe" to another.
11872 struct SCEVMapper
: public SCEVRewriteVisitor
<SCEVMapper
> {
11873 SCEVMapper(ScalarEvolution
&SE
) : SCEVRewriteVisitor
<SCEVMapper
>(SE
) {}
11875 const SCEV
*visitConstant(const SCEVConstant
*Constant
) {
11876 return SE
.getConstant(Constant
->getAPInt());
11879 const SCEV
*visitUnknown(const SCEVUnknown
*Expr
) {
11880 return SE
.getUnknown(Expr
->getValue());
11883 const SCEV
*visitCouldNotCompute(const SCEVCouldNotCompute
*Expr
) {
11884 return SE
.getCouldNotCompute();
11888 SCEVMapper
SCM(SE2
);
11890 while (!LoopStack
.empty()) {
11891 auto *L
= LoopStack
.pop_back_val();
11892 LoopStack
.insert(LoopStack
.end(), L
->begin(), L
->end());
11894 auto *CurBECount
= SCM
.visit(
11895 const_cast<ScalarEvolution
*>(this)->getBackedgeTakenCount(L
));
11896 auto *NewBECount
= SE2
.getBackedgeTakenCount(L
);
11898 if (CurBECount
== SE2
.getCouldNotCompute() ||
11899 NewBECount
== SE2
.getCouldNotCompute()) {
11900 // NB! This situation is legal, but is very suspicious -- whatever pass
11901 // change the loop to make a trip count go from could not compute to
11902 // computable or vice-versa *should have* invalidated SCEV. However, we
11903 // choose not to assert here (for now) since we don't want false
11908 if (containsUndefs(CurBECount
) || containsUndefs(NewBECount
)) {
11909 // SCEV treats "undef" as an unknown but consistent value (i.e. it does
11910 // not propagate undef aggressively). This means we can (and do) fail
11911 // verification in cases where a transform makes the trip count of a loop
11912 // go from "undef" to "undef+1" (say). The transform is fine, since in
11913 // both cases the loop iterates "undef" times, but SCEV thinks we
11914 // increased the trip count of the loop by 1 incorrectly.
11918 if (SE
.getTypeSizeInBits(CurBECount
->getType()) >
11919 SE
.getTypeSizeInBits(NewBECount
->getType()))
11920 NewBECount
= SE2
.getZeroExtendExpr(NewBECount
, CurBECount
->getType());
11921 else if (SE
.getTypeSizeInBits(CurBECount
->getType()) <
11922 SE
.getTypeSizeInBits(NewBECount
->getType()))
11923 CurBECount
= SE2
.getZeroExtendExpr(CurBECount
, NewBECount
->getType());
11925 auto *ConstantDelta
=
11926 dyn_cast
<SCEVConstant
>(SE2
.getMinusSCEV(CurBECount
, NewBECount
));
11928 if (ConstantDelta
&& ConstantDelta
->getAPInt() != 0) {
11929 dbgs() << "Trip Count Changed!\n";
11930 dbgs() << "Old: " << *CurBECount
<< "\n";
11931 dbgs() << "New: " << *NewBECount
<< "\n";
11932 dbgs() << "Delta: " << *ConstantDelta
<< "\n";
11938 bool ScalarEvolution::invalidate(
11939 Function
&F
, const PreservedAnalyses
&PA
,
11940 FunctionAnalysisManager::Invalidator
&Inv
) {
11941 // Invalidate the ScalarEvolution object whenever it isn't preserved or one
11942 // of its dependencies is invalidated.
11943 auto PAC
= PA
.getChecker
<ScalarEvolutionAnalysis
>();
11944 return !(PAC
.preserved() || PAC
.preservedSet
<AllAnalysesOn
<Function
>>()) ||
11945 Inv
.invalidate
<AssumptionAnalysis
>(F
, PA
) ||
11946 Inv
.invalidate
<DominatorTreeAnalysis
>(F
, PA
) ||
11947 Inv
.invalidate
<LoopAnalysis
>(F
, PA
);
11950 AnalysisKey
ScalarEvolutionAnalysis::Key
;
11952 ScalarEvolution
ScalarEvolutionAnalysis::run(Function
&F
,
11953 FunctionAnalysisManager
&AM
) {
11954 return ScalarEvolution(F
, AM
.getResult
<TargetLibraryAnalysis
>(F
),
11955 AM
.getResult
<AssumptionAnalysis
>(F
),
11956 AM
.getResult
<DominatorTreeAnalysis
>(F
),
11957 AM
.getResult
<LoopAnalysis
>(F
));
11961 ScalarEvolutionPrinterPass::run(Function
&F
, FunctionAnalysisManager
&AM
) {
11962 AM
.getResult
<ScalarEvolutionAnalysis
>(F
).print(OS
);
11963 return PreservedAnalyses::all();
11966 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass
, "scalar-evolution",
11967 "Scalar Evolution Analysis", false, true)
11968 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker
)
11969 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass
)
11970 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass
)
11971 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass
)
11972 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass
, "scalar-evolution",
11973 "Scalar Evolution Analysis", false, true)
11975 char ScalarEvolutionWrapperPass::ID
= 0;
11977 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID
) {
11978 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
11981 bool ScalarEvolutionWrapperPass::runOnFunction(Function
&F
) {
11982 SE
.reset(new ScalarEvolution(
11983 F
, getAnalysis
<TargetLibraryInfoWrapperPass
>().getTLI(F
),
11984 getAnalysis
<AssumptionCacheTracker
>().getAssumptionCache(F
),
11985 getAnalysis
<DominatorTreeWrapperPass
>().getDomTree(),
11986 getAnalysis
<LoopInfoWrapperPass
>().getLoopInfo()));
11990 void ScalarEvolutionWrapperPass::releaseMemory() { SE
.reset(); }
11992 void ScalarEvolutionWrapperPass::print(raw_ostream
&OS
, const Module
*) const {
11996 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
12003 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage
&AU
) const {
12004 AU
.setPreservesAll();
12005 AU
.addRequiredTransitive
<AssumptionCacheTracker
>();
12006 AU
.addRequiredTransitive
<LoopInfoWrapperPass
>();
12007 AU
.addRequiredTransitive
<DominatorTreeWrapperPass
>();
12008 AU
.addRequiredTransitive
<TargetLibraryInfoWrapperPass
>();
12011 const SCEVPredicate
*ScalarEvolution::getEqualPredicate(const SCEV
*LHS
,
12013 FoldingSetNodeID ID
;
12014 assert(LHS
->getType() == RHS
->getType() &&
12015 "Type mismatch between LHS and RHS");
12016 // Unique this node based on the arguments
12017 ID
.AddInteger(SCEVPredicate::P_Equal
);
12018 ID
.AddPointer(LHS
);
12019 ID
.AddPointer(RHS
);
12020 void *IP
= nullptr;
12021 if (const auto *S
= UniquePreds
.FindNodeOrInsertPos(ID
, IP
))
12023 SCEVEqualPredicate
*Eq
= new (SCEVAllocator
)
12024 SCEVEqualPredicate(ID
.Intern(SCEVAllocator
), LHS
, RHS
);
12025 UniquePreds
.InsertNode(Eq
, IP
);
12029 const SCEVPredicate
*ScalarEvolution::getWrapPredicate(
12030 const SCEVAddRecExpr
*AR
,
12031 SCEVWrapPredicate::IncrementWrapFlags AddedFlags
) {
12032 FoldingSetNodeID ID
;
12033 // Unique this node based on the arguments
12034 ID
.AddInteger(SCEVPredicate::P_Wrap
);
12036 ID
.AddInteger(AddedFlags
);
12037 void *IP
= nullptr;
12038 if (const auto *S
= UniquePreds
.FindNodeOrInsertPos(ID
, IP
))
12040 auto *OF
= new (SCEVAllocator
)
12041 SCEVWrapPredicate(ID
.Intern(SCEVAllocator
), AR
, AddedFlags
);
12042 UniquePreds
.InsertNode(OF
, IP
);
12048 class SCEVPredicateRewriter
: public SCEVRewriteVisitor
<SCEVPredicateRewriter
> {
12051 /// Rewrites \p S in the context of a loop L and the SCEV predication
12052 /// infrastructure.
12054 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
12055 /// equivalences present in \p Pred.
12057 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
12058 /// \p NewPreds such that the result will be an AddRecExpr.
12059 static const SCEV
*rewrite(const SCEV
*S
, const Loop
*L
, ScalarEvolution
&SE
,
12060 SmallPtrSetImpl
<const SCEVPredicate
*> *NewPreds
,
12061 SCEVUnionPredicate
*Pred
) {
12062 SCEVPredicateRewriter
Rewriter(L
, SE
, NewPreds
, Pred
);
12063 return Rewriter
.visit(S
);
12066 const SCEV
*visitUnknown(const SCEVUnknown
*Expr
) {
12068 auto ExprPreds
= Pred
->getPredicatesForExpr(Expr
);
12069 for (auto *Pred
: ExprPreds
)
12070 if (const auto *IPred
= dyn_cast
<SCEVEqualPredicate
>(Pred
))
12071 if (IPred
->getLHS() == Expr
)
12072 return IPred
->getRHS();
12074 return convertToAddRecWithPreds(Expr
);
12077 const SCEV
*visitZeroExtendExpr(const SCEVZeroExtendExpr
*Expr
) {
12078 const SCEV
*Operand
= visit(Expr
->getOperand());
12079 const SCEVAddRecExpr
*AR
= dyn_cast
<SCEVAddRecExpr
>(Operand
);
12080 if (AR
&& AR
->getLoop() == L
&& AR
->isAffine()) {
12081 // This couldn't be folded because the operand didn't have the nuw
12082 // flag. Add the nusw flag as an assumption that we could make.
12083 const SCEV
*Step
= AR
->getStepRecurrence(SE
);
12084 Type
*Ty
= Expr
->getType();
12085 if (addOverflowAssumption(AR
, SCEVWrapPredicate::IncrementNUSW
))
12086 return SE
.getAddRecExpr(SE
.getZeroExtendExpr(AR
->getStart(), Ty
),
12087 SE
.getSignExtendExpr(Step
, Ty
), L
,
12088 AR
->getNoWrapFlags());
12090 return SE
.getZeroExtendExpr(Operand
, Expr
->getType());
12093 const SCEV
*visitSignExtendExpr(const SCEVSignExtendExpr
*Expr
) {
12094 const SCEV
*Operand
= visit(Expr
->getOperand());
12095 const SCEVAddRecExpr
*AR
= dyn_cast
<SCEVAddRecExpr
>(Operand
);
12096 if (AR
&& AR
->getLoop() == L
&& AR
->isAffine()) {
12097 // This couldn't be folded because the operand didn't have the nsw
12098 // flag. Add the nssw flag as an assumption that we could make.
12099 const SCEV
*Step
= AR
->getStepRecurrence(SE
);
12100 Type
*Ty
= Expr
->getType();
12101 if (addOverflowAssumption(AR
, SCEVWrapPredicate::IncrementNSSW
))
12102 return SE
.getAddRecExpr(SE
.getSignExtendExpr(AR
->getStart(), Ty
),
12103 SE
.getSignExtendExpr(Step
, Ty
), L
,
12104 AR
->getNoWrapFlags());
12106 return SE
.getSignExtendExpr(Operand
, Expr
->getType());
12110 explicit SCEVPredicateRewriter(const Loop
*L
, ScalarEvolution
&SE
,
12111 SmallPtrSetImpl
<const SCEVPredicate
*> *NewPreds
,
12112 SCEVUnionPredicate
*Pred
)
12113 : SCEVRewriteVisitor(SE
), NewPreds(NewPreds
), Pred(Pred
), L(L
) {}
12115 bool addOverflowAssumption(const SCEVPredicate
*P
) {
12117 // Check if we've already made this assumption.
12118 return Pred
&& Pred
->implies(P
);
12120 NewPreds
->insert(P
);
12124 bool addOverflowAssumption(const SCEVAddRecExpr
*AR
,
12125 SCEVWrapPredicate::IncrementWrapFlags AddedFlags
) {
12126 auto *A
= SE
.getWrapPredicate(AR
, AddedFlags
);
12127 return addOverflowAssumption(A
);
12130 // If \p Expr represents a PHINode, we try to see if it can be represented
12131 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
12132 // to add this predicate as a runtime overflow check, we return the AddRec.
12133 // If \p Expr does not meet these conditions (is not a PHI node, or we
12134 // couldn't create an AddRec for it, or couldn't add the predicate), we just
12136 const SCEV
*convertToAddRecWithPreds(const SCEVUnknown
*Expr
) {
12137 if (!isa
<PHINode
>(Expr
->getValue()))
12139 Optional
<std::pair
<const SCEV
*, SmallVector
<const SCEVPredicate
*, 3>>>
12140 PredicatedRewrite
= SE
.createAddRecFromPHIWithCasts(Expr
);
12141 if (!PredicatedRewrite
)
12143 for (auto *P
: PredicatedRewrite
->second
){
12144 // Wrap predicates from outer loops are not supported.
12145 if (auto *WP
= dyn_cast
<const SCEVWrapPredicate
>(P
)) {
12146 auto *AR
= cast
<const SCEVAddRecExpr
>(WP
->getExpr());
12147 if (L
!= AR
->getLoop())
12150 if (!addOverflowAssumption(P
))
12153 return PredicatedRewrite
->first
;
12156 SmallPtrSetImpl
<const SCEVPredicate
*> *NewPreds
;
12157 SCEVUnionPredicate
*Pred
;
12161 } // end anonymous namespace
12163 const SCEV
*ScalarEvolution::rewriteUsingPredicate(const SCEV
*S
, const Loop
*L
,
12164 SCEVUnionPredicate
&Preds
) {
12165 return SCEVPredicateRewriter::rewrite(S
, L
, *this, nullptr, &Preds
);
12168 const SCEVAddRecExpr
*ScalarEvolution::convertSCEVToAddRecWithPredicates(
12169 const SCEV
*S
, const Loop
*L
,
12170 SmallPtrSetImpl
<const SCEVPredicate
*> &Preds
) {
12171 SmallPtrSet
<const SCEVPredicate
*, 4> TransformPreds
;
12172 S
= SCEVPredicateRewriter::rewrite(S
, L
, *this, &TransformPreds
, nullptr);
12173 auto *AddRec
= dyn_cast
<SCEVAddRecExpr
>(S
);
12178 // Since the transformation was successful, we can now transfer the SCEV
12180 for (auto *P
: TransformPreds
)
12186 /// SCEV predicates
12187 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID
,
12188 SCEVPredicateKind Kind
)
12189 : FastID(ID
), Kind(Kind
) {}
12191 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID
,
12192 const SCEV
*LHS
, const SCEV
*RHS
)
12193 : SCEVPredicate(ID
, P_Equal
), LHS(LHS
), RHS(RHS
) {
12194 assert(LHS
->getType() == RHS
->getType() && "LHS and RHS types don't match");
12195 assert(LHS
!= RHS
&& "LHS and RHS are the same SCEV");
12198 bool SCEVEqualPredicate::implies(const SCEVPredicate
*N
) const {
12199 const auto *Op
= dyn_cast
<SCEVEqualPredicate
>(N
);
12204 return Op
->LHS
== LHS
&& Op
->RHS
== RHS
;
12207 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
12209 const SCEV
*SCEVEqualPredicate::getExpr() const { return LHS
; }
12211 void SCEVEqualPredicate::print(raw_ostream
&OS
, unsigned Depth
) const {
12212 OS
.indent(Depth
) << "Equal predicate: " << *LHS
<< " == " << *RHS
<< "\n";
12215 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID
,
12216 const SCEVAddRecExpr
*AR
,
12217 IncrementWrapFlags Flags
)
12218 : SCEVPredicate(ID
, P_Wrap
), AR(AR
), Flags(Flags
) {}
12220 const SCEV
*SCEVWrapPredicate::getExpr() const { return AR
; }
12222 bool SCEVWrapPredicate::implies(const SCEVPredicate
*N
) const {
12223 const auto *Op
= dyn_cast
<SCEVWrapPredicate
>(N
);
12225 return Op
&& Op
->AR
== AR
&& setFlags(Flags
, Op
->Flags
) == Flags
;
12228 bool SCEVWrapPredicate::isAlwaysTrue() const {
12229 SCEV::NoWrapFlags ScevFlags
= AR
->getNoWrapFlags();
12230 IncrementWrapFlags IFlags
= Flags
;
12232 if (ScalarEvolution::setFlags(ScevFlags
, SCEV::FlagNSW
) == ScevFlags
)
12233 IFlags
= clearFlags(IFlags
, IncrementNSSW
);
12235 return IFlags
== IncrementAnyWrap
;
12238 void SCEVWrapPredicate::print(raw_ostream
&OS
, unsigned Depth
) const {
12239 OS
.indent(Depth
) << *getExpr() << " Added Flags: ";
12240 if (SCEVWrapPredicate::IncrementNUSW
& getFlags())
12242 if (SCEVWrapPredicate::IncrementNSSW
& getFlags())
12247 SCEVWrapPredicate::IncrementWrapFlags
12248 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr
*AR
,
12249 ScalarEvolution
&SE
) {
12250 IncrementWrapFlags ImpliedFlags
= IncrementAnyWrap
;
12251 SCEV::NoWrapFlags StaticFlags
= AR
->getNoWrapFlags();
12253 // We can safely transfer the NSW flag as NSSW.
12254 if (ScalarEvolution::setFlags(StaticFlags
, SCEV::FlagNSW
) == StaticFlags
)
12255 ImpliedFlags
= IncrementNSSW
;
12257 if (ScalarEvolution::setFlags(StaticFlags
, SCEV::FlagNUW
) == StaticFlags
) {
12258 // If the increment is positive, the SCEV NUW flag will also imply the
12259 // WrapPredicate NUSW flag.
12260 if (const auto *Step
= dyn_cast
<SCEVConstant
>(AR
->getStepRecurrence(SE
)))
12261 if (Step
->getValue()->getValue().isNonNegative())
12262 ImpliedFlags
= setFlags(ImpliedFlags
, IncrementNUSW
);
12265 return ImpliedFlags
;
12268 /// Union predicates don't get cached so create a dummy set ID for it.
12269 SCEVUnionPredicate::SCEVUnionPredicate()
12270 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union
) {}
12272 bool SCEVUnionPredicate::isAlwaysTrue() const {
12273 return all_of(Preds
,
12274 [](const SCEVPredicate
*I
) { return I
->isAlwaysTrue(); });
12277 ArrayRef
<const SCEVPredicate
*>
12278 SCEVUnionPredicate::getPredicatesForExpr(const SCEV
*Expr
) {
12279 auto I
= SCEVToPreds
.find(Expr
);
12280 if (I
== SCEVToPreds
.end())
12281 return ArrayRef
<const SCEVPredicate
*>();
12285 bool SCEVUnionPredicate::implies(const SCEVPredicate
*N
) const {
12286 if (const auto *Set
= dyn_cast
<SCEVUnionPredicate
>(N
))
12287 return all_of(Set
->Preds
,
12288 [this](const SCEVPredicate
*I
) { return this->implies(I
); });
12290 auto ScevPredsIt
= SCEVToPreds
.find(N
->getExpr());
12291 if (ScevPredsIt
== SCEVToPreds
.end())
12293 auto &SCEVPreds
= ScevPredsIt
->second
;
12295 return any_of(SCEVPreds
,
12296 [N
](const SCEVPredicate
*I
) { return I
->implies(N
); });
12299 const SCEV
*SCEVUnionPredicate::getExpr() const { return nullptr; }
12301 void SCEVUnionPredicate::print(raw_ostream
&OS
, unsigned Depth
) const {
12302 for (auto Pred
: Preds
)
12303 Pred
->print(OS
, Depth
);
12306 void SCEVUnionPredicate::add(const SCEVPredicate
*N
) {
12307 if (const auto *Set
= dyn_cast
<SCEVUnionPredicate
>(N
)) {
12308 for (auto Pred
: Set
->Preds
)
12316 const SCEV
*Key
= N
->getExpr();
12317 assert(Key
&& "Only SCEVUnionPredicate doesn't have an "
12318 " associated expression!");
12320 SCEVToPreds
[Key
].push_back(N
);
12321 Preds
.push_back(N
);
12324 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution
&SE
,
12328 const SCEV
*PredicatedScalarEvolution::getSCEV(Value
*V
) {
12329 const SCEV
*Expr
= SE
.getSCEV(V
);
12330 RewriteEntry
&Entry
= RewriteMap
[Expr
];
12332 // If we already have an entry and the version matches, return it.
12333 if (Entry
.second
&& Generation
== Entry
.first
)
12334 return Entry
.second
;
12336 // We found an entry but it's stale. Rewrite the stale entry
12337 // according to the current predicate.
12339 Expr
= Entry
.second
;
12341 const SCEV
*NewSCEV
= SE
.rewriteUsingPredicate(Expr
, &L
, Preds
);
12342 Entry
= {Generation
, NewSCEV
};
12347 const SCEV
*PredicatedScalarEvolution::getBackedgeTakenCount() {
12348 if (!BackedgeCount
) {
12349 SCEVUnionPredicate BackedgePred
;
12350 BackedgeCount
= SE
.getPredicatedBackedgeTakenCount(&L
, BackedgePred
);
12351 addPredicate(BackedgePred
);
12353 return BackedgeCount
;
12356 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate
&Pred
) {
12357 if (Preds
.implies(&Pred
))
12360 updateGeneration();
12363 const SCEVUnionPredicate
&PredicatedScalarEvolution::getUnionPredicate() const {
12367 void PredicatedScalarEvolution::updateGeneration() {
12368 // If the generation number wrapped recompute everything.
12369 if (++Generation
== 0) {
12370 for (auto &II
: RewriteMap
) {
12371 const SCEV
*Rewritten
= II
.second
.second
;
12372 II
.second
= {Generation
, SE
.rewriteUsingPredicate(Rewritten
, &L
, Preds
)};
12377 void PredicatedScalarEvolution::setNoOverflow(
12378 Value
*V
, SCEVWrapPredicate::IncrementWrapFlags Flags
) {
12379 const SCEV
*Expr
= getSCEV(V
);
12380 const auto *AR
= cast
<SCEVAddRecExpr
>(Expr
);
12382 auto ImpliedFlags
= SCEVWrapPredicate::getImpliedFlags(AR
, SE
);
12384 // Clear the statically implied flags.
12385 Flags
= SCEVWrapPredicate::clearFlags(Flags
, ImpliedFlags
);
12386 addPredicate(*SE
.getWrapPredicate(AR
, Flags
));
12388 auto II
= FlagsMap
.insert({V
, Flags
});
12390 II
.first
->second
= SCEVWrapPredicate::setFlags(Flags
, II
.first
->second
);
12393 bool PredicatedScalarEvolution::hasNoOverflow(
12394 Value
*V
, SCEVWrapPredicate::IncrementWrapFlags Flags
) {
12395 const SCEV
*Expr
= getSCEV(V
);
12396 const auto *AR
= cast
<SCEVAddRecExpr
>(Expr
);
12398 Flags
= SCEVWrapPredicate::clearFlags(
12399 Flags
, SCEVWrapPredicate::getImpliedFlags(AR
, SE
));
12401 auto II
= FlagsMap
.find(V
);
12403 if (II
!= FlagsMap
.end())
12404 Flags
= SCEVWrapPredicate::clearFlags(Flags
, II
->second
);
12406 return Flags
== SCEVWrapPredicate::IncrementAnyWrap
;
12409 const SCEVAddRecExpr
*PredicatedScalarEvolution::getAsAddRec(Value
*V
) {
12410 const SCEV
*Expr
= this->getSCEV(V
);
12411 SmallPtrSet
<const SCEVPredicate
*, 4> NewPreds
;
12412 auto *New
= SE
.convertSCEVToAddRecWithPredicates(Expr
, &L
, NewPreds
);
12417 for (auto *P
: NewPreds
)
12420 updateGeneration();
12421 RewriteMap
[SE
.getSCEV(V
)] = {Generation
, New
};
12425 PredicatedScalarEvolution::PredicatedScalarEvolution(
12426 const PredicatedScalarEvolution
&Init
)
12427 : RewriteMap(Init
.RewriteMap
), SE(Init
.SE
), L(Init
.L
), Preds(Init
.Preds
),
12428 Generation(Init
.Generation
), BackedgeCount(Init
.BackedgeCount
) {
12429 for (const auto &I
: Init
.FlagsMap
)
12430 FlagsMap
.insert(I
);
12433 void PredicatedScalarEvolution::print(raw_ostream
&OS
, unsigned Depth
) const {
12435 for (auto *BB
: L
.getBlocks())
12436 for (auto &I
: *BB
) {
12437 if (!SE
.isSCEVable(I
.getType()))
12440 auto *Expr
= SE
.getSCEV(&I
);
12441 auto II
= RewriteMap
.find(Expr
);
12443 if (II
== RewriteMap
.end())
12446 // Don't print things that are not interesting.
12447 if (II
->second
.second
== Expr
)
12450 OS
.indent(Depth
) << "[PSE]" << I
<< ":\n";
12451 OS
.indent(Depth
+ 2) << *Expr
<< "\n";
12452 OS
.indent(Depth
+ 2) << "--> " << *II
->second
.second
<< "\n";
12456 // Match the mathematical pattern A - (A / B) * B, where A and B can be
12457 // arbitrary expressions.
12458 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is
12459 // 4, A / B becomes X / 8).
12460 bool ScalarEvolution::matchURem(const SCEV
*Expr
, const SCEV
*&LHS
,
12461 const SCEV
*&RHS
) {
12462 const auto *Add
= dyn_cast
<SCEVAddExpr
>(Expr
);
12463 if (Add
== nullptr || Add
->getNumOperands() != 2)
12466 const SCEV
*A
= Add
->getOperand(1);
12467 const auto *Mul
= dyn_cast
<SCEVMulExpr
>(Add
->getOperand(0));
12469 if (Mul
== nullptr)
12472 const auto MatchURemWithDivisor
= [&](const SCEV
*B
) {
12473 // (SomeExpr + (-(SomeExpr / B) * B)).
12474 if (Expr
== getURemExpr(A
, B
)) {
12482 // (SomeExpr + (-1 * (SomeExpr / B) * B)).
12483 if (Mul
->getNumOperands() == 3 && isa
<SCEVConstant
>(Mul
->getOperand(0)))
12484 return MatchURemWithDivisor(Mul
->getOperand(1)) ||
12485 MatchURemWithDivisor(Mul
->getOperand(2));
12487 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)).
12488 if (Mul
->getNumOperands() == 2)
12489 return MatchURemWithDivisor(Mul
->getOperand(1)) ||
12490 MatchURemWithDivisor(Mul
->getOperand(0)) ||
12491 MatchURemWithDivisor(getNegativeSCEV(Mul
->getOperand(1))) ||
12492 MatchURemWithDivisor(getNegativeSCEV(Mul
->getOperand(0)));