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
,
151 cl::desc("Maximum number of iterations SCEV will "
152 "symbolically execute a constant "
156 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
157 static cl::opt
<bool> VerifySCEV(
158 "verify-scev", cl::Hidden
,
159 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
161 VerifySCEVMap("verify-scev-maps", cl::Hidden
,
162 cl::desc("Verify no dangling value in ScalarEvolution's "
163 "ExprValueMap (slow)"));
165 static cl::opt
<bool> VerifyIR(
166 "scev-verify-ir", cl::Hidden
,
167 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
170 static cl::opt
<unsigned> MulOpsInlineThreshold(
171 "scev-mulops-inline-threshold", cl::Hidden
,
172 cl::desc("Threshold for inlining multiplication operands into a SCEV"),
175 static cl::opt
<unsigned> AddOpsInlineThreshold(
176 "scev-addops-inline-threshold", cl::Hidden
,
177 cl::desc("Threshold for inlining addition operands into a SCEV"),
180 static cl::opt
<unsigned> MaxSCEVCompareDepth(
181 "scalar-evolution-max-scev-compare-depth", cl::Hidden
,
182 cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
185 static cl::opt
<unsigned> MaxSCEVOperationsImplicationDepth(
186 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden
,
187 cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
190 static cl::opt
<unsigned> MaxValueCompareDepth(
191 "scalar-evolution-max-value-compare-depth", cl::Hidden
,
192 cl::desc("Maximum depth of recursive value complexity comparisons"),
195 static cl::opt
<unsigned>
196 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden
,
197 cl::desc("Maximum depth of recursive arithmetics"),
200 static cl::opt
<unsigned> MaxConstantEvolvingDepth(
201 "scalar-evolution-max-constant-evolving-depth", cl::Hidden
,
202 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
204 static cl::opt
<unsigned>
205 MaxExtDepth("scalar-evolution-max-ext-depth", cl::Hidden
,
206 cl::desc("Maximum depth of recursive SExt/ZExt"),
209 static cl::opt
<unsigned>
210 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden
,
211 cl::desc("Max coefficients in AddRec during evolving"),
214 static cl::opt
<unsigned>
215 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden
,
216 cl::desc("Size of the expression which is considered huge"),
219 //===----------------------------------------------------------------------===//
220 // SCEV class definitions
221 //===----------------------------------------------------------------------===//
223 //===----------------------------------------------------------------------===//
224 // Implementation of the SCEV class.
227 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
228 LLVM_DUMP_METHOD
void SCEV::dump() const {
234 void SCEV::print(raw_ostream
&OS
) const {
235 switch (static_cast<SCEVTypes
>(getSCEVType())) {
237 cast
<SCEVConstant
>(this)->getValue()->printAsOperand(OS
, false);
240 const SCEVTruncateExpr
*Trunc
= cast
<SCEVTruncateExpr
>(this);
241 const SCEV
*Op
= Trunc
->getOperand();
242 OS
<< "(trunc " << *Op
->getType() << " " << *Op
<< " to "
243 << *Trunc
->getType() << ")";
247 const SCEVZeroExtendExpr
*ZExt
= cast
<SCEVZeroExtendExpr
>(this);
248 const SCEV
*Op
= ZExt
->getOperand();
249 OS
<< "(zext " << *Op
->getType() << " " << *Op
<< " to "
250 << *ZExt
->getType() << ")";
254 const SCEVSignExtendExpr
*SExt
= cast
<SCEVSignExtendExpr
>(this);
255 const SCEV
*Op
= SExt
->getOperand();
256 OS
<< "(sext " << *Op
->getType() << " " << *Op
<< " to "
257 << *SExt
->getType() << ")";
261 const SCEVAddRecExpr
*AR
= cast
<SCEVAddRecExpr
>(this);
262 OS
<< "{" << *AR
->getOperand(0);
263 for (unsigned i
= 1, e
= AR
->getNumOperands(); i
!= e
; ++i
)
264 OS
<< ",+," << *AR
->getOperand(i
);
266 if (AR
->hasNoUnsignedWrap())
268 if (AR
->hasNoSignedWrap())
270 if (AR
->hasNoSelfWrap() &&
271 !AR
->getNoWrapFlags((NoWrapFlags
)(FlagNUW
| FlagNSW
)))
273 AR
->getLoop()->getHeader()->printAsOperand(OS
, /*PrintType=*/false);
281 const SCEVNAryExpr
*NAry
= cast
<SCEVNAryExpr
>(this);
282 const char *OpStr
= nullptr;
283 switch (NAry
->getSCEVType()) {
284 case scAddExpr
: OpStr
= " + "; break;
285 case scMulExpr
: OpStr
= " * "; break;
286 case scUMaxExpr
: OpStr
= " umax "; break;
287 case scSMaxExpr
: OpStr
= " smax "; break;
290 for (SCEVNAryExpr::op_iterator I
= NAry
->op_begin(), E
= NAry
->op_end();
293 if (std::next(I
) != E
)
297 switch (NAry
->getSCEVType()) {
300 if (NAry
->hasNoUnsignedWrap())
302 if (NAry
->hasNoSignedWrap())
308 const SCEVUDivExpr
*UDiv
= cast
<SCEVUDivExpr
>(this);
309 OS
<< "(" << *UDiv
->getLHS() << " /u " << *UDiv
->getRHS() << ")";
313 const SCEVUnknown
*U
= cast
<SCEVUnknown
>(this);
315 if (U
->isSizeOf(AllocTy
)) {
316 OS
<< "sizeof(" << *AllocTy
<< ")";
319 if (U
->isAlignOf(AllocTy
)) {
320 OS
<< "alignof(" << *AllocTy
<< ")";
326 if (U
->isOffsetOf(CTy
, FieldNo
)) {
327 OS
<< "offsetof(" << *CTy
<< ", ";
328 FieldNo
->printAsOperand(OS
, false);
333 // Otherwise just print it normally.
334 U
->getValue()->printAsOperand(OS
, false);
337 case scCouldNotCompute
:
338 OS
<< "***COULDNOTCOMPUTE***";
341 llvm_unreachable("Unknown SCEV kind!");
344 Type
*SCEV::getType() const {
345 switch (static_cast<SCEVTypes
>(getSCEVType())) {
347 return cast
<SCEVConstant
>(this)->getType();
351 return cast
<SCEVCastExpr
>(this)->getType();
356 return cast
<SCEVNAryExpr
>(this)->getType();
358 return cast
<SCEVAddExpr
>(this)->getType();
360 return cast
<SCEVUDivExpr
>(this)->getType();
362 return cast
<SCEVUnknown
>(this)->getType();
363 case scCouldNotCompute
:
364 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
366 llvm_unreachable("Unknown SCEV kind!");
369 bool SCEV::isZero() const {
370 if (const SCEVConstant
*SC
= dyn_cast
<SCEVConstant
>(this))
371 return SC
->getValue()->isZero();
375 bool SCEV::isOne() const {
376 if (const SCEVConstant
*SC
= dyn_cast
<SCEVConstant
>(this))
377 return SC
->getValue()->isOne();
381 bool SCEV::isAllOnesValue() const {
382 if (const SCEVConstant
*SC
= dyn_cast
<SCEVConstant
>(this))
383 return SC
->getValue()->isMinusOne();
387 bool SCEV::isNonConstantNegative() const {
388 const SCEVMulExpr
*Mul
= dyn_cast
<SCEVMulExpr
>(this);
389 if (!Mul
) return false;
391 // If there is a constant factor, it will be first.
392 const SCEVConstant
*SC
= dyn_cast
<SCEVConstant
>(Mul
->getOperand(0));
393 if (!SC
) return false;
395 // Return true if the value is negative, this matches things like (-42 * V).
396 return SC
->getAPInt().isNegative();
399 SCEVCouldNotCompute::SCEVCouldNotCompute() :
400 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute
, 0) {}
402 bool SCEVCouldNotCompute::classof(const SCEV
*S
) {
403 return S
->getSCEVType() == scCouldNotCompute
;
406 const SCEV
*ScalarEvolution::getConstant(ConstantInt
*V
) {
408 ID
.AddInteger(scConstant
);
411 if (const SCEV
*S
= UniqueSCEVs
.FindNodeOrInsertPos(ID
, IP
)) return S
;
412 SCEV
*S
= new (SCEVAllocator
) SCEVConstant(ID
.Intern(SCEVAllocator
), V
);
413 UniqueSCEVs
.InsertNode(S
, IP
);
417 const SCEV
*ScalarEvolution::getConstant(const APInt
&Val
) {
418 return getConstant(ConstantInt::get(getContext(), Val
));
422 ScalarEvolution::getConstant(Type
*Ty
, uint64_t V
, bool isSigned
) {
423 IntegerType
*ITy
= cast
<IntegerType
>(getEffectiveSCEVType(Ty
));
424 return getConstant(ConstantInt::get(ITy
, V
, isSigned
));
427 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID
,
428 unsigned SCEVTy
, const SCEV
*op
, Type
*ty
)
429 : SCEV(ID
, SCEVTy
, computeExpressionSize(op
)), Op(op
), Ty(ty
) {}
431 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID
,
432 const SCEV
*op
, Type
*ty
)
433 : SCEVCastExpr(ID
, scTruncate
, op
, ty
) {
434 assert(Op
->getType()->isIntOrPtrTy() && Ty
->isIntOrPtrTy() &&
435 "Cannot truncate non-integer value!");
438 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID
,
439 const SCEV
*op
, Type
*ty
)
440 : SCEVCastExpr(ID
, scZeroExtend
, op
, ty
) {
441 assert(Op
->getType()->isIntOrPtrTy() && Ty
->isIntOrPtrTy() &&
442 "Cannot zero extend non-integer value!");
445 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID
,
446 const SCEV
*op
, Type
*ty
)
447 : SCEVCastExpr(ID
, scSignExtend
, op
, ty
) {
448 assert(Op
->getType()->isIntOrPtrTy() && Ty
->isIntOrPtrTy() &&
449 "Cannot sign extend non-integer value!");
452 void SCEVUnknown::deleted() {
453 // Clear this SCEVUnknown from various maps.
454 SE
->forgetMemoizedResults(this);
456 // Remove this SCEVUnknown from the uniquing map.
457 SE
->UniqueSCEVs
.RemoveNode(this);
459 // Release the value.
463 void SCEVUnknown::allUsesReplacedWith(Value
*New
) {
464 // Remove this SCEVUnknown from the uniquing map.
465 SE
->UniqueSCEVs
.RemoveNode(this);
467 // Update this SCEVUnknown to point to the new value. This is needed
468 // because there may still be outstanding SCEVs which still point to
473 bool SCEVUnknown::isSizeOf(Type
*&AllocTy
) const {
474 if (ConstantExpr
*VCE
= dyn_cast
<ConstantExpr
>(getValue()))
475 if (VCE
->getOpcode() == Instruction::PtrToInt
)
476 if (ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(VCE
->getOperand(0)))
477 if (CE
->getOpcode() == Instruction::GetElementPtr
&&
478 CE
->getOperand(0)->isNullValue() &&
479 CE
->getNumOperands() == 2)
480 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(CE
->getOperand(1)))
482 AllocTy
= cast
<PointerType
>(CE
->getOperand(0)->getType())
490 bool SCEVUnknown::isAlignOf(Type
*&AllocTy
) const {
491 if (ConstantExpr
*VCE
= dyn_cast
<ConstantExpr
>(getValue()))
492 if (VCE
->getOpcode() == Instruction::PtrToInt
)
493 if (ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(VCE
->getOperand(0)))
494 if (CE
->getOpcode() == Instruction::GetElementPtr
&&
495 CE
->getOperand(0)->isNullValue()) {
497 cast
<PointerType
>(CE
->getOperand(0)->getType())->getElementType();
498 if (StructType
*STy
= dyn_cast
<StructType
>(Ty
))
499 if (!STy
->isPacked() &&
500 CE
->getNumOperands() == 3 &&
501 CE
->getOperand(1)->isNullValue()) {
502 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(CE
->getOperand(2)))
504 STy
->getNumElements() == 2 &&
505 STy
->getElementType(0)->isIntegerTy(1)) {
506 AllocTy
= STy
->getElementType(1);
515 bool SCEVUnknown::isOffsetOf(Type
*&CTy
, Constant
*&FieldNo
) const {
516 if (ConstantExpr
*VCE
= dyn_cast
<ConstantExpr
>(getValue()))
517 if (VCE
->getOpcode() == Instruction::PtrToInt
)
518 if (ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(VCE
->getOperand(0)))
519 if (CE
->getOpcode() == Instruction::GetElementPtr
&&
520 CE
->getNumOperands() == 3 &&
521 CE
->getOperand(0)->isNullValue() &&
522 CE
->getOperand(1)->isNullValue()) {
524 cast
<PointerType
>(CE
->getOperand(0)->getType())->getElementType();
525 // Ignore vector types here so that ScalarEvolutionExpander doesn't
526 // emit getelementptrs that index into vectors.
527 if (Ty
->isStructTy() || Ty
->isArrayTy()) {
529 FieldNo
= CE
->getOperand(2);
537 //===----------------------------------------------------------------------===//
539 //===----------------------------------------------------------------------===//
541 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
542 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
543 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that
544 /// have been previously deemed to be "equally complex" by this routine. It is
545 /// intended to avoid exponential time complexity in cases like:
555 /// CompareValueComplexity(%f, %c)
557 /// Since we do not continue running this routine on expression trees once we
558 /// have seen unequal values, there is no need to track them in the cache.
560 CompareValueComplexity(EquivalenceClasses
<const Value
*> &EqCacheValue
,
561 const LoopInfo
*const LI
, Value
*LV
, Value
*RV
,
563 if (Depth
> MaxValueCompareDepth
|| EqCacheValue
.isEquivalent(LV
, RV
))
566 // Order pointer values after integer values. This helps SCEVExpander form
568 bool LIsPointer
= LV
->getType()->isPointerTy(),
569 RIsPointer
= RV
->getType()->isPointerTy();
570 if (LIsPointer
!= RIsPointer
)
571 return (int)LIsPointer
- (int)RIsPointer
;
573 // Compare getValueID values.
574 unsigned LID
= LV
->getValueID(), RID
= RV
->getValueID();
576 return (int)LID
- (int)RID
;
578 // Sort arguments by their position.
579 if (const auto *LA
= dyn_cast
<Argument
>(LV
)) {
580 const auto *RA
= cast
<Argument
>(RV
);
581 unsigned LArgNo
= LA
->getArgNo(), RArgNo
= RA
->getArgNo();
582 return (int)LArgNo
- (int)RArgNo
;
585 if (const auto *LGV
= dyn_cast
<GlobalValue
>(LV
)) {
586 const auto *RGV
= cast
<GlobalValue
>(RV
);
588 const auto IsGVNameSemantic
= [&](const GlobalValue
*GV
) {
589 auto LT
= GV
->getLinkage();
590 return !(GlobalValue::isPrivateLinkage(LT
) ||
591 GlobalValue::isInternalLinkage(LT
));
594 // Use the names to distinguish the two values, but only if the
595 // names are semantically important.
596 if (IsGVNameSemantic(LGV
) && IsGVNameSemantic(RGV
))
597 return LGV
->getName().compare(RGV
->getName());
600 // For instructions, compare their loop depth, and their operand count. This
602 if (const auto *LInst
= dyn_cast
<Instruction
>(LV
)) {
603 const auto *RInst
= cast
<Instruction
>(RV
);
605 // Compare loop depths.
606 const BasicBlock
*LParent
= LInst
->getParent(),
607 *RParent
= RInst
->getParent();
608 if (LParent
!= RParent
) {
609 unsigned LDepth
= LI
->getLoopDepth(LParent
),
610 RDepth
= LI
->getLoopDepth(RParent
);
611 if (LDepth
!= RDepth
)
612 return (int)LDepth
- (int)RDepth
;
615 // Compare the number of operands.
616 unsigned LNumOps
= LInst
->getNumOperands(),
617 RNumOps
= RInst
->getNumOperands();
618 if (LNumOps
!= RNumOps
)
619 return (int)LNumOps
- (int)RNumOps
;
621 for (unsigned Idx
: seq(0u, LNumOps
)) {
623 CompareValueComplexity(EqCacheValue
, LI
, LInst
->getOperand(Idx
),
624 RInst
->getOperand(Idx
), Depth
+ 1);
630 EqCacheValue
.unionSets(LV
, RV
);
634 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
635 // than RHS, respectively. A three-way result allows recursive comparisons to be
637 static int CompareSCEVComplexity(
638 EquivalenceClasses
<const SCEV
*> &EqCacheSCEV
,
639 EquivalenceClasses
<const Value
*> &EqCacheValue
,
640 const LoopInfo
*const LI
, const SCEV
*LHS
, const SCEV
*RHS
,
641 DominatorTree
&DT
, unsigned Depth
= 0) {
642 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
646 // Primarily, sort the SCEVs by their getSCEVType().
647 unsigned LType
= LHS
->getSCEVType(), RType
= RHS
->getSCEVType();
649 return (int)LType
- (int)RType
;
651 if (Depth
> MaxSCEVCompareDepth
|| EqCacheSCEV
.isEquivalent(LHS
, RHS
))
653 // Aside from the getSCEVType() ordering, the particular ordering
654 // isn't very important except that it's beneficial to be consistent,
655 // so that (a + b) and (b + a) don't end up as different expressions.
656 switch (static_cast<SCEVTypes
>(LType
)) {
658 const SCEVUnknown
*LU
= cast
<SCEVUnknown
>(LHS
);
659 const SCEVUnknown
*RU
= cast
<SCEVUnknown
>(RHS
);
661 int X
= CompareValueComplexity(EqCacheValue
, LI
, LU
->getValue(),
662 RU
->getValue(), Depth
+ 1);
664 EqCacheSCEV
.unionSets(LHS
, RHS
);
669 const SCEVConstant
*LC
= cast
<SCEVConstant
>(LHS
);
670 const SCEVConstant
*RC
= cast
<SCEVConstant
>(RHS
);
672 // Compare constant values.
673 const APInt
&LA
= LC
->getAPInt();
674 const APInt
&RA
= RC
->getAPInt();
675 unsigned LBitWidth
= LA
.getBitWidth(), RBitWidth
= RA
.getBitWidth();
676 if (LBitWidth
!= RBitWidth
)
677 return (int)LBitWidth
- (int)RBitWidth
;
678 return LA
.ult(RA
) ? -1 : 1;
682 const SCEVAddRecExpr
*LA
= cast
<SCEVAddRecExpr
>(LHS
);
683 const SCEVAddRecExpr
*RA
= cast
<SCEVAddRecExpr
>(RHS
);
685 // There is always a dominance between two recs that are used by one SCEV,
686 // so we can safely sort recs by loop header dominance. We require such
687 // order in getAddExpr.
688 const Loop
*LLoop
= LA
->getLoop(), *RLoop
= RA
->getLoop();
689 if (LLoop
!= RLoop
) {
690 const BasicBlock
*LHead
= LLoop
->getHeader(), *RHead
= RLoop
->getHeader();
691 assert(LHead
!= RHead
&& "Two loops share the same header?");
692 if (DT
.dominates(LHead
, RHead
))
695 assert(DT
.dominates(RHead
, LHead
) &&
696 "No dominance between recurrences used by one SCEV?");
700 // Addrec complexity grows with operand count.
701 unsigned LNumOps
= LA
->getNumOperands(), RNumOps
= RA
->getNumOperands();
702 if (LNumOps
!= RNumOps
)
703 return (int)LNumOps
- (int)RNumOps
;
705 // Lexicographically compare.
706 for (unsigned i
= 0; i
!= LNumOps
; ++i
) {
707 int X
= CompareSCEVComplexity(EqCacheSCEV
, EqCacheValue
, LI
,
708 LA
->getOperand(i
), RA
->getOperand(i
), DT
,
713 EqCacheSCEV
.unionSets(LHS
, RHS
);
721 const SCEVNAryExpr
*LC
= cast
<SCEVNAryExpr
>(LHS
);
722 const SCEVNAryExpr
*RC
= cast
<SCEVNAryExpr
>(RHS
);
724 // Lexicographically compare n-ary expressions.
725 unsigned LNumOps
= LC
->getNumOperands(), RNumOps
= RC
->getNumOperands();
726 if (LNumOps
!= RNumOps
)
727 return (int)LNumOps
- (int)RNumOps
;
729 for (unsigned i
= 0; i
!= LNumOps
; ++i
) {
730 int X
= CompareSCEVComplexity(EqCacheSCEV
, EqCacheValue
, LI
,
731 LC
->getOperand(i
), RC
->getOperand(i
), DT
,
736 EqCacheSCEV
.unionSets(LHS
, RHS
);
741 const SCEVUDivExpr
*LC
= cast
<SCEVUDivExpr
>(LHS
);
742 const SCEVUDivExpr
*RC
= cast
<SCEVUDivExpr
>(RHS
);
744 // Lexicographically compare udiv expressions.
745 int X
= CompareSCEVComplexity(EqCacheSCEV
, EqCacheValue
, LI
, LC
->getLHS(),
746 RC
->getLHS(), DT
, Depth
+ 1);
749 X
= CompareSCEVComplexity(EqCacheSCEV
, EqCacheValue
, LI
, LC
->getRHS(),
750 RC
->getRHS(), DT
, Depth
+ 1);
752 EqCacheSCEV
.unionSets(LHS
, RHS
);
759 const SCEVCastExpr
*LC
= cast
<SCEVCastExpr
>(LHS
);
760 const SCEVCastExpr
*RC
= cast
<SCEVCastExpr
>(RHS
);
762 // Compare cast expressions by operand.
763 int X
= CompareSCEVComplexity(EqCacheSCEV
, EqCacheValue
, LI
,
764 LC
->getOperand(), RC
->getOperand(), DT
,
767 EqCacheSCEV
.unionSets(LHS
, RHS
);
771 case scCouldNotCompute
:
772 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
774 llvm_unreachable("Unknown SCEV kind!");
777 /// Given a list of SCEV objects, order them by their complexity, and group
778 /// objects of the same complexity together by value. When this routine is
779 /// finished, we know that any duplicates in the vector are consecutive and that
780 /// complexity is monotonically increasing.
782 /// Note that we go take special precautions to ensure that we get deterministic
783 /// results from this routine. In other words, we don't want the results of
784 /// this to depend on where the addresses of various SCEV objects happened to
786 static void GroupByComplexity(SmallVectorImpl
<const SCEV
*> &Ops
,
787 LoopInfo
*LI
, DominatorTree
&DT
) {
788 if (Ops
.size() < 2) return; // Noop
790 EquivalenceClasses
<const SCEV
*> EqCacheSCEV
;
791 EquivalenceClasses
<const Value
*> EqCacheValue
;
792 if (Ops
.size() == 2) {
793 // This is the common case, which also happens to be trivially simple.
795 const SCEV
*&LHS
= Ops
[0], *&RHS
= Ops
[1];
796 if (CompareSCEVComplexity(EqCacheSCEV
, EqCacheValue
, LI
, RHS
, LHS
, DT
) < 0)
801 // Do the rough sort by complexity.
802 std::stable_sort(Ops
.begin(), Ops
.end(),
803 [&](const SCEV
*LHS
, const SCEV
*RHS
) {
804 return CompareSCEVComplexity(EqCacheSCEV
, EqCacheValue
, LI
,
808 // Now that we are sorted by complexity, group elements of the same
809 // complexity. Note that this is, at worst, N^2, but the vector is likely to
810 // be extremely short in practice. Note that we take this approach because we
811 // do not want to depend on the addresses of the objects we are grouping.
812 for (unsigned i
= 0, e
= Ops
.size(); i
!= e
-2; ++i
) {
813 const SCEV
*S
= Ops
[i
];
814 unsigned Complexity
= S
->getSCEVType();
816 // If there are any objects of the same complexity and same value as this
818 for (unsigned j
= i
+1; j
!= e
&& Ops
[j
]->getSCEVType() == Complexity
; ++j
) {
819 if (Ops
[j
] == S
) { // Found a duplicate.
820 // Move it to immediately after i'th element.
821 std::swap(Ops
[i
+1], Ops
[j
]);
822 ++i
; // no need to rescan it.
823 if (i
== e
-2) return; // Done!
829 // Returns the size of the SCEV S.
830 static inline int sizeOfSCEV(const SCEV
*S
) {
831 struct FindSCEVSize
{
834 FindSCEVSize() = default;
836 bool follow(const SCEV
*S
) {
838 // Keep looking at all operands of S.
842 bool isDone() const {
848 SCEVTraversal
<FindSCEVSize
> ST(F
);
853 /// Returns true if the subtree of \p S contains at least HugeExprThreshold
855 static bool isHugeExpression(const SCEV
*S
) {
856 return S
->getExpressionSize() >= HugeExprThreshold
;
859 /// Returns true of \p Ops contains a huge SCEV (see definition above).
860 static bool hasHugeExpression(ArrayRef
<const SCEV
*> Ops
) {
861 return any_of(Ops
, isHugeExpression
);
866 struct SCEVDivision
: public SCEVVisitor
<SCEVDivision
, void> {
868 // Computes the Quotient and Remainder of the division of Numerator by
870 static void divide(ScalarEvolution
&SE
, const SCEV
*Numerator
,
871 const SCEV
*Denominator
, const SCEV
**Quotient
,
872 const SCEV
**Remainder
) {
873 assert(Numerator
&& Denominator
&& "Uninitialized SCEV");
875 SCEVDivision
D(SE
, Numerator
, Denominator
);
877 // Check for the trivial case here to avoid having to check for it in the
879 if (Numerator
== Denominator
) {
885 if (Numerator
->isZero()) {
891 // A simple case when N/1. The quotient is N.
892 if (Denominator
->isOne()) {
893 *Quotient
= Numerator
;
898 // Split the Denominator when it is a product.
899 if (const SCEVMulExpr
*T
= dyn_cast
<SCEVMulExpr
>(Denominator
)) {
901 *Quotient
= Numerator
;
902 for (const SCEV
*Op
: T
->operands()) {
903 divide(SE
, *Quotient
, Op
, &Q
, &R
);
906 // Bail out when the Numerator is not divisible by one of the terms of
910 *Remainder
= Numerator
;
919 *Quotient
= D
.Quotient
;
920 *Remainder
= D
.Remainder
;
923 // Except in the trivial case described above, we do not know how to divide
924 // Expr by Denominator for the following functions with empty implementation.
925 void visitTruncateExpr(const SCEVTruncateExpr
*Numerator
) {}
926 void visitZeroExtendExpr(const SCEVZeroExtendExpr
*Numerator
) {}
927 void visitSignExtendExpr(const SCEVSignExtendExpr
*Numerator
) {}
928 void visitUDivExpr(const SCEVUDivExpr
*Numerator
) {}
929 void visitSMaxExpr(const SCEVSMaxExpr
*Numerator
) {}
930 void visitUMaxExpr(const SCEVUMaxExpr
*Numerator
) {}
931 void visitUnknown(const SCEVUnknown
*Numerator
) {}
932 void visitCouldNotCompute(const SCEVCouldNotCompute
*Numerator
) {}
934 void visitConstant(const SCEVConstant
*Numerator
) {
935 if (const SCEVConstant
*D
= dyn_cast
<SCEVConstant
>(Denominator
)) {
936 APInt NumeratorVal
= Numerator
->getAPInt();
937 APInt DenominatorVal
= D
->getAPInt();
938 uint32_t NumeratorBW
= NumeratorVal
.getBitWidth();
939 uint32_t DenominatorBW
= DenominatorVal
.getBitWidth();
941 if (NumeratorBW
> DenominatorBW
)
942 DenominatorVal
= DenominatorVal
.sext(NumeratorBW
);
943 else if (NumeratorBW
< DenominatorBW
)
944 NumeratorVal
= NumeratorVal
.sext(DenominatorBW
);
946 APInt
QuotientVal(NumeratorVal
.getBitWidth(), 0);
947 APInt
RemainderVal(NumeratorVal
.getBitWidth(), 0);
948 APInt::sdivrem(NumeratorVal
, DenominatorVal
, QuotientVal
, RemainderVal
);
949 Quotient
= SE
.getConstant(QuotientVal
);
950 Remainder
= SE
.getConstant(RemainderVal
);
955 void visitAddRecExpr(const SCEVAddRecExpr
*Numerator
) {
956 const SCEV
*StartQ
, *StartR
, *StepQ
, *StepR
;
957 if (!Numerator
->isAffine())
958 return cannotDivide(Numerator
);
959 divide(SE
, Numerator
->getStart(), Denominator
, &StartQ
, &StartR
);
960 divide(SE
, Numerator
->getStepRecurrence(SE
), Denominator
, &StepQ
, &StepR
);
961 // Bail out if the types do not match.
962 Type
*Ty
= Denominator
->getType();
963 if (Ty
!= StartQ
->getType() || Ty
!= StartR
->getType() ||
964 Ty
!= StepQ
->getType() || Ty
!= StepR
->getType())
965 return cannotDivide(Numerator
);
966 Quotient
= SE
.getAddRecExpr(StartQ
, StepQ
, Numerator
->getLoop(),
967 Numerator
->getNoWrapFlags());
968 Remainder
= SE
.getAddRecExpr(StartR
, StepR
, Numerator
->getLoop(),
969 Numerator
->getNoWrapFlags());
972 void visitAddExpr(const SCEVAddExpr
*Numerator
) {
973 SmallVector
<const SCEV
*, 2> Qs
, Rs
;
974 Type
*Ty
= Denominator
->getType();
976 for (const SCEV
*Op
: Numerator
->operands()) {
978 divide(SE
, Op
, Denominator
, &Q
, &R
);
980 // Bail out if types do not match.
981 if (Ty
!= Q
->getType() || Ty
!= R
->getType())
982 return cannotDivide(Numerator
);
988 if (Qs
.size() == 1) {
994 Quotient
= SE
.getAddExpr(Qs
);
995 Remainder
= SE
.getAddExpr(Rs
);
998 void visitMulExpr(const SCEVMulExpr
*Numerator
) {
999 SmallVector
<const SCEV
*, 2> Qs
;
1000 Type
*Ty
= Denominator
->getType();
1002 bool FoundDenominatorTerm
= false;
1003 for (const SCEV
*Op
: Numerator
->operands()) {
1004 // Bail out if types do not match.
1005 if (Ty
!= Op
->getType())
1006 return cannotDivide(Numerator
);
1008 if (FoundDenominatorTerm
) {
1013 // Check whether Denominator divides one of the product operands.
1015 divide(SE
, Op
, Denominator
, &Q
, &R
);
1021 // Bail out if types do not match.
1022 if (Ty
!= Q
->getType())
1023 return cannotDivide(Numerator
);
1025 FoundDenominatorTerm
= true;
1029 if (FoundDenominatorTerm
) {
1034 Quotient
= SE
.getMulExpr(Qs
);
1038 if (!isa
<SCEVUnknown
>(Denominator
))
1039 return cannotDivide(Numerator
);
1041 // The Remainder is obtained by replacing Denominator by 0 in Numerator.
1042 ValueToValueMap RewriteMap
;
1043 RewriteMap
[cast
<SCEVUnknown
>(Denominator
)->getValue()] =
1044 cast
<SCEVConstant
>(Zero
)->getValue();
1045 Remainder
= SCEVParameterRewriter::rewrite(Numerator
, SE
, RewriteMap
, true);
1047 if (Remainder
->isZero()) {
1048 // The Quotient is obtained by replacing Denominator by 1 in Numerator.
1049 RewriteMap
[cast
<SCEVUnknown
>(Denominator
)->getValue()] =
1050 cast
<SCEVConstant
>(One
)->getValue();
1052 SCEVParameterRewriter::rewrite(Numerator
, SE
, RewriteMap
, true);
1056 // Quotient is (Numerator - Remainder) divided by Denominator.
1058 const SCEV
*Diff
= SE
.getMinusSCEV(Numerator
, Remainder
);
1059 // This SCEV does not seem to simplify: fail the division here.
1060 if (sizeOfSCEV(Diff
) > sizeOfSCEV(Numerator
))
1061 return cannotDivide(Numerator
);
1062 divide(SE
, Diff
, Denominator
, &Q
, &R
);
1064 return cannotDivide(Numerator
);
1069 SCEVDivision(ScalarEvolution
&S
, const SCEV
*Numerator
,
1070 const SCEV
*Denominator
)
1071 : SE(S
), Denominator(Denominator
) {
1072 Zero
= SE
.getZero(Denominator
->getType());
1073 One
= SE
.getOne(Denominator
->getType());
1075 // We generally do not know how to divide Expr by Denominator. We
1076 // initialize the division to a "cannot divide" state to simplify the rest
1078 cannotDivide(Numerator
);
1081 // Convenience function for giving up on the division. We set the quotient to
1082 // be equal to zero and the remainder to be equal to the numerator.
1083 void cannotDivide(const SCEV
*Numerator
) {
1085 Remainder
= Numerator
;
1088 ScalarEvolution
&SE
;
1089 const SCEV
*Denominator
, *Quotient
, *Remainder
, *Zero
, *One
;
1092 } // end anonymous namespace
1094 //===----------------------------------------------------------------------===//
1095 // Simple SCEV method implementations
1096 //===----------------------------------------------------------------------===//
1098 /// Compute BC(It, K). The result has width W. Assume, K > 0.
1099 static const SCEV
*BinomialCoefficient(const SCEV
*It
, unsigned K
,
1100 ScalarEvolution
&SE
,
1102 // Handle the simplest case efficiently.
1104 return SE
.getTruncateOrZeroExtend(It
, ResultTy
);
1106 // We are using the following formula for BC(It, K):
1108 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1110 // Suppose, W is the bitwidth of the return value. We must be prepared for
1111 // overflow. Hence, we must assure that the result of our computation is
1112 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
1113 // safe in modular arithmetic.
1115 // However, this code doesn't use exactly that formula; the formula it uses
1116 // is something like the following, where T is the number of factors of 2 in
1117 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1120 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
1122 // This formula is trivially equivalent to the previous formula. However,
1123 // this formula can be implemented much more efficiently. The trick is that
1124 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1125 // arithmetic. To do exact division in modular arithmetic, all we have
1126 // to do is multiply by the inverse. Therefore, this step can be done at
1129 // The next issue is how to safely do the division by 2^T. The way this
1130 // is done is by doing the multiplication step at a width of at least W + T
1131 // bits. This way, the bottom W+T bits of the product are accurate. Then,
1132 // when we perform the division by 2^T (which is equivalent to a right shift
1133 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
1134 // truncated out after the division by 2^T.
1136 // In comparison to just directly using the first formula, this technique
1137 // is much more efficient; using the first formula requires W * K bits,
1138 // but this formula less than W + K bits. Also, the first formula requires
1139 // a division step, whereas this formula only requires multiplies and shifts.
1141 // It doesn't matter whether the subtraction step is done in the calculation
1142 // width or the input iteration count's width; if the subtraction overflows,
1143 // the result must be zero anyway. We prefer here to do it in the width of
1144 // the induction variable because it helps a lot for certain cases; CodeGen
1145 // isn't smart enough to ignore the overflow, which leads to much less
1146 // efficient code if the width of the subtraction is wider than the native
1149 // (It's possible to not widen at all by pulling out factors of 2 before
1150 // the multiplication; for example, K=2 can be calculated as
1151 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1152 // extra arithmetic, so it's not an obvious win, and it gets
1153 // much more complicated for K > 3.)
1155 // Protection from insane SCEVs; this bound is conservative,
1156 // but it probably doesn't matter.
1158 return SE
.getCouldNotCompute();
1160 unsigned W
= SE
.getTypeSizeInBits(ResultTy
);
1162 // Calculate K! / 2^T and T; we divide out the factors of two before
1163 // multiplying for calculating K! / 2^T to avoid overflow.
1164 // Other overflow doesn't matter because we only care about the bottom
1165 // W bits of the result.
1166 APInt
OddFactorial(W
, 1);
1168 for (unsigned i
= 3; i
<= K
; ++i
) {
1170 unsigned TwoFactors
= Mult
.countTrailingZeros();
1172 Mult
.lshrInPlace(TwoFactors
);
1173 OddFactorial
*= Mult
;
1176 // We need at least W + T bits for the multiplication step
1177 unsigned CalculationBits
= W
+ T
;
1179 // Calculate 2^T, at width T+W.
1180 APInt DivFactor
= APInt::getOneBitSet(CalculationBits
, T
);
1182 // Calculate the multiplicative inverse of K! / 2^T;
1183 // this multiplication factor will perform the exact division by
1185 APInt Mod
= APInt::getSignedMinValue(W
+1);
1186 APInt MultiplyFactor
= OddFactorial
.zext(W
+1);
1187 MultiplyFactor
= MultiplyFactor
.multiplicativeInverse(Mod
);
1188 MultiplyFactor
= MultiplyFactor
.trunc(W
);
1190 // Calculate the product, at width T+W
1191 IntegerType
*CalculationTy
= IntegerType::get(SE
.getContext(),
1193 const SCEV
*Dividend
= SE
.getTruncateOrZeroExtend(It
, CalculationTy
);
1194 for (unsigned i
= 1; i
!= K
; ++i
) {
1195 const SCEV
*S
= SE
.getMinusSCEV(It
, SE
.getConstant(It
->getType(), i
));
1196 Dividend
= SE
.getMulExpr(Dividend
,
1197 SE
.getTruncateOrZeroExtend(S
, CalculationTy
));
1201 const SCEV
*DivResult
= SE
.getUDivExpr(Dividend
, SE
.getConstant(DivFactor
));
1203 // Truncate the result, and divide by K! / 2^T.
1205 return SE
.getMulExpr(SE
.getConstant(MultiplyFactor
),
1206 SE
.getTruncateOrZeroExtend(DivResult
, ResultTy
));
1209 /// Return the value of this chain of recurrences at the specified iteration
1210 /// number. We can evaluate this recurrence by multiplying each element in the
1211 /// chain by the binomial coefficient corresponding to it. In other words, we
1212 /// can evaluate {A,+,B,+,C,+,D} as:
1214 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1216 /// where BC(It, k) stands for binomial coefficient.
1217 const SCEV
*SCEVAddRecExpr::evaluateAtIteration(const SCEV
*It
,
1218 ScalarEvolution
&SE
) const {
1219 const SCEV
*Result
= getStart();
1220 for (unsigned i
= 1, e
= getNumOperands(); i
!= e
; ++i
) {
1221 // The computation is correct in the face of overflow provided that the
1222 // multiplication is performed _after_ the evaluation of the binomial
1224 const SCEV
*Coeff
= BinomialCoefficient(It
, i
, SE
, getType());
1225 if (isa
<SCEVCouldNotCompute
>(Coeff
))
1228 Result
= SE
.getAddExpr(Result
, SE
.getMulExpr(getOperand(i
), Coeff
));
1233 //===----------------------------------------------------------------------===//
1234 // SCEV Expression folder implementations
1235 //===----------------------------------------------------------------------===//
1237 const SCEV
*ScalarEvolution::getTruncateExpr(const SCEV
*Op
,
1239 assert(getTypeSizeInBits(Op
->getType()) > getTypeSizeInBits(Ty
) &&
1240 "This is not a truncating conversion!");
1241 assert(isSCEVable(Ty
) &&
1242 "This is not a conversion to a SCEVable type!");
1243 Ty
= getEffectiveSCEVType(Ty
);
1245 FoldingSetNodeID ID
;
1246 ID
.AddInteger(scTruncate
);
1250 if (const SCEV
*S
= UniqueSCEVs
.FindNodeOrInsertPos(ID
, IP
)) return S
;
1252 // Fold if the operand is constant.
1253 if (const SCEVConstant
*SC
= dyn_cast
<SCEVConstant
>(Op
))
1255 cast
<ConstantInt
>(ConstantExpr::getTrunc(SC
->getValue(), Ty
)));
1257 // trunc(trunc(x)) --> trunc(x)
1258 if (const SCEVTruncateExpr
*ST
= dyn_cast
<SCEVTruncateExpr
>(Op
))
1259 return getTruncateExpr(ST
->getOperand(), Ty
);
1261 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1262 if (const SCEVSignExtendExpr
*SS
= dyn_cast
<SCEVSignExtendExpr
>(Op
))
1263 return getTruncateOrSignExtend(SS
->getOperand(), Ty
);
1265 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1266 if (const SCEVZeroExtendExpr
*SZ
= dyn_cast
<SCEVZeroExtendExpr
>(Op
))
1267 return getTruncateOrZeroExtend(SZ
->getOperand(), Ty
);
1269 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1270 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1271 // if after transforming we have at most one truncate, not counting truncates
1272 // that replace other casts.
1273 if (isa
<SCEVAddExpr
>(Op
) || isa
<SCEVMulExpr
>(Op
)) {
1274 auto *CommOp
= cast
<SCEVCommutativeExpr
>(Op
);
1275 SmallVector
<const SCEV
*, 4> Operands
;
1276 unsigned numTruncs
= 0;
1277 for (unsigned i
= 0, e
= CommOp
->getNumOperands(); i
!= e
&& numTruncs
< 2;
1279 const SCEV
*S
= getTruncateExpr(CommOp
->getOperand(i
), Ty
);
1280 if (!isa
<SCEVCastExpr
>(CommOp
->getOperand(i
)) && isa
<SCEVTruncateExpr
>(S
))
1282 Operands
.push_back(S
);
1284 if (numTruncs
< 2) {
1285 if (isa
<SCEVAddExpr
>(Op
))
1286 return getAddExpr(Operands
);
1287 else if (isa
<SCEVMulExpr
>(Op
))
1288 return getMulExpr(Operands
);
1290 llvm_unreachable("Unexpected SCEV type for Op.");
1292 // Although we checked in the beginning that ID is not in the cache, it is
1293 // possible that during recursion and different modification ID was inserted
1294 // into the cache. So if we find it, just return it.
1295 if (const SCEV
*S
= UniqueSCEVs
.FindNodeOrInsertPos(ID
, IP
))
1299 // If the input value is a chrec scev, truncate the chrec's operands.
1300 if (const SCEVAddRecExpr
*AddRec
= dyn_cast
<SCEVAddRecExpr
>(Op
)) {
1301 SmallVector
<const SCEV
*, 4> Operands
;
1302 for (const SCEV
*Op
: AddRec
->operands())
1303 Operands
.push_back(getTruncateExpr(Op
, Ty
));
1304 return getAddRecExpr(Operands
, AddRec
->getLoop(), SCEV::FlagAnyWrap
);
1307 // The cast wasn't folded; create an explicit cast node. We can reuse
1308 // the existing insert position since if we get here, we won't have
1309 // made any changes which would invalidate it.
1310 SCEV
*S
= new (SCEVAllocator
) SCEVTruncateExpr(ID
.Intern(SCEVAllocator
),
1312 UniqueSCEVs
.InsertNode(S
, IP
);
1313 addToLoopUseLists(S
);
1317 // Get the limit of a recurrence such that incrementing by Step cannot cause
1318 // signed overflow as long as the value of the recurrence within the
1319 // loop does not exceed this limit before incrementing.
1320 static const SCEV
*getSignedOverflowLimitForStep(const SCEV
*Step
,
1321 ICmpInst::Predicate
*Pred
,
1322 ScalarEvolution
*SE
) {
1323 unsigned BitWidth
= SE
->getTypeSizeInBits(Step
->getType());
1324 if (SE
->isKnownPositive(Step
)) {
1325 *Pred
= ICmpInst::ICMP_SLT
;
1326 return SE
->getConstant(APInt::getSignedMinValue(BitWidth
) -
1327 SE
->getSignedRangeMax(Step
));
1329 if (SE
->isKnownNegative(Step
)) {
1330 *Pred
= ICmpInst::ICMP_SGT
;
1331 return SE
->getConstant(APInt::getSignedMaxValue(BitWidth
) -
1332 SE
->getSignedRangeMin(Step
));
1337 // Get the limit of a recurrence such that incrementing by Step cannot cause
1338 // unsigned overflow as long as the value of the recurrence within the loop does
1339 // not exceed this limit before incrementing.
1340 static const SCEV
*getUnsignedOverflowLimitForStep(const SCEV
*Step
,
1341 ICmpInst::Predicate
*Pred
,
1342 ScalarEvolution
*SE
) {
1343 unsigned BitWidth
= SE
->getTypeSizeInBits(Step
->getType());
1344 *Pred
= ICmpInst::ICMP_ULT
;
1346 return SE
->getConstant(APInt::getMinValue(BitWidth
) -
1347 SE
->getUnsignedRangeMax(Step
));
1352 struct ExtendOpTraitsBase
{
1353 typedef const SCEV
*(ScalarEvolution::*GetExtendExprTy
)(const SCEV
*, Type
*,
1357 // Used to make code generic over signed and unsigned overflow.
1358 template <typename ExtendOp
> struct ExtendOpTraits
{
1361 // static const SCEV::NoWrapFlags WrapType;
1363 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1365 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1366 // ICmpInst::Predicate *Pred,
1367 // ScalarEvolution *SE);
1371 struct ExtendOpTraits
<SCEVSignExtendExpr
> : public ExtendOpTraitsBase
{
1372 static const SCEV::NoWrapFlags WrapType
= SCEV::FlagNSW
;
1374 static const GetExtendExprTy GetExtendExpr
;
1376 static const SCEV
*getOverflowLimitForStep(const SCEV
*Step
,
1377 ICmpInst::Predicate
*Pred
,
1378 ScalarEvolution
*SE
) {
1379 return getSignedOverflowLimitForStep(Step
, Pred
, SE
);
1383 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits
<
1384 SCEVSignExtendExpr
>::GetExtendExpr
= &ScalarEvolution::getSignExtendExpr
;
1387 struct ExtendOpTraits
<SCEVZeroExtendExpr
> : public ExtendOpTraitsBase
{
1388 static const SCEV::NoWrapFlags WrapType
= SCEV::FlagNUW
;
1390 static const GetExtendExprTy GetExtendExpr
;
1392 static const SCEV
*getOverflowLimitForStep(const SCEV
*Step
,
1393 ICmpInst::Predicate
*Pred
,
1394 ScalarEvolution
*SE
) {
1395 return getUnsignedOverflowLimitForStep(Step
, Pred
, SE
);
1399 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits
<
1400 SCEVZeroExtendExpr
>::GetExtendExpr
= &ScalarEvolution::getZeroExtendExpr
;
1402 } // end anonymous namespace
1404 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1405 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1406 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1407 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1408 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1409 // expression "Step + sext/zext(PreIncAR)" is congruent with
1410 // "sext/zext(PostIncAR)"
1411 template <typename ExtendOpTy
>
1412 static const SCEV
*getPreStartForExtend(const SCEVAddRecExpr
*AR
, Type
*Ty
,
1413 ScalarEvolution
*SE
, unsigned Depth
) {
1414 auto WrapType
= ExtendOpTraits
<ExtendOpTy
>::WrapType
;
1415 auto GetExtendExpr
= ExtendOpTraits
<ExtendOpTy
>::GetExtendExpr
;
1417 const Loop
*L
= AR
->getLoop();
1418 const SCEV
*Start
= AR
->getStart();
1419 const SCEV
*Step
= AR
->getStepRecurrence(*SE
);
1421 // Check for a simple looking step prior to loop entry.
1422 const SCEVAddExpr
*SA
= dyn_cast
<SCEVAddExpr
>(Start
);
1426 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1427 // subtraction is expensive. For this purpose, perform a quick and dirty
1428 // difference, by checking for Step in the operand list.
1429 SmallVector
<const SCEV
*, 4> DiffOps
;
1430 for (const SCEV
*Op
: SA
->operands())
1432 DiffOps
.push_back(Op
);
1434 if (DiffOps
.size() == SA
->getNumOperands())
1437 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1440 // 1. NSW/NUW flags on the step increment.
1441 auto PreStartFlags
=
1442 ScalarEvolution::maskFlags(SA
->getNoWrapFlags(), SCEV::FlagNUW
);
1443 const SCEV
*PreStart
= SE
->getAddExpr(DiffOps
, PreStartFlags
);
1444 const SCEVAddRecExpr
*PreAR
= dyn_cast
<SCEVAddRecExpr
>(
1445 SE
->getAddRecExpr(PreStart
, Step
, L
, SCEV::FlagAnyWrap
));
1447 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1448 // "S+X does not sign/unsign-overflow".
1451 const SCEV
*BECount
= SE
->getBackedgeTakenCount(L
);
1452 if (PreAR
&& PreAR
->getNoWrapFlags(WrapType
) &&
1453 !isa
<SCEVCouldNotCompute
>(BECount
) && SE
->isKnownPositive(BECount
))
1456 // 2. Direct overflow check on the step operation's expression.
1457 unsigned BitWidth
= SE
->getTypeSizeInBits(AR
->getType());
1458 Type
*WideTy
= IntegerType::get(SE
->getContext(), BitWidth
* 2);
1459 const SCEV
*OperandExtendedStart
=
1460 SE
->getAddExpr((SE
->*GetExtendExpr
)(PreStart
, WideTy
, Depth
),
1461 (SE
->*GetExtendExpr
)(Step
, WideTy
, Depth
));
1462 if ((SE
->*GetExtendExpr
)(Start
, WideTy
, Depth
) == OperandExtendedStart
) {
1463 if (PreAR
&& AR
->getNoWrapFlags(WrapType
)) {
1464 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1465 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1466 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1467 const_cast<SCEVAddRecExpr
*>(PreAR
)->setNoWrapFlags(WrapType
);
1472 // 3. Loop precondition.
1473 ICmpInst::Predicate Pred
;
1474 const SCEV
*OverflowLimit
=
1475 ExtendOpTraits
<ExtendOpTy
>::getOverflowLimitForStep(Step
, &Pred
, SE
);
1477 if (OverflowLimit
&&
1478 SE
->isLoopEntryGuardedByCond(L
, Pred
, PreStart
, OverflowLimit
))
1484 // Get the normalized zero or sign extended expression for this AddRec's Start.
1485 template <typename ExtendOpTy
>
1486 static const SCEV
*getExtendAddRecStart(const SCEVAddRecExpr
*AR
, Type
*Ty
,
1487 ScalarEvolution
*SE
,
1489 auto GetExtendExpr
= ExtendOpTraits
<ExtendOpTy
>::GetExtendExpr
;
1491 const SCEV
*PreStart
= getPreStartForExtend
<ExtendOpTy
>(AR
, Ty
, SE
, Depth
);
1493 return (SE
->*GetExtendExpr
)(AR
->getStart(), Ty
, Depth
);
1495 return SE
->getAddExpr((SE
->*GetExtendExpr
)(AR
->getStepRecurrence(*SE
), Ty
,
1497 (SE
->*GetExtendExpr
)(PreStart
, Ty
, Depth
));
1500 // Try to prove away overflow by looking at "nearby" add recurrences. A
1501 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1502 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1506 // {S,+,X} == {S-T,+,X} + T
1507 // => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1509 // If ({S-T,+,X} + T) does not overflow ... (1)
1511 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1513 // If {S-T,+,X} does not overflow ... (2)
1515 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1516 // == {Ext(S-T)+Ext(T),+,Ext(X)}
1518 // If (S-T)+T does not overflow ... (3)
1520 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1521 // == {Ext(S),+,Ext(X)} == LHS
1523 // Thus, if (1), (2) and (3) are true for some T, then
1524 // Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1526 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1527 // does not overflow" restricted to the 0th iteration. Therefore we only need
1528 // to check for (1) and (2).
1530 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1531 // is `Delta` (defined below).
1532 template <typename ExtendOpTy
>
1533 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV
*Start
,
1536 auto WrapType
= ExtendOpTraits
<ExtendOpTy
>::WrapType
;
1538 // We restrict `Start` to a constant to prevent SCEV from spending too much
1539 // time here. It is correct (but more expensive) to continue with a
1540 // non-constant `Start` and do a general SCEV subtraction to compute
1541 // `PreStart` below.
1542 const SCEVConstant
*StartC
= dyn_cast
<SCEVConstant
>(Start
);
1546 APInt StartAI
= StartC
->getAPInt();
1548 for (unsigned Delta
: {-2, -1, 1, 2}) {
1549 const SCEV
*PreStart
= getConstant(StartAI
- Delta
);
1551 FoldingSetNodeID ID
;
1552 ID
.AddInteger(scAddRecExpr
);
1553 ID
.AddPointer(PreStart
);
1554 ID
.AddPointer(Step
);
1558 static_cast<SCEVAddRecExpr
*>(UniqueSCEVs
.FindNodeOrInsertPos(ID
, IP
));
1560 // Give up if we don't already have the add recurrence we need because
1561 // actually constructing an add recurrence is relatively expensive.
1562 if (PreAR
&& PreAR
->getNoWrapFlags(WrapType
)) { // proves (2)
1563 const SCEV
*DeltaS
= getConstant(StartC
->getType(), Delta
);
1564 ICmpInst::Predicate Pred
= ICmpInst::BAD_ICMP_PREDICATE
;
1565 const SCEV
*Limit
= ExtendOpTraits
<ExtendOpTy
>::getOverflowLimitForStep(
1566 DeltaS
, &Pred
, this);
1567 if (Limit
&& isKnownPredicate(Pred
, PreAR
, Limit
)) // proves (1)
1575 // Finds an integer D for an expression (C + x + y + ...) such that the top
1576 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1577 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1578 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1579 // the (C + x + y + ...) expression is \p WholeAddExpr.
1580 static APInt
extractConstantWithoutWrapping(ScalarEvolution
&SE
,
1581 const SCEVConstant
*ConstantTerm
,
1582 const SCEVAddExpr
*WholeAddExpr
) {
1583 const APInt C
= ConstantTerm
->getAPInt();
1584 const unsigned BitWidth
= C
.getBitWidth();
1585 // Find number of trailing zeros of (x + y + ...) w/o the C first:
1586 uint32_t TZ
= BitWidth
;
1587 for (unsigned I
= 1, E
= WholeAddExpr
->getNumOperands(); I
< E
&& TZ
; ++I
)
1588 TZ
= std::min(TZ
, SE
.GetMinTrailingZeros(WholeAddExpr
->getOperand(I
)));
1590 // Set D to be as many least significant bits of C as possible while still
1591 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1592 return TZ
< BitWidth
? C
.trunc(TZ
).zext(BitWidth
) : C
;
1594 return APInt(BitWidth
, 0);
1597 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1598 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1599 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1600 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1601 static APInt
extractConstantWithoutWrapping(ScalarEvolution
&SE
,
1602 const APInt
&ConstantStart
,
1604 const unsigned BitWidth
= ConstantStart
.getBitWidth();
1605 const uint32_t TZ
= SE
.GetMinTrailingZeros(Step
);
1607 return TZ
< BitWidth
? ConstantStart
.trunc(TZ
).zext(BitWidth
)
1609 return APInt(BitWidth
, 0);
1613 ScalarEvolution::getZeroExtendExpr(const SCEV
*Op
, Type
*Ty
, unsigned Depth
) {
1614 assert(getTypeSizeInBits(Op
->getType()) < getTypeSizeInBits(Ty
) &&
1615 "This is not an extending conversion!");
1616 assert(isSCEVable(Ty
) &&
1617 "This is not a conversion to a SCEVable type!");
1618 Ty
= getEffectiveSCEVType(Ty
);
1620 // Fold if the operand is constant.
1621 if (const SCEVConstant
*SC
= dyn_cast
<SCEVConstant
>(Op
))
1623 cast
<ConstantInt
>(ConstantExpr::getZExt(SC
->getValue(), Ty
)));
1625 // zext(zext(x)) --> zext(x)
1626 if (const SCEVZeroExtendExpr
*SZ
= dyn_cast
<SCEVZeroExtendExpr
>(Op
))
1627 return getZeroExtendExpr(SZ
->getOperand(), Ty
, Depth
+ 1);
1629 // Before doing any expensive analysis, check to see if we've already
1630 // computed a SCEV for this Op and Ty.
1631 FoldingSetNodeID ID
;
1632 ID
.AddInteger(scZeroExtend
);
1636 if (const SCEV
*S
= UniqueSCEVs
.FindNodeOrInsertPos(ID
, IP
)) return S
;
1637 if (Depth
> MaxExtDepth
) {
1638 SCEV
*S
= new (SCEVAllocator
) SCEVZeroExtendExpr(ID
.Intern(SCEVAllocator
),
1640 UniqueSCEVs
.InsertNode(S
, IP
);
1641 addToLoopUseLists(S
);
1645 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1646 if (const SCEVTruncateExpr
*ST
= dyn_cast
<SCEVTruncateExpr
>(Op
)) {
1647 // It's possible the bits taken off by the truncate were all zero bits. If
1648 // so, we should be able to simplify this further.
1649 const SCEV
*X
= ST
->getOperand();
1650 ConstantRange CR
= getUnsignedRange(X
);
1651 unsigned TruncBits
= getTypeSizeInBits(ST
->getType());
1652 unsigned NewBits
= getTypeSizeInBits(Ty
);
1653 if (CR
.truncate(TruncBits
).zeroExtend(NewBits
).contains(
1654 CR
.zextOrTrunc(NewBits
)))
1655 return getTruncateOrZeroExtend(X
, Ty
);
1658 // If the input value is a chrec scev, and we can prove that the value
1659 // did not overflow the old, smaller, value, we can zero extend all of the
1660 // operands (often constants). This allows analysis of something like
1661 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1662 if (const SCEVAddRecExpr
*AR
= dyn_cast
<SCEVAddRecExpr
>(Op
))
1663 if (AR
->isAffine()) {
1664 const SCEV
*Start
= AR
->getStart();
1665 const SCEV
*Step
= AR
->getStepRecurrence(*this);
1666 unsigned BitWidth
= getTypeSizeInBits(AR
->getType());
1667 const Loop
*L
= AR
->getLoop();
1669 if (!AR
->hasNoUnsignedWrap()) {
1670 auto NewFlags
= proveNoWrapViaConstantRanges(AR
);
1671 const_cast<SCEVAddRecExpr
*>(AR
)->setNoWrapFlags(NewFlags
);
1674 // If we have special knowledge that this addrec won't overflow,
1675 // we don't need to do any further analysis.
1676 if (AR
->hasNoUnsignedWrap())
1677 return getAddRecExpr(
1678 getExtendAddRecStart
<SCEVZeroExtendExpr
>(AR
, Ty
, this, Depth
+ 1),
1679 getZeroExtendExpr(Step
, Ty
, Depth
+ 1), L
, AR
->getNoWrapFlags());
1681 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1682 // Note that this serves two purposes: It filters out loops that are
1683 // simply not analyzable, and it covers the case where this code is
1684 // being called from within backedge-taken count analysis, such that
1685 // attempting to ask for the backedge-taken count would likely result
1686 // in infinite recursion. In the later case, the analysis code will
1687 // cope with a conservative value, and it will take care to purge
1688 // that value once it has finished.
1689 const SCEV
*MaxBECount
= getMaxBackedgeTakenCount(L
);
1690 if (!isa
<SCEVCouldNotCompute
>(MaxBECount
)) {
1691 // Manually compute the final value for AR, checking for
1694 // Check whether the backedge-taken count can be losslessly casted to
1695 // the addrec's type. The count is always unsigned.
1696 const SCEV
*CastedMaxBECount
=
1697 getTruncateOrZeroExtend(MaxBECount
, Start
->getType());
1698 const SCEV
*RecastedMaxBECount
=
1699 getTruncateOrZeroExtend(CastedMaxBECount
, MaxBECount
->getType());
1700 if (MaxBECount
== RecastedMaxBECount
) {
1701 Type
*WideTy
= IntegerType::get(getContext(), BitWidth
* 2);
1702 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1703 const SCEV
*ZMul
= getMulExpr(CastedMaxBECount
, Step
,
1704 SCEV::FlagAnyWrap
, Depth
+ 1);
1705 const SCEV
*ZAdd
= getZeroExtendExpr(getAddExpr(Start
, ZMul
,
1709 const SCEV
*WideStart
= getZeroExtendExpr(Start
, WideTy
, Depth
+ 1);
1710 const SCEV
*WideMaxBECount
=
1711 getZeroExtendExpr(CastedMaxBECount
, WideTy
, Depth
+ 1);
1712 const SCEV
*OperandExtendedAdd
=
1713 getAddExpr(WideStart
,
1714 getMulExpr(WideMaxBECount
,
1715 getZeroExtendExpr(Step
, WideTy
, Depth
+ 1),
1716 SCEV::FlagAnyWrap
, Depth
+ 1),
1717 SCEV::FlagAnyWrap
, Depth
+ 1);
1718 if (ZAdd
== OperandExtendedAdd
) {
1719 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1720 const_cast<SCEVAddRecExpr
*>(AR
)->setNoWrapFlags(SCEV::FlagNUW
);
1721 // Return the expression with the addrec on the outside.
1722 return getAddRecExpr(
1723 getExtendAddRecStart
<SCEVZeroExtendExpr
>(AR
, Ty
, this,
1725 getZeroExtendExpr(Step
, Ty
, Depth
+ 1), L
,
1726 AR
->getNoWrapFlags());
1728 // Similar to above, only this time treat the step value as signed.
1729 // This covers loops that count down.
1730 OperandExtendedAdd
=
1731 getAddExpr(WideStart
,
1732 getMulExpr(WideMaxBECount
,
1733 getSignExtendExpr(Step
, WideTy
, Depth
+ 1),
1734 SCEV::FlagAnyWrap
, Depth
+ 1),
1735 SCEV::FlagAnyWrap
, Depth
+ 1);
1736 if (ZAdd
== OperandExtendedAdd
) {
1737 // Cache knowledge of AR NW, which is propagated to this AddRec.
1738 // Negative step causes unsigned wrap, but it still can't self-wrap.
1739 const_cast<SCEVAddRecExpr
*>(AR
)->setNoWrapFlags(SCEV::FlagNW
);
1740 // Return the expression with the addrec on the outside.
1741 return getAddRecExpr(
1742 getExtendAddRecStart
<SCEVZeroExtendExpr
>(AR
, Ty
, this,
1744 getSignExtendExpr(Step
, Ty
, Depth
+ 1), L
,
1745 AR
->getNoWrapFlags());
1750 // Normally, in the cases we can prove no-overflow via a
1751 // backedge guarding condition, we can also compute a backedge
1752 // taken count for the loop. The exceptions are assumptions and
1753 // guards present in the loop -- SCEV is not great at exploiting
1754 // these to compute max backedge taken counts, but can still use
1755 // these to prove lack of overflow. Use this fact to avoid
1756 // doing extra work that may not pay off.
1757 if (!isa
<SCEVCouldNotCompute
>(MaxBECount
) || HasGuards
||
1758 !AC
.assumptions().empty()) {
1759 // If the backedge is guarded by a comparison with the pre-inc
1760 // value the addrec is safe. Also, if the entry is guarded by
1761 // a comparison with the start value and the backedge is
1762 // guarded by a comparison with the post-inc value, the addrec
1764 if (isKnownPositive(Step
)) {
1765 const SCEV
*N
= getConstant(APInt::getMinValue(BitWidth
) -
1766 getUnsignedRangeMax(Step
));
1767 if (isLoopBackedgeGuardedByCond(L
, ICmpInst::ICMP_ULT
, AR
, N
) ||
1768 isKnownOnEveryIteration(ICmpInst::ICMP_ULT
, AR
, N
)) {
1769 // Cache knowledge of AR NUW, which is propagated to this
1771 const_cast<SCEVAddRecExpr
*>(AR
)->setNoWrapFlags(SCEV::FlagNUW
);
1772 // Return the expression with the addrec on the outside.
1773 return getAddRecExpr(
1774 getExtendAddRecStart
<SCEVZeroExtendExpr
>(AR
, Ty
, this,
1776 getZeroExtendExpr(Step
, Ty
, Depth
+ 1), L
,
1777 AR
->getNoWrapFlags());
1779 } else if (isKnownNegative(Step
)) {
1780 const SCEV
*N
= getConstant(APInt::getMaxValue(BitWidth
) -
1781 getSignedRangeMin(Step
));
1782 if (isLoopBackedgeGuardedByCond(L
, ICmpInst::ICMP_UGT
, AR
, N
) ||
1783 isKnownOnEveryIteration(ICmpInst::ICMP_UGT
, AR
, N
)) {
1784 // Cache knowledge of AR NW, which is propagated to this
1785 // AddRec. Negative step causes unsigned wrap, but it
1786 // still can't self-wrap.
1787 const_cast<SCEVAddRecExpr
*>(AR
)->setNoWrapFlags(SCEV::FlagNW
);
1788 // Return the expression with the addrec on the outside.
1789 return getAddRecExpr(
1790 getExtendAddRecStart
<SCEVZeroExtendExpr
>(AR
, Ty
, this,
1792 getSignExtendExpr(Step
, Ty
, Depth
+ 1), L
,
1793 AR
->getNoWrapFlags());
1798 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1799 // if D + (C - D + Step * n) could be proven to not unsigned wrap
1800 // where D maximizes the number of trailing zeros of (C - D + Step * n)
1801 if (const auto *SC
= dyn_cast
<SCEVConstant
>(Start
)) {
1802 const APInt
&C
= SC
->getAPInt();
1803 const APInt
&D
= extractConstantWithoutWrapping(*this, C
, Step
);
1805 const SCEV
*SZExtD
= getZeroExtendExpr(getConstant(D
), Ty
, Depth
);
1806 const SCEV
*SResidual
=
1807 getAddRecExpr(getConstant(C
- D
), Step
, L
, AR
->getNoWrapFlags());
1808 const SCEV
*SZExtR
= getZeroExtendExpr(SResidual
, Ty
, Depth
+ 1);
1809 return getAddExpr(SZExtD
, SZExtR
,
1810 (SCEV::NoWrapFlags
)(SCEV::FlagNSW
| SCEV::FlagNUW
),
1815 if (proveNoWrapByVaryingStart
<SCEVZeroExtendExpr
>(Start
, Step
, L
)) {
1816 const_cast<SCEVAddRecExpr
*>(AR
)->setNoWrapFlags(SCEV::FlagNUW
);
1817 return getAddRecExpr(
1818 getExtendAddRecStart
<SCEVZeroExtendExpr
>(AR
, Ty
, this, Depth
+ 1),
1819 getZeroExtendExpr(Step
, Ty
, Depth
+ 1), L
, AR
->getNoWrapFlags());
1823 // zext(A % B) --> zext(A) % zext(B)
1827 if (matchURem(Op
, LHS
, RHS
))
1828 return getURemExpr(getZeroExtendExpr(LHS
, Ty
, Depth
+ 1),
1829 getZeroExtendExpr(RHS
, Ty
, Depth
+ 1));
1832 // zext(A / B) --> zext(A) / zext(B).
1833 if (auto *Div
= dyn_cast
<SCEVUDivExpr
>(Op
))
1834 return getUDivExpr(getZeroExtendExpr(Div
->getLHS(), Ty
, Depth
+ 1),
1835 getZeroExtendExpr(Div
->getRHS(), Ty
, Depth
+ 1));
1837 if (auto *SA
= dyn_cast
<SCEVAddExpr
>(Op
)) {
1838 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1839 if (SA
->hasNoUnsignedWrap()) {
1840 // If the addition does not unsign overflow then we can, by definition,
1841 // commute the zero extension with the addition operation.
1842 SmallVector
<const SCEV
*, 4> Ops
;
1843 for (const auto *Op
: SA
->operands())
1844 Ops
.push_back(getZeroExtendExpr(Op
, Ty
, Depth
+ 1));
1845 return getAddExpr(Ops
, SCEV::FlagNUW
, Depth
+ 1);
1848 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1849 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1850 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1852 // Often address arithmetics contain expressions like
1853 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1854 // This transformation is useful while proving that such expressions are
1855 // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1856 if (const auto *SC
= dyn_cast
<SCEVConstant
>(SA
->getOperand(0))) {
1857 const APInt
&D
= extractConstantWithoutWrapping(*this, SC
, SA
);
1859 const SCEV
*SZExtD
= getZeroExtendExpr(getConstant(D
), Ty
, Depth
);
1860 const SCEV
*SResidual
=
1861 getAddExpr(getConstant(-D
), SA
, SCEV::FlagAnyWrap
, Depth
);
1862 const SCEV
*SZExtR
= getZeroExtendExpr(SResidual
, Ty
, Depth
+ 1);
1863 return getAddExpr(SZExtD
, SZExtR
,
1864 (SCEV::NoWrapFlags
)(SCEV::FlagNSW
| SCEV::FlagNUW
),
1870 if (auto *SM
= dyn_cast
<SCEVMulExpr
>(Op
)) {
1871 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1872 if (SM
->hasNoUnsignedWrap()) {
1873 // If the multiply does not unsign overflow then we can, by definition,
1874 // commute the zero extension with the multiply operation.
1875 SmallVector
<const SCEV
*, 4> Ops
;
1876 for (const auto *Op
: SM
->operands())
1877 Ops
.push_back(getZeroExtendExpr(Op
, Ty
, Depth
+ 1));
1878 return getMulExpr(Ops
, SCEV::FlagNUW
, Depth
+ 1);
1881 // zext(2^K * (trunc X to iN)) to iM ->
1882 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1886 // zext(2^K * (trunc X to iN)) to iM
1887 // = zext((trunc X to iN) << K) to iM
1888 // = zext((trunc X to i{N-K}) << K)<nuw> to iM
1889 // (because shl removes the top K bits)
1890 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1891 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1893 if (SM
->getNumOperands() == 2)
1894 if (auto *MulLHS
= dyn_cast
<SCEVConstant
>(SM
->getOperand(0)))
1895 if (MulLHS
->getAPInt().isPowerOf2())
1896 if (auto *TruncRHS
= dyn_cast
<SCEVTruncateExpr
>(SM
->getOperand(1))) {
1897 int NewTruncBits
= getTypeSizeInBits(TruncRHS
->getType()) -
1898 MulLHS
->getAPInt().logBase2();
1899 Type
*NewTruncTy
= IntegerType::get(getContext(), NewTruncBits
);
1901 getZeroExtendExpr(MulLHS
, Ty
),
1903 getTruncateExpr(TruncRHS
->getOperand(), NewTruncTy
), Ty
),
1904 SCEV::FlagNUW
, Depth
+ 1);
1908 // The cast wasn't folded; create an explicit cast node.
1909 // Recompute the insert position, as it may have been invalidated.
1910 if (const SCEV
*S
= UniqueSCEVs
.FindNodeOrInsertPos(ID
, IP
)) return S
;
1911 SCEV
*S
= new (SCEVAllocator
) SCEVZeroExtendExpr(ID
.Intern(SCEVAllocator
),
1913 UniqueSCEVs
.InsertNode(S
, IP
);
1914 addToLoopUseLists(S
);
1919 ScalarEvolution::getSignExtendExpr(const SCEV
*Op
, Type
*Ty
, unsigned Depth
) {
1920 assert(getTypeSizeInBits(Op
->getType()) < getTypeSizeInBits(Ty
) &&
1921 "This is not an extending conversion!");
1922 assert(isSCEVable(Ty
) &&
1923 "This is not a conversion to a SCEVable type!");
1924 Ty
= getEffectiveSCEVType(Ty
);
1926 // Fold if the operand is constant.
1927 if (const SCEVConstant
*SC
= dyn_cast
<SCEVConstant
>(Op
))
1929 cast
<ConstantInt
>(ConstantExpr::getSExt(SC
->getValue(), Ty
)));
1931 // sext(sext(x)) --> sext(x)
1932 if (const SCEVSignExtendExpr
*SS
= dyn_cast
<SCEVSignExtendExpr
>(Op
))
1933 return getSignExtendExpr(SS
->getOperand(), Ty
, Depth
+ 1);
1935 // sext(zext(x)) --> zext(x)
1936 if (const SCEVZeroExtendExpr
*SZ
= dyn_cast
<SCEVZeroExtendExpr
>(Op
))
1937 return getZeroExtendExpr(SZ
->getOperand(), Ty
, Depth
+ 1);
1939 // Before doing any expensive analysis, check to see if we've already
1940 // computed a SCEV for this Op and Ty.
1941 FoldingSetNodeID ID
;
1942 ID
.AddInteger(scSignExtend
);
1946 if (const SCEV
*S
= UniqueSCEVs
.FindNodeOrInsertPos(ID
, IP
)) return S
;
1947 // Limit recursion depth.
1948 if (Depth
> MaxExtDepth
) {
1949 SCEV
*S
= new (SCEVAllocator
) SCEVSignExtendExpr(ID
.Intern(SCEVAllocator
),
1951 UniqueSCEVs
.InsertNode(S
, IP
);
1952 addToLoopUseLists(S
);
1956 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1957 if (const SCEVTruncateExpr
*ST
= dyn_cast
<SCEVTruncateExpr
>(Op
)) {
1958 // It's possible the bits taken off by the truncate were all sign bits. If
1959 // so, we should be able to simplify this further.
1960 const SCEV
*X
= ST
->getOperand();
1961 ConstantRange CR
= getSignedRange(X
);
1962 unsigned TruncBits
= getTypeSizeInBits(ST
->getType());
1963 unsigned NewBits
= getTypeSizeInBits(Ty
);
1964 if (CR
.truncate(TruncBits
).signExtend(NewBits
).contains(
1965 CR
.sextOrTrunc(NewBits
)))
1966 return getTruncateOrSignExtend(X
, Ty
);
1969 if (auto *SA
= dyn_cast
<SCEVAddExpr
>(Op
)) {
1970 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1971 if (SA
->hasNoSignedWrap()) {
1972 // If the addition does not sign overflow then we can, by definition,
1973 // commute the sign extension with the addition operation.
1974 SmallVector
<const SCEV
*, 4> Ops
;
1975 for (const auto *Op
: SA
->operands())
1976 Ops
.push_back(getSignExtendExpr(Op
, Ty
, Depth
+ 1));
1977 return getAddExpr(Ops
, SCEV::FlagNSW
, Depth
+ 1);
1980 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1981 // if D + (C - D + x + y + ...) could be proven to not signed wrap
1982 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1984 // For instance, this will bring two seemingly different expressions:
1985 // 1 + sext(5 + 20 * %x + 24 * %y) and
1986 // sext(6 + 20 * %x + 24 * %y)
1987 // to the same form:
1988 // 2 + sext(4 + 20 * %x + 24 * %y)
1989 if (const auto *SC
= dyn_cast
<SCEVConstant
>(SA
->getOperand(0))) {
1990 const APInt
&D
= extractConstantWithoutWrapping(*this, SC
, SA
);
1992 const SCEV
*SSExtD
= getSignExtendExpr(getConstant(D
), Ty
, Depth
);
1993 const SCEV
*SResidual
=
1994 getAddExpr(getConstant(-D
), SA
, SCEV::FlagAnyWrap
, Depth
);
1995 const SCEV
*SSExtR
= getSignExtendExpr(SResidual
, Ty
, Depth
+ 1);
1996 return getAddExpr(SSExtD
, SSExtR
,
1997 (SCEV::NoWrapFlags
)(SCEV::FlagNSW
| SCEV::FlagNUW
),
2002 // If the input value is a chrec scev, and we can prove that the value
2003 // did not overflow the old, smaller, value, we can sign extend all of the
2004 // operands (often constants). This allows analysis of something like
2005 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
2006 if (const SCEVAddRecExpr
*AR
= dyn_cast
<SCEVAddRecExpr
>(Op
))
2007 if (AR
->isAffine()) {
2008 const SCEV
*Start
= AR
->getStart();
2009 const SCEV
*Step
= AR
->getStepRecurrence(*this);
2010 unsigned BitWidth
= getTypeSizeInBits(AR
->getType());
2011 const Loop
*L
= AR
->getLoop();
2013 if (!AR
->hasNoSignedWrap()) {
2014 auto NewFlags
= proveNoWrapViaConstantRanges(AR
);
2015 const_cast<SCEVAddRecExpr
*>(AR
)->setNoWrapFlags(NewFlags
);
2018 // If we have special knowledge that this addrec won't overflow,
2019 // we don't need to do any further analysis.
2020 if (AR
->hasNoSignedWrap())
2021 return getAddRecExpr(
2022 getExtendAddRecStart
<SCEVSignExtendExpr
>(AR
, Ty
, this, Depth
+ 1),
2023 getSignExtendExpr(Step
, Ty
, Depth
+ 1), L
, SCEV::FlagNSW
);
2025 // Check whether the backedge-taken count is SCEVCouldNotCompute.
2026 // Note that this serves two purposes: It filters out loops that are
2027 // simply not analyzable, and it covers the case where this code is
2028 // being called from within backedge-taken count analysis, such that
2029 // attempting to ask for the backedge-taken count would likely result
2030 // in infinite recursion. In the later case, the analysis code will
2031 // cope with a conservative value, and it will take care to purge
2032 // that value once it has finished.
2033 const SCEV
*MaxBECount
= getMaxBackedgeTakenCount(L
);
2034 if (!isa
<SCEVCouldNotCompute
>(MaxBECount
)) {
2035 // Manually compute the final value for AR, checking for
2038 // Check whether the backedge-taken count can be losslessly casted to
2039 // the addrec's type. The count is always unsigned.
2040 const SCEV
*CastedMaxBECount
=
2041 getTruncateOrZeroExtend(MaxBECount
, Start
->getType());
2042 const SCEV
*RecastedMaxBECount
=
2043 getTruncateOrZeroExtend(CastedMaxBECount
, MaxBECount
->getType());
2044 if (MaxBECount
== RecastedMaxBECount
) {
2045 Type
*WideTy
= IntegerType::get(getContext(), BitWidth
* 2);
2046 // Check whether Start+Step*MaxBECount has no signed overflow.
2047 const SCEV
*SMul
= getMulExpr(CastedMaxBECount
, Step
,
2048 SCEV::FlagAnyWrap
, Depth
+ 1);
2049 const SCEV
*SAdd
= getSignExtendExpr(getAddExpr(Start
, SMul
,
2053 const SCEV
*WideStart
= getSignExtendExpr(Start
, WideTy
, Depth
+ 1);
2054 const SCEV
*WideMaxBECount
=
2055 getZeroExtendExpr(CastedMaxBECount
, WideTy
, Depth
+ 1);
2056 const SCEV
*OperandExtendedAdd
=
2057 getAddExpr(WideStart
,
2058 getMulExpr(WideMaxBECount
,
2059 getSignExtendExpr(Step
, WideTy
, Depth
+ 1),
2060 SCEV::FlagAnyWrap
, Depth
+ 1),
2061 SCEV::FlagAnyWrap
, Depth
+ 1);
2062 if (SAdd
== OperandExtendedAdd
) {
2063 // Cache knowledge of AR NSW, which is propagated to this AddRec.
2064 const_cast<SCEVAddRecExpr
*>(AR
)->setNoWrapFlags(SCEV::FlagNSW
);
2065 // Return the expression with the addrec on the outside.
2066 return getAddRecExpr(
2067 getExtendAddRecStart
<SCEVSignExtendExpr
>(AR
, Ty
, this,
2069 getSignExtendExpr(Step
, Ty
, Depth
+ 1), L
,
2070 AR
->getNoWrapFlags());
2072 // Similar to above, only this time treat the step value as unsigned.
2073 // This covers loops that count up with an unsigned step.
2074 OperandExtendedAdd
=
2075 getAddExpr(WideStart
,
2076 getMulExpr(WideMaxBECount
,
2077 getZeroExtendExpr(Step
, WideTy
, Depth
+ 1),
2078 SCEV::FlagAnyWrap
, Depth
+ 1),
2079 SCEV::FlagAnyWrap
, Depth
+ 1);
2080 if (SAdd
== OperandExtendedAdd
) {
2081 // If AR wraps around then
2083 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
2084 // => SAdd != OperandExtendedAdd
2086 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2087 // (SAdd == OperandExtendedAdd => AR is NW)
2089 const_cast<SCEVAddRecExpr
*>(AR
)->setNoWrapFlags(SCEV::FlagNW
);
2091 // Return the expression with the addrec on the outside.
2092 return getAddRecExpr(
2093 getExtendAddRecStart
<SCEVSignExtendExpr
>(AR
, Ty
, this,
2095 getZeroExtendExpr(Step
, Ty
, Depth
+ 1), L
,
2096 AR
->getNoWrapFlags());
2101 // Normally, in the cases we can prove no-overflow via a
2102 // backedge guarding condition, we can also compute a backedge
2103 // taken count for the loop. The exceptions are assumptions and
2104 // guards present in the loop -- SCEV is not great at exploiting
2105 // these to compute max backedge taken counts, but can still use
2106 // these to prove lack of overflow. Use this fact to avoid
2107 // doing extra work that may not pay off.
2109 if (!isa
<SCEVCouldNotCompute
>(MaxBECount
) || HasGuards
||
2110 !AC
.assumptions().empty()) {
2111 // If the backedge is guarded by a comparison with the pre-inc
2112 // value the addrec is safe. Also, if the entry is guarded by
2113 // a comparison with the start value and the backedge is
2114 // guarded by a comparison with the post-inc value, the addrec
2116 ICmpInst::Predicate Pred
;
2117 const SCEV
*OverflowLimit
=
2118 getSignedOverflowLimitForStep(Step
, &Pred
, this);
2119 if (OverflowLimit
&&
2120 (isLoopBackedgeGuardedByCond(L
, Pred
, AR
, OverflowLimit
) ||
2121 isKnownOnEveryIteration(Pred
, AR
, OverflowLimit
))) {
2122 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
2123 const_cast<SCEVAddRecExpr
*>(AR
)->setNoWrapFlags(SCEV::FlagNSW
);
2124 return getAddRecExpr(
2125 getExtendAddRecStart
<SCEVSignExtendExpr
>(AR
, Ty
, this, Depth
+ 1),
2126 getSignExtendExpr(Step
, Ty
, Depth
+ 1), L
, AR
->getNoWrapFlags());
2130 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2131 // if D + (C - D + Step * n) could be proven to not signed wrap
2132 // where D maximizes the number of trailing zeros of (C - D + Step * n)
2133 if (const auto *SC
= dyn_cast
<SCEVConstant
>(Start
)) {
2134 const APInt
&C
= SC
->getAPInt();
2135 const APInt
&D
= extractConstantWithoutWrapping(*this, C
, Step
);
2137 const SCEV
*SSExtD
= getSignExtendExpr(getConstant(D
), Ty
, Depth
);
2138 const SCEV
*SResidual
=
2139 getAddRecExpr(getConstant(C
- D
), Step
, L
, AR
->getNoWrapFlags());
2140 const SCEV
*SSExtR
= getSignExtendExpr(SResidual
, Ty
, Depth
+ 1);
2141 return getAddExpr(SSExtD
, SSExtR
,
2142 (SCEV::NoWrapFlags
)(SCEV::FlagNSW
| SCEV::FlagNUW
),
2147 if (proveNoWrapByVaryingStart
<SCEVSignExtendExpr
>(Start
, Step
, L
)) {
2148 const_cast<SCEVAddRecExpr
*>(AR
)->setNoWrapFlags(SCEV::FlagNSW
);
2149 return getAddRecExpr(
2150 getExtendAddRecStart
<SCEVSignExtendExpr
>(AR
, Ty
, this, Depth
+ 1),
2151 getSignExtendExpr(Step
, Ty
, Depth
+ 1), L
, AR
->getNoWrapFlags());
2155 // If the input value is provably positive and we could not simplify
2156 // away the sext build a zext instead.
2157 if (isKnownNonNegative(Op
))
2158 return getZeroExtendExpr(Op
, Ty
, Depth
+ 1);
2160 // The cast wasn't folded; create an explicit cast node.
2161 // Recompute the insert position, as it may have been invalidated.
2162 if (const SCEV
*S
= UniqueSCEVs
.FindNodeOrInsertPos(ID
, IP
)) return S
;
2163 SCEV
*S
= new (SCEVAllocator
) SCEVSignExtendExpr(ID
.Intern(SCEVAllocator
),
2165 UniqueSCEVs
.InsertNode(S
, IP
);
2166 addToLoopUseLists(S
);
2170 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2171 /// unspecified bits out to the given type.
2172 const SCEV
*ScalarEvolution::getAnyExtendExpr(const SCEV
*Op
,
2174 assert(getTypeSizeInBits(Op
->getType()) < getTypeSizeInBits(Ty
) &&
2175 "This is not an extending conversion!");
2176 assert(isSCEVable(Ty
) &&
2177 "This is not a conversion to a SCEVable type!");
2178 Ty
= getEffectiveSCEVType(Ty
);
2180 // Sign-extend negative constants.
2181 if (const SCEVConstant
*SC
= dyn_cast
<SCEVConstant
>(Op
))
2182 if (SC
->getAPInt().isNegative())
2183 return getSignExtendExpr(Op
, Ty
);
2185 // Peel off a truncate cast.
2186 if (const SCEVTruncateExpr
*T
= dyn_cast
<SCEVTruncateExpr
>(Op
)) {
2187 const SCEV
*NewOp
= T
->getOperand();
2188 if (getTypeSizeInBits(NewOp
->getType()) < getTypeSizeInBits(Ty
))
2189 return getAnyExtendExpr(NewOp
, Ty
);
2190 return getTruncateOrNoop(NewOp
, Ty
);
2193 // Next try a zext cast. If the cast is folded, use it.
2194 const SCEV
*ZExt
= getZeroExtendExpr(Op
, Ty
);
2195 if (!isa
<SCEVZeroExtendExpr
>(ZExt
))
2198 // Next try a sext cast. If the cast is folded, use it.
2199 const SCEV
*SExt
= getSignExtendExpr(Op
, Ty
);
2200 if (!isa
<SCEVSignExtendExpr
>(SExt
))
2203 // Force the cast to be folded into the operands of an addrec.
2204 if (const SCEVAddRecExpr
*AR
= dyn_cast
<SCEVAddRecExpr
>(Op
)) {
2205 SmallVector
<const SCEV
*, 4> Ops
;
2206 for (const SCEV
*Op
: AR
->operands())
2207 Ops
.push_back(getAnyExtendExpr(Op
, Ty
));
2208 return getAddRecExpr(Ops
, AR
->getLoop(), SCEV::FlagNW
);
2211 // If the expression is obviously signed, use the sext cast value.
2212 if (isa
<SCEVSMaxExpr
>(Op
))
2215 // Absent any other information, use the zext cast value.
2219 /// Process the given Ops list, which is a list of operands to be added under
2220 /// the given scale, update the given map. This is a helper function for
2221 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2222 /// that would form an add expression like this:
2224 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2226 /// where A and B are constants, update the map with these values:
2228 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2230 /// and add 13 + A*B*29 to AccumulatedConstant.
2231 /// This will allow getAddRecExpr to produce this:
2233 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2235 /// This form often exposes folding opportunities that are hidden in
2236 /// the original operand list.
2238 /// Return true iff it appears that any interesting folding opportunities
2239 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2240 /// the common case where no interesting opportunities are present, and
2241 /// is also used as a check to avoid infinite recursion.
2243 CollectAddOperandsWithScales(DenseMap
<const SCEV
*, APInt
> &M
,
2244 SmallVectorImpl
<const SCEV
*> &NewOps
,
2245 APInt
&AccumulatedConstant
,
2246 const SCEV
*const *Ops
, size_t NumOperands
,
2248 ScalarEvolution
&SE
) {
2249 bool Interesting
= false;
2251 // Iterate over the add operands. They are sorted, with constants first.
2253 while (const SCEVConstant
*C
= dyn_cast
<SCEVConstant
>(Ops
[i
])) {
2255 // Pull a buried constant out to the outside.
2256 if (Scale
!= 1 || AccumulatedConstant
!= 0 || C
->getValue()->isZero())
2258 AccumulatedConstant
+= Scale
* C
->getAPInt();
2261 // Next comes everything else. We're especially interested in multiplies
2262 // here, but they're in the middle, so just visit the rest with one loop.
2263 for (; i
!= NumOperands
; ++i
) {
2264 const SCEVMulExpr
*Mul
= dyn_cast
<SCEVMulExpr
>(Ops
[i
]);
2265 if (Mul
&& isa
<SCEVConstant
>(Mul
->getOperand(0))) {
2267 Scale
* cast
<SCEVConstant
>(Mul
->getOperand(0))->getAPInt();
2268 if (Mul
->getNumOperands() == 2 && isa
<SCEVAddExpr
>(Mul
->getOperand(1))) {
2269 // A multiplication of a constant with another add; recurse.
2270 const SCEVAddExpr
*Add
= cast
<SCEVAddExpr
>(Mul
->getOperand(1));
2272 CollectAddOperandsWithScales(M
, NewOps
, AccumulatedConstant
,
2273 Add
->op_begin(), Add
->getNumOperands(),
2276 // A multiplication of a constant with some other value. Update
2278 SmallVector
<const SCEV
*, 4> MulOps(Mul
->op_begin()+1, Mul
->op_end());
2279 const SCEV
*Key
= SE
.getMulExpr(MulOps
);
2280 auto Pair
= M
.insert({Key
, NewScale
});
2282 NewOps
.push_back(Pair
.first
->first
);
2284 Pair
.first
->second
+= NewScale
;
2285 // The map already had an entry for this value, which may indicate
2286 // a folding opportunity.
2291 // An ordinary operand. Update the map.
2292 std::pair
<DenseMap
<const SCEV
*, APInt
>::iterator
, bool> Pair
=
2293 M
.insert({Ops
[i
], Scale
});
2295 NewOps
.push_back(Pair
.first
->first
);
2297 Pair
.first
->second
+= Scale
;
2298 // The map already had an entry for this value, which may indicate
2299 // a folding opportunity.
2308 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2309 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2310 // can't-overflow flags for the operation if possible.
2311 static SCEV::NoWrapFlags
2312 StrengthenNoWrapFlags(ScalarEvolution
*SE
, SCEVTypes Type
,
2313 const ArrayRef
<const SCEV
*> Ops
,
2314 SCEV::NoWrapFlags Flags
) {
2315 using namespace std::placeholders
;
2317 using OBO
= OverflowingBinaryOperator
;
2320 Type
== scAddExpr
|| Type
== scAddRecExpr
|| Type
== scMulExpr
;
2322 assert(CanAnalyze
&& "don't call from other places!");
2324 int SignOrUnsignMask
= SCEV::FlagNUW
| SCEV::FlagNSW
;
2325 SCEV::NoWrapFlags SignOrUnsignWrap
=
2326 ScalarEvolution::maskFlags(Flags
, SignOrUnsignMask
);
2328 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2329 auto IsKnownNonNegative
= [&](const SCEV
*S
) {
2330 return SE
->isKnownNonNegative(S
);
2333 if (SignOrUnsignWrap
== SCEV::FlagNSW
&& all_of(Ops
, IsKnownNonNegative
))
2335 ScalarEvolution::setFlags(Flags
, (SCEV::NoWrapFlags
)SignOrUnsignMask
);
2337 SignOrUnsignWrap
= ScalarEvolution::maskFlags(Flags
, SignOrUnsignMask
);
2339 if (SignOrUnsignWrap
!= SignOrUnsignMask
&&
2340 (Type
== scAddExpr
|| Type
== scMulExpr
) && Ops
.size() == 2 &&
2341 isa
<SCEVConstant
>(Ops
[0])) {
2346 return Instruction::Add
;
2348 return Instruction::Mul
;
2350 llvm_unreachable("Unexpected SCEV op.");
2354 const APInt
&C
= cast
<SCEVConstant
>(Ops
[0])->getAPInt();
2356 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2357 if (!(SignOrUnsignWrap
& SCEV::FlagNSW
)) {
2358 auto NSWRegion
= ConstantRange::makeGuaranteedNoWrapRegion(
2359 Opcode
, C
, OBO::NoSignedWrap
);
2360 if (NSWRegion
.contains(SE
->getSignedRange(Ops
[1])))
2361 Flags
= ScalarEvolution::setFlags(Flags
, SCEV::FlagNSW
);
2364 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2365 if (!(SignOrUnsignWrap
& SCEV::FlagNUW
)) {
2366 auto NUWRegion
= ConstantRange::makeGuaranteedNoWrapRegion(
2367 Opcode
, C
, OBO::NoUnsignedWrap
);
2368 if (NUWRegion
.contains(SE
->getUnsignedRange(Ops
[1])))
2369 Flags
= ScalarEvolution::setFlags(Flags
, SCEV::FlagNUW
);
2376 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV
*S
, const Loop
*L
) {
2377 return isLoopInvariant(S
, L
) && properlyDominates(S
, L
->getHeader());
2380 /// Get a canonical add expression, or something simpler if possible.
2381 const SCEV
*ScalarEvolution::getAddExpr(SmallVectorImpl
<const SCEV
*> &Ops
,
2382 SCEV::NoWrapFlags Flags
,
2384 assert(!(Flags
& ~(SCEV::FlagNUW
| SCEV::FlagNSW
)) &&
2385 "only nuw or nsw allowed");
2386 assert(!Ops
.empty() && "Cannot get empty add!");
2387 if (Ops
.size() == 1) return Ops
[0];
2389 Type
*ETy
= getEffectiveSCEVType(Ops
[0]->getType());
2390 for (unsigned i
= 1, e
= Ops
.size(); i
!= e
; ++i
)
2391 assert(getEffectiveSCEVType(Ops
[i
]->getType()) == ETy
&&
2392 "SCEVAddExpr operand types don't match!");
2395 // Sort by complexity, this groups all similar expression types together.
2396 GroupByComplexity(Ops
, &LI
, DT
);
2398 Flags
= StrengthenNoWrapFlags(this, scAddExpr
, Ops
, Flags
);
2400 // If there are any constants, fold them together.
2402 if (const SCEVConstant
*LHSC
= dyn_cast
<SCEVConstant
>(Ops
[0])) {
2404 assert(Idx
< Ops
.size());
2405 while (const SCEVConstant
*RHSC
= dyn_cast
<SCEVConstant
>(Ops
[Idx
])) {
2406 // We found two constants, fold them together!
2407 Ops
[0] = getConstant(LHSC
->getAPInt() + RHSC
->getAPInt());
2408 if (Ops
.size() == 2) return Ops
[0];
2409 Ops
.erase(Ops
.begin()+1); // Erase the folded element
2410 LHSC
= cast
<SCEVConstant
>(Ops
[0]);
2413 // If we are left with a constant zero being added, strip it off.
2414 if (LHSC
->getValue()->isZero()) {
2415 Ops
.erase(Ops
.begin());
2419 if (Ops
.size() == 1) return Ops
[0];
2422 // Limit recursion calls depth.
2423 if (Depth
> MaxArithDepth
|| hasHugeExpression(Ops
))
2424 return getOrCreateAddExpr(Ops
, Flags
);
2426 // Okay, check to see if the same value occurs in the operand list more than
2427 // once. If so, merge them together into an multiply expression. Since we
2428 // sorted the list, these values are required to be adjacent.
2429 Type
*Ty
= Ops
[0]->getType();
2430 bool FoundMatch
= false;
2431 for (unsigned i
= 0, e
= Ops
.size(); i
!= e
-1; ++i
)
2432 if (Ops
[i
] == Ops
[i
+1]) { // X + Y + Y --> X + Y*2
2433 // Scan ahead to count how many equal operands there are.
2435 while (i
+Count
!= e
&& Ops
[i
+Count
] == Ops
[i
])
2437 // Merge the values into a multiply.
2438 const SCEV
*Scale
= getConstant(Ty
, Count
);
2439 const SCEV
*Mul
= getMulExpr(Scale
, Ops
[i
], SCEV::FlagAnyWrap
, Depth
+ 1);
2440 if (Ops
.size() == Count
)
2443 Ops
.erase(Ops
.begin()+i
+1, Ops
.begin()+i
+Count
);
2444 --i
; e
-= Count
- 1;
2448 return getAddExpr(Ops
, Flags
, Depth
+ 1);
2450 // Check for truncates. If all the operands are truncated from the same
2451 // type, see if factoring out the truncate would permit the result to be
2452 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2453 // if the contents of the resulting outer trunc fold to something simple.
2454 auto FindTruncSrcType
= [&]() -> Type
* {
2455 // We're ultimately looking to fold an addrec of truncs and muls of only
2456 // constants and truncs, so if we find any other types of SCEV
2457 // as operands of the addrec then we bail and return nullptr here.
2458 // Otherwise, we return the type of the operand of a trunc that we find.
2459 if (auto *T
= dyn_cast
<SCEVTruncateExpr
>(Ops
[Idx
]))
2460 return T
->getOperand()->getType();
2461 if (const auto *Mul
= dyn_cast
<SCEVMulExpr
>(Ops
[Idx
])) {
2462 const auto *LastOp
= Mul
->getOperand(Mul
->getNumOperands() - 1);
2463 if (const auto *T
= dyn_cast
<SCEVTruncateExpr
>(LastOp
))
2464 return T
->getOperand()->getType();
2468 if (auto *SrcType
= FindTruncSrcType()) {
2469 SmallVector
<const SCEV
*, 8> LargeOps
;
2471 // Check all the operands to see if they can be represented in the
2472 // source type of the truncate.
2473 for (unsigned i
= 0, e
= Ops
.size(); i
!= e
; ++i
) {
2474 if (const SCEVTruncateExpr
*T
= dyn_cast
<SCEVTruncateExpr
>(Ops
[i
])) {
2475 if (T
->getOperand()->getType() != SrcType
) {
2479 LargeOps
.push_back(T
->getOperand());
2480 } else if (const SCEVConstant
*C
= dyn_cast
<SCEVConstant
>(Ops
[i
])) {
2481 LargeOps
.push_back(getAnyExtendExpr(C
, SrcType
));
2482 } else if (const SCEVMulExpr
*M
= dyn_cast
<SCEVMulExpr
>(Ops
[i
])) {
2483 SmallVector
<const SCEV
*, 8> LargeMulOps
;
2484 for (unsigned j
= 0, f
= M
->getNumOperands(); j
!= f
&& Ok
; ++j
) {
2485 if (const SCEVTruncateExpr
*T
=
2486 dyn_cast
<SCEVTruncateExpr
>(M
->getOperand(j
))) {
2487 if (T
->getOperand()->getType() != SrcType
) {
2491 LargeMulOps
.push_back(T
->getOperand());
2492 } else if (const auto *C
= dyn_cast
<SCEVConstant
>(M
->getOperand(j
))) {
2493 LargeMulOps
.push_back(getAnyExtendExpr(C
, SrcType
));
2500 LargeOps
.push_back(getMulExpr(LargeMulOps
, SCEV::FlagAnyWrap
, Depth
+ 1));
2507 // Evaluate the expression in the larger type.
2508 const SCEV
*Fold
= getAddExpr(LargeOps
, SCEV::FlagAnyWrap
, Depth
+ 1);
2509 // If it folds to something simple, use it. Otherwise, don't.
2510 if (isa
<SCEVConstant
>(Fold
) || isa
<SCEVUnknown
>(Fold
))
2511 return getTruncateExpr(Fold
, Ty
);
2515 // Skip past any other cast SCEVs.
2516 while (Idx
< Ops
.size() && Ops
[Idx
]->getSCEVType() < scAddExpr
)
2519 // If there are add operands they would be next.
2520 if (Idx
< Ops
.size()) {
2521 bool DeletedAdd
= false;
2522 while (const SCEVAddExpr
*Add
= dyn_cast
<SCEVAddExpr
>(Ops
[Idx
])) {
2523 if (Ops
.size() > AddOpsInlineThreshold
||
2524 Add
->getNumOperands() > AddOpsInlineThreshold
)
2526 // If we have an add, expand the add operands onto the end of the operands
2528 Ops
.erase(Ops
.begin()+Idx
);
2529 Ops
.append(Add
->op_begin(), Add
->op_end());
2533 // If we deleted at least one add, we added operands to the end of the list,
2534 // and they are not necessarily sorted. Recurse to resort and resimplify
2535 // any operands we just acquired.
2537 return getAddExpr(Ops
, SCEV::FlagAnyWrap
, Depth
+ 1);
2540 // Skip over the add expression until we get to a multiply.
2541 while (Idx
< Ops
.size() && Ops
[Idx
]->getSCEVType() < scMulExpr
)
2544 // Check to see if there are any folding opportunities present with
2545 // operands multiplied by constant values.
2546 if (Idx
< Ops
.size() && isa
<SCEVMulExpr
>(Ops
[Idx
])) {
2547 uint64_t BitWidth
= getTypeSizeInBits(Ty
);
2548 DenseMap
<const SCEV
*, APInt
> M
;
2549 SmallVector
<const SCEV
*, 8> NewOps
;
2550 APInt
AccumulatedConstant(BitWidth
, 0);
2551 if (CollectAddOperandsWithScales(M
, NewOps
, AccumulatedConstant
,
2552 Ops
.data(), Ops
.size(),
2553 APInt(BitWidth
, 1), *this)) {
2554 struct APIntCompare
{
2555 bool operator()(const APInt
&LHS
, const APInt
&RHS
) const {
2556 return LHS
.ult(RHS
);
2560 // Some interesting folding opportunity is present, so its worthwhile to
2561 // re-generate the operands list. Group the operands by constant scale,
2562 // to avoid multiplying by the same constant scale multiple times.
2563 std::map
<APInt
, SmallVector
<const SCEV
*, 4>, APIntCompare
> MulOpLists
;
2564 for (const SCEV
*NewOp
: NewOps
)
2565 MulOpLists
[M
.find(NewOp
)->second
].push_back(NewOp
);
2566 // Re-generate the operands list.
2568 if (AccumulatedConstant
!= 0)
2569 Ops
.push_back(getConstant(AccumulatedConstant
));
2570 for (auto &MulOp
: MulOpLists
)
2571 if (MulOp
.first
!= 0)
2572 Ops
.push_back(getMulExpr(
2573 getConstant(MulOp
.first
),
2574 getAddExpr(MulOp
.second
, SCEV::FlagAnyWrap
, Depth
+ 1),
2575 SCEV::FlagAnyWrap
, Depth
+ 1));
2578 if (Ops
.size() == 1)
2580 return getAddExpr(Ops
, SCEV::FlagAnyWrap
, Depth
+ 1);
2584 // If we are adding something to a multiply expression, make sure the
2585 // something is not already an operand of the multiply. If so, merge it into
2587 for (; Idx
< Ops
.size() && isa
<SCEVMulExpr
>(Ops
[Idx
]); ++Idx
) {
2588 const SCEVMulExpr
*Mul
= cast
<SCEVMulExpr
>(Ops
[Idx
]);
2589 for (unsigned MulOp
= 0, e
= Mul
->getNumOperands(); MulOp
!= e
; ++MulOp
) {
2590 const SCEV
*MulOpSCEV
= Mul
->getOperand(MulOp
);
2591 if (isa
<SCEVConstant
>(MulOpSCEV
))
2593 for (unsigned AddOp
= 0, e
= Ops
.size(); AddOp
!= e
; ++AddOp
)
2594 if (MulOpSCEV
== Ops
[AddOp
]) {
2595 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2596 const SCEV
*InnerMul
= Mul
->getOperand(MulOp
== 0);
2597 if (Mul
->getNumOperands() != 2) {
2598 // If the multiply has more than two operands, we must get the
2600 SmallVector
<const SCEV
*, 4> MulOps(Mul
->op_begin(),
2601 Mul
->op_begin()+MulOp
);
2602 MulOps
.append(Mul
->op_begin()+MulOp
+1, Mul
->op_end());
2603 InnerMul
= getMulExpr(MulOps
, SCEV::FlagAnyWrap
, Depth
+ 1);
2605 SmallVector
<const SCEV
*, 2> TwoOps
= {getOne(Ty
), InnerMul
};
2606 const SCEV
*AddOne
= getAddExpr(TwoOps
, SCEV::FlagAnyWrap
, Depth
+ 1);
2607 const SCEV
*OuterMul
= getMulExpr(AddOne
, MulOpSCEV
,
2608 SCEV::FlagAnyWrap
, Depth
+ 1);
2609 if (Ops
.size() == 2) return OuterMul
;
2611 Ops
.erase(Ops
.begin()+AddOp
);
2612 Ops
.erase(Ops
.begin()+Idx
-1);
2614 Ops
.erase(Ops
.begin()+Idx
);
2615 Ops
.erase(Ops
.begin()+AddOp
-1);
2617 Ops
.push_back(OuterMul
);
2618 return getAddExpr(Ops
, SCEV::FlagAnyWrap
, Depth
+ 1);
2621 // Check this multiply against other multiplies being added together.
2622 for (unsigned OtherMulIdx
= Idx
+1;
2623 OtherMulIdx
< Ops
.size() && isa
<SCEVMulExpr
>(Ops
[OtherMulIdx
]);
2625 const SCEVMulExpr
*OtherMul
= cast
<SCEVMulExpr
>(Ops
[OtherMulIdx
]);
2626 // If MulOp occurs in OtherMul, we can fold the two multiplies
2628 for (unsigned OMulOp
= 0, e
= OtherMul
->getNumOperands();
2629 OMulOp
!= e
; ++OMulOp
)
2630 if (OtherMul
->getOperand(OMulOp
) == MulOpSCEV
) {
2631 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2632 const SCEV
*InnerMul1
= Mul
->getOperand(MulOp
== 0);
2633 if (Mul
->getNumOperands() != 2) {
2634 SmallVector
<const SCEV
*, 4> MulOps(Mul
->op_begin(),
2635 Mul
->op_begin()+MulOp
);
2636 MulOps
.append(Mul
->op_begin()+MulOp
+1, Mul
->op_end());
2637 InnerMul1
= getMulExpr(MulOps
, SCEV::FlagAnyWrap
, Depth
+ 1);
2639 const SCEV
*InnerMul2
= OtherMul
->getOperand(OMulOp
== 0);
2640 if (OtherMul
->getNumOperands() != 2) {
2641 SmallVector
<const SCEV
*, 4> MulOps(OtherMul
->op_begin(),
2642 OtherMul
->op_begin()+OMulOp
);
2643 MulOps
.append(OtherMul
->op_begin()+OMulOp
+1, OtherMul
->op_end());
2644 InnerMul2
= getMulExpr(MulOps
, SCEV::FlagAnyWrap
, Depth
+ 1);
2646 SmallVector
<const SCEV
*, 2> TwoOps
= {InnerMul1
, InnerMul2
};
2647 const SCEV
*InnerMulSum
=
2648 getAddExpr(TwoOps
, SCEV::FlagAnyWrap
, Depth
+ 1);
2649 const SCEV
*OuterMul
= getMulExpr(MulOpSCEV
, InnerMulSum
,
2650 SCEV::FlagAnyWrap
, Depth
+ 1);
2651 if (Ops
.size() == 2) return OuterMul
;
2652 Ops
.erase(Ops
.begin()+Idx
);
2653 Ops
.erase(Ops
.begin()+OtherMulIdx
-1);
2654 Ops
.push_back(OuterMul
);
2655 return getAddExpr(Ops
, SCEV::FlagAnyWrap
, Depth
+ 1);
2661 // If there are any add recurrences in the operands list, see if any other
2662 // added values are loop invariant. If so, we can fold them into the
2664 while (Idx
< Ops
.size() && Ops
[Idx
]->getSCEVType() < scAddRecExpr
)
2667 // Scan over all recurrences, trying to fold loop invariants into them.
2668 for (; Idx
< Ops
.size() && isa
<SCEVAddRecExpr
>(Ops
[Idx
]); ++Idx
) {
2669 // Scan all of the other operands to this add and add them to the vector if
2670 // they are loop invariant w.r.t. the recurrence.
2671 SmallVector
<const SCEV
*, 8> LIOps
;
2672 const SCEVAddRecExpr
*AddRec
= cast
<SCEVAddRecExpr
>(Ops
[Idx
]);
2673 const Loop
*AddRecLoop
= AddRec
->getLoop();
2674 for (unsigned i
= 0, e
= Ops
.size(); i
!= e
; ++i
)
2675 if (isAvailableAtLoopEntry(Ops
[i
], AddRecLoop
)) {
2676 LIOps
.push_back(Ops
[i
]);
2677 Ops
.erase(Ops
.begin()+i
);
2681 // If we found some loop invariants, fold them into the recurrence.
2682 if (!LIOps
.empty()) {
2683 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2684 LIOps
.push_back(AddRec
->getStart());
2686 SmallVector
<const SCEV
*, 4> AddRecOps(AddRec
->op_begin(),
2688 // This follows from the fact that the no-wrap flags on the outer add
2689 // expression are applicable on the 0th iteration, when the add recurrence
2690 // will be equal to its start value.
2691 AddRecOps
[0] = getAddExpr(LIOps
, Flags
, Depth
+ 1);
2693 // Build the new addrec. Propagate the NUW and NSW flags if both the
2694 // outer add and the inner addrec are guaranteed to have no overflow.
2695 // Always propagate NW.
2696 Flags
= AddRec
->getNoWrapFlags(setFlags(Flags
, SCEV::FlagNW
));
2697 const SCEV
*NewRec
= getAddRecExpr(AddRecOps
, AddRecLoop
, Flags
);
2699 // If all of the other operands were loop invariant, we are done.
2700 if (Ops
.size() == 1) return NewRec
;
2702 // Otherwise, add the folded AddRec by the non-invariant parts.
2703 for (unsigned i
= 0;; ++i
)
2704 if (Ops
[i
] == AddRec
) {
2708 return getAddExpr(Ops
, SCEV::FlagAnyWrap
, Depth
+ 1);
2711 // Okay, if there weren't any loop invariants to be folded, check to see if
2712 // there are multiple AddRec's with the same loop induction variable being
2713 // added together. If so, we can fold them.
2714 for (unsigned OtherIdx
= Idx
+1;
2715 OtherIdx
< Ops
.size() && isa
<SCEVAddRecExpr
>(Ops
[OtherIdx
]);
2717 // We expect the AddRecExpr's to be sorted in reverse dominance order,
2718 // so that the 1st found AddRecExpr is dominated by all others.
2719 assert(DT
.dominates(
2720 cast
<SCEVAddRecExpr
>(Ops
[OtherIdx
])->getLoop()->getHeader(),
2721 AddRec
->getLoop()->getHeader()) &&
2722 "AddRecExprs are not sorted in reverse dominance order?");
2723 if (AddRecLoop
== cast
<SCEVAddRecExpr
>(Ops
[OtherIdx
])->getLoop()) {
2724 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2725 SmallVector
<const SCEV
*, 4> AddRecOps(AddRec
->op_begin(),
2727 for (; OtherIdx
!= Ops
.size() && isa
<SCEVAddRecExpr
>(Ops
[OtherIdx
]);
2729 const auto *OtherAddRec
= cast
<SCEVAddRecExpr
>(Ops
[OtherIdx
]);
2730 if (OtherAddRec
->getLoop() == AddRecLoop
) {
2731 for (unsigned i
= 0, e
= OtherAddRec
->getNumOperands();
2733 if (i
>= AddRecOps
.size()) {
2734 AddRecOps
.append(OtherAddRec
->op_begin()+i
,
2735 OtherAddRec
->op_end());
2738 SmallVector
<const SCEV
*, 2> TwoOps
= {
2739 AddRecOps
[i
], OtherAddRec
->getOperand(i
)};
2740 AddRecOps
[i
] = getAddExpr(TwoOps
, SCEV::FlagAnyWrap
, Depth
+ 1);
2742 Ops
.erase(Ops
.begin() + OtherIdx
); --OtherIdx
;
2745 // Step size has changed, so we cannot guarantee no self-wraparound.
2746 Ops
[Idx
] = getAddRecExpr(AddRecOps
, AddRecLoop
, SCEV::FlagAnyWrap
);
2747 return getAddExpr(Ops
, SCEV::FlagAnyWrap
, Depth
+ 1);
2751 // Otherwise couldn't fold anything into this recurrence. Move onto the
2755 // Okay, it looks like we really DO need an add expr. Check to see if we
2756 // already have one, otherwise create a new one.
2757 return getOrCreateAddExpr(Ops
, Flags
);
2761 ScalarEvolution::getOrCreateAddExpr(ArrayRef
<const SCEV
*> Ops
,
2762 SCEV::NoWrapFlags Flags
) {
2763 FoldingSetNodeID ID
;
2764 ID
.AddInteger(scAddExpr
);
2765 for (const SCEV
*Op
: Ops
)
2769 static_cast<SCEVAddExpr
*>(UniqueSCEVs
.FindNodeOrInsertPos(ID
, IP
));
2771 const SCEV
**O
= SCEVAllocator
.Allocate
<const SCEV
*>(Ops
.size());
2772 std::uninitialized_copy(Ops
.begin(), Ops
.end(), O
);
2773 S
= new (SCEVAllocator
)
2774 SCEVAddExpr(ID
.Intern(SCEVAllocator
), O
, Ops
.size());
2775 UniqueSCEVs
.InsertNode(S
, IP
);
2776 addToLoopUseLists(S
);
2778 S
->setNoWrapFlags(Flags
);
2783 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef
<const SCEV
*> Ops
,
2784 const Loop
*L
, SCEV::NoWrapFlags Flags
) {
2785 FoldingSetNodeID ID
;
2786 ID
.AddInteger(scAddRecExpr
);
2787 for (unsigned i
= 0, e
= Ops
.size(); i
!= e
; ++i
)
2788 ID
.AddPointer(Ops
[i
]);
2792 static_cast<SCEVAddRecExpr
*>(UniqueSCEVs
.FindNodeOrInsertPos(ID
, IP
));
2794 const SCEV
**O
= SCEVAllocator
.Allocate
<const SCEV
*>(Ops
.size());
2795 std::uninitialized_copy(Ops
.begin(), Ops
.end(), O
);
2796 S
= new (SCEVAllocator
)
2797 SCEVAddRecExpr(ID
.Intern(SCEVAllocator
), O
, Ops
.size(), L
);
2798 UniqueSCEVs
.InsertNode(S
, IP
);
2799 addToLoopUseLists(S
);
2801 S
->setNoWrapFlags(Flags
);
2806 ScalarEvolution::getOrCreateMulExpr(ArrayRef
<const SCEV
*> Ops
,
2807 SCEV::NoWrapFlags Flags
) {
2808 FoldingSetNodeID ID
;
2809 ID
.AddInteger(scMulExpr
);
2810 for (unsigned i
= 0, e
= Ops
.size(); i
!= e
; ++i
)
2811 ID
.AddPointer(Ops
[i
]);
2814 static_cast<SCEVMulExpr
*>(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
) SCEVMulExpr(ID
.Intern(SCEVAllocator
),
2820 UniqueSCEVs
.InsertNode(S
, IP
);
2821 addToLoopUseLists(S
);
2823 S
->setNoWrapFlags(Flags
);
2827 static uint64_t umul_ov(uint64_t i
, uint64_t j
, bool &Overflow
) {
2829 if (j
> 1 && k
/ j
!= i
) Overflow
= true;
2833 /// Compute the result of "n choose k", the binomial coefficient. If an
2834 /// intermediate computation overflows, Overflow will be set and the return will
2835 /// be garbage. Overflow is not cleared on absence of overflow.
2836 static uint64_t Choose(uint64_t n
, uint64_t k
, bool &Overflow
) {
2837 // We use the multiplicative formula:
2838 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2839 // At each iteration, we take the n-th term of the numeral and divide by the
2840 // (k-n)th term of the denominator. This division will always produce an
2841 // integral result, and helps reduce the chance of overflow in the
2842 // intermediate computations. However, we can still overflow even when the
2843 // final result would fit.
2845 if (n
== 0 || n
== k
) return 1;
2846 if (k
> n
) return 0;
2852 for (uint64_t i
= 1; i
<= k
; ++i
) {
2853 r
= umul_ov(r
, n
-(i
-1), Overflow
);
2859 /// Determine if any of the operands in this SCEV are a constant or if
2860 /// any of the add or multiply expressions in this SCEV contain a constant.
2861 static bool containsConstantInAddMulChain(const SCEV
*StartExpr
) {
2862 struct FindConstantInAddMulChain
{
2863 bool FoundConstant
= false;
2865 bool follow(const SCEV
*S
) {
2866 FoundConstant
|= isa
<SCEVConstant
>(S
);
2867 return isa
<SCEVAddExpr
>(S
) || isa
<SCEVMulExpr
>(S
);
2870 bool isDone() const {
2871 return FoundConstant
;
2875 FindConstantInAddMulChain F
;
2876 SCEVTraversal
<FindConstantInAddMulChain
> ST(F
);
2877 ST
.visitAll(StartExpr
);
2878 return F
.FoundConstant
;
2881 /// Get a canonical multiply expression, or something simpler if possible.
2882 const SCEV
*ScalarEvolution::getMulExpr(SmallVectorImpl
<const SCEV
*> &Ops
,
2883 SCEV::NoWrapFlags Flags
,
2885 assert(Flags
== maskFlags(Flags
, SCEV::FlagNUW
| SCEV::FlagNSW
) &&
2886 "only nuw or nsw allowed");
2887 assert(!Ops
.empty() && "Cannot get empty mul!");
2888 if (Ops
.size() == 1) return Ops
[0];
2890 Type
*ETy
= getEffectiveSCEVType(Ops
[0]->getType());
2891 for (unsigned i
= 1, e
= Ops
.size(); i
!= e
; ++i
)
2892 assert(getEffectiveSCEVType(Ops
[i
]->getType()) == ETy
&&
2893 "SCEVMulExpr operand types don't match!");
2896 // Sort by complexity, this groups all similar expression types together.
2897 GroupByComplexity(Ops
, &LI
, DT
);
2899 Flags
= StrengthenNoWrapFlags(this, scMulExpr
, Ops
, Flags
);
2901 // Limit recursion calls depth.
2902 if (Depth
> MaxArithDepth
|| hasHugeExpression(Ops
))
2903 return getOrCreateMulExpr(Ops
, Flags
);
2905 // If there are any constants, fold them together.
2907 if (const SCEVConstant
*LHSC
= dyn_cast
<SCEVConstant
>(Ops
[0])) {
2909 if (Ops
.size() == 2)
2910 // C1*(C2+V) -> C1*C2 + C1*V
2911 if (const SCEVAddExpr
*Add
= dyn_cast
<SCEVAddExpr
>(Ops
[1]))
2912 // If any of Add's ops are Adds or Muls with a constant, apply this
2913 // transformation as well.
2915 // TODO: There are some cases where this transformation is not
2916 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of
2917 // this transformation should be narrowed down.
2918 if (Add
->getNumOperands() == 2 && containsConstantInAddMulChain(Add
))
2919 return getAddExpr(getMulExpr(LHSC
, Add
->getOperand(0),
2920 SCEV::FlagAnyWrap
, Depth
+ 1),
2921 getMulExpr(LHSC
, Add
->getOperand(1),
2922 SCEV::FlagAnyWrap
, Depth
+ 1),
2923 SCEV::FlagAnyWrap
, Depth
+ 1);
2926 while (const SCEVConstant
*RHSC
= dyn_cast
<SCEVConstant
>(Ops
[Idx
])) {
2927 // We found two constants, fold them together!
2929 ConstantInt::get(getContext(), LHSC
->getAPInt() * RHSC
->getAPInt());
2930 Ops
[0] = getConstant(Fold
);
2931 Ops
.erase(Ops
.begin()+1); // Erase the folded element
2932 if (Ops
.size() == 1) return Ops
[0];
2933 LHSC
= cast
<SCEVConstant
>(Ops
[0]);
2936 // If we are left with a constant one being multiplied, strip it off.
2937 if (cast
<SCEVConstant
>(Ops
[0])->getValue()->isOne()) {
2938 Ops
.erase(Ops
.begin());
2940 } else if (cast
<SCEVConstant
>(Ops
[0])->getValue()->isZero()) {
2941 // If we have a multiply of zero, it will always be zero.
2943 } else if (Ops
[0]->isAllOnesValue()) {
2944 // If we have a mul by -1 of an add, try distributing the -1 among the
2946 if (Ops
.size() == 2) {
2947 if (const SCEVAddExpr
*Add
= dyn_cast
<SCEVAddExpr
>(Ops
[1])) {
2948 SmallVector
<const SCEV
*, 4> NewOps
;
2949 bool AnyFolded
= false;
2950 for (const SCEV
*AddOp
: Add
->operands()) {
2951 const SCEV
*Mul
= getMulExpr(Ops
[0], AddOp
, SCEV::FlagAnyWrap
,
2953 if (!isa
<SCEVMulExpr
>(Mul
)) AnyFolded
= true;
2954 NewOps
.push_back(Mul
);
2957 return getAddExpr(NewOps
, SCEV::FlagAnyWrap
, Depth
+ 1);
2958 } else if (const auto *AddRec
= dyn_cast
<SCEVAddRecExpr
>(Ops
[1])) {
2959 // Negation preserves a recurrence's no self-wrap property.
2960 SmallVector
<const SCEV
*, 4> Operands
;
2961 for (const SCEV
*AddRecOp
: AddRec
->operands())
2962 Operands
.push_back(getMulExpr(Ops
[0], AddRecOp
, SCEV::FlagAnyWrap
,
2965 return getAddRecExpr(Operands
, AddRec
->getLoop(),
2966 AddRec
->getNoWrapFlags(SCEV::FlagNW
));
2971 if (Ops
.size() == 1)
2975 // Skip over the add expression until we get to a multiply.
2976 while (Idx
< Ops
.size() && Ops
[Idx
]->getSCEVType() < scMulExpr
)
2979 // If there are mul operands inline them all into this expression.
2980 if (Idx
< Ops
.size()) {
2981 bool DeletedMul
= false;
2982 while (const SCEVMulExpr
*Mul
= dyn_cast
<SCEVMulExpr
>(Ops
[Idx
])) {
2983 if (Ops
.size() > MulOpsInlineThreshold
)
2985 // If we have an mul, expand the mul operands onto the end of the
2987 Ops
.erase(Ops
.begin()+Idx
);
2988 Ops
.append(Mul
->op_begin(), Mul
->op_end());
2992 // If we deleted at least one mul, we added operands to the end of the
2993 // list, and they are not necessarily sorted. Recurse to resort and
2994 // resimplify any operands we just acquired.
2996 return getMulExpr(Ops
, SCEV::FlagAnyWrap
, Depth
+ 1);
2999 // If there are any add recurrences in the operands list, see if any other
3000 // added values are loop invariant. If so, we can fold them into the
3002 while (Idx
< Ops
.size() && Ops
[Idx
]->getSCEVType() < scAddRecExpr
)
3005 // Scan over all recurrences, trying to fold loop invariants into them.
3006 for (; Idx
< Ops
.size() && isa
<SCEVAddRecExpr
>(Ops
[Idx
]); ++Idx
) {
3007 // Scan all of the other operands to this mul and add them to the vector
3008 // if they are loop invariant w.r.t. the recurrence.
3009 SmallVector
<const SCEV
*, 8> LIOps
;
3010 const SCEVAddRecExpr
*AddRec
= cast
<SCEVAddRecExpr
>(Ops
[Idx
]);
3011 const Loop
*AddRecLoop
= AddRec
->getLoop();
3012 for (unsigned i
= 0, e
= Ops
.size(); i
!= e
; ++i
)
3013 if (isAvailableAtLoopEntry(Ops
[i
], AddRecLoop
)) {
3014 LIOps
.push_back(Ops
[i
]);
3015 Ops
.erase(Ops
.begin()+i
);
3019 // If we found some loop invariants, fold them into the recurrence.
3020 if (!LIOps
.empty()) {
3021 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
3022 SmallVector
<const SCEV
*, 4> NewOps
;
3023 NewOps
.reserve(AddRec
->getNumOperands());
3024 const SCEV
*Scale
= getMulExpr(LIOps
, SCEV::FlagAnyWrap
, Depth
+ 1);
3025 for (unsigned i
= 0, e
= AddRec
->getNumOperands(); i
!= e
; ++i
)
3026 NewOps
.push_back(getMulExpr(Scale
, AddRec
->getOperand(i
),
3027 SCEV::FlagAnyWrap
, Depth
+ 1));
3029 // Build the new addrec. Propagate the NUW and NSW flags if both the
3030 // outer mul and the inner addrec are guaranteed to have no overflow.
3032 // No self-wrap cannot be guaranteed after changing the step size, but
3033 // will be inferred if either NUW or NSW is true.
3034 Flags
= AddRec
->getNoWrapFlags(clearFlags(Flags
, SCEV::FlagNW
));
3035 const SCEV
*NewRec
= getAddRecExpr(NewOps
, AddRecLoop
, Flags
);
3037 // If all of the other operands were loop invariant, we are done.
3038 if (Ops
.size() == 1) return NewRec
;
3040 // Otherwise, multiply the folded AddRec by the non-invariant parts.
3041 for (unsigned i
= 0;; ++i
)
3042 if (Ops
[i
] == AddRec
) {
3046 return getMulExpr(Ops
, SCEV::FlagAnyWrap
, Depth
+ 1);
3049 // Okay, if there weren't any loop invariants to be folded, check to see
3050 // if there are multiple AddRec's with the same loop induction variable
3051 // being multiplied together. If so, we can fold them.
3053 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3054 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3055 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3056 // ]]],+,...up to x=2n}.
3057 // Note that the arguments to choose() are always integers with values
3058 // known at compile time, never SCEV objects.
3060 // The implementation avoids pointless extra computations when the two
3061 // addrec's are of different length (mathematically, it's equivalent to
3062 // an infinite stream of zeros on the right).
3063 bool OpsModified
= false;
3064 for (unsigned OtherIdx
= Idx
+1;
3065 OtherIdx
!= Ops
.size() && isa
<SCEVAddRecExpr
>(Ops
[OtherIdx
]);
3067 const SCEVAddRecExpr
*OtherAddRec
=
3068 dyn_cast
<SCEVAddRecExpr
>(Ops
[OtherIdx
]);
3069 if (!OtherAddRec
|| OtherAddRec
->getLoop() != AddRecLoop
)
3072 // Limit max number of arguments to avoid creation of unreasonably big
3073 // SCEVAddRecs with very complex operands.
3074 if (AddRec
->getNumOperands() + OtherAddRec
->getNumOperands() - 1 >
3075 MaxAddRecSize
|| isHugeExpression(AddRec
) ||
3076 isHugeExpression(OtherAddRec
))
3079 bool Overflow
= false;
3080 Type
*Ty
= AddRec
->getType();
3081 bool LargerThan64Bits
= getTypeSizeInBits(Ty
) > 64;
3082 SmallVector
<const SCEV
*, 7> AddRecOps
;
3083 for (int x
= 0, xe
= AddRec
->getNumOperands() +
3084 OtherAddRec
->getNumOperands() - 1; x
!= xe
&& !Overflow
; ++x
) {
3085 SmallVector
<const SCEV
*, 7> SumOps
;
3086 for (int y
= x
, ye
= 2*x
+1; y
!= ye
&& !Overflow
; ++y
) {
3087 uint64_t Coeff1
= Choose(x
, 2*x
- y
, Overflow
);
3088 for (int z
= std::max(y
-x
, y
-(int)AddRec
->getNumOperands()+1),
3089 ze
= std::min(x
+1, (int)OtherAddRec
->getNumOperands());
3090 z
< ze
&& !Overflow
; ++z
) {
3091 uint64_t Coeff2
= Choose(2*x
- y
, x
-z
, Overflow
);
3093 if (LargerThan64Bits
)
3094 Coeff
= umul_ov(Coeff1
, Coeff2
, Overflow
);
3096 Coeff
= Coeff1
*Coeff2
;
3097 const SCEV
*CoeffTerm
= getConstant(Ty
, Coeff
);
3098 const SCEV
*Term1
= AddRec
->getOperand(y
-z
);
3099 const SCEV
*Term2
= OtherAddRec
->getOperand(z
);
3100 SumOps
.push_back(getMulExpr(CoeffTerm
, Term1
, Term2
,
3101 SCEV::FlagAnyWrap
, Depth
+ 1));
3105 SumOps
.push_back(getZero(Ty
));
3106 AddRecOps
.push_back(getAddExpr(SumOps
, SCEV::FlagAnyWrap
, Depth
+ 1));
3109 const SCEV
*NewAddRec
= getAddRecExpr(AddRecOps
, AddRecLoop
,
3111 if (Ops
.size() == 2) return NewAddRec
;
3112 Ops
[Idx
] = NewAddRec
;
3113 Ops
.erase(Ops
.begin() + OtherIdx
); --OtherIdx
;
3115 AddRec
= dyn_cast
<SCEVAddRecExpr
>(NewAddRec
);
3121 return getMulExpr(Ops
, SCEV::FlagAnyWrap
, Depth
+ 1);
3123 // Otherwise couldn't fold anything into this recurrence. Move onto the
3127 // Okay, it looks like we really DO need an mul expr. Check to see if we
3128 // already have one, otherwise create a new one.
3129 return getOrCreateMulExpr(Ops
, Flags
);
3132 /// Represents an unsigned remainder expression based on unsigned division.
3133 const SCEV
*ScalarEvolution::getURemExpr(const SCEV
*LHS
,
3135 assert(getEffectiveSCEVType(LHS
->getType()) ==
3136 getEffectiveSCEVType(RHS
->getType()) &&
3137 "SCEVURemExpr operand types don't match!");
3139 // Short-circuit easy cases
3140 if (const SCEVConstant
*RHSC
= dyn_cast
<SCEVConstant
>(RHS
)) {
3141 // If constant is one, the result is trivial
3142 if (RHSC
->getValue()->isOne())
3143 return getZero(LHS
->getType()); // X urem 1 --> 0
3145 // If constant is a power of two, fold into a zext(trunc(LHS)).
3146 if (RHSC
->getAPInt().isPowerOf2()) {
3147 Type
*FullTy
= LHS
->getType();
3149 IntegerType::get(getContext(), RHSC
->getAPInt().logBase2());
3150 return getZeroExtendExpr(getTruncateExpr(LHS
, TruncTy
), FullTy
);
3154 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3155 const SCEV
*UDiv
= getUDivExpr(LHS
, RHS
);
3156 const SCEV
*Mult
= getMulExpr(UDiv
, RHS
, SCEV::FlagNUW
);
3157 return getMinusSCEV(LHS
, Mult
, SCEV::FlagNUW
);
3160 /// Get a canonical unsigned division expression, or something simpler if
3162 const SCEV
*ScalarEvolution::getUDivExpr(const SCEV
*LHS
,
3164 assert(getEffectiveSCEVType(LHS
->getType()) ==
3165 getEffectiveSCEVType(RHS
->getType()) &&
3166 "SCEVUDivExpr operand types don't match!");
3168 if (const SCEVConstant
*RHSC
= dyn_cast
<SCEVConstant
>(RHS
)) {
3169 if (RHSC
->getValue()->isOne())
3170 return LHS
; // X udiv 1 --> x
3171 // If the denominator is zero, the result of the udiv is undefined. Don't
3172 // try to analyze it, because the resolution chosen here may differ from
3173 // the resolution chosen in other parts of the compiler.
3174 if (!RHSC
->getValue()->isZero()) {
3175 // Determine if the division can be folded into the operands of
3177 // TODO: Generalize this to non-constants by using known-bits information.
3178 Type
*Ty
= LHS
->getType();
3179 unsigned LZ
= RHSC
->getAPInt().countLeadingZeros();
3180 unsigned MaxShiftAmt
= getTypeSizeInBits(Ty
) - LZ
- 1;
3181 // For non-power-of-two values, effectively round the value up to the
3182 // nearest power of two.
3183 if (!RHSC
->getAPInt().isPowerOf2())
3185 IntegerType
*ExtTy
=
3186 IntegerType::get(getContext(), getTypeSizeInBits(Ty
) + MaxShiftAmt
);
3187 if (const SCEVAddRecExpr
*AR
= dyn_cast
<SCEVAddRecExpr
>(LHS
))
3188 if (const SCEVConstant
*Step
=
3189 dyn_cast
<SCEVConstant
>(AR
->getStepRecurrence(*this))) {
3190 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3191 const APInt
&StepInt
= Step
->getAPInt();
3192 const APInt
&DivInt
= RHSC
->getAPInt();
3193 if (!StepInt
.urem(DivInt
) &&
3194 getZeroExtendExpr(AR
, ExtTy
) ==
3195 getAddRecExpr(getZeroExtendExpr(AR
->getStart(), ExtTy
),
3196 getZeroExtendExpr(Step
, ExtTy
),
3197 AR
->getLoop(), SCEV::FlagAnyWrap
)) {
3198 SmallVector
<const SCEV
*, 4> Operands
;
3199 for (const SCEV
*Op
: AR
->operands())
3200 Operands
.push_back(getUDivExpr(Op
, RHS
));
3201 return getAddRecExpr(Operands
, AR
->getLoop(), SCEV::FlagNW
);
3203 /// Get a canonical UDivExpr for a recurrence.
3204 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3205 // We can currently only fold X%N if X is constant.
3206 const SCEVConstant
*StartC
= dyn_cast
<SCEVConstant
>(AR
->getStart());
3207 if (StartC
&& !DivInt
.urem(StepInt
) &&
3208 getZeroExtendExpr(AR
, ExtTy
) ==
3209 getAddRecExpr(getZeroExtendExpr(AR
->getStart(), ExtTy
),
3210 getZeroExtendExpr(Step
, ExtTy
),
3211 AR
->getLoop(), SCEV::FlagAnyWrap
)) {
3212 const APInt
&StartInt
= StartC
->getAPInt();
3213 const APInt
&StartRem
= StartInt
.urem(StepInt
);
3215 LHS
= getAddRecExpr(getConstant(StartInt
- StartRem
), Step
,
3216 AR
->getLoop(), SCEV::FlagNW
);
3219 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3220 if (const SCEVMulExpr
*M
= dyn_cast
<SCEVMulExpr
>(LHS
)) {
3221 SmallVector
<const SCEV
*, 4> Operands
;
3222 for (const SCEV
*Op
: M
->operands())
3223 Operands
.push_back(getZeroExtendExpr(Op
, ExtTy
));
3224 if (getZeroExtendExpr(M
, ExtTy
) == getMulExpr(Operands
))
3225 // Find an operand that's safely divisible.
3226 for (unsigned i
= 0, e
= M
->getNumOperands(); i
!= e
; ++i
) {
3227 const SCEV
*Op
= M
->getOperand(i
);
3228 const SCEV
*Div
= getUDivExpr(Op
, RHSC
);
3229 if (!isa
<SCEVUDivExpr
>(Div
) && getMulExpr(Div
, RHSC
) == Op
) {
3230 Operands
= SmallVector
<const SCEV
*, 4>(M
->op_begin(),
3233 return getMulExpr(Operands
);
3238 // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3239 if (const SCEVUDivExpr
*OtherDiv
= dyn_cast
<SCEVUDivExpr
>(LHS
)) {
3240 if (auto *DivisorConstant
=
3241 dyn_cast
<SCEVConstant
>(OtherDiv
->getRHS())) {
3242 bool Overflow
= false;
3244 DivisorConstant
->getAPInt().umul_ov(RHSC
->getAPInt(), Overflow
);
3246 return getConstant(RHSC
->getType(), 0, false);
3248 return getUDivExpr(OtherDiv
->getLHS(), getConstant(NewRHS
));
3252 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3253 if (const SCEVAddExpr
*A
= dyn_cast
<SCEVAddExpr
>(LHS
)) {
3254 SmallVector
<const SCEV
*, 4> Operands
;
3255 for (const SCEV
*Op
: A
->operands())
3256 Operands
.push_back(getZeroExtendExpr(Op
, ExtTy
));
3257 if (getZeroExtendExpr(A
, ExtTy
) == getAddExpr(Operands
)) {
3259 for (unsigned i
= 0, e
= A
->getNumOperands(); i
!= e
; ++i
) {
3260 const SCEV
*Op
= getUDivExpr(A
->getOperand(i
), RHS
);
3261 if (isa
<SCEVUDivExpr
>(Op
) ||
3262 getMulExpr(Op
, RHS
) != A
->getOperand(i
))
3264 Operands
.push_back(Op
);
3266 if (Operands
.size() == A
->getNumOperands())
3267 return getAddExpr(Operands
);
3271 // Fold if both operands are constant.
3272 if (const SCEVConstant
*LHSC
= dyn_cast
<SCEVConstant
>(LHS
)) {
3273 Constant
*LHSCV
= LHSC
->getValue();
3274 Constant
*RHSCV
= RHSC
->getValue();
3275 return getConstant(cast
<ConstantInt
>(ConstantExpr::getUDiv(LHSCV
,
3281 FoldingSetNodeID ID
;
3282 ID
.AddInteger(scUDivExpr
);
3286 if (const SCEV
*S
= UniqueSCEVs
.FindNodeOrInsertPos(ID
, IP
)) return S
;
3287 SCEV
*S
= new (SCEVAllocator
) SCEVUDivExpr(ID
.Intern(SCEVAllocator
),
3289 UniqueSCEVs
.InsertNode(S
, IP
);
3290 addToLoopUseLists(S
);
3294 static const APInt
gcd(const SCEVConstant
*C1
, const SCEVConstant
*C2
) {
3295 APInt A
= C1
->getAPInt().abs();
3296 APInt B
= C2
->getAPInt().abs();
3297 uint32_t ABW
= A
.getBitWidth();
3298 uint32_t BBW
= B
.getBitWidth();
3305 return APIntOps::GreatestCommonDivisor(std::move(A
), std::move(B
));
3308 /// Get a canonical unsigned division expression, or something simpler if
3309 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3310 /// can attempt to remove factors from the LHS and RHS. We can't do this when
3311 /// it's not exact because the udiv may be clearing bits.
3312 const SCEV
*ScalarEvolution::getUDivExactExpr(const SCEV
*LHS
,
3314 // TODO: we could try to find factors in all sorts of things, but for now we
3315 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3316 // end of this file for inspiration.
3318 const SCEVMulExpr
*Mul
= dyn_cast
<SCEVMulExpr
>(LHS
);
3319 if (!Mul
|| !Mul
->hasNoUnsignedWrap())
3320 return getUDivExpr(LHS
, RHS
);
3322 if (const SCEVConstant
*RHSCst
= dyn_cast
<SCEVConstant
>(RHS
)) {
3323 // If the mulexpr multiplies by a constant, then that constant must be the
3324 // first element of the mulexpr.
3325 if (const auto *LHSCst
= dyn_cast
<SCEVConstant
>(Mul
->getOperand(0))) {
3326 if (LHSCst
== RHSCst
) {
3327 SmallVector
<const SCEV
*, 2> Operands
;
3328 Operands
.append(Mul
->op_begin() + 1, Mul
->op_end());
3329 return getMulExpr(Operands
);
3332 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3333 // that there's a factor provided by one of the other terms. We need to
3335 APInt Factor
= gcd(LHSCst
, RHSCst
);
3336 if (!Factor
.isIntN(1)) {
3338 cast
<SCEVConstant
>(getConstant(LHSCst
->getAPInt().udiv(Factor
)));
3340 cast
<SCEVConstant
>(getConstant(RHSCst
->getAPInt().udiv(Factor
)));
3341 SmallVector
<const SCEV
*, 2> Operands
;
3342 Operands
.push_back(LHSCst
);
3343 Operands
.append(Mul
->op_begin() + 1, Mul
->op_end());
3344 LHS
= getMulExpr(Operands
);
3346 Mul
= dyn_cast
<SCEVMulExpr
>(LHS
);
3348 return getUDivExactExpr(LHS
, RHS
);
3353 for (int i
= 0, e
= Mul
->getNumOperands(); i
!= e
; ++i
) {
3354 if (Mul
->getOperand(i
) == RHS
) {
3355 SmallVector
<const SCEV
*, 2> Operands
;
3356 Operands
.append(Mul
->op_begin(), Mul
->op_begin() + i
);
3357 Operands
.append(Mul
->op_begin() + i
+ 1, Mul
->op_end());
3358 return getMulExpr(Operands
);
3362 return getUDivExpr(LHS
, RHS
);
3365 /// Get an add recurrence expression for the specified loop. Simplify the
3366 /// expression as much as possible.
3367 const SCEV
*ScalarEvolution::getAddRecExpr(const SCEV
*Start
, const SCEV
*Step
,
3369 SCEV::NoWrapFlags Flags
) {
3370 SmallVector
<const SCEV
*, 4> Operands
;
3371 Operands
.push_back(Start
);
3372 if (const SCEVAddRecExpr
*StepChrec
= dyn_cast
<SCEVAddRecExpr
>(Step
))
3373 if (StepChrec
->getLoop() == L
) {
3374 Operands
.append(StepChrec
->op_begin(), StepChrec
->op_end());
3375 return getAddRecExpr(Operands
, L
, maskFlags(Flags
, SCEV::FlagNW
));
3378 Operands
.push_back(Step
);
3379 return getAddRecExpr(Operands
, L
, Flags
);
3382 /// Get an add recurrence expression for the specified loop. Simplify the
3383 /// expression as much as possible.
3385 ScalarEvolution::getAddRecExpr(SmallVectorImpl
<const SCEV
*> &Operands
,
3386 const Loop
*L
, SCEV::NoWrapFlags Flags
) {
3387 if (Operands
.size() == 1) return Operands
[0];
3389 Type
*ETy
= getEffectiveSCEVType(Operands
[0]->getType());
3390 for (unsigned i
= 1, e
= Operands
.size(); i
!= e
; ++i
)
3391 assert(getEffectiveSCEVType(Operands
[i
]->getType()) == ETy
&&
3392 "SCEVAddRecExpr operand types don't match!");
3393 for (unsigned i
= 0, e
= Operands
.size(); i
!= e
; ++i
)
3394 assert(isLoopInvariant(Operands
[i
], L
) &&
3395 "SCEVAddRecExpr operand is not loop-invariant!");
3398 if (Operands
.back()->isZero()) {
3399 Operands
.pop_back();
3400 return getAddRecExpr(Operands
, L
, SCEV::FlagAnyWrap
); // {X,+,0} --> X
3403 // It's tempting to want to call getMaxBackedgeTakenCount count here and
3404 // use that information to infer NUW and NSW flags. However, computing a
3405 // BE count requires calling getAddRecExpr, so we may not yet have a
3406 // meaningful BE count at this point (and if we don't, we'd be stuck
3407 // with a SCEVCouldNotCompute as the cached BE count).
3409 Flags
= StrengthenNoWrapFlags(this, scAddRecExpr
, Operands
, Flags
);
3411 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3412 if (const SCEVAddRecExpr
*NestedAR
= dyn_cast
<SCEVAddRecExpr
>(Operands
[0])) {
3413 const Loop
*NestedLoop
= NestedAR
->getLoop();
3414 if (L
->contains(NestedLoop
)
3415 ? (L
->getLoopDepth() < NestedLoop
->getLoopDepth())
3416 : (!NestedLoop
->contains(L
) &&
3417 DT
.dominates(L
->getHeader(), NestedLoop
->getHeader()))) {
3418 SmallVector
<const SCEV
*, 4> NestedOperands(NestedAR
->op_begin(),
3419 NestedAR
->op_end());
3420 Operands
[0] = NestedAR
->getStart();
3421 // AddRecs require their operands be loop-invariant with respect to their
3422 // loops. Don't perform this transformation if it would break this
3424 bool AllInvariant
= all_of(
3425 Operands
, [&](const SCEV
*Op
) { return isLoopInvariant(Op
, L
); });
3428 // Create a recurrence for the outer loop with the same step size.
3430 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3431 // inner recurrence has the same property.
3432 SCEV::NoWrapFlags OuterFlags
=
3433 maskFlags(Flags
, SCEV::FlagNW
| NestedAR
->getNoWrapFlags());
3435 NestedOperands
[0] = getAddRecExpr(Operands
, L
, OuterFlags
);
3436 AllInvariant
= all_of(NestedOperands
, [&](const SCEV
*Op
) {
3437 return isLoopInvariant(Op
, NestedLoop
);
3441 // Ok, both add recurrences are valid after the transformation.
3443 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3444 // the outer recurrence has the same property.
3445 SCEV::NoWrapFlags InnerFlags
=
3446 maskFlags(NestedAR
->getNoWrapFlags(), SCEV::FlagNW
| Flags
);
3447 return getAddRecExpr(NestedOperands
, NestedLoop
, InnerFlags
);
3450 // Reset Operands to its original state.
3451 Operands
[0] = NestedAR
;
3455 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3456 // already have one, otherwise create a new one.
3457 return getOrCreateAddRecExpr(Operands
, L
, Flags
);
3461 ScalarEvolution::getGEPExpr(GEPOperator
*GEP
,
3462 const SmallVectorImpl
<const SCEV
*> &IndexExprs
) {
3463 const SCEV
*BaseExpr
= getSCEV(GEP
->getPointerOperand());
3464 // getSCEV(Base)->getType() has the same address space as Base->getType()
3465 // because SCEV::getType() preserves the address space.
3466 Type
*IntPtrTy
= getEffectiveSCEVType(BaseExpr
->getType());
3467 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3468 // instruction to its SCEV, because the Instruction may be guarded by control
3469 // flow and the no-overflow bits may not be valid for the expression in any
3470 // context. This can be fixed similarly to how these flags are handled for
3472 SCEV::NoWrapFlags Wrap
= GEP
->isInBounds() ? SCEV::FlagNSW
3473 : SCEV::FlagAnyWrap
;
3475 const SCEV
*TotalOffset
= getZero(IntPtrTy
);
3476 // The array size is unimportant. The first thing we do on CurTy is getting
3477 // its element type.
3478 Type
*CurTy
= ArrayType::get(GEP
->getSourceElementType(), 0);
3479 for (const SCEV
*IndexExpr
: IndexExprs
) {
3480 // Compute the (potentially symbolic) offset in bytes for this index.
3481 if (StructType
*STy
= dyn_cast
<StructType
>(CurTy
)) {
3482 // For a struct, add the member offset.
3483 ConstantInt
*Index
= cast
<SCEVConstant
>(IndexExpr
)->getValue();
3484 unsigned FieldNo
= Index
->getZExtValue();
3485 const SCEV
*FieldOffset
= getOffsetOfExpr(IntPtrTy
, STy
, FieldNo
);
3487 // Add the field offset to the running total offset.
3488 TotalOffset
= getAddExpr(TotalOffset
, FieldOffset
);
3490 // Update CurTy to the type of the field at Index.
3491 CurTy
= STy
->getTypeAtIndex(Index
);
3493 // Update CurTy to its element type.
3494 CurTy
= cast
<SequentialType
>(CurTy
)->getElementType();
3495 // For an array, add the element offset, explicitly scaled.
3496 const SCEV
*ElementSize
= getSizeOfExpr(IntPtrTy
, CurTy
);
3497 // Getelementptr indices are signed.
3498 IndexExpr
= getTruncateOrSignExtend(IndexExpr
, IntPtrTy
);
3500 // Multiply the index by the element size to compute the element offset.
3501 const SCEV
*LocalOffset
= getMulExpr(IndexExpr
, ElementSize
, Wrap
);
3503 // Add the element offset to the running total offset.
3504 TotalOffset
= getAddExpr(TotalOffset
, LocalOffset
);
3508 // Add the total offset from all the GEP indices to the base.
3509 return getAddExpr(BaseExpr
, TotalOffset
, Wrap
);
3512 const SCEV
*ScalarEvolution::getSMaxExpr(const SCEV
*LHS
,
3514 SmallVector
<const SCEV
*, 2> Ops
= {LHS
, RHS
};
3515 return getSMaxExpr(Ops
);
3519 ScalarEvolution::getSMaxExpr(SmallVectorImpl
<const SCEV
*> &Ops
) {
3520 assert(!Ops
.empty() && "Cannot get empty smax!");
3521 if (Ops
.size() == 1) return Ops
[0];
3523 Type
*ETy
= getEffectiveSCEVType(Ops
[0]->getType());
3524 for (unsigned i
= 1, e
= Ops
.size(); i
!= e
; ++i
)
3525 assert(getEffectiveSCEVType(Ops
[i
]->getType()) == ETy
&&
3526 "SCEVSMaxExpr operand types don't match!");
3529 // Sort by complexity, this groups all similar expression types together.
3530 GroupByComplexity(Ops
, &LI
, DT
);
3532 // If there are any constants, fold them together.
3534 if (const SCEVConstant
*LHSC
= dyn_cast
<SCEVConstant
>(Ops
[0])) {
3536 assert(Idx
< Ops
.size());
3537 while (const SCEVConstant
*RHSC
= dyn_cast
<SCEVConstant
>(Ops
[Idx
])) {
3538 // We found two constants, fold them together!
3539 ConstantInt
*Fold
= ConstantInt::get(
3540 getContext(), APIntOps::smax(LHSC
->getAPInt(), RHSC
->getAPInt()));
3541 Ops
[0] = getConstant(Fold
);
3542 Ops
.erase(Ops
.begin()+1); // Erase the folded element
3543 if (Ops
.size() == 1) return Ops
[0];
3544 LHSC
= cast
<SCEVConstant
>(Ops
[0]);
3547 // If we are left with a constant minimum-int, strip it off.
3548 if (cast
<SCEVConstant
>(Ops
[0])->getValue()->isMinValue(true)) {
3549 Ops
.erase(Ops
.begin());
3551 } else if (cast
<SCEVConstant
>(Ops
[0])->getValue()->isMaxValue(true)) {
3552 // If we have an smax with a constant maximum-int, it will always be
3557 if (Ops
.size() == 1) return Ops
[0];
3560 // Find the first SMax
3561 while (Idx
< Ops
.size() && Ops
[Idx
]->getSCEVType() < scSMaxExpr
)
3564 // Check to see if one of the operands is an SMax. If so, expand its operands
3565 // onto our operand list, and recurse to simplify.
3566 if (Idx
< Ops
.size()) {
3567 bool DeletedSMax
= false;
3568 while (const SCEVSMaxExpr
*SMax
= dyn_cast
<SCEVSMaxExpr
>(Ops
[Idx
])) {
3569 Ops
.erase(Ops
.begin()+Idx
);
3570 Ops
.append(SMax
->op_begin(), SMax
->op_end());
3575 return getSMaxExpr(Ops
);
3578 // Okay, check to see if the same value occurs in the operand list twice. If
3579 // so, delete one. Since we sorted the list, these values are required to
3581 for (unsigned i
= 0, e
= Ops
.size()-1; i
!= e
; ++i
)
3582 // X smax Y smax Y --> X smax Y
3583 // X smax Y --> X, if X is always greater than Y
3584 if (Ops
[i
] == Ops
[i
+1] ||
3585 isKnownPredicate(ICmpInst::ICMP_SGE
, Ops
[i
], Ops
[i
+1])) {
3586 Ops
.erase(Ops
.begin()+i
+1, Ops
.begin()+i
+2);
3588 } else if (isKnownPredicate(ICmpInst::ICMP_SLE
, Ops
[i
], Ops
[i
+1])) {
3589 Ops
.erase(Ops
.begin()+i
, Ops
.begin()+i
+1);
3593 if (Ops
.size() == 1) return Ops
[0];
3595 assert(!Ops
.empty() && "Reduced smax down to nothing!");
3597 // Okay, it looks like we really DO need an smax expr. Check to see if we
3598 // already have one, otherwise create a new one.
3599 FoldingSetNodeID ID
;
3600 ID
.AddInteger(scSMaxExpr
);
3601 for (unsigned i
= 0, e
= Ops
.size(); i
!= e
; ++i
)
3602 ID
.AddPointer(Ops
[i
]);
3604 if (const SCEV
*S
= UniqueSCEVs
.FindNodeOrInsertPos(ID
, IP
)) return S
;
3605 const SCEV
**O
= SCEVAllocator
.Allocate
<const SCEV
*>(Ops
.size());
3606 std::uninitialized_copy(Ops
.begin(), Ops
.end(), O
);
3607 SCEV
*S
= new (SCEVAllocator
) SCEVSMaxExpr(ID
.Intern(SCEVAllocator
),
3609 UniqueSCEVs
.InsertNode(S
, IP
);
3610 addToLoopUseLists(S
);
3614 const SCEV
*ScalarEvolution::getUMaxExpr(const SCEV
*LHS
,
3616 SmallVector
<const SCEV
*, 2> Ops
= {LHS
, RHS
};
3617 return getUMaxExpr(Ops
);
3621 ScalarEvolution::getUMaxExpr(SmallVectorImpl
<const SCEV
*> &Ops
) {
3622 assert(!Ops
.empty() && "Cannot get empty umax!");
3623 if (Ops
.size() == 1) return Ops
[0];
3625 Type
*ETy
= getEffectiveSCEVType(Ops
[0]->getType());
3626 for (unsigned i
= 1, e
= Ops
.size(); i
!= e
; ++i
)
3627 assert(getEffectiveSCEVType(Ops
[i
]->getType()) == ETy
&&
3628 "SCEVUMaxExpr operand types don't match!");
3631 // Sort by complexity, this groups all similar expression types together.
3632 GroupByComplexity(Ops
, &LI
, DT
);
3634 // If there are any constants, fold them together.
3636 if (const SCEVConstant
*LHSC
= dyn_cast
<SCEVConstant
>(Ops
[0])) {
3638 assert(Idx
< Ops
.size());
3639 while (const SCEVConstant
*RHSC
= dyn_cast
<SCEVConstant
>(Ops
[Idx
])) {
3640 // We found two constants, fold them together!
3641 ConstantInt
*Fold
= ConstantInt::get(
3642 getContext(), APIntOps::umax(LHSC
->getAPInt(), RHSC
->getAPInt()));
3643 Ops
[0] = getConstant(Fold
);
3644 Ops
.erase(Ops
.begin()+1); // Erase the folded element
3645 if (Ops
.size() == 1) return Ops
[0];
3646 LHSC
= cast
<SCEVConstant
>(Ops
[0]);
3649 // If we are left with a constant minimum-int, strip it off.
3650 if (cast
<SCEVConstant
>(Ops
[0])->getValue()->isMinValue(false)) {
3651 Ops
.erase(Ops
.begin());
3653 } else if (cast
<SCEVConstant
>(Ops
[0])->getValue()->isMaxValue(false)) {
3654 // If we have an umax with a constant maximum-int, it will always be
3659 if (Ops
.size() == 1) return Ops
[0];
3662 // Find the first UMax
3663 while (Idx
< Ops
.size() && Ops
[Idx
]->getSCEVType() < scUMaxExpr
)
3666 // Check to see if one of the operands is a UMax. If so, expand its operands
3667 // onto our operand list, and recurse to simplify.
3668 if (Idx
< Ops
.size()) {
3669 bool DeletedUMax
= false;
3670 while (const SCEVUMaxExpr
*UMax
= dyn_cast
<SCEVUMaxExpr
>(Ops
[Idx
])) {
3671 Ops
.erase(Ops
.begin()+Idx
);
3672 Ops
.append(UMax
->op_begin(), UMax
->op_end());
3677 return getUMaxExpr(Ops
);
3680 // Okay, check to see if the same value occurs in the operand list twice. If
3681 // so, delete one. Since we sorted the list, these values are required to
3683 for (unsigned i
= 0, e
= Ops
.size()-1; i
!= e
; ++i
)
3684 // X umax Y umax Y --> X umax Y
3685 // X umax Y --> X, if X is always greater than Y
3686 if (Ops
[i
] == Ops
[i
+ 1] || isKnownViaNonRecursiveReasoning(
3687 ICmpInst::ICMP_UGE
, Ops
[i
], Ops
[i
+ 1])) {
3688 Ops
.erase(Ops
.begin() + i
+ 1, Ops
.begin() + i
+ 2);
3690 } else if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE
, Ops
[i
],
3692 Ops
.erase(Ops
.begin() + i
, Ops
.begin() + i
+ 1);
3696 if (Ops
.size() == 1) return Ops
[0];
3698 assert(!Ops
.empty() && "Reduced umax down to nothing!");
3700 // Okay, it looks like we really DO need a umax expr. Check to see if we
3701 // already have one, otherwise create a new one.
3702 FoldingSetNodeID ID
;
3703 ID
.AddInteger(scUMaxExpr
);
3704 for (unsigned i
= 0, e
= Ops
.size(); i
!= e
; ++i
)
3705 ID
.AddPointer(Ops
[i
]);
3707 if (const SCEV
*S
= UniqueSCEVs
.FindNodeOrInsertPos(ID
, IP
)) return S
;
3708 const SCEV
**O
= SCEVAllocator
.Allocate
<const SCEV
*>(Ops
.size());
3709 std::uninitialized_copy(Ops
.begin(), Ops
.end(), O
);
3710 SCEV
*S
= new (SCEVAllocator
) SCEVUMaxExpr(ID
.Intern(SCEVAllocator
),
3712 UniqueSCEVs
.InsertNode(S
, IP
);
3713 addToLoopUseLists(S
);
3717 const SCEV
*ScalarEvolution::getSMinExpr(const SCEV
*LHS
,
3719 SmallVector
<const SCEV
*, 2> Ops
= { LHS
, RHS
};
3720 return getSMinExpr(Ops
);
3723 const SCEV
*ScalarEvolution::getSMinExpr(SmallVectorImpl
<const SCEV
*> &Ops
) {
3724 // ~smax(~x, ~y, ~z) == smin(x, y, z).
3725 SmallVector
<const SCEV
*, 2> NotOps
;
3727 NotOps
.push_back(getNotSCEV(S
));
3728 return getNotSCEV(getSMaxExpr(NotOps
));
3731 const SCEV
*ScalarEvolution::getUMinExpr(const SCEV
*LHS
,
3733 SmallVector
<const SCEV
*, 2> Ops
= { LHS
, RHS
};
3734 return getUMinExpr(Ops
);
3737 const SCEV
*ScalarEvolution::getUMinExpr(SmallVectorImpl
<const SCEV
*> &Ops
) {
3738 assert(!Ops
.empty() && "At least one operand must be!");
3740 if (Ops
.size() == 1)
3743 // ~umax(~x, ~y, ~z) == umin(x, y, z).
3744 SmallVector
<const SCEV
*, 2> NotOps
;
3746 NotOps
.push_back(getNotSCEV(S
));
3747 return getNotSCEV(getUMaxExpr(NotOps
));
3750 const SCEV
*ScalarEvolution::getSizeOfExpr(Type
*IntTy
, Type
*AllocTy
) {
3751 // We can bypass creating a target-independent
3752 // constant expression and then folding it back into a ConstantInt.
3753 // This is just a compile-time optimization.
3754 return getConstant(IntTy
, getDataLayout().getTypeAllocSize(AllocTy
));
3757 const SCEV
*ScalarEvolution::getOffsetOfExpr(Type
*IntTy
,
3760 // We can bypass creating a target-independent
3761 // constant expression and then folding it back into a ConstantInt.
3762 // This is just a compile-time optimization.
3764 IntTy
, getDataLayout().getStructLayout(STy
)->getElementOffset(FieldNo
));
3767 const SCEV
*ScalarEvolution::getUnknown(Value
*V
) {
3768 // Don't attempt to do anything other than create a SCEVUnknown object
3769 // here. createSCEV only calls getUnknown after checking for all other
3770 // interesting possibilities, and any other code that calls getUnknown
3771 // is doing so in order to hide a value from SCEV canonicalization.
3773 FoldingSetNodeID ID
;
3774 ID
.AddInteger(scUnknown
);
3777 if (SCEV
*S
= UniqueSCEVs
.FindNodeOrInsertPos(ID
, IP
)) {
3778 assert(cast
<SCEVUnknown
>(S
)->getValue() == V
&&
3779 "Stale SCEVUnknown in uniquing map!");
3782 SCEV
*S
= new (SCEVAllocator
) SCEVUnknown(ID
.Intern(SCEVAllocator
), V
, this,
3784 FirstUnknown
= cast
<SCEVUnknown
>(S
);
3785 UniqueSCEVs
.InsertNode(S
, IP
);
3789 //===----------------------------------------------------------------------===//
3790 // Basic SCEV Analysis and PHI Idiom Recognition Code
3793 /// Test if values of the given type are analyzable within the SCEV
3794 /// framework. This primarily includes integer types, and it can optionally
3795 /// include pointer types if the ScalarEvolution class has access to
3796 /// target-specific information.
3797 bool ScalarEvolution::isSCEVable(Type
*Ty
) const {
3798 // Integers and pointers are always SCEVable.
3799 return Ty
->isIntOrPtrTy();
3802 /// Return the size in bits of the specified type, for which isSCEVable must
3804 uint64_t ScalarEvolution::getTypeSizeInBits(Type
*Ty
) const {
3805 assert(isSCEVable(Ty
) && "Type is not SCEVable!");
3806 if (Ty
->isPointerTy())
3807 return getDataLayout().getIndexTypeSizeInBits(Ty
);
3808 return getDataLayout().getTypeSizeInBits(Ty
);
3811 /// Return a type with the same bitwidth as the given type and which represents
3812 /// how SCEV will treat the given type, for which isSCEVable must return
3813 /// true. For pointer types, this is the pointer-sized integer type.
3814 Type
*ScalarEvolution::getEffectiveSCEVType(Type
*Ty
) const {
3815 assert(isSCEVable(Ty
) && "Type is not SCEVable!");
3817 if (Ty
->isIntegerTy())
3820 // The only other support type is pointer.
3821 assert(Ty
->isPointerTy() && "Unexpected non-pointer non-integer type!");
3822 return getDataLayout().getIntPtrType(Ty
);
3825 Type
*ScalarEvolution::getWiderType(Type
*T1
, Type
*T2
) const {
3826 return getTypeSizeInBits(T1
) >= getTypeSizeInBits(T2
) ? T1
: T2
;
3829 const SCEV
*ScalarEvolution::getCouldNotCompute() {
3830 return CouldNotCompute
.get();
3833 bool ScalarEvolution::checkValidity(const SCEV
*S
) const {
3834 bool ContainsNulls
= SCEVExprContains(S
, [](const SCEV
*S
) {
3835 auto *SU
= dyn_cast
<SCEVUnknown
>(S
);
3836 return SU
&& SU
->getValue() == nullptr;
3839 return !ContainsNulls
;
3842 bool ScalarEvolution::containsAddRecurrence(const SCEV
*S
) {
3843 HasRecMapType::iterator I
= HasRecMap
.find(S
);
3844 if (I
!= HasRecMap
.end())
3847 bool FoundAddRec
= SCEVExprContains(S
, isa
<SCEVAddRecExpr
, const SCEV
*>);
3848 HasRecMap
.insert({S
, FoundAddRec
});
3852 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3853 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3854 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3855 static std::pair
<const SCEV
*, ConstantInt
*> splitAddExpr(const SCEV
*S
) {
3856 const auto *Add
= dyn_cast
<SCEVAddExpr
>(S
);
3858 return {S
, nullptr};
3860 if (Add
->getNumOperands() != 2)
3861 return {S
, nullptr};
3863 auto *ConstOp
= dyn_cast
<SCEVConstant
>(Add
->getOperand(0));
3865 return {S
, nullptr};
3867 return {Add
->getOperand(1), ConstOp
->getValue()};
3870 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3871 /// by the value and offset from any ValueOffsetPair in the set.
3872 SetVector
<ScalarEvolution::ValueOffsetPair
> *
3873 ScalarEvolution::getSCEVValues(const SCEV
*S
) {
3874 ExprValueMapType::iterator SI
= ExprValueMap
.find_as(S
);
3875 if (SI
== ExprValueMap
.end())
3878 if (VerifySCEVMap
) {
3879 // Check there is no dangling Value in the set returned.
3880 for (const auto &VE
: SI
->second
)
3881 assert(ValueExprMap
.count(VE
.first
));
3887 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3888 /// cannot be used separately. eraseValueFromMap should be used to remove
3889 /// V from ValueExprMap and ExprValueMap at the same time.
3890 void ScalarEvolution::eraseValueFromMap(Value
*V
) {
3891 ValueExprMapType::iterator I
= ValueExprMap
.find_as(V
);
3892 if (I
!= ValueExprMap
.end()) {
3893 const SCEV
*S
= I
->second
;
3894 // Remove {V, 0} from the set of ExprValueMap[S]
3895 if (SetVector
<ValueOffsetPair
> *SV
= getSCEVValues(S
))
3896 SV
->remove({V
, nullptr});
3898 // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3899 const SCEV
*Stripped
;
3900 ConstantInt
*Offset
;
3901 std::tie(Stripped
, Offset
) = splitAddExpr(S
);
3902 if (Offset
!= nullptr) {
3903 if (SetVector
<ValueOffsetPair
> *SV
= getSCEVValues(Stripped
))
3904 SV
->remove({V
, Offset
});
3906 ValueExprMap
.erase(V
);
3910 /// Check whether value has nuw/nsw/exact set but SCEV does not.
3911 /// TODO: In reality it is better to check the poison recursively
3912 /// but this is better than nothing.
3913 static bool SCEVLostPoisonFlags(const SCEV
*S
, const Value
*V
) {
3914 if (auto *I
= dyn_cast
<Instruction
>(V
)) {
3915 if (isa
<OverflowingBinaryOperator
>(I
)) {
3916 if (auto *NS
= dyn_cast
<SCEVNAryExpr
>(S
)) {
3917 if (I
->hasNoSignedWrap() && !NS
->hasNoSignedWrap())
3919 if (I
->hasNoUnsignedWrap() && !NS
->hasNoUnsignedWrap())
3922 } else if (isa
<PossiblyExactOperator
>(I
) && I
->isExact())
3928 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3929 /// create a new one.
3930 const SCEV
*ScalarEvolution::getSCEV(Value
*V
) {
3931 assert(isSCEVable(V
->getType()) && "Value is not SCEVable!");
3933 const SCEV
*S
= getExistingSCEV(V
);
3936 // During PHI resolution, it is possible to create two SCEVs for the same
3937 // V, so it is needed to double check whether V->S is inserted into
3938 // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3939 std::pair
<ValueExprMapType::iterator
, bool> Pair
=
3940 ValueExprMap
.insert({SCEVCallbackVH(V
, this), S
});
3941 if (Pair
.second
&& !SCEVLostPoisonFlags(S
, V
)) {
3942 ExprValueMap
[S
].insert({V
, nullptr});
3944 // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3946 const SCEV
*Stripped
= S
;
3947 ConstantInt
*Offset
= nullptr;
3948 std::tie(Stripped
, Offset
) = splitAddExpr(S
);
3949 // If stripped is SCEVUnknown, don't bother to save
3950 // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3951 // increase the complexity of the expansion code.
3952 // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3953 // because it may generate add/sub instead of GEP in SCEV expansion.
3954 if (Offset
!= nullptr && !isa
<SCEVUnknown
>(Stripped
) &&
3955 !isa
<GetElementPtrInst
>(V
))
3956 ExprValueMap
[Stripped
].insert({V
, Offset
});
3962 const SCEV
*ScalarEvolution::getExistingSCEV(Value
*V
) {
3963 assert(isSCEVable(V
->getType()) && "Value is not SCEVable!");
3965 ValueExprMapType::iterator I
= ValueExprMap
.find_as(V
);
3966 if (I
!= ValueExprMap
.end()) {
3967 const SCEV
*S
= I
->second
;
3968 if (checkValidity(S
))
3970 eraseValueFromMap(V
);
3971 forgetMemoizedResults(S
);
3976 /// Return a SCEV corresponding to -V = -1*V
3977 const SCEV
*ScalarEvolution::getNegativeSCEV(const SCEV
*V
,
3978 SCEV::NoWrapFlags Flags
) {
3979 if (const SCEVConstant
*VC
= dyn_cast
<SCEVConstant
>(V
))
3981 cast
<ConstantInt
>(ConstantExpr::getNeg(VC
->getValue())));
3983 Type
*Ty
= V
->getType();
3984 Ty
= getEffectiveSCEVType(Ty
);
3986 V
, getConstant(cast
<ConstantInt
>(Constant::getAllOnesValue(Ty
))), Flags
);
3989 /// Return a SCEV corresponding to ~V = -1-V
3990 const SCEV
*ScalarEvolution::getNotSCEV(const SCEV
*V
) {
3991 if (const SCEVConstant
*VC
= dyn_cast
<SCEVConstant
>(V
))
3993 cast
<ConstantInt
>(ConstantExpr::getNot(VC
->getValue())));
3995 Type
*Ty
= V
->getType();
3996 Ty
= getEffectiveSCEVType(Ty
);
3997 const SCEV
*AllOnes
=
3998 getConstant(cast
<ConstantInt
>(Constant::getAllOnesValue(Ty
)));
3999 return getMinusSCEV(AllOnes
, V
);
4002 const SCEV
*ScalarEvolution::getMinusSCEV(const SCEV
*LHS
, const SCEV
*RHS
,
4003 SCEV::NoWrapFlags Flags
,
4005 // Fast path: X - X --> 0.
4007 return getZero(LHS
->getType());
4009 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4010 // makes it so that we cannot make much use of NUW.
4011 auto AddFlags
= SCEV::FlagAnyWrap
;
4012 const bool RHSIsNotMinSigned
=
4013 !getSignedRangeMin(RHS
).isMinSignedValue();
4014 if (maskFlags(Flags
, SCEV::FlagNSW
) == SCEV::FlagNSW
) {
4015 // Let M be the minimum representable signed value. Then (-1)*RHS
4016 // signed-wraps if and only if RHS is M. That can happen even for
4017 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4018 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4019 // (-1)*RHS, we need to prove that RHS != M.
4021 // If LHS is non-negative and we know that LHS - RHS does not
4022 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4023 // either by proving that RHS > M or that LHS >= 0.
4024 if (RHSIsNotMinSigned
|| isKnownNonNegative(LHS
)) {
4025 AddFlags
= SCEV::FlagNSW
;
4029 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4030 // RHS is NSW and LHS >= 0.
4032 // The difficulty here is that the NSW flag may have been proven
4033 // relative to a loop that is to be found in a recurrence in LHS and
4034 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4035 // larger scope than intended.
4036 auto NegFlags
= RHSIsNotMinSigned
? SCEV::FlagNSW
: SCEV::FlagAnyWrap
;
4038 return getAddExpr(LHS
, getNegativeSCEV(RHS
, NegFlags
), AddFlags
, Depth
);
4042 ScalarEvolution::getTruncateOrZeroExtend(const SCEV
*V
, Type
*Ty
) {
4043 Type
*SrcTy
= V
->getType();
4044 assert(SrcTy
->isIntOrPtrTy() && Ty
->isIntOrPtrTy() &&
4045 "Cannot truncate or zero extend with non-integer arguments!");
4046 if (getTypeSizeInBits(SrcTy
) == getTypeSizeInBits(Ty
))
4047 return V
; // No conversion
4048 if (getTypeSizeInBits(SrcTy
) > getTypeSizeInBits(Ty
))
4049 return getTruncateExpr(V
, Ty
);
4050 return getZeroExtendExpr(V
, Ty
);
4054 ScalarEvolution::getTruncateOrSignExtend(const SCEV
*V
,
4056 Type
*SrcTy
= V
->getType();
4057 assert(SrcTy
->isIntOrPtrTy() && Ty
->isIntOrPtrTy() &&
4058 "Cannot truncate or zero extend with non-integer arguments!");
4059 if (getTypeSizeInBits(SrcTy
) == getTypeSizeInBits(Ty
))
4060 return V
; // No conversion
4061 if (getTypeSizeInBits(SrcTy
) > getTypeSizeInBits(Ty
))
4062 return getTruncateExpr(V
, Ty
);
4063 return getSignExtendExpr(V
, Ty
);
4067 ScalarEvolution::getNoopOrZeroExtend(const SCEV
*V
, Type
*Ty
) {
4068 Type
*SrcTy
= V
->getType();
4069 assert(SrcTy
->isIntOrPtrTy() && Ty
->isIntOrPtrTy() &&
4070 "Cannot noop or zero extend with non-integer arguments!");
4071 assert(getTypeSizeInBits(SrcTy
) <= getTypeSizeInBits(Ty
) &&
4072 "getNoopOrZeroExtend cannot truncate!");
4073 if (getTypeSizeInBits(SrcTy
) == getTypeSizeInBits(Ty
))
4074 return V
; // No conversion
4075 return getZeroExtendExpr(V
, Ty
);
4079 ScalarEvolution::getNoopOrSignExtend(const SCEV
*V
, Type
*Ty
) {
4080 Type
*SrcTy
= V
->getType();
4081 assert(SrcTy
->isIntOrPtrTy() && Ty
->isIntOrPtrTy() &&
4082 "Cannot noop or sign extend with non-integer arguments!");
4083 assert(getTypeSizeInBits(SrcTy
) <= getTypeSizeInBits(Ty
) &&
4084 "getNoopOrSignExtend cannot truncate!");
4085 if (getTypeSizeInBits(SrcTy
) == getTypeSizeInBits(Ty
))
4086 return V
; // No conversion
4087 return getSignExtendExpr(V
, Ty
);
4091 ScalarEvolution::getNoopOrAnyExtend(const SCEV
*V
, Type
*Ty
) {
4092 Type
*SrcTy
= V
->getType();
4093 assert(SrcTy
->isIntOrPtrTy() && Ty
->isIntOrPtrTy() &&
4094 "Cannot noop or any extend with non-integer arguments!");
4095 assert(getTypeSizeInBits(SrcTy
) <= getTypeSizeInBits(Ty
) &&
4096 "getNoopOrAnyExtend cannot truncate!");
4097 if (getTypeSizeInBits(SrcTy
) == getTypeSizeInBits(Ty
))
4098 return V
; // No conversion
4099 return getAnyExtendExpr(V
, Ty
);
4103 ScalarEvolution::getTruncateOrNoop(const SCEV
*V
, Type
*Ty
) {
4104 Type
*SrcTy
= V
->getType();
4105 assert(SrcTy
->isIntOrPtrTy() && Ty
->isIntOrPtrTy() &&
4106 "Cannot truncate or noop with non-integer arguments!");
4107 assert(getTypeSizeInBits(SrcTy
) >= getTypeSizeInBits(Ty
) &&
4108 "getTruncateOrNoop cannot extend!");
4109 if (getTypeSizeInBits(SrcTy
) == getTypeSizeInBits(Ty
))
4110 return V
; // No conversion
4111 return getTruncateExpr(V
, Ty
);
4114 const SCEV
*ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV
*LHS
,
4116 const SCEV
*PromotedLHS
= LHS
;
4117 const SCEV
*PromotedRHS
= RHS
;
4119 if (getTypeSizeInBits(LHS
->getType()) > getTypeSizeInBits(RHS
->getType()))
4120 PromotedRHS
= getZeroExtendExpr(RHS
, LHS
->getType());
4122 PromotedLHS
= getNoopOrZeroExtend(LHS
, RHS
->getType());
4124 return getUMaxExpr(PromotedLHS
, PromotedRHS
);
4127 const SCEV
*ScalarEvolution::getUMinFromMismatchedTypes(const SCEV
*LHS
,
4129 SmallVector
<const SCEV
*, 2> Ops
= { LHS
, RHS
};
4130 return getUMinFromMismatchedTypes(Ops
);
4133 const SCEV
*ScalarEvolution::getUMinFromMismatchedTypes(
4134 SmallVectorImpl
<const SCEV
*> &Ops
) {
4135 assert(!Ops
.empty() && "At least one operand must be!");
4137 if (Ops
.size() == 1)
4140 // Find the max type first.
4141 Type
*MaxType
= nullptr;
4144 MaxType
= getWiderType(MaxType
, S
->getType());
4146 MaxType
= S
->getType();
4148 // Extend all ops to max type.
4149 SmallVector
<const SCEV
*, 2> PromotedOps
;
4151 PromotedOps
.push_back(getNoopOrZeroExtend(S
, MaxType
));
4154 return getUMinExpr(PromotedOps
);
4157 const SCEV
*ScalarEvolution::getPointerBase(const SCEV
*V
) {
4158 // A pointer operand may evaluate to a nonpointer expression, such as null.
4159 if (!V
->getType()->isPointerTy())
4162 if (const SCEVCastExpr
*Cast
= dyn_cast
<SCEVCastExpr
>(V
)) {
4163 return getPointerBase(Cast
->getOperand());
4164 } else if (const SCEVNAryExpr
*NAry
= dyn_cast
<SCEVNAryExpr
>(V
)) {
4165 const SCEV
*PtrOp
= nullptr;
4166 for (const SCEV
*NAryOp
: NAry
->operands()) {
4167 if (NAryOp
->getType()->isPointerTy()) {
4168 // Cannot find the base of an expression with multiple pointer operands.
4176 return getPointerBase(PtrOp
);
4181 /// Push users of the given Instruction onto the given Worklist.
4183 PushDefUseChildren(Instruction
*I
,
4184 SmallVectorImpl
<Instruction
*> &Worklist
) {
4185 // Push the def-use children onto the Worklist stack.
4186 for (User
*U
: I
->users())
4187 Worklist
.push_back(cast
<Instruction
>(U
));
4190 void ScalarEvolution::forgetSymbolicName(Instruction
*PN
, const SCEV
*SymName
) {
4191 SmallVector
<Instruction
*, 16> Worklist
;
4192 PushDefUseChildren(PN
, Worklist
);
4194 SmallPtrSet
<Instruction
*, 8> Visited
;
4196 while (!Worklist
.empty()) {
4197 Instruction
*I
= Worklist
.pop_back_val();
4198 if (!Visited
.insert(I
).second
)
4201 auto It
= ValueExprMap
.find_as(static_cast<Value
*>(I
));
4202 if (It
!= ValueExprMap
.end()) {
4203 const SCEV
*Old
= It
->second
;
4205 // Short-circuit the def-use traversal if the symbolic name
4206 // ceases to appear in expressions.
4207 if (Old
!= SymName
&& !hasOperand(Old
, SymName
))
4210 // SCEVUnknown for a PHI either means that it has an unrecognized
4211 // structure, it's a PHI that's in the progress of being computed
4212 // by createNodeForPHI, or it's a single-value PHI. In the first case,
4213 // additional loop trip count information isn't going to change anything.
4214 // In the second case, createNodeForPHI will perform the necessary
4215 // updates on its own when it gets to that point. In the third, we do
4216 // want to forget the SCEVUnknown.
4217 if (!isa
<PHINode
>(I
) ||
4218 !isa
<SCEVUnknown
>(Old
) ||
4219 (I
!= PN
&& Old
== SymName
)) {
4220 eraseValueFromMap(It
->first
);
4221 forgetMemoizedResults(Old
);
4225 PushDefUseChildren(I
, Worklist
);
4231 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4232 /// expression in case its Loop is L. If it is not L then
4233 /// if IgnoreOtherLoops is true then use AddRec itself
4234 /// otherwise rewrite cannot be done.
4235 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4236 class SCEVInitRewriter
: public SCEVRewriteVisitor
<SCEVInitRewriter
> {
4238 static const SCEV
*rewrite(const SCEV
*S
, const Loop
*L
, ScalarEvolution
&SE
,
4239 bool IgnoreOtherLoops
= true) {
4240 SCEVInitRewriter
Rewriter(L
, SE
);
4241 const SCEV
*Result
= Rewriter
.visit(S
);
4242 if (Rewriter
.hasSeenLoopVariantSCEVUnknown())
4243 return SE
.getCouldNotCompute();
4244 return Rewriter
.hasSeenOtherLoops() && !IgnoreOtherLoops
4245 ? SE
.getCouldNotCompute()
4249 const SCEV
*visitUnknown(const SCEVUnknown
*Expr
) {
4250 if (!SE
.isLoopInvariant(Expr
, L
))
4251 SeenLoopVariantSCEVUnknown
= true;
4255 const SCEV
*visitAddRecExpr(const SCEVAddRecExpr
*Expr
) {
4256 // Only re-write AddRecExprs for this loop.
4257 if (Expr
->getLoop() == L
)
4258 return Expr
->getStart();
4259 SeenOtherLoops
= true;
4263 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown
; }
4265 bool hasSeenOtherLoops() { return SeenOtherLoops
; }
4268 explicit SCEVInitRewriter(const Loop
*L
, ScalarEvolution
&SE
)
4269 : SCEVRewriteVisitor(SE
), L(L
) {}
4272 bool SeenLoopVariantSCEVUnknown
= false;
4273 bool SeenOtherLoops
= false;
4276 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4277 /// increment expression in case its Loop is L. If it is not L then
4278 /// use AddRec itself.
4279 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4280 class SCEVPostIncRewriter
: public SCEVRewriteVisitor
<SCEVPostIncRewriter
> {
4282 static const SCEV
*rewrite(const SCEV
*S
, const Loop
*L
, ScalarEvolution
&SE
) {
4283 SCEVPostIncRewriter
Rewriter(L
, SE
);
4284 const SCEV
*Result
= Rewriter
.visit(S
);
4285 return Rewriter
.hasSeenLoopVariantSCEVUnknown()
4286 ? SE
.getCouldNotCompute()
4290 const SCEV
*visitUnknown(const SCEVUnknown
*Expr
) {
4291 if (!SE
.isLoopInvariant(Expr
, L
))
4292 SeenLoopVariantSCEVUnknown
= true;
4296 const SCEV
*visitAddRecExpr(const SCEVAddRecExpr
*Expr
) {
4297 // Only re-write AddRecExprs for this loop.
4298 if (Expr
->getLoop() == L
)
4299 return Expr
->getPostIncExpr(SE
);
4300 SeenOtherLoops
= true;
4304 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown
; }
4306 bool hasSeenOtherLoops() { return SeenOtherLoops
; }
4309 explicit SCEVPostIncRewriter(const Loop
*L
, ScalarEvolution
&SE
)
4310 : SCEVRewriteVisitor(SE
), L(L
) {}
4313 bool SeenLoopVariantSCEVUnknown
= false;
4314 bool SeenOtherLoops
= false;
4317 /// This class evaluates the compare condition by matching it against the
4318 /// condition of loop latch. If there is a match we assume a true value
4319 /// for the condition while building SCEV nodes.
4320 class SCEVBackedgeConditionFolder
4321 : public SCEVRewriteVisitor
<SCEVBackedgeConditionFolder
> {
4323 static const SCEV
*rewrite(const SCEV
*S
, const Loop
*L
,
4324 ScalarEvolution
&SE
) {
4325 bool IsPosBECond
= false;
4326 Value
*BECond
= nullptr;
4327 if (BasicBlock
*Latch
= L
->getLoopLatch()) {
4328 BranchInst
*BI
= dyn_cast
<BranchInst
>(Latch
->getTerminator());
4329 if (BI
&& BI
->isConditional()) {
4330 assert(BI
->getSuccessor(0) != BI
->getSuccessor(1) &&
4331 "Both outgoing branches should not target same header!");
4332 BECond
= BI
->getCondition();
4333 IsPosBECond
= BI
->getSuccessor(0) == L
->getHeader();
4338 SCEVBackedgeConditionFolder
Rewriter(L
, BECond
, IsPosBECond
, SE
);
4339 return Rewriter
.visit(S
);
4342 const SCEV
*visitUnknown(const SCEVUnknown
*Expr
) {
4343 const SCEV
*Result
= Expr
;
4344 bool InvariantF
= SE
.isLoopInvariant(Expr
, L
);
4347 Instruction
*I
= cast
<Instruction
>(Expr
->getValue());
4348 switch (I
->getOpcode()) {
4349 case Instruction::Select
: {
4350 SelectInst
*SI
= cast
<SelectInst
>(I
);
4351 Optional
<const SCEV
*> Res
=
4352 compareWithBackedgeCondition(SI
->getCondition());
4353 if (Res
.hasValue()) {
4354 bool IsOne
= cast
<SCEVConstant
>(Res
.getValue())->getValue()->isOne();
4355 Result
= SE
.getSCEV(IsOne
? SI
->getTrueValue() : SI
->getFalseValue());
4360 Optional
<const SCEV
*> Res
= compareWithBackedgeCondition(I
);
4362 Result
= Res
.getValue();
4371 explicit SCEVBackedgeConditionFolder(const Loop
*L
, Value
*BECond
,
4372 bool IsPosBECond
, ScalarEvolution
&SE
)
4373 : SCEVRewriteVisitor(SE
), L(L
), BackedgeCond(BECond
),
4374 IsPositiveBECond(IsPosBECond
) {}
4376 Optional
<const SCEV
*> compareWithBackedgeCondition(Value
*IC
);
4379 /// Loop back condition.
4380 Value
*BackedgeCond
= nullptr;
4381 /// Set to true if loop back is on positive branch condition.
4382 bool IsPositiveBECond
;
4385 Optional
<const SCEV
*>
4386 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value
*IC
) {
4388 // If value matches the backedge condition for loop latch,
4389 // then return a constant evolution node based on loopback
4391 if (BackedgeCond
== IC
)
4392 return IsPositiveBECond
? SE
.getOne(Type::getInt1Ty(SE
.getContext()))
4393 : SE
.getZero(Type::getInt1Ty(SE
.getContext()));
4397 class SCEVShiftRewriter
: public SCEVRewriteVisitor
<SCEVShiftRewriter
> {
4399 static const SCEV
*rewrite(const SCEV
*S
, const Loop
*L
,
4400 ScalarEvolution
&SE
) {
4401 SCEVShiftRewriter
Rewriter(L
, SE
);
4402 const SCEV
*Result
= Rewriter
.visit(S
);
4403 return Rewriter
.isValid() ? Result
: SE
.getCouldNotCompute();
4406 const SCEV
*visitUnknown(const SCEVUnknown
*Expr
) {
4407 // Only allow AddRecExprs for this loop.
4408 if (!SE
.isLoopInvariant(Expr
, L
))
4413 const SCEV
*visitAddRecExpr(const SCEVAddRecExpr
*Expr
) {
4414 if (Expr
->getLoop() == L
&& Expr
->isAffine())
4415 return SE
.getMinusSCEV(Expr
, Expr
->getStepRecurrence(SE
));
4420 bool isValid() { return Valid
; }
4423 explicit SCEVShiftRewriter(const Loop
*L
, ScalarEvolution
&SE
)
4424 : SCEVRewriteVisitor(SE
), L(L
) {}
4430 } // end anonymous namespace
4433 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr
*AR
) {
4434 if (!AR
->isAffine())
4435 return SCEV::FlagAnyWrap
;
4437 using OBO
= OverflowingBinaryOperator
;
4439 SCEV::NoWrapFlags Result
= SCEV::FlagAnyWrap
;
4441 if (!AR
->hasNoSignedWrap()) {
4442 ConstantRange AddRecRange
= getSignedRange(AR
);
4443 ConstantRange IncRange
= getSignedRange(AR
->getStepRecurrence(*this));
4445 auto NSWRegion
= ConstantRange::makeGuaranteedNoWrapRegion(
4446 Instruction::Add
, IncRange
, OBO::NoSignedWrap
);
4447 if (NSWRegion
.contains(AddRecRange
))
4448 Result
= ScalarEvolution::setFlags(Result
, SCEV::FlagNSW
);
4451 if (!AR
->hasNoUnsignedWrap()) {
4452 ConstantRange AddRecRange
= getUnsignedRange(AR
);
4453 ConstantRange IncRange
= getUnsignedRange(AR
->getStepRecurrence(*this));
4455 auto NUWRegion
= ConstantRange::makeGuaranteedNoWrapRegion(
4456 Instruction::Add
, IncRange
, OBO::NoUnsignedWrap
);
4457 if (NUWRegion
.contains(AddRecRange
))
4458 Result
= ScalarEvolution::setFlags(Result
, SCEV::FlagNUW
);
4466 /// Represents an abstract binary operation. This may exist as a
4467 /// normal instruction or constant expression, or may have been
4468 /// derived from an expression tree.
4476 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4477 /// constant expression.
4478 Operator
*Op
= nullptr;
4480 explicit BinaryOp(Operator
*Op
)
4481 : Opcode(Op
->getOpcode()), LHS(Op
->getOperand(0)), RHS(Op
->getOperand(1)),
4483 if (auto *OBO
= dyn_cast
<OverflowingBinaryOperator
>(Op
)) {
4484 IsNSW
= OBO
->hasNoSignedWrap();
4485 IsNUW
= OBO
->hasNoUnsignedWrap();
4489 explicit BinaryOp(unsigned Opcode
, Value
*LHS
, Value
*RHS
, bool IsNSW
= false,
4491 : Opcode(Opcode
), LHS(LHS
), RHS(RHS
), IsNSW(IsNSW
), IsNUW(IsNUW
) {}
4494 } // end anonymous namespace
4496 /// Try to map \p V into a BinaryOp, and return \c None on failure.
4497 static Optional
<BinaryOp
> MatchBinaryOp(Value
*V
, DominatorTree
&DT
) {
4498 auto *Op
= dyn_cast
<Operator
>(V
);
4502 // Implementation detail: all the cleverness here should happen without
4503 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4504 // SCEV expressions when possible, and we should not break that.
4506 switch (Op
->getOpcode()) {
4507 case Instruction::Add
:
4508 case Instruction::Sub
:
4509 case Instruction::Mul
:
4510 case Instruction::UDiv
:
4511 case Instruction::URem
:
4512 case Instruction::And
:
4513 case Instruction::Or
:
4514 case Instruction::AShr
:
4515 case Instruction::Shl
:
4516 return BinaryOp(Op
);
4518 case Instruction::Xor
:
4519 if (auto *RHSC
= dyn_cast
<ConstantInt
>(Op
->getOperand(1)))
4520 // If the RHS of the xor is a signmask, then this is just an add.
4521 // Instcombine turns add of signmask into xor as a strength reduction step.
4522 if (RHSC
->getValue().isSignMask())
4523 return BinaryOp(Instruction::Add
, Op
->getOperand(0), Op
->getOperand(1));
4524 return BinaryOp(Op
);
4526 case Instruction::LShr
:
4527 // Turn logical shift right of a constant into a unsigned divide.
4528 if (ConstantInt
*SA
= dyn_cast
<ConstantInt
>(Op
->getOperand(1))) {
4529 uint32_t BitWidth
= cast
<IntegerType
>(Op
->getType())->getBitWidth();
4531 // If the shift count is not less than the bitwidth, the result of
4532 // the shift is undefined. Don't try to analyze it, because the
4533 // resolution chosen here may differ from the resolution chosen in
4534 // other parts of the compiler.
4535 if (SA
->getValue().ult(BitWidth
)) {
4537 ConstantInt::get(SA
->getContext(),
4538 APInt::getOneBitSet(BitWidth
, SA
->getZExtValue()));
4539 return BinaryOp(Instruction::UDiv
, Op
->getOperand(0), X
);
4542 return BinaryOp(Op
);
4544 case Instruction::ExtractValue
: {
4545 auto *EVI
= cast
<ExtractValueInst
>(Op
);
4546 if (EVI
->getNumIndices() != 1 || EVI
->getIndices()[0] != 0)
4549 auto *CI
= dyn_cast
<CallInst
>(EVI
->getAggregateOperand());
4553 if (auto *F
= CI
->getCalledFunction())
4554 switch (F
->getIntrinsicID()) {
4555 case Intrinsic::sadd_with_overflow
:
4556 case Intrinsic::uadd_with_overflow
:
4557 if (!isOverflowIntrinsicNoWrap(cast
<IntrinsicInst
>(CI
), DT
))
4558 return BinaryOp(Instruction::Add
, CI
->getArgOperand(0),
4559 CI
->getArgOperand(1));
4561 // Now that we know that all uses of the arithmetic-result component of
4562 // CI are guarded by the overflow check, we can go ahead and pretend
4563 // that the arithmetic is non-overflowing.
4564 if (F
->getIntrinsicID() == Intrinsic::sadd_with_overflow
)
4565 return BinaryOp(Instruction::Add
, CI
->getArgOperand(0),
4566 CI
->getArgOperand(1), /* IsNSW = */ true,
4567 /* IsNUW = */ false);
4569 return BinaryOp(Instruction::Add
, CI
->getArgOperand(0),
4570 CI
->getArgOperand(1), /* IsNSW = */ false,
4572 case Intrinsic::ssub_with_overflow
:
4573 case Intrinsic::usub_with_overflow
:
4574 if (!isOverflowIntrinsicNoWrap(cast
<IntrinsicInst
>(CI
), DT
))
4575 return BinaryOp(Instruction::Sub
, CI
->getArgOperand(0),
4576 CI
->getArgOperand(1));
4578 // The same reasoning as sadd/uadd above.
4579 if (F
->getIntrinsicID() == Intrinsic::ssub_with_overflow
)
4580 return BinaryOp(Instruction::Sub
, CI
->getArgOperand(0),
4581 CI
->getArgOperand(1), /* IsNSW = */ true,
4582 /* IsNUW = */ false);
4584 return BinaryOp(Instruction::Sub
, CI
->getArgOperand(0),
4585 CI
->getArgOperand(1), /* IsNSW = */ false,
4586 /* IsNUW = */ true);
4587 case Intrinsic::smul_with_overflow
:
4588 case Intrinsic::umul_with_overflow
:
4589 return BinaryOp(Instruction::Mul
, CI
->getArgOperand(0),
4590 CI
->getArgOperand(1));
4604 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4605 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4606 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4607 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4608 /// follows one of the following patterns:
4609 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4610 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4611 /// If the SCEV expression of \p Op conforms with one of the expected patterns
4612 /// we return the type of the truncation operation, and indicate whether the
4613 /// truncated type should be treated as signed/unsigned by setting
4614 /// \p Signed to true/false, respectively.
4615 static Type
*isSimpleCastedPHI(const SCEV
*Op
, const SCEVUnknown
*SymbolicPHI
,
4616 bool &Signed
, ScalarEvolution
&SE
) {
4617 // The case where Op == SymbolicPHI (that is, with no type conversions on
4618 // the way) is handled by the regular add recurrence creating logic and
4619 // would have already been triggered in createAddRecForPHI. Reaching it here
4620 // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4621 // because one of the other operands of the SCEVAddExpr updating this PHI is
4624 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4625 // this case predicates that allow us to prove that Op == SymbolicPHI will
4627 if (Op
== SymbolicPHI
)
4630 unsigned SourceBits
= SE
.getTypeSizeInBits(SymbolicPHI
->getType());
4631 unsigned NewBits
= SE
.getTypeSizeInBits(Op
->getType());
4632 if (SourceBits
!= NewBits
)
4635 const SCEVSignExtendExpr
*SExt
= dyn_cast
<SCEVSignExtendExpr
>(Op
);
4636 const SCEVZeroExtendExpr
*ZExt
= dyn_cast
<SCEVZeroExtendExpr
>(Op
);
4639 const SCEVTruncateExpr
*Trunc
=
4640 SExt
? dyn_cast
<SCEVTruncateExpr
>(SExt
->getOperand())
4641 : dyn_cast
<SCEVTruncateExpr
>(ZExt
->getOperand());
4644 const SCEV
*X
= Trunc
->getOperand();
4645 if (X
!= SymbolicPHI
)
4647 Signed
= SExt
!= nullptr;
4648 return Trunc
->getType();
4651 static const Loop
*isIntegerLoopHeaderPHI(const PHINode
*PN
, LoopInfo
&LI
) {
4652 if (!PN
->getType()->isIntegerTy())
4654 const Loop
*L
= LI
.getLoopFor(PN
->getParent());
4655 if (!L
|| L
->getHeader() != PN
->getParent())
4660 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4661 // computation that updates the phi follows the following pattern:
4662 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4663 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4664 // If so, try to see if it can be rewritten as an AddRecExpr under some
4665 // Predicates. If successful, return them as a pair. Also cache the results
4668 // Example usage scenario:
4669 // Say the Rewriter is called for the following SCEV:
4670 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4672 // %X = phi i64 (%Start, %BEValue)
4673 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4674 // and call this function with %SymbolicPHI = %X.
4676 // The analysis will find that the value coming around the backedge has
4677 // the following SCEV:
4678 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4679 // Upon concluding that this matches the desired pattern, the function
4680 // will return the pair {NewAddRec, SmallPredsVec} where:
4681 // NewAddRec = {%Start,+,%Step}
4682 // SmallPredsVec = {P1, P2, P3} as follows:
4683 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4684 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4685 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4686 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4687 // under the predicates {P1,P2,P3}.
4688 // This predicated rewrite will be cached in PredicatedSCEVRewrites:
4689 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4693 // 1) Extend the Induction descriptor to also support inductions that involve
4694 // casts: When needed (namely, when we are called in the context of the
4695 // vectorizer induction analysis), a Set of cast instructions will be
4696 // populated by this method, and provided back to isInductionPHI. This is
4697 // needed to allow the vectorizer to properly record them to be ignored by
4698 // the cost model and to avoid vectorizing them (otherwise these casts,
4699 // which are redundant under the runtime overflow checks, will be
4700 // vectorized, which can be costly).
4702 // 2) Support additional induction/PHISCEV patterns: We also want to support
4703 // inductions where the sext-trunc / zext-trunc operations (partly) occur
4704 // after the induction update operation (the induction increment):
4706 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4707 // which correspond to a phi->add->trunc->sext/zext->phi update chain.
4709 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4710 // which correspond to a phi->trunc->add->sext/zext->phi update chain.
4712 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
4713 Optional
<std::pair
<const SCEV
*, SmallVector
<const SCEVPredicate
*, 3>>>
4714 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown
*SymbolicPHI
) {
4715 SmallVector
<const SCEVPredicate
*, 3> Predicates
;
4717 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4718 // return an AddRec expression under some predicate.
4720 auto *PN
= cast
<PHINode
>(SymbolicPHI
->getValue());
4721 const Loop
*L
= isIntegerLoopHeaderPHI(PN
, LI
);
4722 assert(L
&& "Expecting an integer loop header phi");
4724 // The loop may have multiple entrances or multiple exits; we can analyze
4725 // this phi as an addrec if it has a unique entry value and a unique
4727 Value
*BEValueV
= nullptr, *StartValueV
= nullptr;
4728 for (unsigned i
= 0, e
= PN
->getNumIncomingValues(); i
!= e
; ++i
) {
4729 Value
*V
= PN
->getIncomingValue(i
);
4730 if (L
->contains(PN
->getIncomingBlock(i
))) {
4733 } else if (BEValueV
!= V
) {
4737 } else if (!StartValueV
) {
4739 } else if (StartValueV
!= V
) {
4740 StartValueV
= nullptr;
4744 if (!BEValueV
|| !StartValueV
)
4747 const SCEV
*BEValue
= getSCEV(BEValueV
);
4749 // If the value coming around the backedge is an add with the symbolic
4750 // value we just inserted, possibly with casts that we can ignore under
4751 // an appropriate runtime guard, then we found a simple induction variable!
4752 const auto *Add
= dyn_cast
<SCEVAddExpr
>(BEValue
);
4756 // If there is a single occurrence of the symbolic value, possibly
4757 // casted, replace it with a recurrence.
4758 unsigned FoundIndex
= Add
->getNumOperands();
4759 Type
*TruncTy
= nullptr;
4761 for (unsigned i
= 0, e
= Add
->getNumOperands(); i
!= e
; ++i
)
4763 isSimpleCastedPHI(Add
->getOperand(i
), SymbolicPHI
, Signed
, *this)))
4764 if (FoundIndex
== e
) {
4769 if (FoundIndex
== Add
->getNumOperands())
4772 // Create an add with everything but the specified operand.
4773 SmallVector
<const SCEV
*, 8> Ops
;
4774 for (unsigned i
= 0, e
= Add
->getNumOperands(); i
!= e
; ++i
)
4775 if (i
!= FoundIndex
)
4776 Ops
.push_back(Add
->getOperand(i
));
4777 const SCEV
*Accum
= getAddExpr(Ops
);
4779 // The runtime checks will not be valid if the step amount is
4780 // varying inside the loop.
4781 if (!isLoopInvariant(Accum
, L
))
4784 // *** Part2: Create the predicates
4786 // Analysis was successful: we have a phi-with-cast pattern for which we
4787 // can return an AddRec expression under the following predicates:
4789 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4790 // fits within the truncated type (does not overflow) for i = 0 to n-1.
4791 // P2: An Equal predicate that guarantees that
4792 // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4793 // P3: An Equal predicate that guarantees that
4794 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4796 // As we next prove, the above predicates guarantee that:
4797 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4800 // More formally, we want to prove that:
4801 // Expr(i+1) = Start + (i+1) * Accum
4802 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4805 // 1) Expr(0) = Start
4806 // 2) Expr(1) = Start + Accum
4807 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4808 // 3) Induction hypothesis (step i):
4809 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4813 // = Start + (i+1)*Accum
4814 // = (Start + i*Accum) + Accum
4815 // = Expr(i) + Accum
4816 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4819 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4821 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4822 // + (Ext ix (Trunc iy (Accum) to ix) to iy)
4823 // + Accum :: from P3
4825 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4826 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4828 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4829 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4831 // By induction, the same applies to all iterations 1<=i<n:
4834 // Create a truncated addrec for which we will add a no overflow check (P1).
4835 const SCEV
*StartVal
= getSCEV(StartValueV
);
4836 const SCEV
*PHISCEV
=
4837 getAddRecExpr(getTruncateExpr(StartVal
, TruncTy
),
4838 getTruncateExpr(Accum
, TruncTy
), L
, SCEV::FlagAnyWrap
);
4840 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
4841 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
4842 // will be constant.
4844 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
4846 if (const auto *AR
= dyn_cast
<SCEVAddRecExpr
>(PHISCEV
)) {
4847 SCEVWrapPredicate::IncrementWrapFlags AddedFlags
=
4848 Signed
? SCEVWrapPredicate::IncrementNSSW
4849 : SCEVWrapPredicate::IncrementNUSW
;
4850 const SCEVPredicate
*AddRecPred
= getWrapPredicate(AR
, AddedFlags
);
4851 Predicates
.push_back(AddRecPred
);
4854 // Create the Equal Predicates P2,P3:
4856 // It is possible that the predicates P2 and/or P3 are computable at
4857 // compile time due to StartVal and/or Accum being constants.
4858 // If either one is, then we can check that now and escape if either P2
4861 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
4862 // for each of StartVal and Accum
4863 auto getExtendedExpr
= [&](const SCEV
*Expr
,
4864 bool CreateSignExtend
) -> const SCEV
* {
4865 assert(isLoopInvariant(Expr
, L
) && "Expr is expected to be invariant");
4866 const SCEV
*TruncatedExpr
= getTruncateExpr(Expr
, TruncTy
);
4867 const SCEV
*ExtendedExpr
=
4868 CreateSignExtend
? getSignExtendExpr(TruncatedExpr
, Expr
->getType())
4869 : getZeroExtendExpr(TruncatedExpr
, Expr
->getType());
4870 return ExtendedExpr
;
4874 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
4875 // = getExtendedExpr(Expr)
4876 // Determine whether the predicate P: Expr == ExtendedExpr
4877 // is known to be false at compile time
4878 auto PredIsKnownFalse
= [&](const SCEV
*Expr
,
4879 const SCEV
*ExtendedExpr
) -> bool {
4880 return Expr
!= ExtendedExpr
&&
4881 isKnownPredicate(ICmpInst::ICMP_NE
, Expr
, ExtendedExpr
);
4884 const SCEV
*StartExtended
= getExtendedExpr(StartVal
, Signed
);
4885 if (PredIsKnownFalse(StartVal
, StartExtended
)) {
4886 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
4890 // The Step is always Signed (because the overflow checks are either
4892 const SCEV
*AccumExtended
= getExtendedExpr(Accum
, /*CreateSignExtend=*/true);
4893 if (PredIsKnownFalse(Accum
, AccumExtended
)) {
4894 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
4898 auto AppendPredicate
= [&](const SCEV
*Expr
,
4899 const SCEV
*ExtendedExpr
) -> void {
4900 if (Expr
!= ExtendedExpr
&&
4901 !isKnownPredicate(ICmpInst::ICMP_EQ
, Expr
, ExtendedExpr
)) {
4902 const SCEVPredicate
*Pred
= getEqualPredicate(Expr
, ExtendedExpr
);
4903 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred
);
4904 Predicates
.push_back(Pred
);
4908 AppendPredicate(StartVal
, StartExtended
);
4909 AppendPredicate(Accum
, AccumExtended
);
4911 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
4912 // which the casts had been folded away. The caller can rewrite SymbolicPHI
4913 // into NewAR if it will also add the runtime overflow checks specified in
4915 auto *NewAR
= getAddRecExpr(StartVal
, Accum
, L
, SCEV::FlagAnyWrap
);
4917 std::pair
<const SCEV
*, SmallVector
<const SCEVPredicate
*, 3>> PredRewrite
=
4918 std::make_pair(NewAR
, Predicates
);
4919 // Remember the result of the analysis for this SCEV at this locayyytion.
4920 PredicatedSCEVRewrites
[{SymbolicPHI
, L
}] = PredRewrite
;
4924 Optional
<std::pair
<const SCEV
*, SmallVector
<const SCEVPredicate
*, 3>>>
4925 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown
*SymbolicPHI
) {
4926 auto *PN
= cast
<PHINode
>(SymbolicPHI
->getValue());
4927 const Loop
*L
= isIntegerLoopHeaderPHI(PN
, LI
);
4931 // Check to see if we already analyzed this PHI.
4932 auto I
= PredicatedSCEVRewrites
.find({SymbolicPHI
, L
});
4933 if (I
!= PredicatedSCEVRewrites
.end()) {
4934 std::pair
<const SCEV
*, SmallVector
<const SCEVPredicate
*, 3>> Rewrite
=
4936 // Analysis was done before and failed to create an AddRec:
4937 if (Rewrite
.first
== SymbolicPHI
)
4939 // Analysis was done before and succeeded to create an AddRec under
4941 assert(isa
<SCEVAddRecExpr
>(Rewrite
.first
) && "Expected an AddRec");
4942 assert(!(Rewrite
.second
).empty() && "Expected to find Predicates");
4946 Optional
<std::pair
<const SCEV
*, SmallVector
<const SCEVPredicate
*, 3>>>
4947 Rewrite
= createAddRecFromPHIWithCastsImpl(SymbolicPHI
);
4949 // Record in the cache that the analysis failed
4951 SmallVector
<const SCEVPredicate
*, 3> Predicates
;
4952 PredicatedSCEVRewrites
[{SymbolicPHI
, L
}] = {SymbolicPHI
, Predicates
};
4959 // FIXME: This utility is currently required because the Rewriter currently
4960 // does not rewrite this expression:
4961 // {0, +, (sext ix (trunc iy to ix) to iy)}
4962 // into {0, +, %step},
4963 // even when the following Equal predicate exists:
4964 // "%step == (sext ix (trunc iy to ix) to iy)".
4965 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
4966 const SCEVAddRecExpr
*AR1
, const SCEVAddRecExpr
*AR2
) const {
4970 auto areExprsEqual
= [&](const SCEV
*Expr1
, const SCEV
*Expr2
) -> bool {
4971 if (Expr1
!= Expr2
&& !Preds
.implies(SE
.getEqualPredicate(Expr1
, Expr2
)) &&
4972 !Preds
.implies(SE
.getEqualPredicate(Expr2
, Expr1
)))
4977 if (!areExprsEqual(AR1
->getStart(), AR2
->getStart()) ||
4978 !areExprsEqual(AR1
->getStepRecurrence(SE
), AR2
->getStepRecurrence(SE
)))
4983 /// A helper function for createAddRecFromPHI to handle simple cases.
4985 /// This function tries to find an AddRec expression for the simplest (yet most
4986 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
4987 /// If it fails, createAddRecFromPHI will use a more general, but slow,
4988 /// technique for finding the AddRec expression.
4989 const SCEV
*ScalarEvolution::createSimpleAffineAddRec(PHINode
*PN
,
4991 Value
*StartValueV
) {
4992 const Loop
*L
= LI
.getLoopFor(PN
->getParent());
4993 assert(L
&& L
->getHeader() == PN
->getParent());
4994 assert(BEValueV
&& StartValueV
);
4996 auto BO
= MatchBinaryOp(BEValueV
, DT
);
5000 if (BO
->Opcode
!= Instruction::Add
)
5003 const SCEV
*Accum
= nullptr;
5004 if (BO
->LHS
== PN
&& L
->isLoopInvariant(BO
->RHS
))
5005 Accum
= getSCEV(BO
->RHS
);
5006 else if (BO
->RHS
== PN
&& L
->isLoopInvariant(BO
->LHS
))
5007 Accum
= getSCEV(BO
->LHS
);
5012 SCEV::NoWrapFlags Flags
= SCEV::FlagAnyWrap
;
5014 Flags
= setFlags(Flags
, SCEV::FlagNUW
);
5016 Flags
= setFlags(Flags
, SCEV::FlagNSW
);
5018 const SCEV
*StartVal
= getSCEV(StartValueV
);
5019 const SCEV
*PHISCEV
= getAddRecExpr(StartVal
, Accum
, L
, Flags
);
5021 ValueExprMap
[SCEVCallbackVH(PN
, this)] = PHISCEV
;
5023 // We can add Flags to the post-inc expression only if we
5024 // know that it is *undefined behavior* for BEValueV to
5026 if (auto *BEInst
= dyn_cast
<Instruction
>(BEValueV
))
5027 if (isLoopInvariant(Accum
, L
) && isAddRecNeverPoison(BEInst
, L
))
5028 (void)getAddRecExpr(getAddExpr(StartVal
, Accum
), Accum
, L
, Flags
);
5033 const SCEV
*ScalarEvolution::createAddRecFromPHI(PHINode
*PN
) {
5034 const Loop
*L
= LI
.getLoopFor(PN
->getParent());
5035 if (!L
|| L
->getHeader() != PN
->getParent())
5038 // The loop may have multiple entrances or multiple exits; we can analyze
5039 // this phi as an addrec if it has a unique entry value and a unique
5041 Value
*BEValueV
= nullptr, *StartValueV
= nullptr;
5042 for (unsigned i
= 0, e
= PN
->getNumIncomingValues(); i
!= e
; ++i
) {
5043 Value
*V
= PN
->getIncomingValue(i
);
5044 if (L
->contains(PN
->getIncomingBlock(i
))) {
5047 } else if (BEValueV
!= V
) {
5051 } else if (!StartValueV
) {
5053 } else if (StartValueV
!= V
) {
5054 StartValueV
= nullptr;
5058 if (!BEValueV
|| !StartValueV
)
5061 assert(ValueExprMap
.find_as(PN
) == ValueExprMap
.end() &&
5062 "PHI node already processed?");
5064 // First, try to find AddRec expression without creating a fictituos symbolic
5066 if (auto *S
= createSimpleAffineAddRec(PN
, BEValueV
, StartValueV
))
5069 // Handle PHI node value symbolically.
5070 const SCEV
*SymbolicName
= getUnknown(PN
);
5071 ValueExprMap
.insert({SCEVCallbackVH(PN
, this), SymbolicName
});
5073 // Using this symbolic name for the PHI, analyze the value coming around
5075 const SCEV
*BEValue
= getSCEV(BEValueV
);
5077 // NOTE: If BEValue is loop invariant, we know that the PHI node just
5078 // has a special value for the first iteration of the loop.
5080 // If the value coming around the backedge is an add with the symbolic
5081 // value we just inserted, then we found a simple induction variable!
5082 if (const SCEVAddExpr
*Add
= dyn_cast
<SCEVAddExpr
>(BEValue
)) {
5083 // If there is a single occurrence of the symbolic value, replace it
5084 // with a recurrence.
5085 unsigned FoundIndex
= Add
->getNumOperands();
5086 for (unsigned i
= 0, e
= Add
->getNumOperands(); i
!= e
; ++i
)
5087 if (Add
->getOperand(i
) == SymbolicName
)
5088 if (FoundIndex
== e
) {
5093 if (FoundIndex
!= Add
->getNumOperands()) {
5094 // Create an add with everything but the specified operand.
5095 SmallVector
<const SCEV
*, 8> Ops
;
5096 for (unsigned i
= 0, e
= Add
->getNumOperands(); i
!= e
; ++i
)
5097 if (i
!= FoundIndex
)
5098 Ops
.push_back(SCEVBackedgeConditionFolder::rewrite(Add
->getOperand(i
),
5100 const SCEV
*Accum
= getAddExpr(Ops
);
5102 // This is not a valid addrec if the step amount is varying each
5103 // loop iteration, but is not itself an addrec in this loop.
5104 if (isLoopInvariant(Accum
, L
) ||
5105 (isa
<SCEVAddRecExpr
>(Accum
) &&
5106 cast
<SCEVAddRecExpr
>(Accum
)->getLoop() == L
)) {
5107 SCEV::NoWrapFlags Flags
= SCEV::FlagAnyWrap
;
5109 if (auto BO
= MatchBinaryOp(BEValueV
, DT
)) {
5110 if (BO
->Opcode
== Instruction::Add
&& BO
->LHS
== PN
) {
5112 Flags
= setFlags(Flags
, SCEV::FlagNUW
);
5114 Flags
= setFlags(Flags
, SCEV::FlagNSW
);
5116 } else if (GEPOperator
*GEP
= dyn_cast
<GEPOperator
>(BEValueV
)) {
5117 // If the increment is an inbounds GEP, then we know the address
5118 // space cannot be wrapped around. We cannot make any guarantee
5119 // about signed or unsigned overflow because pointers are
5120 // unsigned but we may have a negative index from the base
5121 // pointer. We can guarantee that no unsigned wrap occurs if the
5122 // indices form a positive value.
5123 if (GEP
->isInBounds() && GEP
->getOperand(0) == PN
) {
5124 Flags
= setFlags(Flags
, SCEV::FlagNW
);
5126 const SCEV
*Ptr
= getSCEV(GEP
->getPointerOperand());
5127 if (isKnownPositive(getMinusSCEV(getSCEV(GEP
), Ptr
)))
5128 Flags
= setFlags(Flags
, SCEV::FlagNUW
);
5131 // We cannot transfer nuw and nsw flags from subtraction
5132 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5136 const SCEV
*StartVal
= getSCEV(StartValueV
);
5137 const SCEV
*PHISCEV
= getAddRecExpr(StartVal
, Accum
, L
, Flags
);
5139 // Okay, for the entire analysis of this edge we assumed the PHI
5140 // to be symbolic. We now need to go back and purge all of the
5141 // entries for the scalars that use the symbolic expression.
5142 forgetSymbolicName(PN
, SymbolicName
);
5143 ValueExprMap
[SCEVCallbackVH(PN
, this)] = PHISCEV
;
5145 // We can add Flags to the post-inc expression only if we
5146 // know that it is *undefined behavior* for BEValueV to
5148 if (auto *BEInst
= dyn_cast
<Instruction
>(BEValueV
))
5149 if (isLoopInvariant(Accum
, L
) && isAddRecNeverPoison(BEInst
, L
))
5150 (void)getAddRecExpr(getAddExpr(StartVal
, Accum
), Accum
, L
, Flags
);
5156 // Otherwise, this could be a loop like this:
5157 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
5158 // In this case, j = {1,+,1} and BEValue is j.
5159 // Because the other in-value of i (0) fits the evolution of BEValue
5160 // i really is an addrec evolution.
5162 // We can generalize this saying that i is the shifted value of BEValue
5163 // by one iteration:
5164 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
5165 const SCEV
*Shifted
= SCEVShiftRewriter::rewrite(BEValue
, L
, *this);
5166 const SCEV
*Start
= SCEVInitRewriter::rewrite(Shifted
, L
, *this, false);
5167 if (Shifted
!= getCouldNotCompute() &&
5168 Start
!= getCouldNotCompute()) {
5169 const SCEV
*StartVal
= getSCEV(StartValueV
);
5170 if (Start
== StartVal
) {
5171 // Okay, for the entire analysis of this edge we assumed the PHI
5172 // to be symbolic. We now need to go back and purge all of the
5173 // entries for the scalars that use the symbolic expression.
5174 forgetSymbolicName(PN
, SymbolicName
);
5175 ValueExprMap
[SCEVCallbackVH(PN
, this)] = Shifted
;
5181 // Remove the temporary PHI node SCEV that has been inserted while intending
5182 // to create an AddRecExpr for this PHI node. We can not keep this temporary
5183 // as it will prevent later (possibly simpler) SCEV expressions to be added
5184 // to the ValueExprMap.
5185 eraseValueFromMap(PN
);
5190 // Checks if the SCEV S is available at BB. S is considered available at BB
5191 // if S can be materialized at BB without introducing a fault.
5192 static bool IsAvailableOnEntry(const Loop
*L
, DominatorTree
&DT
, const SCEV
*S
,
5194 struct CheckAvailable
{
5195 bool TraversalDone
= false;
5196 bool Available
= true;
5198 const Loop
*L
= nullptr; // The loop BB is in (can be nullptr)
5199 BasicBlock
*BB
= nullptr;
5202 CheckAvailable(const Loop
*L
, BasicBlock
*BB
, DominatorTree
&DT
)
5203 : L(L
), BB(BB
), DT(DT
) {}
5205 bool setUnavailable() {
5206 TraversalDone
= true;
5211 bool follow(const SCEV
*S
) {
5212 switch (S
->getSCEVType()) {
5213 case scConstant
: case scTruncate
: case scZeroExtend
: case scSignExtend
:
5214 case scAddExpr
: case scMulExpr
: case scUMaxExpr
: case scSMaxExpr
:
5215 // These expressions are available if their operand(s) is/are.
5218 case scAddRecExpr
: {
5219 // We allow add recurrences that are on the loop BB is in, or some
5220 // outer loop. This guarantees availability because the value of the
5221 // add recurrence at BB is simply the "current" value of the induction
5222 // variable. We can relax this in the future; for instance an add
5223 // recurrence on a sibling dominating loop is also available at BB.
5224 const auto *ARLoop
= cast
<SCEVAddRecExpr
>(S
)->getLoop();
5225 if (L
&& (ARLoop
== L
|| ARLoop
->contains(L
)))
5228 return setUnavailable();
5232 // For SCEVUnknown, we check for simple dominance.
5233 const auto *SU
= cast
<SCEVUnknown
>(S
);
5234 Value
*V
= SU
->getValue();
5236 if (isa
<Argument
>(V
))
5239 if (isa
<Instruction
>(V
) && DT
.dominates(cast
<Instruction
>(V
), BB
))
5242 return setUnavailable();
5246 case scCouldNotCompute
:
5247 // We do not try to smart about these at all.
5248 return setUnavailable();
5250 llvm_unreachable("switch should be fully covered!");
5253 bool isDone() { return TraversalDone
; }
5256 CheckAvailable
CA(L
, BB
, DT
);
5257 SCEVTraversal
<CheckAvailable
> ST(CA
);
5260 return CA
.Available
;
5263 // Try to match a control flow sequence that branches out at BI and merges back
5264 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
5266 static bool BrPHIToSelect(DominatorTree
&DT
, BranchInst
*BI
, PHINode
*Merge
,
5267 Value
*&C
, Value
*&LHS
, Value
*&RHS
) {
5268 C
= BI
->getCondition();
5270 BasicBlockEdge
LeftEdge(BI
->getParent(), BI
->getSuccessor(0));
5271 BasicBlockEdge
RightEdge(BI
->getParent(), BI
->getSuccessor(1));
5273 if (!LeftEdge
.isSingleEdge())
5276 assert(RightEdge
.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5278 Use
&LeftUse
= Merge
->getOperandUse(0);
5279 Use
&RightUse
= Merge
->getOperandUse(1);
5281 if (DT
.dominates(LeftEdge
, LeftUse
) && DT
.dominates(RightEdge
, RightUse
)) {
5287 if (DT
.dominates(LeftEdge
, RightUse
) && DT
.dominates(RightEdge
, LeftUse
)) {
5296 const SCEV
*ScalarEvolution::createNodeFromSelectLikePHI(PHINode
*PN
) {
5298 [&](BasicBlock
*BB
) { return DT
.isReachableFromEntry(BB
); };
5299 if (PN
->getNumIncomingValues() == 2 && all_of(PN
->blocks(), IsReachable
)) {
5300 const Loop
*L
= LI
.getLoopFor(PN
->getParent());
5302 // We don't want to break LCSSA, even in a SCEV expression tree.
5303 for (unsigned i
= 0, e
= PN
->getNumIncomingValues(); i
!= e
; ++i
)
5304 if (LI
.getLoopFor(PN
->getIncomingBlock(i
)) != L
)
5309 // br %cond, label %left, label %right
5315 // V = phi [ %x, %left ], [ %y, %right ]
5317 // as "select %cond, %x, %y"
5319 BasicBlock
*IDom
= DT
[PN
->getParent()]->getIDom()->getBlock();
5320 assert(IDom
&& "At least the entry block should dominate PN");
5322 auto *BI
= dyn_cast
<BranchInst
>(IDom
->getTerminator());
5323 Value
*Cond
= nullptr, *LHS
= nullptr, *RHS
= nullptr;
5325 if (BI
&& BI
->isConditional() &&
5326 BrPHIToSelect(DT
, BI
, PN
, Cond
, LHS
, RHS
) &&
5327 IsAvailableOnEntry(L
, DT
, getSCEV(LHS
), PN
->getParent()) &&
5328 IsAvailableOnEntry(L
, DT
, getSCEV(RHS
), PN
->getParent()))
5329 return createNodeForSelectOrPHI(PN
, Cond
, LHS
, RHS
);
5335 const SCEV
*ScalarEvolution::createNodeForPHI(PHINode
*PN
) {
5336 if (const SCEV
*S
= createAddRecFromPHI(PN
))
5339 if (const SCEV
*S
= createNodeFromSelectLikePHI(PN
))
5342 // If the PHI has a single incoming value, follow that value, unless the
5343 // PHI's incoming blocks are in a different loop, in which case doing so
5344 // risks breaking LCSSA form. Instcombine would normally zap these, but
5345 // it doesn't have DominatorTree information, so it may miss cases.
5346 if (Value
*V
= SimplifyInstruction(PN
, {getDataLayout(), &TLI
, &DT
, &AC
}))
5347 if (LI
.replacementPreservesLCSSAForm(PN
, V
))
5350 // If it's not a loop phi, we can't handle it yet.
5351 return getUnknown(PN
);
5354 const SCEV
*ScalarEvolution::createNodeForSelectOrPHI(Instruction
*I
,
5358 // Handle "constant" branch or select. This can occur for instance when a
5359 // loop pass transforms an inner loop and moves on to process the outer loop.
5360 if (auto *CI
= dyn_cast
<ConstantInt
>(Cond
))
5361 return getSCEV(CI
->isOne() ? TrueVal
: FalseVal
);
5363 // Try to match some simple smax or umax patterns.
5364 auto *ICI
= dyn_cast
<ICmpInst
>(Cond
);
5366 return getUnknown(I
);
5368 Value
*LHS
= ICI
->getOperand(0);
5369 Value
*RHS
= ICI
->getOperand(1);
5371 switch (ICI
->getPredicate()) {
5372 case ICmpInst::ICMP_SLT
:
5373 case ICmpInst::ICMP_SLE
:
5374 std::swap(LHS
, RHS
);
5376 case ICmpInst::ICMP_SGT
:
5377 case ICmpInst::ICMP_SGE
:
5378 // a >s b ? a+x : b+x -> smax(a, b)+x
5379 // a >s b ? b+x : a+x -> smin(a, b)+x
5380 if (getTypeSizeInBits(LHS
->getType()) <= getTypeSizeInBits(I
->getType())) {
5381 const SCEV
*LS
= getNoopOrSignExtend(getSCEV(LHS
), I
->getType());
5382 const SCEV
*RS
= getNoopOrSignExtend(getSCEV(RHS
), I
->getType());
5383 const SCEV
*LA
= getSCEV(TrueVal
);
5384 const SCEV
*RA
= getSCEV(FalseVal
);
5385 const SCEV
*LDiff
= getMinusSCEV(LA
, LS
);
5386 const SCEV
*RDiff
= getMinusSCEV(RA
, RS
);
5388 return getAddExpr(getSMaxExpr(LS
, RS
), LDiff
);
5389 LDiff
= getMinusSCEV(LA
, RS
);
5390 RDiff
= getMinusSCEV(RA
, LS
);
5392 return getAddExpr(getSMinExpr(LS
, RS
), LDiff
);
5395 case ICmpInst::ICMP_ULT
:
5396 case ICmpInst::ICMP_ULE
:
5397 std::swap(LHS
, RHS
);
5399 case ICmpInst::ICMP_UGT
:
5400 case ICmpInst::ICMP_UGE
:
5401 // a >u b ? a+x : b+x -> umax(a, b)+x
5402 // a >u b ? b+x : a+x -> umin(a, b)+x
5403 if (getTypeSizeInBits(LHS
->getType()) <= getTypeSizeInBits(I
->getType())) {
5404 const SCEV
*LS
= getNoopOrZeroExtend(getSCEV(LHS
), I
->getType());
5405 const SCEV
*RS
= getNoopOrZeroExtend(getSCEV(RHS
), I
->getType());
5406 const SCEV
*LA
= getSCEV(TrueVal
);
5407 const SCEV
*RA
= getSCEV(FalseVal
);
5408 const SCEV
*LDiff
= getMinusSCEV(LA
, LS
);
5409 const SCEV
*RDiff
= getMinusSCEV(RA
, RS
);
5411 return getAddExpr(getUMaxExpr(LS
, RS
), LDiff
);
5412 LDiff
= getMinusSCEV(LA
, RS
);
5413 RDiff
= getMinusSCEV(RA
, LS
);
5415 return getAddExpr(getUMinExpr(LS
, RS
), LDiff
);
5418 case ICmpInst::ICMP_NE
:
5419 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
5420 if (getTypeSizeInBits(LHS
->getType()) <= getTypeSizeInBits(I
->getType()) &&
5421 isa
<ConstantInt
>(RHS
) && cast
<ConstantInt
>(RHS
)->isZero()) {
5422 const SCEV
*One
= getOne(I
->getType());
5423 const SCEV
*LS
= getNoopOrZeroExtend(getSCEV(LHS
), I
->getType());
5424 const SCEV
*LA
= getSCEV(TrueVal
);
5425 const SCEV
*RA
= getSCEV(FalseVal
);
5426 const SCEV
*LDiff
= getMinusSCEV(LA
, LS
);
5427 const SCEV
*RDiff
= getMinusSCEV(RA
, One
);
5429 return getAddExpr(getUMaxExpr(One
, LS
), LDiff
);
5432 case ICmpInst::ICMP_EQ
:
5433 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
5434 if (getTypeSizeInBits(LHS
->getType()) <= getTypeSizeInBits(I
->getType()) &&
5435 isa
<ConstantInt
>(RHS
) && cast
<ConstantInt
>(RHS
)->isZero()) {
5436 const SCEV
*One
= getOne(I
->getType());
5437 const SCEV
*LS
= getNoopOrZeroExtend(getSCEV(LHS
), I
->getType());
5438 const SCEV
*LA
= getSCEV(TrueVal
);
5439 const SCEV
*RA
= getSCEV(FalseVal
);
5440 const SCEV
*LDiff
= getMinusSCEV(LA
, One
);
5441 const SCEV
*RDiff
= getMinusSCEV(RA
, LS
);
5443 return getAddExpr(getUMaxExpr(One
, LS
), LDiff
);
5450 return getUnknown(I
);
5453 /// Expand GEP instructions into add and multiply operations. This allows them
5454 /// to be analyzed by regular SCEV code.
5455 const SCEV
*ScalarEvolution::createNodeForGEP(GEPOperator
*GEP
) {
5456 // Don't attempt to analyze GEPs over unsized objects.
5457 if (!GEP
->getSourceElementType()->isSized())
5458 return getUnknown(GEP
);
5460 SmallVector
<const SCEV
*, 4> IndexExprs
;
5461 for (auto Index
= GEP
->idx_begin(); Index
!= GEP
->idx_end(); ++Index
)
5462 IndexExprs
.push_back(getSCEV(*Index
));
5463 return getGEPExpr(GEP
, IndexExprs
);
5466 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV
*S
) {
5467 if (const SCEVConstant
*C
= dyn_cast
<SCEVConstant
>(S
))
5468 return C
->getAPInt().countTrailingZeros();
5470 if (const SCEVTruncateExpr
*T
= dyn_cast
<SCEVTruncateExpr
>(S
))
5471 return std::min(GetMinTrailingZeros(T
->getOperand()),
5472 (uint32_t)getTypeSizeInBits(T
->getType()));
5474 if (const SCEVZeroExtendExpr
*E
= dyn_cast
<SCEVZeroExtendExpr
>(S
)) {
5475 uint32_t OpRes
= GetMinTrailingZeros(E
->getOperand());
5476 return OpRes
== getTypeSizeInBits(E
->getOperand()->getType())
5477 ? getTypeSizeInBits(E
->getType())
5481 if (const SCEVSignExtendExpr
*E
= dyn_cast
<SCEVSignExtendExpr
>(S
)) {
5482 uint32_t OpRes
= GetMinTrailingZeros(E
->getOperand());
5483 return OpRes
== getTypeSizeInBits(E
->getOperand()->getType())
5484 ? getTypeSizeInBits(E
->getType())
5488 if (const SCEVAddExpr
*A
= dyn_cast
<SCEVAddExpr
>(S
)) {
5489 // The result is the min of all operands results.
5490 uint32_t MinOpRes
= GetMinTrailingZeros(A
->getOperand(0));
5491 for (unsigned i
= 1, e
= A
->getNumOperands(); MinOpRes
&& i
!= e
; ++i
)
5492 MinOpRes
= std::min(MinOpRes
, GetMinTrailingZeros(A
->getOperand(i
)));
5496 if (const SCEVMulExpr
*M
= dyn_cast
<SCEVMulExpr
>(S
)) {
5497 // The result is the sum of all operands results.
5498 uint32_t SumOpRes
= GetMinTrailingZeros(M
->getOperand(0));
5499 uint32_t BitWidth
= getTypeSizeInBits(M
->getType());
5500 for (unsigned i
= 1, e
= M
->getNumOperands();
5501 SumOpRes
!= BitWidth
&& i
!= e
; ++i
)
5503 std::min(SumOpRes
+ GetMinTrailingZeros(M
->getOperand(i
)), BitWidth
);
5507 if (const SCEVAddRecExpr
*A
= dyn_cast
<SCEVAddRecExpr
>(S
)) {
5508 // The result is the min of all operands results.
5509 uint32_t MinOpRes
= GetMinTrailingZeros(A
->getOperand(0));
5510 for (unsigned i
= 1, e
= A
->getNumOperands(); MinOpRes
&& i
!= e
; ++i
)
5511 MinOpRes
= std::min(MinOpRes
, GetMinTrailingZeros(A
->getOperand(i
)));
5515 if (const SCEVSMaxExpr
*M
= dyn_cast
<SCEVSMaxExpr
>(S
)) {
5516 // The result is the min of all operands results.
5517 uint32_t MinOpRes
= GetMinTrailingZeros(M
->getOperand(0));
5518 for (unsigned i
= 1, e
= M
->getNumOperands(); MinOpRes
&& i
!= e
; ++i
)
5519 MinOpRes
= std::min(MinOpRes
, GetMinTrailingZeros(M
->getOperand(i
)));
5523 if (const SCEVUMaxExpr
*M
= dyn_cast
<SCEVUMaxExpr
>(S
)) {
5524 // The result is the min of all operands results.
5525 uint32_t MinOpRes
= GetMinTrailingZeros(M
->getOperand(0));
5526 for (unsigned i
= 1, e
= M
->getNumOperands(); MinOpRes
&& i
!= e
; ++i
)
5527 MinOpRes
= std::min(MinOpRes
, GetMinTrailingZeros(M
->getOperand(i
)));
5531 if (const SCEVUnknown
*U
= dyn_cast
<SCEVUnknown
>(S
)) {
5532 // For a SCEVUnknown, ask ValueTracking.
5533 KnownBits Known
= computeKnownBits(U
->getValue(), getDataLayout(), 0, &AC
, nullptr, &DT
);
5534 return Known
.countMinTrailingZeros();
5541 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV
*S
) {
5542 auto I
= MinTrailingZerosCache
.find(S
);
5543 if (I
!= MinTrailingZerosCache
.end())
5546 uint32_t Result
= GetMinTrailingZerosImpl(S
);
5547 auto InsertPair
= MinTrailingZerosCache
.insert({S
, Result
});
5548 assert(InsertPair
.second
&& "Should insert a new key");
5549 return InsertPair
.first
->second
;
5552 /// Helper method to assign a range to V from metadata present in the IR.
5553 static Optional
<ConstantRange
> GetRangeFromMetadata(Value
*V
) {
5554 if (Instruction
*I
= dyn_cast
<Instruction
>(V
))
5555 if (MDNode
*MD
= I
->getMetadata(LLVMContext::MD_range
))
5556 return getConstantRangeFromMetadata(*MD
);
5561 /// Determine the range for a particular SCEV. If SignHint is
5562 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5563 /// with a "cleaner" unsigned (resp. signed) representation.
5564 const ConstantRange
&
5565 ScalarEvolution::getRangeRef(const SCEV
*S
,
5566 ScalarEvolution::RangeSignHint SignHint
) {
5567 DenseMap
<const SCEV
*, ConstantRange
> &Cache
=
5568 SignHint
== ScalarEvolution::HINT_RANGE_UNSIGNED
? UnsignedRanges
5571 // See if we've computed this range already.
5572 DenseMap
<const SCEV
*, ConstantRange
>::iterator I
= Cache
.find(S
);
5573 if (I
!= Cache
.end())
5576 if (const SCEVConstant
*C
= dyn_cast
<SCEVConstant
>(S
))
5577 return setRange(C
, SignHint
, ConstantRange(C
->getAPInt()));
5579 unsigned BitWidth
= getTypeSizeInBits(S
->getType());
5580 ConstantRange
ConservativeResult(BitWidth
, /*isFullSet=*/true);
5582 // If the value has known zeros, the maximum value will have those known zeros
5584 uint32_t TZ
= GetMinTrailingZeros(S
);
5586 if (SignHint
== ScalarEvolution::HINT_RANGE_UNSIGNED
)
5587 ConservativeResult
=
5588 ConstantRange(APInt::getMinValue(BitWidth
),
5589 APInt::getMaxValue(BitWidth
).lshr(TZ
).shl(TZ
) + 1);
5591 ConservativeResult
= ConstantRange(
5592 APInt::getSignedMinValue(BitWidth
),
5593 APInt::getSignedMaxValue(BitWidth
).ashr(TZ
).shl(TZ
) + 1);
5596 if (const SCEVAddExpr
*Add
= dyn_cast
<SCEVAddExpr
>(S
)) {
5597 ConstantRange X
= getRangeRef(Add
->getOperand(0), SignHint
);
5598 for (unsigned i
= 1, e
= Add
->getNumOperands(); i
!= e
; ++i
)
5599 X
= X
.add(getRangeRef(Add
->getOperand(i
), SignHint
));
5600 return setRange(Add
, SignHint
, ConservativeResult
.intersectWith(X
));
5603 if (const SCEVMulExpr
*Mul
= dyn_cast
<SCEVMulExpr
>(S
)) {
5604 ConstantRange X
= getRangeRef(Mul
->getOperand(0), SignHint
);
5605 for (unsigned i
= 1, e
= Mul
->getNumOperands(); i
!= e
; ++i
)
5606 X
= X
.multiply(getRangeRef(Mul
->getOperand(i
), SignHint
));
5607 return setRange(Mul
, SignHint
, ConservativeResult
.intersectWith(X
));
5610 if (const SCEVSMaxExpr
*SMax
= dyn_cast
<SCEVSMaxExpr
>(S
)) {
5611 ConstantRange X
= getRangeRef(SMax
->getOperand(0), SignHint
);
5612 for (unsigned i
= 1, e
= SMax
->getNumOperands(); i
!= e
; ++i
)
5613 X
= X
.smax(getRangeRef(SMax
->getOperand(i
), SignHint
));
5614 return setRange(SMax
, SignHint
, ConservativeResult
.intersectWith(X
));
5617 if (const SCEVUMaxExpr
*UMax
= dyn_cast
<SCEVUMaxExpr
>(S
)) {
5618 ConstantRange X
= getRangeRef(UMax
->getOperand(0), SignHint
);
5619 for (unsigned i
= 1, e
= UMax
->getNumOperands(); i
!= e
; ++i
)
5620 X
= X
.umax(getRangeRef(UMax
->getOperand(i
), SignHint
));
5621 return setRange(UMax
, SignHint
, ConservativeResult
.intersectWith(X
));
5624 if (const SCEVUDivExpr
*UDiv
= dyn_cast
<SCEVUDivExpr
>(S
)) {
5625 ConstantRange X
= getRangeRef(UDiv
->getLHS(), SignHint
);
5626 ConstantRange Y
= getRangeRef(UDiv
->getRHS(), SignHint
);
5627 return setRange(UDiv
, SignHint
,
5628 ConservativeResult
.intersectWith(X
.udiv(Y
)));
5631 if (const SCEVZeroExtendExpr
*ZExt
= dyn_cast
<SCEVZeroExtendExpr
>(S
)) {
5632 ConstantRange X
= getRangeRef(ZExt
->getOperand(), SignHint
);
5633 return setRange(ZExt
, SignHint
,
5634 ConservativeResult
.intersectWith(X
.zeroExtend(BitWidth
)));
5637 if (const SCEVSignExtendExpr
*SExt
= dyn_cast
<SCEVSignExtendExpr
>(S
)) {
5638 ConstantRange X
= getRangeRef(SExt
->getOperand(), SignHint
);
5639 return setRange(SExt
, SignHint
,
5640 ConservativeResult
.intersectWith(X
.signExtend(BitWidth
)));
5643 if (const SCEVTruncateExpr
*Trunc
= dyn_cast
<SCEVTruncateExpr
>(S
)) {
5644 ConstantRange X
= getRangeRef(Trunc
->getOperand(), SignHint
);
5645 return setRange(Trunc
, SignHint
,
5646 ConservativeResult
.intersectWith(X
.truncate(BitWidth
)));
5649 if (const SCEVAddRecExpr
*AddRec
= dyn_cast
<SCEVAddRecExpr
>(S
)) {
5650 // If there's no unsigned wrap, the value will never be less than its
5652 if (AddRec
->hasNoUnsignedWrap())
5653 if (const SCEVConstant
*C
= dyn_cast
<SCEVConstant
>(AddRec
->getStart()))
5654 if (!C
->getValue()->isZero())
5655 ConservativeResult
= ConservativeResult
.intersectWith(
5656 ConstantRange(C
->getAPInt(), APInt(BitWidth
, 0)));
5658 // If there's no signed wrap, and all the operands have the same sign or
5659 // zero, the value won't ever change sign.
5660 if (AddRec
->hasNoSignedWrap()) {
5661 bool AllNonNeg
= true;
5662 bool AllNonPos
= true;
5663 for (unsigned i
= 0, e
= AddRec
->getNumOperands(); i
!= e
; ++i
) {
5664 if (!isKnownNonNegative(AddRec
->getOperand(i
))) AllNonNeg
= false;
5665 if (!isKnownNonPositive(AddRec
->getOperand(i
))) AllNonPos
= false;
5668 ConservativeResult
= ConservativeResult
.intersectWith(
5669 ConstantRange(APInt(BitWidth
, 0),
5670 APInt::getSignedMinValue(BitWidth
)));
5672 ConservativeResult
= ConservativeResult
.intersectWith(
5673 ConstantRange(APInt::getSignedMinValue(BitWidth
),
5674 APInt(BitWidth
, 1)));
5677 // TODO: non-affine addrec
5678 if (AddRec
->isAffine()) {
5679 const SCEV
*MaxBECount
= getMaxBackedgeTakenCount(AddRec
->getLoop());
5680 if (!isa
<SCEVCouldNotCompute
>(MaxBECount
) &&
5681 getTypeSizeInBits(MaxBECount
->getType()) <= BitWidth
) {
5682 auto RangeFromAffine
= getRangeForAffineAR(
5683 AddRec
->getStart(), AddRec
->getStepRecurrence(*this), MaxBECount
,
5685 if (!RangeFromAffine
.isFullSet())
5686 ConservativeResult
=
5687 ConservativeResult
.intersectWith(RangeFromAffine
);
5689 auto RangeFromFactoring
= getRangeViaFactoring(
5690 AddRec
->getStart(), AddRec
->getStepRecurrence(*this), MaxBECount
,
5692 if (!RangeFromFactoring
.isFullSet())
5693 ConservativeResult
=
5694 ConservativeResult
.intersectWith(RangeFromFactoring
);
5698 return setRange(AddRec
, SignHint
, std::move(ConservativeResult
));
5701 if (const SCEVUnknown
*U
= dyn_cast
<SCEVUnknown
>(S
)) {
5702 // Check if the IR explicitly contains !range metadata.
5703 Optional
<ConstantRange
> MDRange
= GetRangeFromMetadata(U
->getValue());
5704 if (MDRange
.hasValue())
5705 ConservativeResult
= ConservativeResult
.intersectWith(MDRange
.getValue());
5707 // Split here to avoid paying the compile-time cost of calling both
5708 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted
5710 const DataLayout
&DL
= getDataLayout();
5711 if (SignHint
== ScalarEvolution::HINT_RANGE_UNSIGNED
) {
5712 // For a SCEVUnknown, ask ValueTracking.
5713 KnownBits Known
= computeKnownBits(U
->getValue(), DL
, 0, &AC
, nullptr, &DT
);
5714 if (Known
.One
!= ~Known
.Zero
+ 1)
5715 ConservativeResult
=
5716 ConservativeResult
.intersectWith(ConstantRange(Known
.One
,
5719 assert(SignHint
== ScalarEvolution::HINT_RANGE_SIGNED
&&
5720 "generalize as needed!");
5721 unsigned NS
= ComputeNumSignBits(U
->getValue(), DL
, 0, &AC
, nullptr, &DT
);
5723 ConservativeResult
= ConservativeResult
.intersectWith(
5724 ConstantRange(APInt::getSignedMinValue(BitWidth
).ashr(NS
- 1),
5725 APInt::getSignedMaxValue(BitWidth
).ashr(NS
- 1) + 1));
5728 // A range of Phi is a subset of union of all ranges of its input.
5729 if (const PHINode
*Phi
= dyn_cast
<PHINode
>(U
->getValue())) {
5730 // Make sure that we do not run over cycled Phis.
5731 if (PendingPhiRanges
.insert(Phi
).second
) {
5732 ConstantRange
RangeFromOps(BitWidth
, /*isFullSet=*/false);
5733 for (auto &Op
: Phi
->operands()) {
5734 auto OpRange
= getRangeRef(getSCEV(Op
), SignHint
);
5735 RangeFromOps
= RangeFromOps
.unionWith(OpRange
);
5736 // No point to continue if we already have a full set.
5737 if (RangeFromOps
.isFullSet())
5740 ConservativeResult
= ConservativeResult
.intersectWith(RangeFromOps
);
5741 bool Erased
= PendingPhiRanges
.erase(Phi
);
5742 assert(Erased
&& "Failed to erase Phi properly?");
5747 return setRange(U
, SignHint
, std::move(ConservativeResult
));
5750 return setRange(S
, SignHint
, std::move(ConservativeResult
));
5753 // Given a StartRange, Step and MaxBECount for an expression compute a range of
5754 // values that the expression can take. Initially, the expression has a value
5755 // from StartRange and then is changed by Step up to MaxBECount times. Signed
5756 // argument defines if we treat Step as signed or unsigned.
5757 static ConstantRange
getRangeForAffineARHelper(APInt Step
,
5758 const ConstantRange
&StartRange
,
5759 const APInt
&MaxBECount
,
5760 unsigned BitWidth
, bool Signed
) {
5761 // If either Step or MaxBECount is 0, then the expression won't change, and we
5762 // just need to return the initial range.
5763 if (Step
== 0 || MaxBECount
== 0)
5766 // If we don't know anything about the initial value (i.e. StartRange is
5767 // FullRange), then we don't know anything about the final range either.
5768 // Return FullRange.
5769 if (StartRange
.isFullSet())
5770 return ConstantRange(BitWidth
, /* isFullSet = */ true);
5772 // If Step is signed and negative, then we use its absolute value, but we also
5773 // note that we're moving in the opposite direction.
5774 bool Descending
= Signed
&& Step
.isNegative();
5777 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
5778 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
5779 // This equations hold true due to the well-defined wrap-around behavior of
5783 // Check if Offset is more than full span of BitWidth. If it is, the
5784 // expression is guaranteed to overflow.
5785 if (APInt::getMaxValue(StartRange
.getBitWidth()).udiv(Step
).ult(MaxBECount
))
5786 return ConstantRange(BitWidth
, /* isFullSet = */ true);
5788 // Offset is by how much the expression can change. Checks above guarantee no
5790 APInt Offset
= Step
* MaxBECount
;
5792 // Minimum value of the final range will match the minimal value of StartRange
5793 // if the expression is increasing and will be decreased by Offset otherwise.
5794 // Maximum value of the final range will match the maximal value of StartRange
5795 // if the expression is decreasing and will be increased by Offset otherwise.
5796 APInt StartLower
= StartRange
.getLower();
5797 APInt StartUpper
= StartRange
.getUpper() - 1;
5798 APInt MovedBoundary
= Descending
? (StartLower
- std::move(Offset
))
5799 : (StartUpper
+ std::move(Offset
));
5801 // It's possible that the new minimum/maximum value will fall into the initial
5802 // range (due to wrap around). This means that the expression can take any
5803 // value in this bitwidth, and we have to return full range.
5804 if (StartRange
.contains(MovedBoundary
))
5805 return ConstantRange(BitWidth
, /* isFullSet = */ true);
5808 Descending
? std::move(MovedBoundary
) : std::move(StartLower
);
5810 Descending
? std::move(StartUpper
) : std::move(MovedBoundary
);
5813 // If we end up with full range, return a proper full range.
5814 if (NewLower
== NewUpper
)
5815 return ConstantRange(BitWidth
, /* isFullSet = */ true);
5817 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
5818 return ConstantRange(std::move(NewLower
), std::move(NewUpper
));
5821 ConstantRange
ScalarEvolution::getRangeForAffineAR(const SCEV
*Start
,
5823 const SCEV
*MaxBECount
,
5824 unsigned BitWidth
) {
5825 assert(!isa
<SCEVCouldNotCompute
>(MaxBECount
) &&
5826 getTypeSizeInBits(MaxBECount
->getType()) <= BitWidth
&&
5829 MaxBECount
= getNoopOrZeroExtend(MaxBECount
, Start
->getType());
5830 APInt MaxBECountValue
= getUnsignedRangeMax(MaxBECount
);
5832 // First, consider step signed.
5833 ConstantRange StartSRange
= getSignedRange(Start
);
5834 ConstantRange StepSRange
= getSignedRange(Step
);
5836 // If Step can be both positive and negative, we need to find ranges for the
5837 // maximum absolute step values in both directions and union them.
5839 getRangeForAffineARHelper(StepSRange
.getSignedMin(), StartSRange
,
5840 MaxBECountValue
, BitWidth
, /* Signed = */ true);
5841 SR
= SR
.unionWith(getRangeForAffineARHelper(StepSRange
.getSignedMax(),
5842 StartSRange
, MaxBECountValue
,
5843 BitWidth
, /* Signed = */ true));
5845 // Next, consider step unsigned.
5846 ConstantRange UR
= getRangeForAffineARHelper(
5847 getUnsignedRangeMax(Step
), getUnsignedRange(Start
),
5848 MaxBECountValue
, BitWidth
, /* Signed = */ false);
5850 // Finally, intersect signed and unsigned ranges.
5851 return SR
.intersectWith(UR
);
5854 ConstantRange
ScalarEvolution::getRangeViaFactoring(const SCEV
*Start
,
5856 const SCEV
*MaxBECount
,
5857 unsigned BitWidth
) {
5858 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
5859 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
5861 struct SelectPattern
{
5862 Value
*Condition
= nullptr;
5866 explicit SelectPattern(ScalarEvolution
&SE
, unsigned BitWidth
,
5868 Optional
<unsigned> CastOp
;
5869 APInt
Offset(BitWidth
, 0);
5871 assert(SE
.getTypeSizeInBits(S
->getType()) == BitWidth
&&
5874 // Peel off a constant offset:
5875 if (auto *SA
= dyn_cast
<SCEVAddExpr
>(S
)) {
5876 // In the future we could consider being smarter here and handle
5877 // {Start+Step,+,Step} too.
5878 if (SA
->getNumOperands() != 2 || !isa
<SCEVConstant
>(SA
->getOperand(0)))
5881 Offset
= cast
<SCEVConstant
>(SA
->getOperand(0))->getAPInt();
5882 S
= SA
->getOperand(1);
5885 // Peel off a cast operation
5886 if (auto *SCast
= dyn_cast
<SCEVCastExpr
>(S
)) {
5887 CastOp
= SCast
->getSCEVType();
5888 S
= SCast
->getOperand();
5891 using namespace llvm::PatternMatch
;
5893 auto *SU
= dyn_cast
<SCEVUnknown
>(S
);
5894 const APInt
*TrueVal
, *FalseVal
;
5896 !match(SU
->getValue(), m_Select(m_Value(Condition
), m_APInt(TrueVal
),
5897 m_APInt(FalseVal
)))) {
5898 Condition
= nullptr;
5902 TrueValue
= *TrueVal
;
5903 FalseValue
= *FalseVal
;
5905 // Re-apply the cast we peeled off earlier
5906 if (CastOp
.hasValue())
5909 llvm_unreachable("Unknown SCEV cast type!");
5912 TrueValue
= TrueValue
.trunc(BitWidth
);
5913 FalseValue
= FalseValue
.trunc(BitWidth
);
5916 TrueValue
= TrueValue
.zext(BitWidth
);
5917 FalseValue
= FalseValue
.zext(BitWidth
);
5920 TrueValue
= TrueValue
.sext(BitWidth
);
5921 FalseValue
= FalseValue
.sext(BitWidth
);
5925 // Re-apply the constant offset we peeled off earlier
5926 TrueValue
+= Offset
;
5927 FalseValue
+= Offset
;
5930 bool isRecognized() { return Condition
!= nullptr; }
5933 SelectPattern
StartPattern(*this, BitWidth
, Start
);
5934 if (!StartPattern
.isRecognized())
5935 return ConstantRange(BitWidth
, /* isFullSet = */ true);
5937 SelectPattern
StepPattern(*this, BitWidth
, Step
);
5938 if (!StepPattern
.isRecognized())
5939 return ConstantRange(BitWidth
, /* isFullSet = */ true);
5941 if (StartPattern
.Condition
!= StepPattern
.Condition
) {
5942 // We don't handle this case today; but we could, by considering four
5943 // possibilities below instead of two. I'm not sure if there are cases where
5944 // that will help over what getRange already does, though.
5945 return ConstantRange(BitWidth
, /* isFullSet = */ true);
5948 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
5949 // construct arbitrary general SCEV expressions here. This function is called
5950 // from deep in the call stack, and calling getSCEV (on a sext instruction,
5951 // say) can end up caching a suboptimal value.
5953 // FIXME: without the explicit `this` receiver below, MSVC errors out with
5954 // C2352 and C2512 (otherwise it isn't needed).
5956 const SCEV
*TrueStart
= this->getConstant(StartPattern
.TrueValue
);
5957 const SCEV
*TrueStep
= this->getConstant(StepPattern
.TrueValue
);
5958 const SCEV
*FalseStart
= this->getConstant(StartPattern
.FalseValue
);
5959 const SCEV
*FalseStep
= this->getConstant(StepPattern
.FalseValue
);
5961 ConstantRange TrueRange
=
5962 this->getRangeForAffineAR(TrueStart
, TrueStep
, MaxBECount
, BitWidth
);
5963 ConstantRange FalseRange
=
5964 this->getRangeForAffineAR(FalseStart
, FalseStep
, MaxBECount
, BitWidth
);
5966 return TrueRange
.unionWith(FalseRange
);
5969 SCEV::NoWrapFlags
ScalarEvolution::getNoWrapFlagsFromUB(const Value
*V
) {
5970 if (isa
<ConstantExpr
>(V
)) return SCEV::FlagAnyWrap
;
5971 const BinaryOperator
*BinOp
= cast
<BinaryOperator
>(V
);
5973 // Return early if there are no flags to propagate to the SCEV.
5974 SCEV::NoWrapFlags Flags
= SCEV::FlagAnyWrap
;
5975 if (BinOp
->hasNoUnsignedWrap())
5976 Flags
= ScalarEvolution::setFlags(Flags
, SCEV::FlagNUW
);
5977 if (BinOp
->hasNoSignedWrap())
5978 Flags
= ScalarEvolution::setFlags(Flags
, SCEV::FlagNSW
);
5979 if (Flags
== SCEV::FlagAnyWrap
)
5980 return SCEV::FlagAnyWrap
;
5982 return isSCEVExprNeverPoison(BinOp
) ? Flags
: SCEV::FlagAnyWrap
;
5985 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction
*I
) {
5986 // Here we check that I is in the header of the innermost loop containing I,
5987 // since we only deal with instructions in the loop header. The actual loop we
5988 // need to check later will come from an add recurrence, but getting that
5989 // requires computing the SCEV of the operands, which can be expensive. This
5990 // check we can do cheaply to rule out some cases early.
5991 Loop
*InnermostContainingLoop
= LI
.getLoopFor(I
->getParent());
5992 if (InnermostContainingLoop
== nullptr ||
5993 InnermostContainingLoop
->getHeader() != I
->getParent())
5996 // Only proceed if we can prove that I does not yield poison.
5997 if (!programUndefinedIfFullPoison(I
))
6000 // At this point we know that if I is executed, then it does not wrap
6001 // according to at least one of NSW or NUW. If I is not executed, then we do
6002 // not know if the calculation that I represents would wrap. Multiple
6003 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
6004 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
6005 // derived from other instructions that map to the same SCEV. We cannot make
6006 // that guarantee for cases where I is not executed. So we need to find the
6007 // loop that I is considered in relation to and prove that I is executed for
6008 // every iteration of that loop. That implies that the value that I
6009 // calculates does not wrap anywhere in the loop, so then we can apply the
6010 // flags to the SCEV.
6012 // We check isLoopInvariant to disambiguate in case we are adding recurrences
6013 // from different loops, so that we know which loop to prove that I is
6015 for (unsigned OpIndex
= 0; OpIndex
< I
->getNumOperands(); ++OpIndex
) {
6016 // I could be an extractvalue from a call to an overflow intrinsic.
6017 // TODO: We can do better here in some cases.
6018 if (!isSCEVable(I
->getOperand(OpIndex
)->getType()))
6020 const SCEV
*Op
= getSCEV(I
->getOperand(OpIndex
));
6021 if (auto *AddRec
= dyn_cast
<SCEVAddRecExpr
>(Op
)) {
6022 bool AllOtherOpsLoopInvariant
= true;
6023 for (unsigned OtherOpIndex
= 0; OtherOpIndex
< I
->getNumOperands();
6025 if (OtherOpIndex
!= OpIndex
) {
6026 const SCEV
*OtherOp
= getSCEV(I
->getOperand(OtherOpIndex
));
6027 if (!isLoopInvariant(OtherOp
, AddRec
->getLoop())) {
6028 AllOtherOpsLoopInvariant
= false;
6033 if (AllOtherOpsLoopInvariant
&&
6034 isGuaranteedToExecuteForEveryIteration(I
, AddRec
->getLoop()))
6041 bool ScalarEvolution::isAddRecNeverPoison(const Instruction
*I
, const Loop
*L
) {
6042 // If we know that \c I can never be poison period, then that's enough.
6043 if (isSCEVExprNeverPoison(I
))
6046 // For an add recurrence specifically, we assume that infinite loops without
6047 // side effects are undefined behavior, and then reason as follows:
6049 // If the add recurrence is poison in any iteration, it is poison on all
6050 // future iterations (since incrementing poison yields poison). If the result
6051 // of the add recurrence is fed into the loop latch condition and the loop
6052 // does not contain any throws or exiting blocks other than the latch, we now
6053 // have the ability to "choose" whether the backedge is taken or not (by
6054 // choosing a sufficiently evil value for the poison feeding into the branch)
6055 // for every iteration including and after the one in which \p I first became
6056 // poison. There are two possibilities (let's call the iteration in which \p
6057 // I first became poison as K):
6059 // 1. In the set of iterations including and after K, the loop body executes
6060 // no side effects. In this case executing the backege an infinte number
6061 // of times will yield undefined behavior.
6063 // 2. In the set of iterations including and after K, the loop body executes
6064 // at least one side effect. In this case, that specific instance of side
6065 // effect is control dependent on poison, which also yields undefined
6068 auto *ExitingBB
= L
->getExitingBlock();
6069 auto *LatchBB
= L
->getLoopLatch();
6070 if (!ExitingBB
|| !LatchBB
|| ExitingBB
!= LatchBB
)
6073 SmallPtrSet
<const Instruction
*, 16> Pushed
;
6074 SmallVector
<const Instruction
*, 8> PoisonStack
;
6076 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
6077 // things that are known to be fully poison under that assumption go on the
6080 PoisonStack
.push_back(I
);
6082 bool LatchControlDependentOnPoison
= false;
6083 while (!PoisonStack
.empty() && !LatchControlDependentOnPoison
) {
6084 const Instruction
*Poison
= PoisonStack
.pop_back_val();
6086 for (auto *PoisonUser
: Poison
->users()) {
6087 if (propagatesFullPoison(cast
<Instruction
>(PoisonUser
))) {
6088 if (Pushed
.insert(cast
<Instruction
>(PoisonUser
)).second
)
6089 PoisonStack
.push_back(cast
<Instruction
>(PoisonUser
));
6090 } else if (auto *BI
= dyn_cast
<BranchInst
>(PoisonUser
)) {
6091 assert(BI
->isConditional() && "Only possibility!");
6092 if (BI
->getParent() == LatchBB
) {
6093 LatchControlDependentOnPoison
= true;
6100 return LatchControlDependentOnPoison
&& loopHasNoAbnormalExits(L
);
6103 ScalarEvolution::LoopProperties
6104 ScalarEvolution::getLoopProperties(const Loop
*L
) {
6105 using LoopProperties
= ScalarEvolution::LoopProperties
;
6107 auto Itr
= LoopPropertiesCache
.find(L
);
6108 if (Itr
== LoopPropertiesCache
.end()) {
6109 auto HasSideEffects
= [](Instruction
*I
) {
6110 if (auto *SI
= dyn_cast
<StoreInst
>(I
))
6111 return !SI
->isSimple();
6113 return I
->mayHaveSideEffects();
6116 LoopProperties LP
= {/* HasNoAbnormalExits */ true,
6117 /*HasNoSideEffects*/ true};
6119 for (auto *BB
: L
->getBlocks())
6120 for (auto &I
: *BB
) {
6121 if (!isGuaranteedToTransferExecutionToSuccessor(&I
))
6122 LP
.HasNoAbnormalExits
= false;
6123 if (HasSideEffects(&I
))
6124 LP
.HasNoSideEffects
= false;
6125 if (!LP
.HasNoAbnormalExits
&& !LP
.HasNoSideEffects
)
6126 break; // We're already as pessimistic as we can get.
6129 auto InsertPair
= LoopPropertiesCache
.insert({L
, LP
});
6130 assert(InsertPair
.second
&& "We just checked!");
6131 Itr
= InsertPair
.first
;
6137 const SCEV
*ScalarEvolution::createSCEV(Value
*V
) {
6138 if (!isSCEVable(V
->getType()))
6139 return getUnknown(V
);
6141 if (Instruction
*I
= dyn_cast
<Instruction
>(V
)) {
6142 // Don't attempt to analyze instructions in blocks that aren't
6143 // reachable. Such instructions don't matter, and they aren't required
6144 // to obey basic rules for definitions dominating uses which this
6145 // analysis depends on.
6146 if (!DT
.isReachableFromEntry(I
->getParent()))
6147 return getUnknown(UndefValue::get(V
->getType()));
6148 } else if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(V
))
6149 return getConstant(CI
);
6150 else if (isa
<ConstantPointerNull
>(V
))
6151 return getZero(V
->getType());
6152 else if (GlobalAlias
*GA
= dyn_cast
<GlobalAlias
>(V
))
6153 return GA
->isInterposable() ? getUnknown(V
) : getSCEV(GA
->getAliasee());
6154 else if (!isa
<ConstantExpr
>(V
))
6155 return getUnknown(V
);
6157 Operator
*U
= cast
<Operator
>(V
);
6158 if (auto BO
= MatchBinaryOp(U
, DT
)) {
6159 switch (BO
->Opcode
) {
6160 case Instruction::Add
: {
6161 // The simple thing to do would be to just call getSCEV on both operands
6162 // and call getAddExpr with the result. However if we're looking at a
6163 // bunch of things all added together, this can be quite inefficient,
6164 // because it leads to N-1 getAddExpr calls for N ultimate operands.
6165 // Instead, gather up all the operands and make a single getAddExpr call.
6166 // LLVM IR canonical form means we need only traverse the left operands.
6167 SmallVector
<const SCEV
*, 4> AddOps
;
6170 if (auto *OpSCEV
= getExistingSCEV(BO
->Op
)) {
6171 AddOps
.push_back(OpSCEV
);
6175 // If a NUW or NSW flag can be applied to the SCEV for this
6176 // addition, then compute the SCEV for this addition by itself
6177 // with a separate call to getAddExpr. We need to do that
6178 // instead of pushing the operands of the addition onto AddOps,
6179 // since the flags are only known to apply to this particular
6180 // addition - they may not apply to other additions that can be
6181 // formed with operands from AddOps.
6182 const SCEV
*RHS
= getSCEV(BO
->RHS
);
6183 SCEV::NoWrapFlags Flags
= getNoWrapFlagsFromUB(BO
->Op
);
6184 if (Flags
!= SCEV::FlagAnyWrap
) {
6185 const SCEV
*LHS
= getSCEV(BO
->LHS
);
6186 if (BO
->Opcode
== Instruction::Sub
)
6187 AddOps
.push_back(getMinusSCEV(LHS
, RHS
, Flags
));
6189 AddOps
.push_back(getAddExpr(LHS
, RHS
, Flags
));
6194 if (BO
->Opcode
== Instruction::Sub
)
6195 AddOps
.push_back(getNegativeSCEV(getSCEV(BO
->RHS
)));
6197 AddOps
.push_back(getSCEV(BO
->RHS
));
6199 auto NewBO
= MatchBinaryOp(BO
->LHS
, DT
);
6200 if (!NewBO
|| (NewBO
->Opcode
!= Instruction::Add
&&
6201 NewBO
->Opcode
!= Instruction::Sub
)) {
6202 AddOps
.push_back(getSCEV(BO
->LHS
));
6208 return getAddExpr(AddOps
);
6211 case Instruction::Mul
: {
6212 SmallVector
<const SCEV
*, 4> MulOps
;
6215 if (auto *OpSCEV
= getExistingSCEV(BO
->Op
)) {
6216 MulOps
.push_back(OpSCEV
);
6220 SCEV::NoWrapFlags Flags
= getNoWrapFlagsFromUB(BO
->Op
);
6221 if (Flags
!= SCEV::FlagAnyWrap
) {
6223 getMulExpr(getSCEV(BO
->LHS
), getSCEV(BO
->RHS
), Flags
));
6228 MulOps
.push_back(getSCEV(BO
->RHS
));
6229 auto NewBO
= MatchBinaryOp(BO
->LHS
, DT
);
6230 if (!NewBO
|| NewBO
->Opcode
!= Instruction::Mul
) {
6231 MulOps
.push_back(getSCEV(BO
->LHS
));
6237 return getMulExpr(MulOps
);
6239 case Instruction::UDiv
:
6240 return getUDivExpr(getSCEV(BO
->LHS
), getSCEV(BO
->RHS
));
6241 case Instruction::URem
:
6242 return getURemExpr(getSCEV(BO
->LHS
), getSCEV(BO
->RHS
));
6243 case Instruction::Sub
: {
6244 SCEV::NoWrapFlags Flags
= SCEV::FlagAnyWrap
;
6246 Flags
= getNoWrapFlagsFromUB(BO
->Op
);
6247 return getMinusSCEV(getSCEV(BO
->LHS
), getSCEV(BO
->RHS
), Flags
);
6249 case Instruction::And
:
6250 // For an expression like x&255 that merely masks off the high bits,
6251 // use zext(trunc(x)) as the SCEV expression.
6252 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(BO
->RHS
)) {
6254 return getSCEV(BO
->RHS
);
6255 if (CI
->isMinusOne())
6256 return getSCEV(BO
->LHS
);
6257 const APInt
&A
= CI
->getValue();
6259 // Instcombine's ShrinkDemandedConstant may strip bits out of
6260 // constants, obscuring what would otherwise be a low-bits mask.
6261 // Use computeKnownBits to compute what ShrinkDemandedConstant
6262 // knew about to reconstruct a low-bits mask value.
6263 unsigned LZ
= A
.countLeadingZeros();
6264 unsigned TZ
= A
.countTrailingZeros();
6265 unsigned BitWidth
= A
.getBitWidth();
6266 KnownBits
Known(BitWidth
);
6267 computeKnownBits(BO
->LHS
, Known
, getDataLayout(),
6268 0, &AC
, nullptr, &DT
);
6270 APInt EffectiveMask
=
6271 APInt::getLowBitsSet(BitWidth
, BitWidth
- LZ
- TZ
).shl(TZ
);
6272 if ((LZ
!= 0 || TZ
!= 0) && !((~A
& ~Known
.Zero
) & EffectiveMask
)) {
6273 const SCEV
*MulCount
= getConstant(APInt::getOneBitSet(BitWidth
, TZ
));
6274 const SCEV
*LHS
= getSCEV(BO
->LHS
);
6275 const SCEV
*ShiftedLHS
= nullptr;
6276 if (auto *LHSMul
= dyn_cast
<SCEVMulExpr
>(LHS
)) {
6277 if (auto *OpC
= dyn_cast
<SCEVConstant
>(LHSMul
->getOperand(0))) {
6278 // For an expression like (x * 8) & 8, simplify the multiply.
6279 unsigned MulZeros
= OpC
->getAPInt().countTrailingZeros();
6280 unsigned GCD
= std::min(MulZeros
, TZ
);
6281 APInt DivAmt
= APInt::getOneBitSet(BitWidth
, TZ
- GCD
);
6282 SmallVector
<const SCEV
*, 4> MulOps
;
6283 MulOps
.push_back(getConstant(OpC
->getAPInt().lshr(GCD
)));
6284 MulOps
.append(LHSMul
->op_begin() + 1, LHSMul
->op_end());
6285 auto *NewMul
= getMulExpr(MulOps
, LHSMul
->getNoWrapFlags());
6286 ShiftedLHS
= getUDivExpr(NewMul
, getConstant(DivAmt
));
6290 ShiftedLHS
= getUDivExpr(LHS
, MulCount
);
6293 getTruncateExpr(ShiftedLHS
,
6294 IntegerType::get(getContext(), BitWidth
- LZ
- TZ
)),
6295 BO
->LHS
->getType()),
6301 case Instruction::Or
:
6302 // If the RHS of the Or is a constant, we may have something like:
6303 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
6304 // optimizations will transparently handle this case.
6306 // In order for this transformation to be safe, the LHS must be of the
6307 // form X*(2^n) and the Or constant must be less than 2^n.
6308 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(BO
->RHS
)) {
6309 const SCEV
*LHS
= getSCEV(BO
->LHS
);
6310 const APInt
&CIVal
= CI
->getValue();
6311 if (GetMinTrailingZeros(LHS
) >=
6312 (CIVal
.getBitWidth() - CIVal
.countLeadingZeros())) {
6313 // Build a plain add SCEV.
6314 const SCEV
*S
= getAddExpr(LHS
, getSCEV(CI
));
6315 // If the LHS of the add was an addrec and it has no-wrap flags,
6316 // transfer the no-wrap flags, since an or won't introduce a wrap.
6317 if (const SCEVAddRecExpr
*NewAR
= dyn_cast
<SCEVAddRecExpr
>(S
)) {
6318 const SCEVAddRecExpr
*OldAR
= cast
<SCEVAddRecExpr
>(LHS
);
6319 const_cast<SCEVAddRecExpr
*>(NewAR
)->setNoWrapFlags(
6320 OldAR
->getNoWrapFlags());
6327 case Instruction::Xor
:
6328 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(BO
->RHS
)) {
6329 // If the RHS of xor is -1, then this is a not operation.
6330 if (CI
->isMinusOne())
6331 return getNotSCEV(getSCEV(BO
->LHS
));
6333 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
6334 // This is a variant of the check for xor with -1, and it handles
6335 // the case where instcombine has trimmed non-demanded bits out
6336 // of an xor with -1.
6337 if (auto *LBO
= dyn_cast
<BinaryOperator
>(BO
->LHS
))
6338 if (ConstantInt
*LCI
= dyn_cast
<ConstantInt
>(LBO
->getOperand(1)))
6339 if (LBO
->getOpcode() == Instruction::And
&&
6340 LCI
->getValue() == CI
->getValue())
6341 if (const SCEVZeroExtendExpr
*Z
=
6342 dyn_cast
<SCEVZeroExtendExpr
>(getSCEV(BO
->LHS
))) {
6343 Type
*UTy
= BO
->LHS
->getType();
6344 const SCEV
*Z0
= Z
->getOperand();
6345 Type
*Z0Ty
= Z0
->getType();
6346 unsigned Z0TySize
= getTypeSizeInBits(Z0Ty
);
6348 // If C is a low-bits mask, the zero extend is serving to
6349 // mask off the high bits. Complement the operand and
6350 // re-apply the zext.
6351 if (CI
->getValue().isMask(Z0TySize
))
6352 return getZeroExtendExpr(getNotSCEV(Z0
), UTy
);
6354 // If C is a single bit, it may be in the sign-bit position
6355 // before the zero-extend. In this case, represent the xor
6356 // using an add, which is equivalent, and re-apply the zext.
6357 APInt Trunc
= CI
->getValue().trunc(Z0TySize
);
6358 if (Trunc
.zext(getTypeSizeInBits(UTy
)) == CI
->getValue() &&
6360 return getZeroExtendExpr(getAddExpr(Z0
, getConstant(Trunc
)),
6366 case Instruction::Shl
:
6367 // Turn shift left of a constant amount into a multiply.
6368 if (ConstantInt
*SA
= dyn_cast
<ConstantInt
>(BO
->RHS
)) {
6369 uint32_t BitWidth
= cast
<IntegerType
>(SA
->getType())->getBitWidth();
6371 // If the shift count is not less than the bitwidth, the result of
6372 // the shift is undefined. Don't try to analyze it, because the
6373 // resolution chosen here may differ from the resolution chosen in
6374 // other parts of the compiler.
6375 if (SA
->getValue().uge(BitWidth
))
6378 // It is currently not resolved how to interpret NSW for left
6379 // shift by BitWidth - 1, so we avoid applying flags in that
6380 // case. Remove this check (or this comment) once the situation
6382 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
6383 // and http://reviews.llvm.org/D8890 .
6384 auto Flags
= SCEV::FlagAnyWrap
;
6385 if (BO
->Op
&& SA
->getValue().ult(BitWidth
- 1))
6386 Flags
= getNoWrapFlagsFromUB(BO
->Op
);
6388 Constant
*X
= ConstantInt::get(
6389 getContext(), APInt::getOneBitSet(BitWidth
, SA
->getZExtValue()));
6390 return getMulExpr(getSCEV(BO
->LHS
), getSCEV(X
), Flags
);
6394 case Instruction::AShr
: {
6395 // AShr X, C, where C is a constant.
6396 ConstantInt
*CI
= dyn_cast
<ConstantInt
>(BO
->RHS
);
6400 Type
*OuterTy
= BO
->LHS
->getType();
6401 uint64_t BitWidth
= getTypeSizeInBits(OuterTy
);
6402 // If the shift count is not less than the bitwidth, the result of
6403 // the shift is undefined. Don't try to analyze it, because the
6404 // resolution chosen here may differ from the resolution chosen in
6405 // other parts of the compiler.
6406 if (CI
->getValue().uge(BitWidth
))
6410 return getSCEV(BO
->LHS
); // shift by zero --> noop
6412 uint64_t AShrAmt
= CI
->getZExtValue();
6413 Type
*TruncTy
= IntegerType::get(getContext(), BitWidth
- AShrAmt
);
6415 Operator
*L
= dyn_cast
<Operator
>(BO
->LHS
);
6416 if (L
&& L
->getOpcode() == Instruction::Shl
) {
6419 // Both n and m are constant.
6421 const SCEV
*ShlOp0SCEV
= getSCEV(L
->getOperand(0));
6422 if (L
->getOperand(1) == BO
->RHS
)
6423 // For a two-shift sext-inreg, i.e. n = m,
6424 // use sext(trunc(x)) as the SCEV expression.
6425 return getSignExtendExpr(
6426 getTruncateExpr(ShlOp0SCEV
, TruncTy
), OuterTy
);
6428 ConstantInt
*ShlAmtCI
= dyn_cast
<ConstantInt
>(L
->getOperand(1));
6429 if (ShlAmtCI
&& ShlAmtCI
->getValue().ult(BitWidth
)) {
6430 uint64_t ShlAmt
= ShlAmtCI
->getZExtValue();
6431 if (ShlAmt
> AShrAmt
) {
6432 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
6433 // expression. We already checked that ShlAmt < BitWidth, so
6434 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
6435 // ShlAmt - AShrAmt < Amt.
6436 APInt Mul
= APInt::getOneBitSet(BitWidth
- AShrAmt
,
6438 return getSignExtendExpr(
6439 getMulExpr(getTruncateExpr(ShlOp0SCEV
, TruncTy
),
6440 getConstant(Mul
)), OuterTy
);
6449 switch (U
->getOpcode()) {
6450 case Instruction::Trunc
:
6451 return getTruncateExpr(getSCEV(U
->getOperand(0)), U
->getType());
6453 case Instruction::ZExt
:
6454 return getZeroExtendExpr(getSCEV(U
->getOperand(0)), U
->getType());
6456 case Instruction::SExt
:
6457 if (auto BO
= MatchBinaryOp(U
->getOperand(0), DT
)) {
6458 // The NSW flag of a subtract does not always survive the conversion to
6459 // A + (-1)*B. By pushing sign extension onto its operands we are much
6460 // more likely to preserve NSW and allow later AddRec optimisations.
6462 // NOTE: This is effectively duplicating this logic from getSignExtend:
6463 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
6464 // but by that point the NSW information has potentially been lost.
6465 if (BO
->Opcode
== Instruction::Sub
&& BO
->IsNSW
) {
6466 Type
*Ty
= U
->getType();
6467 auto *V1
= getSignExtendExpr(getSCEV(BO
->LHS
), Ty
);
6468 auto *V2
= getSignExtendExpr(getSCEV(BO
->RHS
), Ty
);
6469 return getMinusSCEV(V1
, V2
, SCEV::FlagNSW
);
6472 return getSignExtendExpr(getSCEV(U
->getOperand(0)), U
->getType());
6474 case Instruction::BitCast
:
6475 // BitCasts are no-op casts so we just eliminate the cast.
6476 if (isSCEVable(U
->getType()) && isSCEVable(U
->getOperand(0)->getType()))
6477 return getSCEV(U
->getOperand(0));
6480 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
6481 // lead to pointer expressions which cannot safely be expanded to GEPs,
6482 // because ScalarEvolution doesn't respect the GEP aliasing rules when
6483 // simplifying integer expressions.
6485 case Instruction::GetElementPtr
:
6486 return createNodeForGEP(cast
<GEPOperator
>(U
));
6488 case Instruction::PHI
:
6489 return createNodeForPHI(cast
<PHINode
>(U
));
6491 case Instruction::Select
:
6492 // U can also be a select constant expr, which let fall through. Since
6493 // createNodeForSelect only works for a condition that is an `ICmpInst`, and
6494 // constant expressions cannot have instructions as operands, we'd have
6495 // returned getUnknown for a select constant expressions anyway.
6496 if (isa
<Instruction
>(U
))
6497 return createNodeForSelectOrPHI(cast
<Instruction
>(U
), U
->getOperand(0),
6498 U
->getOperand(1), U
->getOperand(2));
6501 case Instruction::Call
:
6502 case Instruction::Invoke
:
6503 if (Value
*RV
= CallSite(U
).getReturnedArgOperand())
6508 return getUnknown(V
);
6511 //===----------------------------------------------------------------------===//
6512 // Iteration Count Computation Code
6515 static unsigned getConstantTripCount(const SCEVConstant
*ExitCount
) {
6519 ConstantInt
*ExitConst
= ExitCount
->getValue();
6521 // Guard against huge trip counts.
6522 if (ExitConst
->getValue().getActiveBits() > 32)
6525 // In case of integer overflow, this returns 0, which is correct.
6526 return ((unsigned)ExitConst
->getZExtValue()) + 1;
6529 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop
*L
) {
6530 if (BasicBlock
*ExitingBB
= L
->getExitingBlock())
6531 return getSmallConstantTripCount(L
, ExitingBB
);
6533 // No trip count information for multiple exits.
6537 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop
*L
,
6538 BasicBlock
*ExitingBlock
) {
6539 assert(ExitingBlock
&& "Must pass a non-null exiting block!");
6540 assert(L
->isLoopExiting(ExitingBlock
) &&
6541 "Exiting block must actually branch out of the loop!");
6542 const SCEVConstant
*ExitCount
=
6543 dyn_cast
<SCEVConstant
>(getExitCount(L
, ExitingBlock
));
6544 return getConstantTripCount(ExitCount
);
6547 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop
*L
) {
6548 const auto *MaxExitCount
=
6549 dyn_cast
<SCEVConstant
>(getMaxBackedgeTakenCount(L
));
6550 return getConstantTripCount(MaxExitCount
);
6553 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop
*L
) {
6554 if (BasicBlock
*ExitingBB
= L
->getExitingBlock())
6555 return getSmallConstantTripMultiple(L
, ExitingBB
);
6557 // No trip multiple information for multiple exits.
6561 /// Returns the largest constant divisor of the trip count of this loop as a
6562 /// normal unsigned value, if possible. This means that the actual trip count is
6563 /// always a multiple of the returned value (don't forget the trip count could
6564 /// very well be zero as well!).
6566 /// Returns 1 if the trip count is unknown or not guaranteed to be the
6567 /// multiple of a constant (which is also the case if the trip count is simply
6568 /// constant, use getSmallConstantTripCount for that case), Will also return 1
6569 /// if the trip count is very large (>= 2^32).
6571 /// As explained in the comments for getSmallConstantTripCount, this assumes
6572 /// that control exits the loop via ExitingBlock.
6574 ScalarEvolution::getSmallConstantTripMultiple(const Loop
*L
,
6575 BasicBlock
*ExitingBlock
) {
6576 assert(ExitingBlock
&& "Must pass a non-null exiting block!");
6577 assert(L
->isLoopExiting(ExitingBlock
) &&
6578 "Exiting block must actually branch out of the loop!");
6579 const SCEV
*ExitCount
= getExitCount(L
, ExitingBlock
);
6580 if (ExitCount
== getCouldNotCompute())
6583 // Get the trip count from the BE count by adding 1.
6584 const SCEV
*TCExpr
= getAddExpr(ExitCount
, getOne(ExitCount
->getType()));
6586 const SCEVConstant
*TC
= dyn_cast
<SCEVConstant
>(TCExpr
);
6588 // Attempt to factor more general cases. Returns the greatest power of
6589 // two divisor. If overflow happens, the trip count expression is still
6590 // divisible by the greatest power of 2 divisor returned.
6591 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr
));
6593 ConstantInt
*Result
= TC
->getValue();
6595 // Guard against huge trip counts (this requires checking
6596 // for zero to handle the case where the trip count == -1 and the
6598 if (!Result
|| Result
->getValue().getActiveBits() > 32 ||
6599 Result
->getValue().getActiveBits() == 0)
6602 return (unsigned)Result
->getZExtValue();
6605 /// Get the expression for the number of loop iterations for which this loop is
6606 /// guaranteed not to exit via ExitingBlock. Otherwise return
6607 /// SCEVCouldNotCompute.
6608 const SCEV
*ScalarEvolution::getExitCount(const Loop
*L
,
6609 BasicBlock
*ExitingBlock
) {
6610 return getBackedgeTakenInfo(L
).getExact(ExitingBlock
, this);
6614 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop
*L
,
6615 SCEVUnionPredicate
&Preds
) {
6616 return getPredicatedBackedgeTakenInfo(L
).getExact(L
, this, &Preds
);
6619 const SCEV
*ScalarEvolution::getBackedgeTakenCount(const Loop
*L
) {
6620 return getBackedgeTakenInfo(L
).getExact(L
, this);
6623 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is
6624 /// known never to be less than the actual backedge taken count.
6625 const SCEV
*ScalarEvolution::getMaxBackedgeTakenCount(const Loop
*L
) {
6626 return getBackedgeTakenInfo(L
).getMax(this);
6629 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop
*L
) {
6630 return getBackedgeTakenInfo(L
).isMaxOrZero(this);
6633 /// Push PHI nodes in the header of the given loop onto the given Worklist.
6635 PushLoopPHIs(const Loop
*L
, SmallVectorImpl
<Instruction
*> &Worklist
) {
6636 BasicBlock
*Header
= L
->getHeader();
6638 // Push all Loop-header PHIs onto the Worklist stack.
6639 for (PHINode
&PN
: Header
->phis())
6640 Worklist
.push_back(&PN
);
6643 const ScalarEvolution::BackedgeTakenInfo
&
6644 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop
*L
) {
6645 auto &BTI
= getBackedgeTakenInfo(L
);
6646 if (BTI
.hasFullInfo())
6649 auto Pair
= PredicatedBackedgeTakenCounts
.insert({L
, BackedgeTakenInfo()});
6652 return Pair
.first
->second
;
6654 BackedgeTakenInfo Result
=
6655 computeBackedgeTakenCount(L
, /*AllowPredicates=*/true);
6657 return PredicatedBackedgeTakenCounts
.find(L
)->second
= std::move(Result
);
6660 const ScalarEvolution::BackedgeTakenInfo
&
6661 ScalarEvolution::getBackedgeTakenInfo(const Loop
*L
) {
6662 // Initially insert an invalid entry for this loop. If the insertion
6663 // succeeds, proceed to actually compute a backedge-taken count and
6664 // update the value. The temporary CouldNotCompute value tells SCEV
6665 // code elsewhere that it shouldn't attempt to request a new
6666 // backedge-taken count, which could result in infinite recursion.
6667 std::pair
<DenseMap
<const Loop
*, BackedgeTakenInfo
>::iterator
, bool> Pair
=
6668 BackedgeTakenCounts
.insert({L
, BackedgeTakenInfo()});
6670 return Pair
.first
->second
;
6672 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
6673 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
6674 // must be cleared in this scope.
6675 BackedgeTakenInfo Result
= computeBackedgeTakenCount(L
);
6677 // In product build, there are no usage of statistic.
6678 (void)NumTripCountsComputed
;
6679 (void)NumTripCountsNotComputed
;
6680 #if LLVM_ENABLE_STATS || !defined(NDEBUG)
6681 const SCEV
*BEExact
= Result
.getExact(L
, this);
6682 if (BEExact
!= getCouldNotCompute()) {
6683 assert(isLoopInvariant(BEExact
, L
) &&
6684 isLoopInvariant(Result
.getMax(this), L
) &&
6685 "Computed backedge-taken count isn't loop invariant for loop!");
6686 ++NumTripCountsComputed
;
6688 else if (Result
.getMax(this) == getCouldNotCompute() &&
6689 isa
<PHINode
>(L
->getHeader()->begin())) {
6690 // Only count loops that have phi nodes as not being computable.
6691 ++NumTripCountsNotComputed
;
6693 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
6695 // Now that we know more about the trip count for this loop, forget any
6696 // existing SCEV values for PHI nodes in this loop since they are only
6697 // conservative estimates made without the benefit of trip count
6698 // information. This is similar to the code in forgetLoop, except that
6699 // it handles SCEVUnknown PHI nodes specially.
6700 if (Result
.hasAnyInfo()) {
6701 SmallVector
<Instruction
*, 16> Worklist
;
6702 PushLoopPHIs(L
, Worklist
);
6704 SmallPtrSet
<Instruction
*, 8> Discovered
;
6705 while (!Worklist
.empty()) {
6706 Instruction
*I
= Worklist
.pop_back_val();
6708 ValueExprMapType::iterator It
=
6709 ValueExprMap
.find_as(static_cast<Value
*>(I
));
6710 if (It
!= ValueExprMap
.end()) {
6711 const SCEV
*Old
= It
->second
;
6713 // SCEVUnknown for a PHI either means that it has an unrecognized
6714 // structure, or it's a PHI that's in the progress of being computed
6715 // by createNodeForPHI. In the former case, additional loop trip
6716 // count information isn't going to change anything. In the later
6717 // case, createNodeForPHI will perform the necessary updates on its
6718 // own when it gets to that point.
6719 if (!isa
<PHINode
>(I
) || !isa
<SCEVUnknown
>(Old
)) {
6720 eraseValueFromMap(It
->first
);
6721 forgetMemoizedResults(Old
);
6723 if (PHINode
*PN
= dyn_cast
<PHINode
>(I
))
6724 ConstantEvolutionLoopExitValue
.erase(PN
);
6727 // Since we don't need to invalidate anything for correctness and we're
6728 // only invalidating to make SCEV's results more precise, we get to stop
6729 // early to avoid invalidating too much. This is especially important in
6732 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node
6740 // where both loop0 and loop1's backedge taken count uses the SCEV
6741 // expression for %v. If we don't have the early stop below then in cases
6742 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip
6743 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip
6744 // count for loop1, effectively nullifying SCEV's trip count cache.
6745 for (auto *U
: I
->users())
6746 if (auto *I
= dyn_cast
<Instruction
>(U
)) {
6747 auto *LoopForUser
= LI
.getLoopFor(I
->getParent());
6748 if (LoopForUser
&& L
->contains(LoopForUser
) &&
6749 Discovered
.insert(I
).second
)
6750 Worklist
.push_back(I
);
6755 // Re-lookup the insert position, since the call to
6756 // computeBackedgeTakenCount above could result in a
6757 // recusive call to getBackedgeTakenInfo (on a different
6758 // loop), which would invalidate the iterator computed
6760 return BackedgeTakenCounts
.find(L
)->second
= std::move(Result
);
6763 void ScalarEvolution::forgetLoop(const Loop
*L
) {
6764 // Drop any stored trip count value.
6765 auto RemoveLoopFromBackedgeMap
=
6766 [](DenseMap
<const Loop
*, BackedgeTakenInfo
> &Map
, const Loop
*L
) {
6767 auto BTCPos
= Map
.find(L
);
6768 if (BTCPos
!= Map
.end()) {
6769 BTCPos
->second
.clear();
6774 SmallVector
<const Loop
*, 16> LoopWorklist(1, L
);
6775 SmallVector
<Instruction
*, 32> Worklist
;
6776 SmallPtrSet
<Instruction
*, 16> Visited
;
6778 // Iterate over all the loops and sub-loops to drop SCEV information.
6779 while (!LoopWorklist
.empty()) {
6780 auto *CurrL
= LoopWorklist
.pop_back_val();
6782 RemoveLoopFromBackedgeMap(BackedgeTakenCounts
, CurrL
);
6783 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts
, CurrL
);
6785 // Drop information about predicated SCEV rewrites for this loop.
6786 for (auto I
= PredicatedSCEVRewrites
.begin();
6787 I
!= PredicatedSCEVRewrites
.end();) {
6788 std::pair
<const SCEV
*, const Loop
*> Entry
= I
->first
;
6789 if (Entry
.second
== CurrL
)
6790 PredicatedSCEVRewrites
.erase(I
++);
6795 auto LoopUsersItr
= LoopUsers
.find(CurrL
);
6796 if (LoopUsersItr
!= LoopUsers
.end()) {
6797 for (auto *S
: LoopUsersItr
->second
)
6798 forgetMemoizedResults(S
);
6799 LoopUsers
.erase(LoopUsersItr
);
6802 // Drop information about expressions based on loop-header PHIs.
6803 PushLoopPHIs(CurrL
, Worklist
);
6805 while (!Worklist
.empty()) {
6806 Instruction
*I
= Worklist
.pop_back_val();
6807 if (!Visited
.insert(I
).second
)
6810 ValueExprMapType::iterator It
=
6811 ValueExprMap
.find_as(static_cast<Value
*>(I
));
6812 if (It
!= ValueExprMap
.end()) {
6813 eraseValueFromMap(It
->first
);
6814 forgetMemoizedResults(It
->second
);
6815 if (PHINode
*PN
= dyn_cast
<PHINode
>(I
))
6816 ConstantEvolutionLoopExitValue
.erase(PN
);
6819 PushDefUseChildren(I
, Worklist
);
6822 LoopPropertiesCache
.erase(CurrL
);
6823 // Forget all contained loops too, to avoid dangling entries in the
6824 // ValuesAtScopes map.
6825 LoopWorklist
.append(CurrL
->begin(), CurrL
->end());
6829 void ScalarEvolution::forgetTopmostLoop(const Loop
*L
) {
6830 while (Loop
*Parent
= L
->getParentLoop())
6835 void ScalarEvolution::forgetValue(Value
*V
) {
6836 Instruction
*I
= dyn_cast
<Instruction
>(V
);
6839 // Drop information about expressions based on loop-header PHIs.
6840 SmallVector
<Instruction
*, 16> Worklist
;
6841 Worklist
.push_back(I
);
6843 SmallPtrSet
<Instruction
*, 8> Visited
;
6844 while (!Worklist
.empty()) {
6845 I
= Worklist
.pop_back_val();
6846 if (!Visited
.insert(I
).second
)
6849 ValueExprMapType::iterator It
=
6850 ValueExprMap
.find_as(static_cast<Value
*>(I
));
6851 if (It
!= ValueExprMap
.end()) {
6852 eraseValueFromMap(It
->first
);
6853 forgetMemoizedResults(It
->second
);
6854 if (PHINode
*PN
= dyn_cast
<PHINode
>(I
))
6855 ConstantEvolutionLoopExitValue
.erase(PN
);
6858 PushDefUseChildren(I
, Worklist
);
6862 /// Get the exact loop backedge taken count considering all loop exits. A
6863 /// computable result can only be returned for loops with all exiting blocks
6864 /// dominating the latch. howFarToZero assumes that the limit of each loop test
6865 /// is never skipped. This is a valid assumption as long as the loop exits via
6866 /// that test. For precise results, it is the caller's responsibility to specify
6867 /// the relevant loop exiting block using getExact(ExitingBlock, SE).
6869 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop
*L
, ScalarEvolution
*SE
,
6870 SCEVUnionPredicate
*Preds
) const {
6871 // If any exits were not computable, the loop is not computable.
6872 if (!isComplete() || ExitNotTaken
.empty())
6873 return SE
->getCouldNotCompute();
6875 const BasicBlock
*Latch
= L
->getLoopLatch();
6876 // All exiting blocks we have collected must dominate the only backedge.
6878 return SE
->getCouldNotCompute();
6880 // All exiting blocks we have gathered dominate loop's latch, so exact trip
6881 // count is simply a minimum out of all these calculated exit counts.
6882 SmallVector
<const SCEV
*, 2> Ops
;
6883 for (auto &ENT
: ExitNotTaken
) {
6884 const SCEV
*BECount
= ENT
.ExactNotTaken
;
6885 assert(BECount
!= SE
->getCouldNotCompute() && "Bad exit SCEV!");
6886 assert(SE
->DT
.dominates(ENT
.ExitingBlock
, Latch
) &&
6887 "We should only have known counts for exiting blocks that dominate "
6890 Ops
.push_back(BECount
);
6892 if (Preds
&& !ENT
.hasAlwaysTruePredicate())
6893 Preds
->add(ENT
.Predicate
.get());
6895 assert((Preds
|| ENT
.hasAlwaysTruePredicate()) &&
6896 "Predicate should be always true!");
6899 return SE
->getUMinFromMismatchedTypes(Ops
);
6902 /// Get the exact not taken count for this loop exit.
6904 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock
*ExitingBlock
,
6905 ScalarEvolution
*SE
) const {
6906 for (auto &ENT
: ExitNotTaken
)
6907 if (ENT
.ExitingBlock
== ExitingBlock
&& ENT
.hasAlwaysTruePredicate())
6908 return ENT
.ExactNotTaken
;
6910 return SE
->getCouldNotCompute();
6913 /// getMax - Get the max backedge taken count for the loop.
6915 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution
*SE
) const {
6916 auto PredicateNotAlwaysTrue
= [](const ExitNotTakenInfo
&ENT
) {
6917 return !ENT
.hasAlwaysTruePredicate();
6920 if (any_of(ExitNotTaken
, PredicateNotAlwaysTrue
) || !getMax())
6921 return SE
->getCouldNotCompute();
6923 assert((isa
<SCEVCouldNotCompute
>(getMax()) || isa
<SCEVConstant
>(getMax())) &&
6924 "No point in having a non-constant max backedge taken count!");
6928 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution
*SE
) const {
6929 auto PredicateNotAlwaysTrue
= [](const ExitNotTakenInfo
&ENT
) {
6930 return !ENT
.hasAlwaysTruePredicate();
6932 return MaxOrZero
&& !any_of(ExitNotTaken
, PredicateNotAlwaysTrue
);
6935 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV
*S
,
6936 ScalarEvolution
*SE
) const {
6937 if (getMax() && getMax() != SE
->getCouldNotCompute() &&
6938 SE
->hasOperand(getMax(), S
))
6941 for (auto &ENT
: ExitNotTaken
)
6942 if (ENT
.ExactNotTaken
!= SE
->getCouldNotCompute() &&
6943 SE
->hasOperand(ENT
.ExactNotTaken
, S
))
6949 ScalarEvolution::ExitLimit::ExitLimit(const SCEV
*E
)
6950 : ExactNotTaken(E
), MaxNotTaken(E
) {
6951 assert((isa
<SCEVCouldNotCompute
>(MaxNotTaken
) ||
6952 isa
<SCEVConstant
>(MaxNotTaken
)) &&
6953 "No point in having a non-constant max backedge taken count!");
6956 ScalarEvolution::ExitLimit::ExitLimit(
6957 const SCEV
*E
, const SCEV
*M
, bool MaxOrZero
,
6958 ArrayRef
<const SmallPtrSetImpl
<const SCEVPredicate
*> *> PredSetList
)
6959 : ExactNotTaken(E
), MaxNotTaken(M
), MaxOrZero(MaxOrZero
) {
6960 assert((isa
<SCEVCouldNotCompute
>(ExactNotTaken
) ||
6961 !isa
<SCEVCouldNotCompute
>(MaxNotTaken
)) &&
6962 "Exact is not allowed to be less precise than Max");
6963 assert((isa
<SCEVCouldNotCompute
>(MaxNotTaken
) ||
6964 isa
<SCEVConstant
>(MaxNotTaken
)) &&
6965 "No point in having a non-constant max backedge taken count!");
6966 for (auto *PredSet
: PredSetList
)
6967 for (auto *P
: *PredSet
)
6971 ScalarEvolution::ExitLimit::ExitLimit(
6972 const SCEV
*E
, const SCEV
*M
, bool MaxOrZero
,
6973 const SmallPtrSetImpl
<const SCEVPredicate
*> &PredSet
)
6974 : ExitLimit(E
, M
, MaxOrZero
, {&PredSet
}) {
6975 assert((isa
<SCEVCouldNotCompute
>(MaxNotTaken
) ||
6976 isa
<SCEVConstant
>(MaxNotTaken
)) &&
6977 "No point in having a non-constant max backedge taken count!");
6980 ScalarEvolution::ExitLimit::ExitLimit(const SCEV
*E
, const SCEV
*M
,
6982 : ExitLimit(E
, M
, MaxOrZero
, None
) {
6983 assert((isa
<SCEVCouldNotCompute
>(MaxNotTaken
) ||
6984 isa
<SCEVConstant
>(MaxNotTaken
)) &&
6985 "No point in having a non-constant max backedge taken count!");
6988 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
6989 /// computable exit into a persistent ExitNotTakenInfo array.
6990 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
6991 ArrayRef
<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo
>
6993 bool Complete
, const SCEV
*MaxCount
, bool MaxOrZero
)
6994 : MaxAndComplete(MaxCount
, Complete
), MaxOrZero(MaxOrZero
) {
6995 using EdgeExitInfo
= ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo
;
6997 ExitNotTaken
.reserve(ExitCounts
.size());
6999 ExitCounts
.begin(), ExitCounts
.end(), std::back_inserter(ExitNotTaken
),
7000 [&](const EdgeExitInfo
&EEI
) {
7001 BasicBlock
*ExitBB
= EEI
.first
;
7002 const ExitLimit
&EL
= EEI
.second
;
7003 if (EL
.Predicates
.empty())
7004 return ExitNotTakenInfo(ExitBB
, EL
.ExactNotTaken
, nullptr);
7006 std::unique_ptr
<SCEVUnionPredicate
> Predicate(new SCEVUnionPredicate
);
7007 for (auto *Pred
: EL
.Predicates
)
7008 Predicate
->add(Pred
);
7010 return ExitNotTakenInfo(ExitBB
, EL
.ExactNotTaken
, std::move(Predicate
));
7012 assert((isa
<SCEVCouldNotCompute
>(MaxCount
) || isa
<SCEVConstant
>(MaxCount
)) &&
7013 "No point in having a non-constant max backedge taken count!");
7016 /// Invalidate this result and free the ExitNotTakenInfo array.
7017 void ScalarEvolution::BackedgeTakenInfo::clear() {
7018 ExitNotTaken
.clear();
7021 /// Compute the number of times the backedge of the specified loop will execute.
7022 ScalarEvolution::BackedgeTakenInfo
7023 ScalarEvolution::computeBackedgeTakenCount(const Loop
*L
,
7024 bool AllowPredicates
) {
7025 SmallVector
<BasicBlock
*, 8> ExitingBlocks
;
7026 L
->getExitingBlocks(ExitingBlocks
);
7028 using EdgeExitInfo
= ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo
;
7030 SmallVector
<EdgeExitInfo
, 4> ExitCounts
;
7031 bool CouldComputeBECount
= true;
7032 BasicBlock
*Latch
= L
->getLoopLatch(); // may be NULL.
7033 const SCEV
*MustExitMaxBECount
= nullptr;
7034 const SCEV
*MayExitMaxBECount
= nullptr;
7035 bool MustExitMaxOrZero
= false;
7037 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
7038 // and compute maxBECount.
7039 // Do a union of all the predicates here.
7040 for (unsigned i
= 0, e
= ExitingBlocks
.size(); i
!= e
; ++i
) {
7041 BasicBlock
*ExitBB
= ExitingBlocks
[i
];
7042 ExitLimit EL
= computeExitLimit(L
, ExitBB
, AllowPredicates
);
7044 assert((AllowPredicates
|| EL
.Predicates
.empty()) &&
7045 "Predicated exit limit when predicates are not allowed!");
7047 // 1. For each exit that can be computed, add an entry to ExitCounts.
7048 // CouldComputeBECount is true only if all exits can be computed.
7049 if (EL
.ExactNotTaken
== getCouldNotCompute())
7050 // We couldn't compute an exact value for this exit, so
7051 // we won't be able to compute an exact value for the loop.
7052 CouldComputeBECount
= false;
7054 ExitCounts
.emplace_back(ExitBB
, EL
);
7056 // 2. Derive the loop's MaxBECount from each exit's max number of
7057 // non-exiting iterations. Partition the loop exits into two kinds:
7058 // LoopMustExits and LoopMayExits.
7060 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
7061 // is a LoopMayExit. If any computable LoopMustExit is found, then
7062 // MaxBECount is the minimum EL.MaxNotTaken of computable
7063 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
7064 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
7065 // computable EL.MaxNotTaken.
7066 if (EL
.MaxNotTaken
!= getCouldNotCompute() && Latch
&&
7067 DT
.dominates(ExitBB
, Latch
)) {
7068 if (!MustExitMaxBECount
) {
7069 MustExitMaxBECount
= EL
.MaxNotTaken
;
7070 MustExitMaxOrZero
= EL
.MaxOrZero
;
7072 MustExitMaxBECount
=
7073 getUMinFromMismatchedTypes(MustExitMaxBECount
, EL
.MaxNotTaken
);
7075 } else if (MayExitMaxBECount
!= getCouldNotCompute()) {
7076 if (!MayExitMaxBECount
|| EL
.MaxNotTaken
== getCouldNotCompute())
7077 MayExitMaxBECount
= EL
.MaxNotTaken
;
7080 getUMaxFromMismatchedTypes(MayExitMaxBECount
, EL
.MaxNotTaken
);
7084 const SCEV
*MaxBECount
= MustExitMaxBECount
? MustExitMaxBECount
:
7085 (MayExitMaxBECount
? MayExitMaxBECount
: getCouldNotCompute());
7086 // The loop backedge will be taken the maximum or zero times if there's
7087 // a single exit that must be taken the maximum or zero times.
7088 bool MaxOrZero
= (MustExitMaxOrZero
&& ExitingBlocks
.size() == 1);
7089 return BackedgeTakenInfo(std::move(ExitCounts
), CouldComputeBECount
,
7090 MaxBECount
, MaxOrZero
);
7093 ScalarEvolution::ExitLimit
7094 ScalarEvolution::computeExitLimit(const Loop
*L
, BasicBlock
*ExitingBlock
,
7095 bool AllowPredicates
) {
7096 assert(L
->contains(ExitingBlock
) && "Exit count for non-loop block?");
7097 // If our exiting block does not dominate the latch, then its connection with
7098 // loop's exit limit may be far from trivial.
7099 const BasicBlock
*Latch
= L
->getLoopLatch();
7100 if (!Latch
|| !DT
.dominates(ExitingBlock
, Latch
))
7101 return getCouldNotCompute();
7103 bool IsOnlyExit
= (L
->getExitingBlock() != nullptr);
7104 Instruction
*Term
= ExitingBlock
->getTerminator();
7105 if (BranchInst
*BI
= dyn_cast
<BranchInst
>(Term
)) {
7106 assert(BI
->isConditional() && "If unconditional, it can't be in loop!");
7107 bool ExitIfTrue
= !L
->contains(BI
->getSuccessor(0));
7108 assert(ExitIfTrue
== L
->contains(BI
->getSuccessor(1)) &&
7109 "It should have one successor in loop and one exit block!");
7110 // Proceed to the next level to examine the exit condition expression.
7111 return computeExitLimitFromCond(
7112 L
, BI
->getCondition(), ExitIfTrue
,
7113 /*ControlsExit=*/IsOnlyExit
, AllowPredicates
);
7116 if (SwitchInst
*SI
= dyn_cast
<SwitchInst
>(Term
)) {
7117 // For switch, make sure that there is a single exit from the loop.
7118 BasicBlock
*Exit
= nullptr;
7119 for (auto *SBB
: successors(ExitingBlock
))
7120 if (!L
->contains(SBB
)) {
7121 if (Exit
) // Multiple exit successors.
7122 return getCouldNotCompute();
7125 assert(Exit
&& "Exiting block must have at least one exit");
7126 return computeExitLimitFromSingleExitSwitch(L
, SI
, Exit
,
7127 /*ControlsExit=*/IsOnlyExit
);
7130 return getCouldNotCompute();
7133 ScalarEvolution::ExitLimit
ScalarEvolution::computeExitLimitFromCond(
7134 const Loop
*L
, Value
*ExitCond
, bool ExitIfTrue
,
7135 bool ControlsExit
, bool AllowPredicates
) {
7136 ScalarEvolution::ExitLimitCacheTy
Cache(L
, ExitIfTrue
, AllowPredicates
);
7137 return computeExitLimitFromCondCached(Cache
, L
, ExitCond
, ExitIfTrue
,
7138 ControlsExit
, AllowPredicates
);
7141 Optional
<ScalarEvolution::ExitLimit
>
7142 ScalarEvolution::ExitLimitCache::find(const Loop
*L
, Value
*ExitCond
,
7143 bool ExitIfTrue
, bool ControlsExit
,
7144 bool AllowPredicates
) {
7146 (void)this->ExitIfTrue
;
7147 (void)this->AllowPredicates
;
7149 assert(this->L
== L
&& this->ExitIfTrue
== ExitIfTrue
&&
7150 this->AllowPredicates
== AllowPredicates
&&
7151 "Variance in assumed invariant key components!");
7152 auto Itr
= TripCountMap
.find({ExitCond
, ControlsExit
});
7153 if (Itr
== TripCountMap
.end())
7158 void ScalarEvolution::ExitLimitCache::insert(const Loop
*L
, Value
*ExitCond
,
7161 bool AllowPredicates
,
7162 const ExitLimit
&EL
) {
7163 assert(this->L
== L
&& this->ExitIfTrue
== ExitIfTrue
&&
7164 this->AllowPredicates
== AllowPredicates
&&
7165 "Variance in assumed invariant key components!");
7167 auto InsertResult
= TripCountMap
.insert({{ExitCond
, ControlsExit
}, EL
});
7168 assert(InsertResult
.second
&& "Expected successful insertion!");
7173 ScalarEvolution::ExitLimit
ScalarEvolution::computeExitLimitFromCondCached(
7174 ExitLimitCacheTy
&Cache
, const Loop
*L
, Value
*ExitCond
, bool ExitIfTrue
,
7175 bool ControlsExit
, bool AllowPredicates
) {
7178 Cache
.find(L
, ExitCond
, ExitIfTrue
, ControlsExit
, AllowPredicates
))
7181 ExitLimit EL
= computeExitLimitFromCondImpl(Cache
, L
, ExitCond
, ExitIfTrue
,
7182 ControlsExit
, AllowPredicates
);
7183 Cache
.insert(L
, ExitCond
, ExitIfTrue
, ControlsExit
, AllowPredicates
, EL
);
7187 ScalarEvolution::ExitLimit
ScalarEvolution::computeExitLimitFromCondImpl(
7188 ExitLimitCacheTy
&Cache
, const Loop
*L
, Value
*ExitCond
, bool ExitIfTrue
,
7189 bool ControlsExit
, bool AllowPredicates
) {
7190 // Check if the controlling expression for this loop is an And or Or.
7191 if (BinaryOperator
*BO
= dyn_cast
<BinaryOperator
>(ExitCond
)) {
7192 if (BO
->getOpcode() == Instruction::And
) {
7193 // Recurse on the operands of the and.
7194 bool EitherMayExit
= !ExitIfTrue
;
7195 ExitLimit EL0
= computeExitLimitFromCondCached(
7196 Cache
, L
, BO
->getOperand(0), ExitIfTrue
,
7197 ControlsExit
&& !EitherMayExit
, AllowPredicates
);
7198 ExitLimit EL1
= computeExitLimitFromCondCached(
7199 Cache
, L
, BO
->getOperand(1), ExitIfTrue
,
7200 ControlsExit
&& !EitherMayExit
, AllowPredicates
);
7201 const SCEV
*BECount
= getCouldNotCompute();
7202 const SCEV
*MaxBECount
= getCouldNotCompute();
7203 if (EitherMayExit
) {
7204 // Both conditions must be true for the loop to continue executing.
7205 // Choose the less conservative count.
7206 if (EL0
.ExactNotTaken
== getCouldNotCompute() ||
7207 EL1
.ExactNotTaken
== getCouldNotCompute())
7208 BECount
= getCouldNotCompute();
7211 getUMinFromMismatchedTypes(EL0
.ExactNotTaken
, EL1
.ExactNotTaken
);
7212 if (EL0
.MaxNotTaken
== getCouldNotCompute())
7213 MaxBECount
= EL1
.MaxNotTaken
;
7214 else if (EL1
.MaxNotTaken
== getCouldNotCompute())
7215 MaxBECount
= EL0
.MaxNotTaken
;
7218 getUMinFromMismatchedTypes(EL0
.MaxNotTaken
, EL1
.MaxNotTaken
);
7220 // Both conditions must be true at the same time for the loop to exit.
7221 // For now, be conservative.
7222 if (EL0
.MaxNotTaken
== EL1
.MaxNotTaken
)
7223 MaxBECount
= EL0
.MaxNotTaken
;
7224 if (EL0
.ExactNotTaken
== EL1
.ExactNotTaken
)
7225 BECount
= EL0
.ExactNotTaken
;
7228 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7229 // to be more aggressive when computing BECount than when computing
7230 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and
7231 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7233 if (isa
<SCEVCouldNotCompute
>(MaxBECount
) &&
7234 !isa
<SCEVCouldNotCompute
>(BECount
))
7235 MaxBECount
= getConstant(getUnsignedRangeMax(BECount
));
7237 return ExitLimit(BECount
, MaxBECount
, false,
7238 {&EL0
.Predicates
, &EL1
.Predicates
});
7240 if (BO
->getOpcode() == Instruction::Or
) {
7241 // Recurse on the operands of the or.
7242 bool EitherMayExit
= ExitIfTrue
;
7243 ExitLimit EL0
= computeExitLimitFromCondCached(
7244 Cache
, L
, BO
->getOperand(0), ExitIfTrue
,
7245 ControlsExit
&& !EitherMayExit
, AllowPredicates
);
7246 ExitLimit EL1
= computeExitLimitFromCondCached(
7247 Cache
, L
, BO
->getOperand(1), ExitIfTrue
,
7248 ControlsExit
&& !EitherMayExit
, AllowPredicates
);
7249 const SCEV
*BECount
= getCouldNotCompute();
7250 const SCEV
*MaxBECount
= getCouldNotCompute();
7251 if (EitherMayExit
) {
7252 // Both conditions must be false for the loop to continue executing.
7253 // Choose the less conservative count.
7254 if (EL0
.ExactNotTaken
== getCouldNotCompute() ||
7255 EL1
.ExactNotTaken
== getCouldNotCompute())
7256 BECount
= getCouldNotCompute();
7259 getUMinFromMismatchedTypes(EL0
.ExactNotTaken
, EL1
.ExactNotTaken
);
7260 if (EL0
.MaxNotTaken
== getCouldNotCompute())
7261 MaxBECount
= EL1
.MaxNotTaken
;
7262 else if (EL1
.MaxNotTaken
== getCouldNotCompute())
7263 MaxBECount
= EL0
.MaxNotTaken
;
7266 getUMinFromMismatchedTypes(EL0
.MaxNotTaken
, EL1
.MaxNotTaken
);
7268 // Both conditions must be false at the same time for the loop to exit.
7269 // For now, be conservative.
7270 if (EL0
.MaxNotTaken
== EL1
.MaxNotTaken
)
7271 MaxBECount
= EL0
.MaxNotTaken
;
7272 if (EL0
.ExactNotTaken
== EL1
.ExactNotTaken
)
7273 BECount
= EL0
.ExactNotTaken
;
7276 return ExitLimit(BECount
, MaxBECount
, false,
7277 {&EL0
.Predicates
, &EL1
.Predicates
});
7281 // With an icmp, it may be feasible to compute an exact backedge-taken count.
7282 // Proceed to the next level to examine the icmp.
7283 if (ICmpInst
*ExitCondICmp
= dyn_cast
<ICmpInst
>(ExitCond
)) {
7285 computeExitLimitFromICmp(L
, ExitCondICmp
, ExitIfTrue
, ControlsExit
);
7286 if (EL
.hasFullInfo() || !AllowPredicates
)
7289 // Try again, but use SCEV predicates this time.
7290 return computeExitLimitFromICmp(L
, ExitCondICmp
, ExitIfTrue
, ControlsExit
,
7291 /*AllowPredicates=*/true);
7294 // Check for a constant condition. These are normally stripped out by
7295 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
7296 // preserve the CFG and is temporarily leaving constant conditions
7298 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(ExitCond
)) {
7299 if (ExitIfTrue
== !CI
->getZExtValue())
7300 // The backedge is always taken.
7301 return getCouldNotCompute();
7303 // The backedge is never taken.
7304 return getZero(CI
->getType());
7307 // If it's not an integer or pointer comparison then compute it the hard way.
7308 return computeExitCountExhaustively(L
, ExitCond
, ExitIfTrue
);
7311 ScalarEvolution::ExitLimit
7312 ScalarEvolution::computeExitLimitFromICmp(const Loop
*L
,
7316 bool AllowPredicates
) {
7317 // If the condition was exit on true, convert the condition to exit on false
7318 ICmpInst::Predicate Pred
;
7320 Pred
= ExitCond
->getPredicate();
7322 Pred
= ExitCond
->getInversePredicate();
7323 const ICmpInst::Predicate OriginalPred
= Pred
;
7325 // Handle common loops like: for (X = "string"; *X; ++X)
7326 if (LoadInst
*LI
= dyn_cast
<LoadInst
>(ExitCond
->getOperand(0)))
7327 if (Constant
*RHS
= dyn_cast
<Constant
>(ExitCond
->getOperand(1))) {
7329 computeLoadConstantCompareExitLimit(LI
, RHS
, L
, Pred
);
7330 if (ItCnt
.hasAnyInfo())
7334 const SCEV
*LHS
= getSCEV(ExitCond
->getOperand(0));
7335 const SCEV
*RHS
= getSCEV(ExitCond
->getOperand(1));
7337 // Try to evaluate any dependencies out of the loop.
7338 LHS
= getSCEVAtScope(LHS
, L
);
7339 RHS
= getSCEVAtScope(RHS
, L
);
7341 // At this point, we would like to compute how many iterations of the
7342 // loop the predicate will return true for these inputs.
7343 if (isLoopInvariant(LHS
, L
) && !isLoopInvariant(RHS
, L
)) {
7344 // If there is a loop-invariant, force it into the RHS.
7345 std::swap(LHS
, RHS
);
7346 Pred
= ICmpInst::getSwappedPredicate(Pred
);
7349 // Simplify the operands before analyzing them.
7350 (void)SimplifyICmpOperands(Pred
, LHS
, RHS
);
7352 // If we have a comparison of a chrec against a constant, try to use value
7353 // ranges to answer this query.
7354 if (const SCEVConstant
*RHSC
= dyn_cast
<SCEVConstant
>(RHS
))
7355 if (const SCEVAddRecExpr
*AddRec
= dyn_cast
<SCEVAddRecExpr
>(LHS
))
7356 if (AddRec
->getLoop() == L
) {
7357 // Form the constant range.
7358 ConstantRange CompRange
=
7359 ConstantRange::makeExactICmpRegion(Pred
, RHSC
->getAPInt());
7361 const SCEV
*Ret
= AddRec
->getNumIterationsInRange(CompRange
, *this);
7362 if (!isa
<SCEVCouldNotCompute
>(Ret
)) return Ret
;
7366 case ICmpInst::ICMP_NE
: { // while (X != Y)
7367 // Convert to: while (X-Y != 0)
7368 ExitLimit EL
= howFarToZero(getMinusSCEV(LHS
, RHS
), L
, ControlsExit
,
7370 if (EL
.hasAnyInfo()) return EL
;
7373 case ICmpInst::ICMP_EQ
: { // while (X == Y)
7374 // Convert to: while (X-Y == 0)
7375 ExitLimit EL
= howFarToNonZero(getMinusSCEV(LHS
, RHS
), L
);
7376 if (EL
.hasAnyInfo()) return EL
;
7379 case ICmpInst::ICMP_SLT
:
7380 case ICmpInst::ICMP_ULT
: { // while (X < Y)
7381 bool IsSigned
= Pred
== ICmpInst::ICMP_SLT
;
7382 ExitLimit EL
= howManyLessThans(LHS
, RHS
, L
, IsSigned
, ControlsExit
,
7384 if (EL
.hasAnyInfo()) return EL
;
7387 case ICmpInst::ICMP_SGT
:
7388 case ICmpInst::ICMP_UGT
: { // while (X > Y)
7389 bool IsSigned
= Pred
== ICmpInst::ICMP_SGT
;
7391 howManyGreaterThans(LHS
, RHS
, L
, IsSigned
, ControlsExit
,
7393 if (EL
.hasAnyInfo()) return EL
;
7400 auto *ExhaustiveCount
=
7401 computeExitCountExhaustively(L
, ExitCond
, ExitIfTrue
);
7403 if (!isa
<SCEVCouldNotCompute
>(ExhaustiveCount
))
7404 return ExhaustiveCount
;
7406 return computeShiftCompareExitLimit(ExitCond
->getOperand(0),
7407 ExitCond
->getOperand(1), L
, OriginalPred
);
7410 ScalarEvolution::ExitLimit
7411 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop
*L
,
7413 BasicBlock
*ExitingBlock
,
7414 bool ControlsExit
) {
7415 assert(!L
->contains(ExitingBlock
) && "Not an exiting block!");
7417 // Give up if the exit is the default dest of a switch.
7418 if (Switch
->getDefaultDest() == ExitingBlock
)
7419 return getCouldNotCompute();
7421 assert(L
->contains(Switch
->getDefaultDest()) &&
7422 "Default case must not exit the loop!");
7423 const SCEV
*LHS
= getSCEVAtScope(Switch
->getCondition(), L
);
7424 const SCEV
*RHS
= getConstant(Switch
->findCaseDest(ExitingBlock
));
7426 // while (X != Y) --> while (X-Y != 0)
7427 ExitLimit EL
= howFarToZero(getMinusSCEV(LHS
, RHS
), L
, ControlsExit
);
7428 if (EL
.hasAnyInfo())
7431 return getCouldNotCompute();
7434 static ConstantInt
*
7435 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr
*AddRec
, ConstantInt
*C
,
7436 ScalarEvolution
&SE
) {
7437 const SCEV
*InVal
= SE
.getConstant(C
);
7438 const SCEV
*Val
= AddRec
->evaluateAtIteration(InVal
, SE
);
7439 assert(isa
<SCEVConstant
>(Val
) &&
7440 "Evaluation of SCEV at constant didn't fold correctly?");
7441 return cast
<SCEVConstant
>(Val
)->getValue();
7444 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
7445 /// compute the backedge execution count.
7446 ScalarEvolution::ExitLimit
7447 ScalarEvolution::computeLoadConstantCompareExitLimit(
7451 ICmpInst::Predicate predicate
) {
7452 if (LI
->isVolatile()) return getCouldNotCompute();
7454 // Check to see if the loaded pointer is a getelementptr of a global.
7455 // TODO: Use SCEV instead of manually grubbing with GEPs.
7456 GetElementPtrInst
*GEP
= dyn_cast
<GetElementPtrInst
>(LI
->getOperand(0));
7457 if (!GEP
) return getCouldNotCompute();
7459 // Make sure that it is really a constant global we are gepping, with an
7460 // initializer, and make sure the first IDX is really 0.
7461 GlobalVariable
*GV
= dyn_cast
<GlobalVariable
>(GEP
->getOperand(0));
7462 if (!GV
|| !GV
->isConstant() || !GV
->hasDefinitiveInitializer() ||
7463 GEP
->getNumOperands() < 3 || !isa
<Constant
>(GEP
->getOperand(1)) ||
7464 !cast
<Constant
>(GEP
->getOperand(1))->isNullValue())
7465 return getCouldNotCompute();
7467 // Okay, we allow one non-constant index into the GEP instruction.
7468 Value
*VarIdx
= nullptr;
7469 std::vector
<Constant
*> Indexes
;
7470 unsigned VarIdxNum
= 0;
7471 for (unsigned i
= 2, e
= GEP
->getNumOperands(); i
!= e
; ++i
)
7472 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(GEP
->getOperand(i
))) {
7473 Indexes
.push_back(CI
);
7474 } else if (!isa
<ConstantInt
>(GEP
->getOperand(i
))) {
7475 if (VarIdx
) return getCouldNotCompute(); // Multiple non-constant idx's.
7476 VarIdx
= GEP
->getOperand(i
);
7478 Indexes
.push_back(nullptr);
7481 // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
7483 return getCouldNotCompute();
7485 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
7486 // Check to see if X is a loop variant variable value now.
7487 const SCEV
*Idx
= getSCEV(VarIdx
);
7488 Idx
= getSCEVAtScope(Idx
, L
);
7490 // We can only recognize very limited forms of loop index expressions, in
7491 // particular, only affine AddRec's like {C1,+,C2}.
7492 const SCEVAddRecExpr
*IdxExpr
= dyn_cast
<SCEVAddRecExpr
>(Idx
);
7493 if (!IdxExpr
|| !IdxExpr
->isAffine() || isLoopInvariant(IdxExpr
, L
) ||
7494 !isa
<SCEVConstant
>(IdxExpr
->getOperand(0)) ||
7495 !isa
<SCEVConstant
>(IdxExpr
->getOperand(1)))
7496 return getCouldNotCompute();
7498 unsigned MaxSteps
= MaxBruteForceIterations
;
7499 for (unsigned IterationNum
= 0; IterationNum
!= MaxSteps
; ++IterationNum
) {
7500 ConstantInt
*ItCst
= ConstantInt::get(
7501 cast
<IntegerType
>(IdxExpr
->getType()), IterationNum
);
7502 ConstantInt
*Val
= EvaluateConstantChrecAtConstant(IdxExpr
, ItCst
, *this);
7504 // Form the GEP offset.
7505 Indexes
[VarIdxNum
] = Val
;
7507 Constant
*Result
= ConstantFoldLoadThroughGEPIndices(GV
->getInitializer(),
7509 if (!Result
) break; // Cannot compute!
7511 // Evaluate the condition for this iteration.
7512 Result
= ConstantExpr::getICmp(predicate
, Result
, RHS
);
7513 if (!isa
<ConstantInt
>(Result
)) break; // Couldn't decide for sure
7514 if (cast
<ConstantInt
>(Result
)->getValue().isMinValue()) {
7515 ++NumArrayLenItCounts
;
7516 return getConstant(ItCst
); // Found terminating iteration!
7519 return getCouldNotCompute();
7522 ScalarEvolution::ExitLimit
ScalarEvolution::computeShiftCompareExitLimit(
7523 Value
*LHS
, Value
*RHSV
, const Loop
*L
, ICmpInst::Predicate Pred
) {
7524 ConstantInt
*RHS
= dyn_cast
<ConstantInt
>(RHSV
);
7526 return getCouldNotCompute();
7528 const BasicBlock
*Latch
= L
->getLoopLatch();
7530 return getCouldNotCompute();
7532 const BasicBlock
*Predecessor
= L
->getLoopPredecessor();
7534 return getCouldNotCompute();
7536 // Return true if V is of the form "LHS `shift_op` <positive constant>".
7537 // Return LHS in OutLHS and shift_opt in OutOpCode.
7538 auto MatchPositiveShift
=
7539 [](Value
*V
, Value
*&OutLHS
, Instruction::BinaryOps
&OutOpCode
) {
7541 using namespace PatternMatch
;
7543 ConstantInt
*ShiftAmt
;
7544 if (match(V
, m_LShr(m_Value(OutLHS
), m_ConstantInt(ShiftAmt
))))
7545 OutOpCode
= Instruction::LShr
;
7546 else if (match(V
, m_AShr(m_Value(OutLHS
), m_ConstantInt(ShiftAmt
))))
7547 OutOpCode
= Instruction::AShr
;
7548 else if (match(V
, m_Shl(m_Value(OutLHS
), m_ConstantInt(ShiftAmt
))))
7549 OutOpCode
= Instruction::Shl
;
7553 return ShiftAmt
->getValue().isStrictlyPositive();
7556 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
7559 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
7560 // %iv.shifted = lshr i32 %iv, <positive constant>
7562 // Return true on a successful match. Return the corresponding PHI node (%iv
7563 // above) in PNOut and the opcode of the shift operation in OpCodeOut.
7564 auto MatchShiftRecurrence
=
7565 [&](Value
*V
, PHINode
*&PNOut
, Instruction::BinaryOps
&OpCodeOut
) {
7566 Optional
<Instruction::BinaryOps
> PostShiftOpCode
;
7569 Instruction::BinaryOps OpC
;
7572 // If we encounter a shift instruction, "peel off" the shift operation,
7573 // and remember that we did so. Later when we inspect %iv's backedge
7574 // value, we will make sure that the backedge value uses the same
7577 // Note: the peeled shift operation does not have to be the same
7578 // instruction as the one feeding into the PHI's backedge value. We only
7579 // really care about it being the same *kind* of shift instruction --
7580 // that's all that is required for our later inferences to hold.
7581 if (MatchPositiveShift(LHS
, V
, OpC
)) {
7582 PostShiftOpCode
= OpC
;
7587 PNOut
= dyn_cast
<PHINode
>(LHS
);
7588 if (!PNOut
|| PNOut
->getParent() != L
->getHeader())
7591 Value
*BEValue
= PNOut
->getIncomingValueForBlock(Latch
);
7595 // The backedge value for the PHI node must be a shift by a positive
7597 MatchPositiveShift(BEValue
, OpLHS
, OpCodeOut
) &&
7599 // of the PHI node itself
7602 // and the kind of shift should be match the kind of shift we peeled
7604 (!PostShiftOpCode
.hasValue() || *PostShiftOpCode
== OpCodeOut
);
7608 Instruction::BinaryOps OpCode
;
7609 if (!MatchShiftRecurrence(LHS
, PN
, OpCode
))
7610 return getCouldNotCompute();
7612 const DataLayout
&DL
= getDataLayout();
7614 // The key rationale for this optimization is that for some kinds of shift
7615 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
7616 // within a finite number of iterations. If the condition guarding the
7617 // backedge (in the sense that the backedge is taken if the condition is true)
7618 // is false for the value the shift recurrence stabilizes to, then we know
7619 // that the backedge is taken only a finite number of times.
7621 ConstantInt
*StableValue
= nullptr;
7624 llvm_unreachable("Impossible case!");
7626 case Instruction::AShr
: {
7627 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
7628 // bitwidth(K) iterations.
7629 Value
*FirstValue
= PN
->getIncomingValueForBlock(Predecessor
);
7630 KnownBits Known
= computeKnownBits(FirstValue
, DL
, 0, nullptr,
7631 Predecessor
->getTerminator(), &DT
);
7632 auto *Ty
= cast
<IntegerType
>(RHS
->getType());
7633 if (Known
.isNonNegative())
7634 StableValue
= ConstantInt::get(Ty
, 0);
7635 else if (Known
.isNegative())
7636 StableValue
= ConstantInt::get(Ty
, -1, true);
7638 return getCouldNotCompute();
7642 case Instruction::LShr
:
7643 case Instruction::Shl
:
7644 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
7645 // stabilize to 0 in at most bitwidth(K) iterations.
7646 StableValue
= ConstantInt::get(cast
<IntegerType
>(RHS
->getType()), 0);
7651 ConstantFoldCompareInstOperands(Pred
, StableValue
, RHS
, DL
, &TLI
);
7652 assert(Result
->getType()->isIntegerTy(1) &&
7653 "Otherwise cannot be an operand to a branch instruction");
7655 if (Result
->isZeroValue()) {
7656 unsigned BitWidth
= getTypeSizeInBits(RHS
->getType());
7657 const SCEV
*UpperBound
=
7658 getConstant(getEffectiveSCEVType(RHS
->getType()), BitWidth
);
7659 return ExitLimit(getCouldNotCompute(), UpperBound
, false);
7662 return getCouldNotCompute();
7665 /// Return true if we can constant fold an instruction of the specified type,
7666 /// assuming that all operands were constants.
7667 static bool CanConstantFold(const Instruction
*I
) {
7668 if (isa
<BinaryOperator
>(I
) || isa
<CmpInst
>(I
) ||
7669 isa
<SelectInst
>(I
) || isa
<CastInst
>(I
) || isa
<GetElementPtrInst
>(I
) ||
7673 if (const CallInst
*CI
= dyn_cast
<CallInst
>(I
))
7674 if (const Function
*F
= CI
->getCalledFunction())
7675 return canConstantFoldCallTo(CI
, F
);
7679 /// Determine whether this instruction can constant evolve within this loop
7680 /// assuming its operands can all constant evolve.
7681 static bool canConstantEvolve(Instruction
*I
, const Loop
*L
) {
7682 // An instruction outside of the loop can't be derived from a loop PHI.
7683 if (!L
->contains(I
)) return false;
7685 if (isa
<PHINode
>(I
)) {
7686 // We don't currently keep track of the control flow needed to evaluate
7687 // PHIs, so we cannot handle PHIs inside of loops.
7688 return L
->getHeader() == I
->getParent();
7691 // If we won't be able to constant fold this expression even if the operands
7692 // are constants, bail early.
7693 return CanConstantFold(I
);
7696 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
7697 /// recursing through each instruction operand until reaching a loop header phi.
7699 getConstantEvolvingPHIOperands(Instruction
*UseInst
, const Loop
*L
,
7700 DenseMap
<Instruction
*, PHINode
*> &PHIMap
,
7702 if (Depth
> MaxConstantEvolvingDepth
)
7705 // Otherwise, we can evaluate this instruction if all of its operands are
7706 // constant or derived from a PHI node themselves.
7707 PHINode
*PHI
= nullptr;
7708 for (Value
*Op
: UseInst
->operands()) {
7709 if (isa
<Constant
>(Op
)) continue;
7711 Instruction
*OpInst
= dyn_cast
<Instruction
>(Op
);
7712 if (!OpInst
|| !canConstantEvolve(OpInst
, L
)) return nullptr;
7714 PHINode
*P
= dyn_cast
<PHINode
>(OpInst
);
7716 // If this operand is already visited, reuse the prior result.
7717 // We may have P != PHI if this is the deepest point at which the
7718 // inconsistent paths meet.
7719 P
= PHIMap
.lookup(OpInst
);
7721 // Recurse and memoize the results, whether a phi is found or not.
7722 // This recursive call invalidates pointers into PHIMap.
7723 P
= getConstantEvolvingPHIOperands(OpInst
, L
, PHIMap
, Depth
+ 1);
7727 return nullptr; // Not evolving from PHI
7728 if (PHI
&& PHI
!= P
)
7729 return nullptr; // Evolving from multiple different PHIs.
7732 // This is a expression evolving from a constant PHI!
7736 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
7737 /// in the loop that V is derived from. We allow arbitrary operations along the
7738 /// way, but the operands of an operation must either be constants or a value
7739 /// derived from a constant PHI. If this expression does not fit with these
7740 /// constraints, return null.
7741 static PHINode
*getConstantEvolvingPHI(Value
*V
, const Loop
*L
) {
7742 Instruction
*I
= dyn_cast
<Instruction
>(V
);
7743 if (!I
|| !canConstantEvolve(I
, L
)) return nullptr;
7745 if (PHINode
*PN
= dyn_cast
<PHINode
>(I
))
7748 // Record non-constant instructions contained by the loop.
7749 DenseMap
<Instruction
*, PHINode
*> PHIMap
;
7750 return getConstantEvolvingPHIOperands(I
, L
, PHIMap
, 0);
7753 /// EvaluateExpression - Given an expression that passes the
7754 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
7755 /// in the loop has the value PHIVal. If we can't fold this expression for some
7756 /// reason, return null.
7757 static Constant
*EvaluateExpression(Value
*V
, const Loop
*L
,
7758 DenseMap
<Instruction
*, Constant
*> &Vals
,
7759 const DataLayout
&DL
,
7760 const TargetLibraryInfo
*TLI
) {
7761 // Convenient constant check, but redundant for recursive calls.
7762 if (Constant
*C
= dyn_cast
<Constant
>(V
)) return C
;
7763 Instruction
*I
= dyn_cast
<Instruction
>(V
);
7764 if (!I
) return nullptr;
7766 if (Constant
*C
= Vals
.lookup(I
)) return C
;
7768 // An instruction inside the loop depends on a value outside the loop that we
7769 // weren't given a mapping for, or a value such as a call inside the loop.
7770 if (!canConstantEvolve(I
, L
)) return nullptr;
7772 // An unmapped PHI can be due to a branch or another loop inside this loop,
7773 // or due to this not being the initial iteration through a loop where we
7774 // couldn't compute the evolution of this particular PHI last time.
7775 if (isa
<PHINode
>(I
)) return nullptr;
7777 std::vector
<Constant
*> Operands(I
->getNumOperands());
7779 for (unsigned i
= 0, e
= I
->getNumOperands(); i
!= e
; ++i
) {
7780 Instruction
*Operand
= dyn_cast
<Instruction
>(I
->getOperand(i
));
7782 Operands
[i
] = dyn_cast
<Constant
>(I
->getOperand(i
));
7783 if (!Operands
[i
]) return nullptr;
7786 Constant
*C
= EvaluateExpression(Operand
, L
, Vals
, DL
, TLI
);
7788 if (!C
) return nullptr;
7792 if (CmpInst
*CI
= dyn_cast
<CmpInst
>(I
))
7793 return ConstantFoldCompareInstOperands(CI
->getPredicate(), Operands
[0],
7794 Operands
[1], DL
, TLI
);
7795 if (LoadInst
*LI
= dyn_cast
<LoadInst
>(I
)) {
7796 if (!LI
->isVolatile())
7797 return ConstantFoldLoadFromConstPtr(Operands
[0], LI
->getType(), DL
);
7799 return ConstantFoldInstOperands(I
, Operands
, DL
, TLI
);
7803 // If every incoming value to PN except the one for BB is a specific Constant,
7804 // return that, else return nullptr.
7805 static Constant
*getOtherIncomingValue(PHINode
*PN
, BasicBlock
*BB
) {
7806 Constant
*IncomingVal
= nullptr;
7808 for (unsigned i
= 0, e
= PN
->getNumIncomingValues(); i
!= e
; ++i
) {
7809 if (PN
->getIncomingBlock(i
) == BB
)
7812 auto *CurrentVal
= dyn_cast
<Constant
>(PN
->getIncomingValue(i
));
7816 if (IncomingVal
!= CurrentVal
) {
7819 IncomingVal
= CurrentVal
;
7826 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
7827 /// in the header of its containing loop, we know the loop executes a
7828 /// constant number of times, and the PHI node is just a recurrence
7829 /// involving constants, fold it.
7831 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode
*PN
,
7834 auto I
= ConstantEvolutionLoopExitValue
.find(PN
);
7835 if (I
!= ConstantEvolutionLoopExitValue
.end())
7838 if (BEs
.ugt(MaxBruteForceIterations
))
7839 return ConstantEvolutionLoopExitValue
[PN
] = nullptr; // Not going to evaluate it.
7841 Constant
*&RetVal
= ConstantEvolutionLoopExitValue
[PN
];
7843 DenseMap
<Instruction
*, Constant
*> CurrentIterVals
;
7844 BasicBlock
*Header
= L
->getHeader();
7845 assert(PN
->getParent() == Header
&& "Can't evaluate PHI not in loop header!");
7847 BasicBlock
*Latch
= L
->getLoopLatch();
7851 for (PHINode
&PHI
: Header
->phis()) {
7852 if (auto *StartCST
= getOtherIncomingValue(&PHI
, Latch
))
7853 CurrentIterVals
[&PHI
] = StartCST
;
7855 if (!CurrentIterVals
.count(PN
))
7856 return RetVal
= nullptr;
7858 Value
*BEValue
= PN
->getIncomingValueForBlock(Latch
);
7860 // Execute the loop symbolically to determine the exit value.
7861 assert(BEs
.getActiveBits() < CHAR_BIT
* sizeof(unsigned) &&
7862 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
7864 unsigned NumIterations
= BEs
.getZExtValue(); // must be in range
7865 unsigned IterationNum
= 0;
7866 const DataLayout
&DL
= getDataLayout();
7867 for (; ; ++IterationNum
) {
7868 if (IterationNum
== NumIterations
)
7869 return RetVal
= CurrentIterVals
[PN
]; // Got exit value!
7871 // Compute the value of the PHIs for the next iteration.
7872 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
7873 DenseMap
<Instruction
*, Constant
*> NextIterVals
;
7875 EvaluateExpression(BEValue
, L
, CurrentIterVals
, DL
, &TLI
);
7877 return nullptr; // Couldn't evaluate!
7878 NextIterVals
[PN
] = NextPHI
;
7880 bool StoppedEvolving
= NextPHI
== CurrentIterVals
[PN
];
7882 // Also evaluate the other PHI nodes. However, we don't get to stop if we
7883 // cease to be able to evaluate one of them or if they stop evolving,
7884 // because that doesn't necessarily prevent us from computing PN.
7885 SmallVector
<std::pair
<PHINode
*, Constant
*>, 8> PHIsToCompute
;
7886 for (const auto &I
: CurrentIterVals
) {
7887 PHINode
*PHI
= dyn_cast
<PHINode
>(I
.first
);
7888 if (!PHI
|| PHI
== PN
|| PHI
->getParent() != Header
) continue;
7889 PHIsToCompute
.emplace_back(PHI
, I
.second
);
7891 // We use two distinct loops because EvaluateExpression may invalidate any
7892 // iterators into CurrentIterVals.
7893 for (const auto &I
: PHIsToCompute
) {
7894 PHINode
*PHI
= I
.first
;
7895 Constant
*&NextPHI
= NextIterVals
[PHI
];
7896 if (!NextPHI
) { // Not already computed.
7897 Value
*BEValue
= PHI
->getIncomingValueForBlock(Latch
);
7898 NextPHI
= EvaluateExpression(BEValue
, L
, CurrentIterVals
, DL
, &TLI
);
7900 if (NextPHI
!= I
.second
)
7901 StoppedEvolving
= false;
7904 // If all entries in CurrentIterVals == NextIterVals then we can stop
7905 // iterating, the loop can't continue to change.
7906 if (StoppedEvolving
)
7907 return RetVal
= CurrentIterVals
[PN
];
7909 CurrentIterVals
.swap(NextIterVals
);
7913 const SCEV
*ScalarEvolution::computeExitCountExhaustively(const Loop
*L
,
7916 PHINode
*PN
= getConstantEvolvingPHI(Cond
, L
);
7917 if (!PN
) return getCouldNotCompute();
7919 // If the loop is canonicalized, the PHI will have exactly two entries.
7920 // That's the only form we support here.
7921 if (PN
->getNumIncomingValues() != 2) return getCouldNotCompute();
7923 DenseMap
<Instruction
*, Constant
*> CurrentIterVals
;
7924 BasicBlock
*Header
= L
->getHeader();
7925 assert(PN
->getParent() == Header
&& "Can't evaluate PHI not in loop header!");
7927 BasicBlock
*Latch
= L
->getLoopLatch();
7928 assert(Latch
&& "Should follow from NumIncomingValues == 2!");
7930 for (PHINode
&PHI
: Header
->phis()) {
7931 if (auto *StartCST
= getOtherIncomingValue(&PHI
, Latch
))
7932 CurrentIterVals
[&PHI
] = StartCST
;
7934 if (!CurrentIterVals
.count(PN
))
7935 return getCouldNotCompute();
7937 // Okay, we find a PHI node that defines the trip count of this loop. Execute
7938 // the loop symbolically to determine when the condition gets a value of
7940 unsigned MaxIterations
= MaxBruteForceIterations
; // Limit analysis.
7941 const DataLayout
&DL
= getDataLayout();
7942 for (unsigned IterationNum
= 0; IterationNum
!= MaxIterations
;++IterationNum
){
7943 auto *CondVal
= dyn_cast_or_null
<ConstantInt
>(
7944 EvaluateExpression(Cond
, L
, CurrentIterVals
, DL
, &TLI
));
7946 // Couldn't symbolically evaluate.
7947 if (!CondVal
) return getCouldNotCompute();
7949 if (CondVal
->getValue() == uint64_t(ExitWhen
)) {
7950 ++NumBruteForceTripCountsComputed
;
7951 return getConstant(Type::getInt32Ty(getContext()), IterationNum
);
7954 // Update all the PHI nodes for the next iteration.
7955 DenseMap
<Instruction
*, Constant
*> NextIterVals
;
7957 // Create a list of which PHIs we need to compute. We want to do this before
7958 // calling EvaluateExpression on them because that may invalidate iterators
7959 // into CurrentIterVals.
7960 SmallVector
<PHINode
*, 8> PHIsToCompute
;
7961 for (const auto &I
: CurrentIterVals
) {
7962 PHINode
*PHI
= dyn_cast
<PHINode
>(I
.first
);
7963 if (!PHI
|| PHI
->getParent() != Header
) continue;
7964 PHIsToCompute
.push_back(PHI
);
7966 for (PHINode
*PHI
: PHIsToCompute
) {
7967 Constant
*&NextPHI
= NextIterVals
[PHI
];
7968 if (NextPHI
) continue; // Already computed!
7970 Value
*BEValue
= PHI
->getIncomingValueForBlock(Latch
);
7971 NextPHI
= EvaluateExpression(BEValue
, L
, CurrentIterVals
, DL
, &TLI
);
7973 CurrentIterVals
.swap(NextIterVals
);
7976 // Too many iterations were needed to evaluate.
7977 return getCouldNotCompute();
7980 const SCEV
*ScalarEvolution::getSCEVAtScope(const SCEV
*V
, const Loop
*L
) {
7981 SmallVector
<std::pair
<const Loop
*, const SCEV
*>, 2> &Values
=
7983 // Check to see if we've folded this expression at this loop before.
7984 for (auto &LS
: Values
)
7986 return LS
.second
? LS
.second
: V
;
7988 Values
.emplace_back(L
, nullptr);
7990 // Otherwise compute it.
7991 const SCEV
*C
= computeSCEVAtScope(V
, L
);
7992 for (auto &LS
: reverse(ValuesAtScopes
[V
]))
7993 if (LS
.first
== L
) {
8000 /// This builds up a Constant using the ConstantExpr interface. That way, we
8001 /// will return Constants for objects which aren't represented by a
8002 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
8003 /// Returns NULL if the SCEV isn't representable as a Constant.
8004 static Constant
*BuildConstantFromSCEV(const SCEV
*V
) {
8005 switch (static_cast<SCEVTypes
>(V
->getSCEVType())) {
8006 case scCouldNotCompute
:
8010 return cast
<SCEVConstant
>(V
)->getValue();
8012 return dyn_cast
<Constant
>(cast
<SCEVUnknown
>(V
)->getValue());
8013 case scSignExtend
: {
8014 const SCEVSignExtendExpr
*SS
= cast
<SCEVSignExtendExpr
>(V
);
8015 if (Constant
*CastOp
= BuildConstantFromSCEV(SS
->getOperand()))
8016 return ConstantExpr::getSExt(CastOp
, SS
->getType());
8019 case scZeroExtend
: {
8020 const SCEVZeroExtendExpr
*SZ
= cast
<SCEVZeroExtendExpr
>(V
);
8021 if (Constant
*CastOp
= BuildConstantFromSCEV(SZ
->getOperand()))
8022 return ConstantExpr::getZExt(CastOp
, SZ
->getType());
8026 const SCEVTruncateExpr
*ST
= cast
<SCEVTruncateExpr
>(V
);
8027 if (Constant
*CastOp
= BuildConstantFromSCEV(ST
->getOperand()))
8028 return ConstantExpr::getTrunc(CastOp
, ST
->getType());
8032 const SCEVAddExpr
*SA
= cast
<SCEVAddExpr
>(V
);
8033 if (Constant
*C
= BuildConstantFromSCEV(SA
->getOperand(0))) {
8034 if (PointerType
*PTy
= dyn_cast
<PointerType
>(C
->getType())) {
8035 unsigned AS
= PTy
->getAddressSpace();
8036 Type
*DestPtrTy
= Type::getInt8PtrTy(C
->getContext(), AS
);
8037 C
= ConstantExpr::getBitCast(C
, DestPtrTy
);
8039 for (unsigned i
= 1, e
= SA
->getNumOperands(); i
!= e
; ++i
) {
8040 Constant
*C2
= BuildConstantFromSCEV(SA
->getOperand(i
));
8041 if (!C2
) return nullptr;
8044 if (!C
->getType()->isPointerTy() && C2
->getType()->isPointerTy()) {
8045 unsigned AS
= C2
->getType()->getPointerAddressSpace();
8047 Type
*DestPtrTy
= Type::getInt8PtrTy(C
->getContext(), AS
);
8048 // The offsets have been converted to bytes. We can add bytes to an
8049 // i8* by GEP with the byte count in the first index.
8050 C
= ConstantExpr::getBitCast(C
, DestPtrTy
);
8053 // Don't bother trying to sum two pointers. We probably can't
8054 // statically compute a load that results from it anyway.
8055 if (C2
->getType()->isPointerTy())
8058 if (PointerType
*PTy
= dyn_cast
<PointerType
>(C
->getType())) {
8059 if (PTy
->getElementType()->isStructTy())
8060 C2
= ConstantExpr::getIntegerCast(
8061 C2
, Type::getInt32Ty(C
->getContext()), true);
8062 C
= ConstantExpr::getGetElementPtr(PTy
->getElementType(), C
, C2
);
8064 C
= ConstantExpr::getAdd(C
, C2
);
8071 const SCEVMulExpr
*SM
= cast
<SCEVMulExpr
>(V
);
8072 if (Constant
*C
= BuildConstantFromSCEV(SM
->getOperand(0))) {
8073 // Don't bother with pointers at all.
8074 if (C
->getType()->isPointerTy()) return nullptr;
8075 for (unsigned i
= 1, e
= SM
->getNumOperands(); i
!= e
; ++i
) {
8076 Constant
*C2
= BuildConstantFromSCEV(SM
->getOperand(i
));
8077 if (!C2
|| C2
->getType()->isPointerTy()) return nullptr;
8078 C
= ConstantExpr::getMul(C
, C2
);
8085 const SCEVUDivExpr
*SU
= cast
<SCEVUDivExpr
>(V
);
8086 if (Constant
*LHS
= BuildConstantFromSCEV(SU
->getLHS()))
8087 if (Constant
*RHS
= BuildConstantFromSCEV(SU
->getRHS()))
8088 if (LHS
->getType() == RHS
->getType())
8089 return ConstantExpr::getUDiv(LHS
, RHS
);
8094 break; // TODO: smax, umax.
8099 const SCEV
*ScalarEvolution::computeSCEVAtScope(const SCEV
*V
, const Loop
*L
) {
8100 if (isa
<SCEVConstant
>(V
)) return V
;
8102 // If this instruction is evolved from a constant-evolving PHI, compute the
8103 // exit value from the loop without using SCEVs.
8104 if (const SCEVUnknown
*SU
= dyn_cast
<SCEVUnknown
>(V
)) {
8105 if (Instruction
*I
= dyn_cast
<Instruction
>(SU
->getValue())) {
8106 if (PHINode
*PN
= dyn_cast
<PHINode
>(I
)) {
8107 const Loop
*LI
= this->LI
[I
->getParent()];
8108 // Looking for loop exit value.
8109 if (LI
&& LI
->getParentLoop() == L
&&
8110 PN
->getParent() == LI
->getHeader()) {
8111 // Okay, there is no closed form solution for the PHI node. Check
8112 // to see if the loop that contains it has a known backedge-taken
8113 // count. If so, we may be able to force computation of the exit
8115 const SCEV
*BackedgeTakenCount
= getBackedgeTakenCount(LI
);
8116 if (const SCEVConstant
*BTCC
=
8117 dyn_cast
<SCEVConstant
>(BackedgeTakenCount
)) {
8119 // This trivial case can show up in some degenerate cases where
8120 // the incoming IR has not yet been fully simplified.
8121 if (BTCC
->getValue()->isZero()) {
8122 Value
*InitValue
= nullptr;
8123 bool MultipleInitValues
= false;
8124 for (unsigned i
= 0; i
< PN
->getNumIncomingValues(); i
++) {
8125 if (!LI
->contains(PN
->getIncomingBlock(i
))) {
8127 InitValue
= PN
->getIncomingValue(i
);
8128 else if (InitValue
!= PN
->getIncomingValue(i
)) {
8129 MultipleInitValues
= true;
8133 if (!MultipleInitValues
&& InitValue
)
8134 return getSCEV(InitValue
);
8137 // Okay, we know how many times the containing loop executes. If
8138 // this is a constant evolving PHI node, get the final value at
8139 // the specified iteration number.
8141 getConstantEvolutionLoopExitValue(PN
, BTCC
->getAPInt(), LI
);
8142 if (RV
) return getSCEV(RV
);
8147 // Okay, this is an expression that we cannot symbolically evaluate
8148 // into a SCEV. Check to see if it's possible to symbolically evaluate
8149 // the arguments into constants, and if so, try to constant propagate the
8150 // result. This is particularly useful for computing loop exit values.
8151 if (CanConstantFold(I
)) {
8152 SmallVector
<Constant
*, 4> Operands
;
8153 bool MadeImprovement
= false;
8154 for (Value
*Op
: I
->operands()) {
8155 if (Constant
*C
= dyn_cast
<Constant
>(Op
)) {
8156 Operands
.push_back(C
);
8160 // If any of the operands is non-constant and if they are
8161 // non-integer and non-pointer, don't even try to analyze them
8162 // with scev techniques.
8163 if (!isSCEVable(Op
->getType()))
8166 const SCEV
*OrigV
= getSCEV(Op
);
8167 const SCEV
*OpV
= getSCEVAtScope(OrigV
, L
);
8168 MadeImprovement
|= OrigV
!= OpV
;
8170 Constant
*C
= BuildConstantFromSCEV(OpV
);
8172 if (C
->getType() != Op
->getType())
8173 C
= ConstantExpr::getCast(CastInst::getCastOpcode(C
, false,
8177 Operands
.push_back(C
);
8180 // Check to see if getSCEVAtScope actually made an improvement.
8181 if (MadeImprovement
) {
8182 Constant
*C
= nullptr;
8183 const DataLayout
&DL
= getDataLayout();
8184 if (const CmpInst
*CI
= dyn_cast
<CmpInst
>(I
))
8185 C
= ConstantFoldCompareInstOperands(CI
->getPredicate(), Operands
[0],
8186 Operands
[1], DL
, &TLI
);
8187 else if (const LoadInst
*LI
= dyn_cast
<LoadInst
>(I
)) {
8188 if (!LI
->isVolatile())
8189 C
= ConstantFoldLoadFromConstPtr(Operands
[0], LI
->getType(), DL
);
8191 C
= ConstantFoldInstOperands(I
, Operands
, DL
, &TLI
);
8198 // This is some other type of SCEVUnknown, just return it.
8202 if (const SCEVCommutativeExpr
*Comm
= dyn_cast
<SCEVCommutativeExpr
>(V
)) {
8203 // Avoid performing the look-up in the common case where the specified
8204 // expression has no loop-variant portions.
8205 for (unsigned i
= 0, e
= Comm
->getNumOperands(); i
!= e
; ++i
) {
8206 const SCEV
*OpAtScope
= getSCEVAtScope(Comm
->getOperand(i
), L
);
8207 if (OpAtScope
!= Comm
->getOperand(i
)) {
8208 // Okay, at least one of these operands is loop variant but might be
8209 // foldable. Build a new instance of the folded commutative expression.
8210 SmallVector
<const SCEV
*, 8> NewOps(Comm
->op_begin(),
8211 Comm
->op_begin()+i
);
8212 NewOps
.push_back(OpAtScope
);
8214 for (++i
; i
!= e
; ++i
) {
8215 OpAtScope
= getSCEVAtScope(Comm
->getOperand(i
), L
);
8216 NewOps
.push_back(OpAtScope
);
8218 if (isa
<SCEVAddExpr
>(Comm
))
8219 return getAddExpr(NewOps
);
8220 if (isa
<SCEVMulExpr
>(Comm
))
8221 return getMulExpr(NewOps
);
8222 if (isa
<SCEVSMaxExpr
>(Comm
))
8223 return getSMaxExpr(NewOps
);
8224 if (isa
<SCEVUMaxExpr
>(Comm
))
8225 return getUMaxExpr(NewOps
);
8226 llvm_unreachable("Unknown commutative SCEV type!");
8229 // If we got here, all operands are loop invariant.
8233 if (const SCEVUDivExpr
*Div
= dyn_cast
<SCEVUDivExpr
>(V
)) {
8234 const SCEV
*LHS
= getSCEVAtScope(Div
->getLHS(), L
);
8235 const SCEV
*RHS
= getSCEVAtScope(Div
->getRHS(), L
);
8236 if (LHS
== Div
->getLHS() && RHS
== Div
->getRHS())
8237 return Div
; // must be loop invariant
8238 return getUDivExpr(LHS
, RHS
);
8241 // If this is a loop recurrence for a loop that does not contain L, then we
8242 // are dealing with the final value computed by the loop.
8243 if (const SCEVAddRecExpr
*AddRec
= dyn_cast
<SCEVAddRecExpr
>(V
)) {
8244 // First, attempt to evaluate each operand.
8245 // Avoid performing the look-up in the common case where the specified
8246 // expression has no loop-variant portions.
8247 for (unsigned i
= 0, e
= AddRec
->getNumOperands(); i
!= e
; ++i
) {
8248 const SCEV
*OpAtScope
= getSCEVAtScope(AddRec
->getOperand(i
), L
);
8249 if (OpAtScope
== AddRec
->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(AddRec
->op_begin(),
8255 AddRec
->op_begin()+i
);
8256 NewOps
.push_back(OpAtScope
);
8257 for (++i
; i
!= e
; ++i
)
8258 NewOps
.push_back(getSCEVAtScope(AddRec
->getOperand(i
), L
));
8260 const SCEV
*FoldedRec
=
8261 getAddRecExpr(NewOps
, AddRec
->getLoop(),
8262 AddRec
->getNoWrapFlags(SCEV::FlagNW
));
8263 AddRec
= dyn_cast
<SCEVAddRecExpr
>(FoldedRec
);
8264 // The addrec may be folded to a nonrecurrence, for example, if the
8265 // induction variable is multiplied by zero after constant folding. Go
8266 // ahead and return the folded value.
8272 // If the scope is outside the addrec's loop, evaluate it by using the
8273 // loop exit value of the addrec.
8274 if (!AddRec
->getLoop()->contains(L
)) {
8275 // To evaluate this recurrence, we need to know how many times the AddRec
8276 // loop iterates. Compute this now.
8277 const SCEV
*BackedgeTakenCount
= getBackedgeTakenCount(AddRec
->getLoop());
8278 if (BackedgeTakenCount
== getCouldNotCompute()) return AddRec
;
8280 // Then, evaluate the AddRec.
8281 return AddRec
->evaluateAtIteration(BackedgeTakenCount
, *this);
8287 if (const SCEVZeroExtendExpr
*Cast
= dyn_cast
<SCEVZeroExtendExpr
>(V
)) {
8288 const SCEV
*Op
= getSCEVAtScope(Cast
->getOperand(), L
);
8289 if (Op
== Cast
->getOperand())
8290 return Cast
; // must be loop invariant
8291 return getZeroExtendExpr(Op
, Cast
->getType());
8294 if (const SCEVSignExtendExpr
*Cast
= dyn_cast
<SCEVSignExtendExpr
>(V
)) {
8295 const SCEV
*Op
= getSCEVAtScope(Cast
->getOperand(), L
);
8296 if (Op
== Cast
->getOperand())
8297 return Cast
; // must be loop invariant
8298 return getSignExtendExpr(Op
, Cast
->getType());
8301 if (const SCEVTruncateExpr
*Cast
= dyn_cast
<SCEVTruncateExpr
>(V
)) {
8302 const SCEV
*Op
= getSCEVAtScope(Cast
->getOperand(), L
);
8303 if (Op
== Cast
->getOperand())
8304 return Cast
; // must be loop invariant
8305 return getTruncateExpr(Op
, Cast
->getType());
8308 llvm_unreachable("Unknown SCEV type!");
8311 const SCEV
*ScalarEvolution::getSCEVAtScope(Value
*V
, const Loop
*L
) {
8312 return getSCEVAtScope(getSCEV(V
), L
);
8315 const SCEV
*ScalarEvolution::stripInjectiveFunctions(const SCEV
*S
) const {
8316 if (const SCEVZeroExtendExpr
*ZExt
= dyn_cast
<SCEVZeroExtendExpr
>(S
))
8317 return stripInjectiveFunctions(ZExt
->getOperand());
8318 if (const SCEVSignExtendExpr
*SExt
= dyn_cast
<SCEVSignExtendExpr
>(S
))
8319 return stripInjectiveFunctions(SExt
->getOperand());
8323 /// Finds the minimum unsigned root of the following equation:
8325 /// A * X = B (mod N)
8327 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
8328 /// A and B isn't important.
8330 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
8331 static const SCEV
*SolveLinEquationWithOverflow(const APInt
&A
, const SCEV
*B
,
8332 ScalarEvolution
&SE
) {
8333 uint32_t BW
= A
.getBitWidth();
8334 assert(BW
== SE
.getTypeSizeInBits(B
->getType()));
8335 assert(A
!= 0 && "A must be non-zero.");
8339 // The gcd of A and N may have only one prime factor: 2. The number of
8340 // trailing zeros in A is its multiplicity
8341 uint32_t Mult2
= A
.countTrailingZeros();
8344 // 2. Check if B is divisible by D.
8346 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
8347 // is not less than multiplicity of this prime factor for D.
8348 if (SE
.GetMinTrailingZeros(B
) < Mult2
)
8349 return SE
.getCouldNotCompute();
8351 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
8354 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
8355 // (N / D) in general. The inverse itself always fits into BW bits, though,
8356 // so we immediately truncate it.
8357 APInt AD
= A
.lshr(Mult2
).zext(BW
+ 1); // AD = A / D
8358 APInt
Mod(BW
+ 1, 0);
8359 Mod
.setBit(BW
- Mult2
); // Mod = N / D
8360 APInt I
= AD
.multiplicativeInverse(Mod
).trunc(BW
);
8362 // 4. Compute the minimum unsigned root of the equation:
8363 // I * (B / D) mod (N / D)
8364 // To simplify the computation, we factor out the divide by D:
8365 // (I * B mod N) / D
8366 const SCEV
*D
= SE
.getConstant(APInt::getOneBitSet(BW
, Mult2
));
8367 return SE
.getUDivExactExpr(SE
.getMulExpr(B
, SE
.getConstant(I
)), D
);
8370 /// For a given quadratic addrec, generate coefficients of the corresponding
8371 /// quadratic equation, multiplied by a common value to ensure that they are
8373 /// The returned value is a tuple { A, B, C, M, BitWidth }, where
8374 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
8375 /// were multiplied by, and BitWidth is the bit width of the original addrec
8377 /// This function returns None if the addrec coefficients are not compile-
8379 static Optional
<std::tuple
<APInt
, APInt
, APInt
, APInt
, unsigned>>
8380 GetQuadraticEquation(const SCEVAddRecExpr
*AddRec
) {
8381 assert(AddRec
->getNumOperands() == 3 && "This is not a quadratic chrec!");
8382 const SCEVConstant
*LC
= dyn_cast
<SCEVConstant
>(AddRec
->getOperand(0));
8383 const SCEVConstant
*MC
= dyn_cast
<SCEVConstant
>(AddRec
->getOperand(1));
8384 const SCEVConstant
*NC
= dyn_cast
<SCEVConstant
>(AddRec
->getOperand(2));
8385 LLVM_DEBUG(dbgs() << __func__
<< ": analyzing quadratic addrec: "
8386 << *AddRec
<< '\n');
8388 // We currently can only solve this if the coefficients are constants.
8389 if (!LC
|| !MC
|| !NC
) {
8390 LLVM_DEBUG(dbgs() << __func__
<< ": coefficients are not constant\n");
8394 APInt L
= LC
->getAPInt();
8395 APInt M
= MC
->getAPInt();
8396 APInt N
= NC
->getAPInt();
8397 assert(!N
.isNullValue() && "This is not a quadratic addrec");
8399 unsigned BitWidth
= LC
->getAPInt().getBitWidth();
8400 unsigned NewWidth
= BitWidth
+ 1;
8401 LLVM_DEBUG(dbgs() << __func__
<< ": addrec coeff bw: "
8402 << BitWidth
<< '\n');
8403 // The sign-extension (as opposed to a zero-extension) here matches the
8404 // extension used in SolveQuadraticEquationWrap (with the same motivation).
8405 N
= N
.sext(NewWidth
);
8406 M
= M
.sext(NewWidth
);
8407 L
= L
.sext(NewWidth
);
8409 // The increments are M, M+N, M+2N, ..., so the accumulated values are
8410 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
8411 // L+M, L+2M+N, L+3M+3N, ...
8412 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
8414 // The equation Acc = 0 is then
8415 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0.
8416 // In a quadratic form it becomes:
8417 // N n^2 + (2M-N) n + 2L = 0.
8420 APInt B
= 2 * M
- A
;
8422 APInt T
= APInt(NewWidth
, 2);
8423 LLVM_DEBUG(dbgs() << __func__
<< ": equation " << A
<< "x^2 + " << B
8424 << "x + " << C
<< ", coeff bw: " << NewWidth
8425 << ", multiplied by " << T
<< '\n');
8426 return std::make_tuple(A
, B
, C
, T
, BitWidth
);
8429 /// Helper function to compare optional APInts:
8430 /// (a) if X and Y both exist, return min(X, Y),
8431 /// (b) if neither X nor Y exist, return None,
8432 /// (c) if exactly one of X and Y exists, return that value.
8433 static Optional
<APInt
> MinOptional(Optional
<APInt
> X
, Optional
<APInt
> Y
) {
8434 if (X
.hasValue() && Y
.hasValue()) {
8435 unsigned W
= std::max(X
->getBitWidth(), Y
->getBitWidth());
8436 APInt XW
= X
->sextOrSelf(W
);
8437 APInt YW
= Y
->sextOrSelf(W
);
8438 return XW
.slt(YW
) ? *X
: *Y
;
8440 if (!X
.hasValue() && !Y
.hasValue())
8442 return X
.hasValue() ? *X
: *Y
;
8445 /// Helper function to truncate an optional APInt to a given BitWidth.
8446 /// When solving addrec-related equations, it is preferable to return a value
8447 /// that has the same bit width as the original addrec's coefficients. If the
8448 /// solution fits in the original bit width, truncate it (except for i1).
8449 /// Returning a value of a different bit width may inhibit some optimizations.
8451 /// In general, a solution to a quadratic equation generated from an addrec
8452 /// may require BW+1 bits, where BW is the bit width of the addrec's
8453 /// coefficients. The reason is that the coefficients of the quadratic
8454 /// equation are BW+1 bits wide (to avoid truncation when converting from
8455 /// the addrec to the equation).
8456 static Optional
<APInt
> TruncIfPossible(Optional
<APInt
> X
, unsigned BitWidth
) {
8459 unsigned W
= X
->getBitWidth();
8460 if (BitWidth
> 1 && BitWidth
< W
&& X
->isIntN(BitWidth
))
8461 return X
->trunc(BitWidth
);
8465 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
8466 /// iterations. The values L, M, N are assumed to be signed, and they
8467 /// should all have the same bit widths.
8468 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
8469 /// where BW is the bit width of the addrec's coefficients.
8470 /// If the calculated value is a BW-bit integer (for BW > 1), it will be
8471 /// returned as such, otherwise the bit width of the returned value may
8472 /// be greater than BW.
8474 /// This function returns None if
8475 /// (a) the addrec coefficients are not constant, or
8476 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
8477 /// like x^2 = 5, no integer solutions exist, in other cases an integer
8478 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it.
8479 static Optional
<APInt
>
8480 SolveQuadraticAddRecExact(const SCEVAddRecExpr
*AddRec
, ScalarEvolution
&SE
) {
8483 auto T
= GetQuadraticEquation(AddRec
);
8487 std::tie(A
, B
, C
, M
, BitWidth
) = *T
;
8488 LLVM_DEBUG(dbgs() << __func__
<< ": solving for unsigned overflow\n");
8489 Optional
<APInt
> X
= APIntOps::SolveQuadraticEquationWrap(A
, B
, C
, BitWidth
+1);
8493 ConstantInt
*CX
= ConstantInt::get(SE
.getContext(), *X
);
8494 ConstantInt
*V
= EvaluateConstantChrecAtConstant(AddRec
, CX
, SE
);
8498 return TruncIfPossible(X
, BitWidth
);
8501 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
8502 /// iterations. The values M, N are assumed to be signed, and they
8503 /// should all have the same bit widths.
8504 /// Find the least n such that c(n) does not belong to the given range,
8505 /// while c(n-1) does.
8507 /// This function returns None if
8508 /// (a) the addrec coefficients are not constant, or
8509 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the
8510 /// bounds of the range.
8511 static Optional
<APInt
>
8512 SolveQuadraticAddRecRange(const SCEVAddRecExpr
*AddRec
,
8513 const ConstantRange
&Range
, ScalarEvolution
&SE
) {
8514 assert(AddRec
->getOperand(0)->isZero() &&
8515 "Starting value of addrec should be 0");
8516 LLVM_DEBUG(dbgs() << __func__
<< ": solving boundary crossing for range "
8517 << Range
<< ", addrec " << *AddRec
<< '\n');
8518 // This case is handled in getNumIterationsInRange. Here we can assume that
8519 // we start in the range.
8520 assert(Range
.contains(APInt(SE
.getTypeSizeInBits(AddRec
->getType()), 0)) &&
8521 "Addrec's initial value should be in range");
8525 auto T
= GetQuadraticEquation(AddRec
);
8529 // Be careful about the return value: there can be two reasons for not
8530 // returning an actual number. First, if no solutions to the equations
8531 // were found, and second, if the solutions don't leave the given range.
8532 // The first case means that the actual solution is "unknown", the second
8533 // means that it's known, but not valid. If the solution is unknown, we
8534 // cannot make any conclusions.
8535 // Return a pair: the optional solution and a flag indicating if the
8536 // solution was found.
8537 auto SolveForBoundary
= [&](APInt Bound
) -> std::pair
<Optional
<APInt
>,bool> {
8538 // Solve for signed overflow and unsigned overflow, pick the lower
8540 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
8541 << Bound
<< " (before multiplying by " << M
<< ")\n");
8542 Bound
*= M
; // The quadratic equation multiplier.
8544 Optional
<APInt
> SO
= None
;
8546 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
8547 "signed overflow\n");
8548 SO
= APIntOps::SolveQuadraticEquationWrap(A
, B
, -Bound
, BitWidth
);
8550 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
8551 "unsigned overflow\n");
8552 Optional
<APInt
> UO
= APIntOps::SolveQuadraticEquationWrap(A
, B
, -Bound
,
8555 auto LeavesRange
= [&] (const APInt
&X
) {
8556 ConstantInt
*C0
= ConstantInt::get(SE
.getContext(), X
);
8557 ConstantInt
*V0
= EvaluateConstantChrecAtConstant(AddRec
, C0
, SE
);
8558 if (Range
.contains(V0
->getValue()))
8560 // X should be at least 1, so X-1 is non-negative.
8561 ConstantInt
*C1
= ConstantInt::get(SE
.getContext(), X
-1);
8562 ConstantInt
*V1
= EvaluateConstantChrecAtConstant(AddRec
, C1
, SE
);
8563 if (Range
.contains(V1
->getValue()))
8568 // If SolveQuadraticEquationWrap returns None, it means that there can
8569 // be a solution, but the function failed to find it. We cannot treat it
8570 // as "no solution".
8571 if (!SO
.hasValue() || !UO
.hasValue())
8572 return { None
, false };
8574 // Check the smaller value first to see if it leaves the range.
8575 // At this point, both SO and UO must have values.
8576 Optional
<APInt
> Min
= MinOptional(SO
, UO
);
8577 if (LeavesRange(*Min
))
8578 return { Min
, true };
8579 Optional
<APInt
> Max
= Min
== SO
? UO
: SO
;
8580 if (LeavesRange(*Max
))
8581 return { Max
, true };
8583 // Solutions were found, but were eliminated, hence the "true".
8584 return { None
, true };
8587 std::tie(A
, B
, C
, M
, BitWidth
) = *T
;
8588 // Lower bound is inclusive, subtract 1 to represent the exiting value.
8589 APInt Lower
= Range
.getLower().sextOrSelf(A
.getBitWidth()) - 1;
8590 APInt Upper
= Range
.getUpper().sextOrSelf(A
.getBitWidth());
8591 auto SL
= SolveForBoundary(Lower
);
8592 auto SU
= SolveForBoundary(Upper
);
8593 // If any of the solutions was unknown, no meaninigful conclusions can
8595 if (!SL
.second
|| !SU
.second
)
8598 // Claim: The correct solution is not some value between Min and Max.
8600 // Justification: Assuming that Min and Max are different values, one of
8601 // them is when the first signed overflow happens, the other is when the
8602 // first unsigned overflow happens. Crossing the range boundary is only
8603 // possible via an overflow (treating 0 as a special case of it, modeling
8604 // an overflow as crossing k*2^W for some k).
8606 // The interesting case here is when Min was eliminated as an invalid
8607 // solution, but Max was not. The argument is that if there was another
8608 // overflow between Min and Max, it would also have been eliminated if
8609 // it was considered.
8611 // For a given boundary, it is possible to have two overflows of the same
8612 // type (signed/unsigned) without having the other type in between: this
8613 // can happen when the vertex of the parabola is between the iterations
8614 // corresponding to the overflows. This is only possible when the two
8615 // overflows cross k*2^W for the same k. In such case, if the second one
8616 // left the range (and was the first one to do so), the first overflow
8617 // would have to enter the range, which would mean that either we had left
8618 // the range before or that we started outside of it. Both of these cases
8619 // are contradictions.
8621 // Claim: In the case where SolveForBoundary returns None, the correct
8622 // solution is not some value between the Max for this boundary and the
8623 // Min of the other boundary.
8625 // Justification: Assume that we had such Max_A and Min_B corresponding
8626 // to range boundaries A and B and such that Max_A < Min_B. If there was
8627 // a solution between Max_A and Min_B, it would have to be caused by an
8628 // overflow corresponding to either A or B. It cannot correspond to B,
8629 // since Min_B is the first occurrence of such an overflow. If it
8630 // corresponded to A, it would have to be either a signed or an unsigned
8631 // overflow that is larger than both eliminated overflows for A. But
8632 // between the eliminated overflows and this overflow, the values would
8633 // cover the entire value space, thus crossing the other boundary, which
8634 // is a contradiction.
8636 return TruncIfPossible(MinOptional(SL
.first
, SU
.first
), BitWidth
);
8639 ScalarEvolution::ExitLimit
8640 ScalarEvolution::howFarToZero(const SCEV
*V
, const Loop
*L
, bool ControlsExit
,
8641 bool AllowPredicates
) {
8643 // This is only used for loops with a "x != y" exit test. The exit condition
8644 // is now expressed as a single expression, V = x-y. So the exit test is
8645 // effectively V != 0. We know and take advantage of the fact that this
8646 // expression only being used in a comparison by zero context.
8648 SmallPtrSet
<const SCEVPredicate
*, 4> Predicates
;
8649 // If the value is a constant
8650 if (const SCEVConstant
*C
= dyn_cast
<SCEVConstant
>(V
)) {
8651 // If the value is already zero, the branch will execute zero times.
8652 if (C
->getValue()->isZero()) return C
;
8653 return getCouldNotCompute(); // Otherwise it will loop infinitely.
8656 const SCEVAddRecExpr
*AddRec
=
8657 dyn_cast
<SCEVAddRecExpr
>(stripInjectiveFunctions(V
));
8659 if (!AddRec
&& AllowPredicates
)
8660 // Try to make this an AddRec using runtime tests, in the first X
8661 // iterations of this loop, where X is the SCEV expression found by the
8663 AddRec
= convertSCEVToAddRecWithPredicates(V
, L
, Predicates
);
8665 if (!AddRec
|| AddRec
->getLoop() != L
)
8666 return getCouldNotCompute();
8668 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
8669 // the quadratic equation to solve it.
8670 if (AddRec
->isQuadratic() && AddRec
->getType()->isIntegerTy()) {
8671 // We can only use this value if the chrec ends up with an exact zero
8672 // value at this index. When solving for "X*X != 5", for example, we
8673 // should not accept a root of 2.
8674 if (auto S
= SolveQuadraticAddRecExact(AddRec
, *this)) {
8675 const auto *R
= cast
<SCEVConstant
>(getConstant(S
.getValue()));
8676 return ExitLimit(R
, R
, false, Predicates
);
8678 return getCouldNotCompute();
8681 // Otherwise we can only handle this if it is affine.
8682 if (!AddRec
->isAffine())
8683 return getCouldNotCompute();
8685 // If this is an affine expression, the execution count of this branch is
8686 // the minimum unsigned root of the following equation:
8688 // Start + Step*N = 0 (mod 2^BW)
8692 // Step*N = -Start (mod 2^BW)
8694 // where BW is the common bit width of Start and Step.
8696 // Get the initial value for the loop.
8697 const SCEV
*Start
= getSCEVAtScope(AddRec
->getStart(), L
->getParentLoop());
8698 const SCEV
*Step
= getSCEVAtScope(AddRec
->getOperand(1), L
->getParentLoop());
8700 // For now we handle only constant steps.
8702 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
8703 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
8704 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
8705 // We have not yet seen any such cases.
8706 const SCEVConstant
*StepC
= dyn_cast
<SCEVConstant
>(Step
);
8707 if (!StepC
|| StepC
->getValue()->isZero())
8708 return getCouldNotCompute();
8710 // For positive steps (counting up until unsigned overflow):
8711 // N = -Start/Step (as unsigned)
8712 // For negative steps (counting down to zero):
8714 // First compute the unsigned distance from zero in the direction of Step.
8715 bool CountDown
= StepC
->getAPInt().isNegative();
8716 const SCEV
*Distance
= CountDown
? Start
: getNegativeSCEV(Start
);
8718 // Handle unitary steps, which cannot wraparound.
8719 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
8720 // N = Distance (as unsigned)
8721 if (StepC
->getValue()->isOne() || StepC
->getValue()->isMinusOne()) {
8722 APInt MaxBECount
= getUnsignedRangeMax(Distance
);
8724 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
8725 // we end up with a loop whose backedge-taken count is n - 1. Detect this
8726 // case, and see if we can improve the bound.
8728 // Explicitly handling this here is necessary because getUnsignedRange
8729 // isn't context-sensitive; it doesn't know that we only care about the
8730 // range inside the loop.
8731 const SCEV
*Zero
= getZero(Distance
->getType());
8732 const SCEV
*One
= getOne(Distance
->getType());
8733 const SCEV
*DistancePlusOne
= getAddExpr(Distance
, One
);
8734 if (isLoopEntryGuardedByCond(L
, ICmpInst::ICMP_NE
, DistancePlusOne
, Zero
)) {
8735 // If Distance + 1 doesn't overflow, we can compute the maximum distance
8736 // as "unsigned_max(Distance + 1) - 1".
8737 ConstantRange CR
= getUnsignedRange(DistancePlusOne
);
8738 MaxBECount
= APIntOps::umin(MaxBECount
, CR
.getUnsignedMax() - 1);
8740 return ExitLimit(Distance
, getConstant(MaxBECount
), false, Predicates
);
8743 // If the condition controls loop exit (the loop exits only if the expression
8744 // is true) and the addition is no-wrap we can use unsigned divide to
8745 // compute the backedge count. In this case, the step may not divide the
8746 // distance, but we don't care because if the condition is "missed" the loop
8747 // will have undefined behavior due to wrapping.
8748 if (ControlsExit
&& AddRec
->hasNoSelfWrap() &&
8749 loopHasNoAbnormalExits(AddRec
->getLoop())) {
8751 getUDivExpr(Distance
, CountDown
? getNegativeSCEV(Step
) : Step
);
8753 Exact
== getCouldNotCompute()
8755 : getConstant(getUnsignedRangeMax(Exact
));
8756 return ExitLimit(Exact
, Max
, false, Predicates
);
8759 // Solve the general equation.
8760 const SCEV
*E
= SolveLinEquationWithOverflow(StepC
->getAPInt(),
8761 getNegativeSCEV(Start
), *this);
8762 const SCEV
*M
= E
== getCouldNotCompute()
8764 : getConstant(getUnsignedRangeMax(E
));
8765 return ExitLimit(E
, M
, false, Predicates
);
8768 ScalarEvolution::ExitLimit
8769 ScalarEvolution::howFarToNonZero(const SCEV
*V
, const Loop
*L
) {
8770 // Loops that look like: while (X == 0) are very strange indeed. We don't
8771 // handle them yet except for the trivial case. This could be expanded in the
8772 // future as needed.
8774 // If the value is a constant, check to see if it is known to be non-zero
8775 // already. If so, the backedge will execute zero times.
8776 if (const SCEVConstant
*C
= dyn_cast
<SCEVConstant
>(V
)) {
8777 if (!C
->getValue()->isZero())
8778 return getZero(C
->getType());
8779 return getCouldNotCompute(); // Otherwise it will loop infinitely.
8782 // We could implement others, but I really doubt anyone writes loops like
8783 // this, and if they did, they would already be constant folded.
8784 return getCouldNotCompute();
8787 std::pair
<BasicBlock
*, BasicBlock
*>
8788 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock
*BB
) {
8789 // If the block has a unique predecessor, then there is no path from the
8790 // predecessor to the block that does not go through the direct edge
8791 // from the predecessor to the block.
8792 if (BasicBlock
*Pred
= BB
->getSinglePredecessor())
8795 // A loop's header is defined to be a block that dominates the loop.
8796 // If the header has a unique predecessor outside the loop, it must be
8797 // a block that has exactly one successor that can reach the loop.
8798 if (Loop
*L
= LI
.getLoopFor(BB
))
8799 return {L
->getLoopPredecessor(), L
->getHeader()};
8801 return {nullptr, nullptr};
8804 /// SCEV structural equivalence is usually sufficient for testing whether two
8805 /// expressions are equal, however for the purposes of looking for a condition
8806 /// guarding a loop, it can be useful to be a little more general, since a
8807 /// front-end may have replicated the controlling expression.
8808 static bool HasSameValue(const SCEV
*A
, const SCEV
*B
) {
8809 // Quick check to see if they are the same SCEV.
8810 if (A
== B
) return true;
8812 auto ComputesEqualValues
= [](const Instruction
*A
, const Instruction
*B
) {
8813 // Not all instructions that are "identical" compute the same value. For
8814 // instance, two distinct alloca instructions allocating the same type are
8815 // identical and do not read memory; but compute distinct values.
8816 return A
->isIdenticalTo(B
) && (isa
<BinaryOperator
>(A
) || isa
<GetElementPtrInst
>(A
));
8819 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
8820 // two different instructions with the same value. Check for this case.
8821 if (const SCEVUnknown
*AU
= dyn_cast
<SCEVUnknown
>(A
))
8822 if (const SCEVUnknown
*BU
= dyn_cast
<SCEVUnknown
>(B
))
8823 if (const Instruction
*AI
= dyn_cast
<Instruction
>(AU
->getValue()))
8824 if (const Instruction
*BI
= dyn_cast
<Instruction
>(BU
->getValue()))
8825 if (ComputesEqualValues(AI
, BI
))
8828 // Otherwise assume they may have a different value.
8832 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate
&Pred
,
8833 const SCEV
*&LHS
, const SCEV
*&RHS
,
8835 bool Changed
= false;
8836 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
8838 auto TrivialCase
= [&](bool TriviallyTrue
) {
8839 LHS
= RHS
= getConstant(ConstantInt::getFalse(getContext()));
8840 Pred
= TriviallyTrue
? ICmpInst::ICMP_EQ
: ICmpInst::ICMP_NE
;
8843 // If we hit the max recursion limit bail out.
8847 // Canonicalize a constant to the right side.
8848 if (const SCEVConstant
*LHSC
= dyn_cast
<SCEVConstant
>(LHS
)) {
8849 // Check for both operands constant.
8850 if (const SCEVConstant
*RHSC
= dyn_cast
<SCEVConstant
>(RHS
)) {
8851 if (ConstantExpr::getICmp(Pred
,
8853 RHSC
->getValue())->isNullValue())
8854 return TrivialCase(false);
8856 return TrivialCase(true);
8858 // Otherwise swap the operands to put the constant on the right.
8859 std::swap(LHS
, RHS
);
8860 Pred
= ICmpInst::getSwappedPredicate(Pred
);
8864 // If we're comparing an addrec with a value which is loop-invariant in the
8865 // addrec's loop, put the addrec on the left. Also make a dominance check,
8866 // as both operands could be addrecs loop-invariant in each other's loop.
8867 if (const SCEVAddRecExpr
*AR
= dyn_cast
<SCEVAddRecExpr
>(RHS
)) {
8868 const Loop
*L
= AR
->getLoop();
8869 if (isLoopInvariant(LHS
, L
) && properlyDominates(LHS
, L
->getHeader())) {
8870 std::swap(LHS
, RHS
);
8871 Pred
= ICmpInst::getSwappedPredicate(Pred
);
8876 // If there's a constant operand, canonicalize comparisons with boundary
8877 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
8878 if (const SCEVConstant
*RC
= dyn_cast
<SCEVConstant
>(RHS
)) {
8879 const APInt
&RA
= RC
->getAPInt();
8881 bool SimplifiedByConstantRange
= false;
8883 if (!ICmpInst::isEquality(Pred
)) {
8884 ConstantRange ExactCR
= ConstantRange::makeExactICmpRegion(Pred
, RA
);
8885 if (ExactCR
.isFullSet())
8886 return TrivialCase(true);
8887 else if (ExactCR
.isEmptySet())
8888 return TrivialCase(false);
8891 CmpInst::Predicate NewPred
;
8892 if (ExactCR
.getEquivalentICmp(NewPred
, NewRHS
) &&
8893 ICmpInst::isEquality(NewPred
)) {
8894 // We were able to convert an inequality to an equality.
8896 RHS
= getConstant(NewRHS
);
8897 Changed
= SimplifiedByConstantRange
= true;
8901 if (!SimplifiedByConstantRange
) {
8905 case ICmpInst::ICMP_EQ
:
8906 case ICmpInst::ICMP_NE
:
8907 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
8909 if (const SCEVAddExpr
*AE
= dyn_cast
<SCEVAddExpr
>(LHS
))
8910 if (const SCEVMulExpr
*ME
=
8911 dyn_cast
<SCEVMulExpr
>(AE
->getOperand(0)))
8912 if (AE
->getNumOperands() == 2 && ME
->getNumOperands() == 2 &&
8913 ME
->getOperand(0)->isAllOnesValue()) {
8914 RHS
= AE
->getOperand(1);
8915 LHS
= ME
->getOperand(1);
8921 // The "Should have been caught earlier!" messages refer to the fact
8922 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
8923 // should have fired on the corresponding cases, and canonicalized the
8924 // check to trivial case.
8926 case ICmpInst::ICMP_UGE
:
8927 assert(!RA
.isMinValue() && "Should have been caught earlier!");
8928 Pred
= ICmpInst::ICMP_UGT
;
8929 RHS
= getConstant(RA
- 1);
8932 case ICmpInst::ICMP_ULE
:
8933 assert(!RA
.isMaxValue() && "Should have been caught earlier!");
8934 Pred
= ICmpInst::ICMP_ULT
;
8935 RHS
= getConstant(RA
+ 1);
8938 case ICmpInst::ICMP_SGE
:
8939 assert(!RA
.isMinSignedValue() && "Should have been caught earlier!");
8940 Pred
= ICmpInst::ICMP_SGT
;
8941 RHS
= getConstant(RA
- 1);
8944 case ICmpInst::ICMP_SLE
:
8945 assert(!RA
.isMaxSignedValue() && "Should have been caught earlier!");
8946 Pred
= ICmpInst::ICMP_SLT
;
8947 RHS
= getConstant(RA
+ 1);
8954 // Check for obvious equality.
8955 if (HasSameValue(LHS
, RHS
)) {
8956 if (ICmpInst::isTrueWhenEqual(Pred
))
8957 return TrivialCase(true);
8958 if (ICmpInst::isFalseWhenEqual(Pred
))
8959 return TrivialCase(false);
8962 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
8963 // adding or subtracting 1 from one of the operands.
8965 case ICmpInst::ICMP_SLE
:
8966 if (!getSignedRangeMax(RHS
).isMaxSignedValue()) {
8967 RHS
= getAddExpr(getConstant(RHS
->getType(), 1, true), RHS
,
8969 Pred
= ICmpInst::ICMP_SLT
;
8971 } else if (!getSignedRangeMin(LHS
).isMinSignedValue()) {
8972 LHS
= getAddExpr(getConstant(RHS
->getType(), (uint64_t)-1, true), LHS
,
8974 Pred
= ICmpInst::ICMP_SLT
;
8978 case ICmpInst::ICMP_SGE
:
8979 if (!getSignedRangeMin(RHS
).isMinSignedValue()) {
8980 RHS
= getAddExpr(getConstant(RHS
->getType(), (uint64_t)-1, true), RHS
,
8982 Pred
= ICmpInst::ICMP_SGT
;
8984 } else if (!getSignedRangeMax(LHS
).isMaxSignedValue()) {
8985 LHS
= getAddExpr(getConstant(RHS
->getType(), 1, true), LHS
,
8987 Pred
= ICmpInst::ICMP_SGT
;
8991 case ICmpInst::ICMP_ULE
:
8992 if (!getUnsignedRangeMax(RHS
).isMaxValue()) {
8993 RHS
= getAddExpr(getConstant(RHS
->getType(), 1, true), RHS
,
8995 Pred
= ICmpInst::ICMP_ULT
;
8997 } else if (!getUnsignedRangeMin(LHS
).isMinValue()) {
8998 LHS
= getAddExpr(getConstant(RHS
->getType(), (uint64_t)-1, true), LHS
);
8999 Pred
= ICmpInst::ICMP_ULT
;
9003 case ICmpInst::ICMP_UGE
:
9004 if (!getUnsignedRangeMin(RHS
).isMinValue()) {
9005 RHS
= getAddExpr(getConstant(RHS
->getType(), (uint64_t)-1, true), RHS
);
9006 Pred
= ICmpInst::ICMP_UGT
;
9008 } else if (!getUnsignedRangeMax(LHS
).isMaxValue()) {
9009 LHS
= getAddExpr(getConstant(RHS
->getType(), 1, true), LHS
,
9011 Pred
= ICmpInst::ICMP_UGT
;
9019 // TODO: More simplifications are possible here.
9021 // Recursively simplify until we either hit a recursion limit or nothing
9024 return SimplifyICmpOperands(Pred
, LHS
, RHS
, Depth
+1);
9029 bool ScalarEvolution::isKnownNegative(const SCEV
*S
) {
9030 return getSignedRangeMax(S
).isNegative();
9033 bool ScalarEvolution::isKnownPositive(const SCEV
*S
) {
9034 return getSignedRangeMin(S
).isStrictlyPositive();
9037 bool ScalarEvolution::isKnownNonNegative(const SCEV
*S
) {
9038 return !getSignedRangeMin(S
).isNegative();
9041 bool ScalarEvolution::isKnownNonPositive(const SCEV
*S
) {
9042 return !getSignedRangeMax(S
).isStrictlyPositive();
9045 bool ScalarEvolution::isKnownNonZero(const SCEV
*S
) {
9046 return isKnownNegative(S
) || isKnownPositive(S
);
9049 std::pair
<const SCEV
*, const SCEV
*>
9050 ScalarEvolution::SplitIntoInitAndPostInc(const Loop
*L
, const SCEV
*S
) {
9051 // Compute SCEV on entry of loop L.
9052 const SCEV
*Start
= SCEVInitRewriter::rewrite(S
, L
, *this);
9053 if (Start
== getCouldNotCompute())
9054 return { Start
, Start
};
9055 // Compute post increment SCEV for loop L.
9056 const SCEV
*PostInc
= SCEVPostIncRewriter::rewrite(S
, L
, *this);
9057 assert(PostInc
!= getCouldNotCompute() && "Unexpected could not compute");
9058 return { Start
, PostInc
};
9061 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred
,
9062 const SCEV
*LHS
, const SCEV
*RHS
) {
9063 // First collect all loops.
9064 SmallPtrSet
<const Loop
*, 8> LoopsUsed
;
9065 getUsedLoops(LHS
, LoopsUsed
);
9066 getUsedLoops(RHS
, LoopsUsed
);
9068 if (LoopsUsed
.empty())
9071 // Domination relationship must be a linear order on collected loops.
9073 for (auto *L1
: LoopsUsed
)
9074 for (auto *L2
: LoopsUsed
)
9075 assert((DT
.dominates(L1
->getHeader(), L2
->getHeader()) ||
9076 DT
.dominates(L2
->getHeader(), L1
->getHeader())) &&
9077 "Domination relationship is not a linear order");
9081 *std::max_element(LoopsUsed
.begin(), LoopsUsed
.end(),
9082 [&](const Loop
*L1
, const Loop
*L2
) {
9083 return DT
.properlyDominates(L1
->getHeader(), L2
->getHeader());
9086 // Get init and post increment value for LHS.
9087 auto SplitLHS
= SplitIntoInitAndPostInc(MDL
, LHS
);
9088 // if LHS contains unknown non-invariant SCEV then bail out.
9089 if (SplitLHS
.first
== getCouldNotCompute())
9091 assert (SplitLHS
.second
!= getCouldNotCompute() && "Unexpected CNC");
9092 // Get init and post increment value for RHS.
9093 auto SplitRHS
= SplitIntoInitAndPostInc(MDL
, RHS
);
9094 // if RHS contains unknown non-invariant SCEV then bail out.
9095 if (SplitRHS
.first
== getCouldNotCompute())
9097 assert (SplitRHS
.second
!= getCouldNotCompute() && "Unexpected CNC");
9098 // It is possible that init SCEV contains an invariant load but it does
9099 // not dominate MDL and is not available at MDL loop entry, so we should
9101 if (!isAvailableAtLoopEntry(SplitLHS
.first
, MDL
) ||
9102 !isAvailableAtLoopEntry(SplitRHS
.first
, MDL
))
9105 return isLoopEntryGuardedByCond(MDL
, Pred
, SplitLHS
.first
, SplitRHS
.first
) &&
9106 isLoopBackedgeGuardedByCond(MDL
, Pred
, SplitLHS
.second
,
9110 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred
,
9111 const SCEV
*LHS
, const SCEV
*RHS
) {
9112 // Canonicalize the inputs first.
9113 (void)SimplifyICmpOperands(Pred
, LHS
, RHS
);
9115 if (isKnownViaInduction(Pred
, LHS
, RHS
))
9118 if (isKnownPredicateViaSplitting(Pred
, LHS
, RHS
))
9121 // Otherwise see what can be done with some simple reasoning.
9122 return isKnownViaNonRecursiveReasoning(Pred
, LHS
, RHS
);
9125 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred
,
9126 const SCEVAddRecExpr
*LHS
,
9128 const Loop
*L
= LHS
->getLoop();
9129 return isLoopEntryGuardedByCond(L
, Pred
, LHS
->getStart(), RHS
) &&
9130 isLoopBackedgeGuardedByCond(L
, Pred
, LHS
->getPostIncExpr(*this), RHS
);
9133 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr
*LHS
,
9134 ICmpInst::Predicate Pred
,
9136 bool Result
= isMonotonicPredicateImpl(LHS
, Pred
, Increasing
);
9139 // Verify an invariant: inverting the predicate should turn a monotonically
9140 // increasing change to a monotonically decreasing one, and vice versa.
9141 bool IncreasingSwapped
;
9142 bool ResultSwapped
= isMonotonicPredicateImpl(
9143 LHS
, ICmpInst::getSwappedPredicate(Pred
), IncreasingSwapped
);
9145 assert(Result
== ResultSwapped
&& "should be able to analyze both!");
9147 assert(Increasing
== !IncreasingSwapped
&&
9148 "monotonicity should flip as we flip the predicate");
9154 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr
*LHS
,
9155 ICmpInst::Predicate Pred
,
9158 // A zero step value for LHS means the induction variable is essentially a
9159 // loop invariant value. We don't really depend on the predicate actually
9160 // flipping from false to true (for increasing predicates, and the other way
9161 // around for decreasing predicates), all we care about is that *if* the
9162 // predicate changes then it only changes from false to true.
9164 // A zero step value in itself is not very useful, but there may be places
9165 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
9166 // as general as possible.
9170 return false; // Conservative answer
9172 case ICmpInst::ICMP_UGT
:
9173 case ICmpInst::ICMP_UGE
:
9174 case ICmpInst::ICMP_ULT
:
9175 case ICmpInst::ICMP_ULE
:
9176 if (!LHS
->hasNoUnsignedWrap())
9179 Increasing
= Pred
== ICmpInst::ICMP_UGT
|| Pred
== ICmpInst::ICMP_UGE
;
9182 case ICmpInst::ICMP_SGT
:
9183 case ICmpInst::ICMP_SGE
:
9184 case ICmpInst::ICMP_SLT
:
9185 case ICmpInst::ICMP_SLE
: {
9186 if (!LHS
->hasNoSignedWrap())
9189 const SCEV
*Step
= LHS
->getStepRecurrence(*this);
9191 if (isKnownNonNegative(Step
)) {
9192 Increasing
= Pred
== ICmpInst::ICMP_SGT
|| Pred
== ICmpInst::ICMP_SGE
;
9196 if (isKnownNonPositive(Step
)) {
9197 Increasing
= Pred
== ICmpInst::ICMP_SLT
|| Pred
== ICmpInst::ICMP_SLE
;
9206 llvm_unreachable("switch has default clause!");
9209 bool ScalarEvolution::isLoopInvariantPredicate(
9210 ICmpInst::Predicate Pred
, const SCEV
*LHS
, const SCEV
*RHS
, const Loop
*L
,
9211 ICmpInst::Predicate
&InvariantPred
, const SCEV
*&InvariantLHS
,
9212 const SCEV
*&InvariantRHS
) {
9214 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
9215 if (!isLoopInvariant(RHS
, L
)) {
9216 if (!isLoopInvariant(LHS
, L
))
9219 std::swap(LHS
, RHS
);
9220 Pred
= ICmpInst::getSwappedPredicate(Pred
);
9223 const SCEVAddRecExpr
*ArLHS
= dyn_cast
<SCEVAddRecExpr
>(LHS
);
9224 if (!ArLHS
|| ArLHS
->getLoop() != L
)
9228 if (!isMonotonicPredicate(ArLHS
, Pred
, Increasing
))
9231 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
9232 // true as the loop iterates, and the backedge is control dependent on
9233 // "ArLHS `Pred` RHS" == true then we can reason as follows:
9235 // * if the predicate was false in the first iteration then the predicate
9236 // is never evaluated again, since the loop exits without taking the
9238 // * if the predicate was true in the first iteration then it will
9239 // continue to be true for all future iterations since it is
9240 // monotonically increasing.
9242 // For both the above possibilities, we can replace the loop varying
9243 // predicate with its value on the first iteration of the loop (which is
9246 // A similar reasoning applies for a monotonically decreasing predicate, by
9247 // replacing true with false and false with true in the above two bullets.
9249 auto P
= Increasing
? Pred
: ICmpInst::getInversePredicate(Pred
);
9251 if (!isLoopBackedgeGuardedByCond(L
, P
, LHS
, RHS
))
9254 InvariantPred
= Pred
;
9255 InvariantLHS
= ArLHS
->getStart();
9260 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
9261 ICmpInst::Predicate Pred
, const SCEV
*LHS
, const SCEV
*RHS
) {
9262 if (HasSameValue(LHS
, RHS
))
9263 return ICmpInst::isTrueWhenEqual(Pred
);
9265 // This code is split out from isKnownPredicate because it is called from
9266 // within isLoopEntryGuardedByCond.
9269 [&](const ConstantRange
&RangeLHS
, const ConstantRange
&RangeRHS
) {
9270 return ConstantRange::makeSatisfyingICmpRegion(Pred
, RangeRHS
)
9271 .contains(RangeLHS
);
9274 // The check at the top of the function catches the case where the values are
9275 // known to be equal.
9276 if (Pred
== CmpInst::ICMP_EQ
)
9279 if (Pred
== CmpInst::ICMP_NE
)
9280 return CheckRanges(getSignedRange(LHS
), getSignedRange(RHS
)) ||
9281 CheckRanges(getUnsignedRange(LHS
), getUnsignedRange(RHS
)) ||
9282 isKnownNonZero(getMinusSCEV(LHS
, RHS
));
9284 if (CmpInst::isSigned(Pred
))
9285 return CheckRanges(getSignedRange(LHS
), getSignedRange(RHS
));
9287 return CheckRanges(getUnsignedRange(LHS
), getUnsignedRange(RHS
));
9290 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred
,
9293 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
9294 // Return Y via OutY.
9295 auto MatchBinaryAddToConst
=
9296 [this](const SCEV
*Result
, const SCEV
*X
, APInt
&OutY
,
9297 SCEV::NoWrapFlags ExpectedFlags
) {
9298 const SCEV
*NonConstOp
, *ConstOp
;
9299 SCEV::NoWrapFlags FlagsPresent
;
9301 if (!splitBinaryAdd(Result
, ConstOp
, NonConstOp
, FlagsPresent
) ||
9302 !isa
<SCEVConstant
>(ConstOp
) || NonConstOp
!= X
)
9305 OutY
= cast
<SCEVConstant
>(ConstOp
)->getAPInt();
9306 return (FlagsPresent
& ExpectedFlags
) == ExpectedFlags
;
9315 case ICmpInst::ICMP_SGE
:
9316 std::swap(LHS
, RHS
);
9318 case ICmpInst::ICMP_SLE
:
9319 // X s<= (X + C)<nsw> if C >= 0
9320 if (MatchBinaryAddToConst(RHS
, LHS
, C
, SCEV::FlagNSW
) && C
.isNonNegative())
9323 // (X + C)<nsw> s<= X if C <= 0
9324 if (MatchBinaryAddToConst(LHS
, RHS
, C
, SCEV::FlagNSW
) &&
9325 !C
.isStrictlyPositive())
9329 case ICmpInst::ICMP_SGT
:
9330 std::swap(LHS
, RHS
);
9332 case ICmpInst::ICMP_SLT
:
9333 // X s< (X + C)<nsw> if C > 0
9334 if (MatchBinaryAddToConst(RHS
, LHS
, C
, SCEV::FlagNSW
) &&
9335 C
.isStrictlyPositive())
9338 // (X + C)<nsw> s< X if C < 0
9339 if (MatchBinaryAddToConst(LHS
, RHS
, C
, SCEV::FlagNSW
) && C
.isNegative())
9347 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred
,
9350 if (Pred
!= ICmpInst::ICMP_ULT
|| ProvingSplitPredicate
)
9353 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
9354 // the stack can result in exponential time complexity.
9355 SaveAndRestore
<bool> Restore(ProvingSplitPredicate
, true);
9357 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
9359 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
9360 // isKnownPredicate. isKnownPredicate is more powerful, but also more
9361 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
9362 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
9363 // use isKnownPredicate later if needed.
9364 return isKnownNonNegative(RHS
) &&
9365 isKnownPredicate(CmpInst::ICMP_SGE
, LHS
, getZero(LHS
->getType())) &&
9366 isKnownPredicate(CmpInst::ICMP_SLT
, LHS
, RHS
);
9369 bool ScalarEvolution::isImpliedViaGuard(BasicBlock
*BB
,
9370 ICmpInst::Predicate Pred
,
9371 const SCEV
*LHS
, const SCEV
*RHS
) {
9372 // No need to even try if we know the module has no guards.
9376 return any_of(*BB
, [&](Instruction
&I
) {
9377 using namespace llvm::PatternMatch
;
9380 return match(&I
, m_Intrinsic
<Intrinsic::experimental_guard
>(
9381 m_Value(Condition
))) &&
9382 isImpliedCond(Pred
, LHS
, RHS
, Condition
, false);
9386 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
9387 /// protected by a conditional between LHS and RHS. This is used to
9388 /// to eliminate casts.
9390 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop
*L
,
9391 ICmpInst::Predicate Pred
,
9392 const SCEV
*LHS
, const SCEV
*RHS
) {
9393 // Interpret a null as meaning no loop, where there is obviously no guard
9394 // (interprocedural conditions notwithstanding).
9395 if (!L
) return true;
9398 assert(!verifyFunction(*L
->getHeader()->getParent(), &dbgs()) &&
9399 "This cannot be done on broken IR!");
9402 if (isKnownViaNonRecursiveReasoning(Pred
, LHS
, RHS
))
9405 BasicBlock
*Latch
= L
->getLoopLatch();
9409 BranchInst
*LoopContinuePredicate
=
9410 dyn_cast
<BranchInst
>(Latch
->getTerminator());
9411 if (LoopContinuePredicate
&& LoopContinuePredicate
->isConditional() &&
9412 isImpliedCond(Pred
, LHS
, RHS
,
9413 LoopContinuePredicate
->getCondition(),
9414 LoopContinuePredicate
->getSuccessor(0) != L
->getHeader()))
9417 // We don't want more than one activation of the following loops on the stack
9418 // -- that can lead to O(n!) time complexity.
9419 if (WalkingBEDominatingConds
)
9422 SaveAndRestore
<bool> ClearOnExit(WalkingBEDominatingConds
, true);
9424 // See if we can exploit a trip count to prove the predicate.
9425 const auto &BETakenInfo
= getBackedgeTakenInfo(L
);
9426 const SCEV
*LatchBECount
= BETakenInfo
.getExact(Latch
, this);
9427 if (LatchBECount
!= getCouldNotCompute()) {
9428 // We know that Latch branches back to the loop header exactly
9429 // LatchBECount times. This means the backdege condition at Latch is
9430 // equivalent to "{0,+,1} u< LatchBECount".
9431 Type
*Ty
= LatchBECount
->getType();
9432 auto NoWrapFlags
= SCEV::NoWrapFlags(SCEV::FlagNUW
| SCEV::FlagNW
);
9433 const SCEV
*LoopCounter
=
9434 getAddRecExpr(getZero(Ty
), getOne(Ty
), L
, NoWrapFlags
);
9435 if (isImpliedCond(Pred
, LHS
, RHS
, ICmpInst::ICMP_ULT
, LoopCounter
,
9440 // Check conditions due to any @llvm.assume intrinsics.
9441 for (auto &AssumeVH
: AC
.assumptions()) {
9444 auto *CI
= cast
<CallInst
>(AssumeVH
);
9445 if (!DT
.dominates(CI
, Latch
->getTerminator()))
9448 if (isImpliedCond(Pred
, LHS
, RHS
, CI
->getArgOperand(0), false))
9452 // If the loop is not reachable from the entry block, we risk running into an
9453 // infinite loop as we walk up into the dom tree. These loops do not matter
9454 // anyway, so we just return a conservative answer when we see them.
9455 if (!DT
.isReachableFromEntry(L
->getHeader()))
9458 if (isImpliedViaGuard(Latch
, Pred
, LHS
, RHS
))
9461 for (DomTreeNode
*DTN
= DT
[Latch
], *HeaderDTN
= DT
[L
->getHeader()];
9462 DTN
!= HeaderDTN
; DTN
= DTN
->getIDom()) {
9463 assert(DTN
&& "should reach the loop header before reaching the root!");
9465 BasicBlock
*BB
= DTN
->getBlock();
9466 if (isImpliedViaGuard(BB
, Pred
, LHS
, RHS
))
9469 BasicBlock
*PBB
= BB
->getSinglePredecessor();
9473 BranchInst
*ContinuePredicate
= dyn_cast
<BranchInst
>(PBB
->getTerminator());
9474 if (!ContinuePredicate
|| !ContinuePredicate
->isConditional())
9477 Value
*Condition
= ContinuePredicate
->getCondition();
9479 // If we have an edge `E` within the loop body that dominates the only
9480 // latch, the condition guarding `E` also guards the backedge. This
9481 // reasoning works only for loops with a single latch.
9483 BasicBlockEdge
DominatingEdge(PBB
, BB
);
9484 if (DominatingEdge
.isSingleEdge()) {
9485 // We're constructively (and conservatively) enumerating edges within the
9486 // loop body that dominate the latch. The dominator tree better agree
9488 assert(DT
.dominates(DominatingEdge
, Latch
) && "should be!");
9490 if (isImpliedCond(Pred
, LHS
, RHS
, Condition
,
9491 BB
!= ContinuePredicate
->getSuccessor(0)))
9500 ScalarEvolution::isLoopEntryGuardedByCond(const Loop
*L
,
9501 ICmpInst::Predicate Pred
,
9502 const SCEV
*LHS
, const SCEV
*RHS
) {
9503 // Interpret a null as meaning no loop, where there is obviously no guard
9504 // (interprocedural conditions notwithstanding).
9505 if (!L
) return false;
9508 assert(!verifyFunction(*L
->getHeader()->getParent(), &dbgs()) &&
9509 "This cannot be done on broken IR!");
9511 // Both LHS and RHS must be available at loop entry.
9512 assert(isAvailableAtLoopEntry(LHS
, L
) &&
9513 "LHS is not available at Loop Entry");
9514 assert(isAvailableAtLoopEntry(RHS
, L
) &&
9515 "RHS is not available at Loop Entry");
9517 if (isKnownViaNonRecursiveReasoning(Pred
, LHS
, RHS
))
9520 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
9521 // the facts (a >= b && a != b) separately. A typical situation is when the
9522 // non-strict comparison is known from ranges and non-equality is known from
9523 // dominating predicates. If we are proving strict comparison, we always try
9524 // to prove non-equality and non-strict comparison separately.
9525 auto NonStrictPredicate
= ICmpInst::getNonStrictPredicate(Pred
);
9526 const bool ProvingStrictComparison
= (Pred
!= NonStrictPredicate
);
9527 bool ProvedNonStrictComparison
= false;
9528 bool ProvedNonEquality
= false;
9530 if (ProvingStrictComparison
) {
9531 ProvedNonStrictComparison
=
9532 isKnownViaNonRecursiveReasoning(NonStrictPredicate
, LHS
, RHS
);
9534 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE
, LHS
, RHS
);
9535 if (ProvedNonStrictComparison
&& ProvedNonEquality
)
9539 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
9540 auto ProveViaGuard
= [&](BasicBlock
*Block
) {
9541 if (isImpliedViaGuard(Block
, Pred
, LHS
, RHS
))
9543 if (ProvingStrictComparison
) {
9544 if (!ProvedNonStrictComparison
)
9545 ProvedNonStrictComparison
=
9546 isImpliedViaGuard(Block
, NonStrictPredicate
, LHS
, RHS
);
9547 if (!ProvedNonEquality
)
9549 isImpliedViaGuard(Block
, ICmpInst::ICMP_NE
, LHS
, RHS
);
9550 if (ProvedNonStrictComparison
&& ProvedNonEquality
)
9556 // Try to prove (Pred, LHS, RHS) using isImpliedCond.
9557 auto ProveViaCond
= [&](Value
*Condition
, bool Inverse
) {
9558 if (isImpliedCond(Pred
, LHS
, RHS
, Condition
, Inverse
))
9560 if (ProvingStrictComparison
) {
9561 if (!ProvedNonStrictComparison
)
9562 ProvedNonStrictComparison
=
9563 isImpliedCond(NonStrictPredicate
, LHS
, RHS
, Condition
, Inverse
);
9564 if (!ProvedNonEquality
)
9566 isImpliedCond(ICmpInst::ICMP_NE
, LHS
, RHS
, Condition
, Inverse
);
9567 if (ProvedNonStrictComparison
&& ProvedNonEquality
)
9573 // Starting at the loop predecessor, climb up the predecessor chain, as long
9574 // as there are predecessors that can be found that have unique successors
9575 // leading to the original header.
9576 for (std::pair
<BasicBlock
*, BasicBlock
*>
9577 Pair(L
->getLoopPredecessor(), L
->getHeader());
9579 Pair
= getPredecessorWithUniqueSuccessorForBB(Pair
.first
)) {
9581 if (ProveViaGuard(Pair
.first
))
9584 BranchInst
*LoopEntryPredicate
=
9585 dyn_cast
<BranchInst
>(Pair
.first
->getTerminator());
9586 if (!LoopEntryPredicate
||
9587 LoopEntryPredicate
->isUnconditional())
9590 if (ProveViaCond(LoopEntryPredicate
->getCondition(),
9591 LoopEntryPredicate
->getSuccessor(0) != Pair
.second
))
9595 // Check conditions due to any @llvm.assume intrinsics.
9596 for (auto &AssumeVH
: AC
.assumptions()) {
9599 auto *CI
= cast
<CallInst
>(AssumeVH
);
9600 if (!DT
.dominates(CI
, L
->getHeader()))
9603 if (ProveViaCond(CI
->getArgOperand(0), false))
9610 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred
,
9611 const SCEV
*LHS
, const SCEV
*RHS
,
9612 Value
*FoundCondValue
,
9614 if (!PendingLoopPredicates
.insert(FoundCondValue
).second
)
9618 make_scope_exit([&]() { PendingLoopPredicates
.erase(FoundCondValue
); });
9620 // Recursively handle And and Or conditions.
9621 if (BinaryOperator
*BO
= dyn_cast
<BinaryOperator
>(FoundCondValue
)) {
9622 if (BO
->getOpcode() == Instruction::And
) {
9624 return isImpliedCond(Pred
, LHS
, RHS
, BO
->getOperand(0), Inverse
) ||
9625 isImpliedCond(Pred
, LHS
, RHS
, BO
->getOperand(1), Inverse
);
9626 } else if (BO
->getOpcode() == Instruction::Or
) {
9628 return isImpliedCond(Pred
, LHS
, RHS
, BO
->getOperand(0), Inverse
) ||
9629 isImpliedCond(Pred
, LHS
, RHS
, BO
->getOperand(1), Inverse
);
9633 ICmpInst
*ICI
= dyn_cast
<ICmpInst
>(FoundCondValue
);
9634 if (!ICI
) return false;
9636 // Now that we found a conditional branch that dominates the loop or controls
9637 // the loop latch. Check to see if it is the comparison we are looking for.
9638 ICmpInst::Predicate FoundPred
;
9640 FoundPred
= ICI
->getInversePredicate();
9642 FoundPred
= ICI
->getPredicate();
9644 const SCEV
*FoundLHS
= getSCEV(ICI
->getOperand(0));
9645 const SCEV
*FoundRHS
= getSCEV(ICI
->getOperand(1));
9647 return isImpliedCond(Pred
, LHS
, RHS
, FoundPred
, FoundLHS
, FoundRHS
);
9650 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred
, const SCEV
*LHS
,
9652 ICmpInst::Predicate FoundPred
,
9653 const SCEV
*FoundLHS
,
9654 const SCEV
*FoundRHS
) {
9655 // Balance the types.
9656 if (getTypeSizeInBits(LHS
->getType()) <
9657 getTypeSizeInBits(FoundLHS
->getType())) {
9658 if (CmpInst::isSigned(Pred
)) {
9659 LHS
= getSignExtendExpr(LHS
, FoundLHS
->getType());
9660 RHS
= getSignExtendExpr(RHS
, FoundLHS
->getType());
9662 LHS
= getZeroExtendExpr(LHS
, FoundLHS
->getType());
9663 RHS
= getZeroExtendExpr(RHS
, FoundLHS
->getType());
9665 } else if (getTypeSizeInBits(LHS
->getType()) >
9666 getTypeSizeInBits(FoundLHS
->getType())) {
9667 if (CmpInst::isSigned(FoundPred
)) {
9668 FoundLHS
= getSignExtendExpr(FoundLHS
, LHS
->getType());
9669 FoundRHS
= getSignExtendExpr(FoundRHS
, LHS
->getType());
9671 FoundLHS
= getZeroExtendExpr(FoundLHS
, LHS
->getType());
9672 FoundRHS
= getZeroExtendExpr(FoundRHS
, LHS
->getType());
9676 // Canonicalize the query to match the way instcombine will have
9677 // canonicalized the comparison.
9678 if (SimplifyICmpOperands(Pred
, LHS
, RHS
))
9680 return CmpInst::isTrueWhenEqual(Pred
);
9681 if (SimplifyICmpOperands(FoundPred
, FoundLHS
, FoundRHS
))
9682 if (FoundLHS
== FoundRHS
)
9683 return CmpInst::isFalseWhenEqual(FoundPred
);
9685 // Check to see if we can make the LHS or RHS match.
9686 if (LHS
== FoundRHS
|| RHS
== FoundLHS
) {
9687 if (isa
<SCEVConstant
>(RHS
)) {
9688 std::swap(FoundLHS
, FoundRHS
);
9689 FoundPred
= ICmpInst::getSwappedPredicate(FoundPred
);
9691 std::swap(LHS
, RHS
);
9692 Pred
= ICmpInst::getSwappedPredicate(Pred
);
9696 // Check whether the found predicate is the same as the desired predicate.
9697 if (FoundPred
== Pred
)
9698 return isImpliedCondOperands(Pred
, LHS
, RHS
, FoundLHS
, FoundRHS
);
9700 // Check whether swapping the found predicate makes it the same as the
9701 // desired predicate.
9702 if (ICmpInst::getSwappedPredicate(FoundPred
) == Pred
) {
9703 if (isa
<SCEVConstant
>(RHS
))
9704 return isImpliedCondOperands(Pred
, LHS
, RHS
, FoundRHS
, FoundLHS
);
9706 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred
),
9707 RHS
, LHS
, FoundLHS
, FoundRHS
);
9710 // Unsigned comparison is the same as signed comparison when both the operands
9711 // are non-negative.
9712 if (CmpInst::isUnsigned(FoundPred
) &&
9713 CmpInst::getSignedPredicate(FoundPred
) == Pred
&&
9714 isKnownNonNegative(FoundLHS
) && isKnownNonNegative(FoundRHS
))
9715 return isImpliedCondOperands(Pred
, LHS
, RHS
, FoundLHS
, FoundRHS
);
9717 // Check if we can make progress by sharpening ranges.
9718 if (FoundPred
== ICmpInst::ICMP_NE
&&
9719 (isa
<SCEVConstant
>(FoundLHS
) || isa
<SCEVConstant
>(FoundRHS
))) {
9721 const SCEVConstant
*C
= nullptr;
9722 const SCEV
*V
= nullptr;
9724 if (isa
<SCEVConstant
>(FoundLHS
)) {
9725 C
= cast
<SCEVConstant
>(FoundLHS
);
9728 C
= cast
<SCEVConstant
>(FoundRHS
);
9732 // The guarding predicate tells us that C != V. If the known range
9733 // of V is [C, t), we can sharpen the range to [C + 1, t). The
9734 // range we consider has to correspond to same signedness as the
9735 // predicate we're interested in folding.
9737 APInt Min
= ICmpInst::isSigned(Pred
) ?
9738 getSignedRangeMin(V
) : getUnsignedRangeMin(V
);
9740 if (Min
== C
->getAPInt()) {
9741 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
9742 // This is true even if (Min + 1) wraps around -- in case of
9743 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
9745 APInt SharperMin
= Min
+ 1;
9748 case ICmpInst::ICMP_SGE
:
9749 case ICmpInst::ICMP_UGE
:
9750 // We know V `Pred` SharperMin. If this implies LHS `Pred`
9752 if (isImpliedCondOperands(Pred
, LHS
, RHS
, V
,
9753 getConstant(SharperMin
)))
9757 case ICmpInst::ICMP_SGT
:
9758 case ICmpInst::ICMP_UGT
:
9759 // We know from the range information that (V `Pred` Min ||
9760 // V == Min). We know from the guarding condition that !(V
9761 // == Min). This gives us
9763 // V `Pred` Min || V == Min && !(V == Min)
9766 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
9768 if (isImpliedCondOperands(Pred
, LHS
, RHS
, V
, getConstant(Min
)))
9779 // Check whether the actual condition is beyond sufficient.
9780 if (FoundPred
== ICmpInst::ICMP_EQ
)
9781 if (ICmpInst::isTrueWhenEqual(Pred
))
9782 if (isImpliedCondOperands(Pred
, LHS
, RHS
, FoundLHS
, FoundRHS
))
9784 if (Pred
== ICmpInst::ICMP_NE
)
9785 if (!ICmpInst::isTrueWhenEqual(FoundPred
))
9786 if (isImpliedCondOperands(FoundPred
, LHS
, RHS
, FoundLHS
, FoundRHS
))
9789 // Otherwise assume the worst.
9793 bool ScalarEvolution::splitBinaryAdd(const SCEV
*Expr
,
9794 const SCEV
*&L
, const SCEV
*&R
,
9795 SCEV::NoWrapFlags
&Flags
) {
9796 const auto *AE
= dyn_cast
<SCEVAddExpr
>(Expr
);
9797 if (!AE
|| AE
->getNumOperands() != 2)
9800 L
= AE
->getOperand(0);
9801 R
= AE
->getOperand(1);
9802 Flags
= AE
->getNoWrapFlags();
9806 Optional
<APInt
> ScalarEvolution::computeConstantDifference(const SCEV
*More
,
9808 // We avoid subtracting expressions here because this function is usually
9809 // fairly deep in the call stack (i.e. is called many times).
9811 if (isa
<SCEVAddRecExpr
>(Less
) && isa
<SCEVAddRecExpr
>(More
)) {
9812 const auto *LAR
= cast
<SCEVAddRecExpr
>(Less
);
9813 const auto *MAR
= cast
<SCEVAddRecExpr
>(More
);
9815 if (LAR
->getLoop() != MAR
->getLoop())
9818 // We look at affine expressions only; not for correctness but to keep
9819 // getStepRecurrence cheap.
9820 if (!LAR
->isAffine() || !MAR
->isAffine())
9823 if (LAR
->getStepRecurrence(*this) != MAR
->getStepRecurrence(*this))
9826 Less
= LAR
->getStart();
9827 More
= MAR
->getStart();
9832 if (isa
<SCEVConstant
>(Less
) && isa
<SCEVConstant
>(More
)) {
9833 const auto &M
= cast
<SCEVConstant
>(More
)->getAPInt();
9834 const auto &L
= cast
<SCEVConstant
>(Less
)->getAPInt();
9838 SCEV::NoWrapFlags Flags
;
9839 const SCEV
*LLess
= nullptr, *RLess
= nullptr;
9840 const SCEV
*LMore
= nullptr, *RMore
= nullptr;
9841 const SCEVConstant
*C1
= nullptr, *C2
= nullptr;
9842 // Compare (X + C1) vs X.
9843 if (splitBinaryAdd(Less
, LLess
, RLess
, Flags
))
9844 if ((C1
= dyn_cast
<SCEVConstant
>(LLess
)))
9846 return -(C1
->getAPInt());
9848 // Compare X vs (X + C2).
9849 if (splitBinaryAdd(More
, LMore
, RMore
, Flags
))
9850 if ((C2
= dyn_cast
<SCEVConstant
>(LMore
)))
9852 return C2
->getAPInt();
9854 // Compare (X + C1) vs (X + C2).
9855 if (C1
&& C2
&& RLess
== RMore
)
9856 return C2
->getAPInt() - C1
->getAPInt();
9861 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
9862 ICmpInst::Predicate Pred
, const SCEV
*LHS
, const SCEV
*RHS
,
9863 const SCEV
*FoundLHS
, const SCEV
*FoundRHS
) {
9864 if (Pred
!= CmpInst::ICMP_SLT
&& Pred
!= CmpInst::ICMP_ULT
)
9867 const auto *AddRecLHS
= dyn_cast
<SCEVAddRecExpr
>(LHS
);
9871 const auto *AddRecFoundLHS
= dyn_cast
<SCEVAddRecExpr
>(FoundLHS
);
9872 if (!AddRecFoundLHS
)
9875 // We'd like to let SCEV reason about control dependencies, so we constrain
9876 // both the inequalities to be about add recurrences on the same loop. This
9877 // way we can use isLoopEntryGuardedByCond later.
9879 const Loop
*L
= AddRecFoundLHS
->getLoop();
9880 if (L
!= AddRecLHS
->getLoop())
9883 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
9885 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
9888 // Informal proof for (2), assuming (1) [*]:
9890 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
9894 // FoundLHS s< FoundRHS s< INT_MIN - C
9895 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
9896 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
9897 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
9898 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
9899 // <=> FoundLHS + C s< FoundRHS + C
9901 // [*]: (1) can be proved by ruling out overflow.
9903 // [**]: This can be proved by analyzing all the four possibilities:
9904 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
9905 // (A s>= 0, B s>= 0).
9908 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
9909 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
9910 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
9911 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
9912 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
9915 Optional
<APInt
> LDiff
= computeConstantDifference(LHS
, FoundLHS
);
9916 Optional
<APInt
> RDiff
= computeConstantDifference(RHS
, FoundRHS
);
9917 if (!LDiff
|| !RDiff
|| *LDiff
!= *RDiff
)
9920 if (LDiff
->isMinValue())
9923 APInt FoundRHSLimit
;
9925 if (Pred
== CmpInst::ICMP_ULT
) {
9926 FoundRHSLimit
= -(*RDiff
);
9928 assert(Pred
== CmpInst::ICMP_SLT
&& "Checked above!");
9929 FoundRHSLimit
= APInt::getSignedMinValue(getTypeSizeInBits(RHS
->getType())) - *RDiff
;
9932 // Try to prove (1) or (2), as needed.
9933 return isAvailableAtLoopEntry(FoundRHS
, L
) &&
9934 isLoopEntryGuardedByCond(L
, Pred
, FoundRHS
,
9935 getConstant(FoundRHSLimit
));
9938 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred
,
9939 const SCEV
*LHS
, const SCEV
*RHS
,
9940 const SCEV
*FoundLHS
,
9941 const SCEV
*FoundRHS
, unsigned Depth
) {
9942 const PHINode
*LPhi
= nullptr, *RPhi
= nullptr;
9944 auto ClearOnExit
= make_scope_exit([&]() {
9946 bool Erased
= PendingMerges
.erase(LPhi
);
9947 assert(Erased
&& "Failed to erase LPhi!");
9951 bool Erased
= PendingMerges
.erase(RPhi
);
9952 assert(Erased
&& "Failed to erase RPhi!");
9957 // Find respective Phis and check that they are not being pending.
9958 if (const SCEVUnknown
*LU
= dyn_cast
<SCEVUnknown
>(LHS
))
9959 if (auto *Phi
= dyn_cast
<PHINode
>(LU
->getValue())) {
9960 if (!PendingMerges
.insert(Phi
).second
)
9964 if (const SCEVUnknown
*RU
= dyn_cast
<SCEVUnknown
>(RHS
))
9965 if (auto *Phi
= dyn_cast
<PHINode
>(RU
->getValue())) {
9966 // If we detect a loop of Phi nodes being processed by this method, for
9969 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
9970 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
9972 // we don't want to deal with a case that complex, so return conservative
9974 if (!PendingMerges
.insert(Phi
).second
)
9979 // If none of LHS, RHS is a Phi, nothing to do here.
9983 // If there is a SCEVUnknown Phi we are interested in, make it left.
9985 std::swap(LHS
, RHS
);
9986 std::swap(FoundLHS
, FoundRHS
);
9987 std::swap(LPhi
, RPhi
);
9988 Pred
= ICmpInst::getSwappedPredicate(Pred
);
9991 assert(LPhi
&& "LPhi should definitely be a SCEVUnknown Phi!");
9992 const BasicBlock
*LBB
= LPhi
->getParent();
9993 const SCEVAddRecExpr
*RAR
= dyn_cast
<SCEVAddRecExpr
>(RHS
);
9995 auto ProvedEasily
= [&](const SCEV
*S1
, const SCEV
*S2
) {
9996 return isKnownViaNonRecursiveReasoning(Pred
, S1
, S2
) ||
9997 isImpliedCondOperandsViaRanges(Pred
, S1
, S2
, FoundLHS
, FoundRHS
) ||
9998 isImpliedViaOperations(Pred
, S1
, S2
, FoundLHS
, FoundRHS
, Depth
);
10001 if (RPhi
&& RPhi
->getParent() == LBB
) {
10002 // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
10003 // If we compare two Phis from the same block, and for each entry block
10004 // the predicate is true for incoming values from this block, then the
10005 // predicate is also true for the Phis.
10006 for (const BasicBlock
*IncBB
: predecessors(LBB
)) {
10007 const SCEV
*L
= getSCEV(LPhi
->getIncomingValueForBlock(IncBB
));
10008 const SCEV
*R
= getSCEV(RPhi
->getIncomingValueForBlock(IncBB
));
10009 if (!ProvedEasily(L
, R
))
10012 } else if (RAR
&& RAR
->getLoop()->getHeader() == LBB
) {
10013 // Case two: RHS is also a Phi from the same basic block, and it is an
10014 // AddRec. It means that there is a loop which has both AddRec and Unknown
10015 // PHIs, for it we can compare incoming values of AddRec from above the loop
10016 // and latch with their respective incoming values of LPhi.
10017 // TODO: Generalize to handle loops with many inputs in a header.
10018 if (LPhi
->getNumIncomingValues() != 2) return false;
10020 auto *RLoop
= RAR
->getLoop();
10021 auto *Predecessor
= RLoop
->getLoopPredecessor();
10022 assert(Predecessor
&& "Loop with AddRec with no predecessor?");
10023 const SCEV
*L1
= getSCEV(LPhi
->getIncomingValueForBlock(Predecessor
));
10024 if (!ProvedEasily(L1
, RAR
->getStart()))
10026 auto *Latch
= RLoop
->getLoopLatch();
10027 assert(Latch
&& "Loop with AddRec with no latch?");
10028 const SCEV
*L2
= getSCEV(LPhi
->getIncomingValueForBlock(Latch
));
10029 if (!ProvedEasily(L2
, RAR
->getPostIncExpr(*this)))
10032 // In all other cases go over inputs of LHS and compare each of them to RHS,
10033 // the predicate is true for (LHS, RHS) if it is true for all such pairs.
10034 // At this point RHS is either a non-Phi, or it is a Phi from some block
10035 // different from LBB.
10036 for (const BasicBlock
*IncBB
: predecessors(LBB
)) {
10037 // Check that RHS is available in this block.
10038 if (!dominates(RHS
, IncBB
))
10040 const SCEV
*L
= getSCEV(LPhi
->getIncomingValueForBlock(IncBB
));
10041 if (!ProvedEasily(L
, RHS
))
10048 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred
,
10049 const SCEV
*LHS
, const SCEV
*RHS
,
10050 const SCEV
*FoundLHS
,
10051 const SCEV
*FoundRHS
) {
10052 if (isImpliedCondOperandsViaRanges(Pred
, LHS
, RHS
, FoundLHS
, FoundRHS
))
10055 if (isImpliedCondOperandsViaNoOverflow(Pred
, LHS
, RHS
, FoundLHS
, FoundRHS
))
10058 return isImpliedCondOperandsHelper(Pred
, LHS
, RHS
,
10059 FoundLHS
, FoundRHS
) ||
10060 // ~x < ~y --> x > y
10061 isImpliedCondOperandsHelper(Pred
, LHS
, RHS
,
10062 getNotSCEV(FoundRHS
),
10063 getNotSCEV(FoundLHS
));
10066 /// If Expr computes ~A, return A else return nullptr
10067 static const SCEV
*MatchNotExpr(const SCEV
*Expr
) {
10068 const SCEVAddExpr
*Add
= dyn_cast
<SCEVAddExpr
>(Expr
);
10069 if (!Add
|| Add
->getNumOperands() != 2 ||
10070 !Add
->getOperand(0)->isAllOnesValue())
10073 const SCEVMulExpr
*AddRHS
= dyn_cast
<SCEVMulExpr
>(Add
->getOperand(1));
10074 if (!AddRHS
|| AddRHS
->getNumOperands() != 2 ||
10075 !AddRHS
->getOperand(0)->isAllOnesValue())
10078 return AddRHS
->getOperand(1);
10081 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
10082 template<typename MaxExprType
>
10083 static bool IsMaxConsistingOf(const SCEV
*MaybeMaxExpr
,
10084 const SCEV
*Candidate
) {
10085 const MaxExprType
*MaxExpr
= dyn_cast
<MaxExprType
>(MaybeMaxExpr
);
10086 if (!MaxExpr
) return false;
10088 return find(MaxExpr
->operands(), Candidate
) != MaxExpr
->op_end();
10091 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
10092 template<typename MaxExprType
>
10093 static bool IsMinConsistingOf(ScalarEvolution
&SE
,
10094 const SCEV
*MaybeMinExpr
,
10095 const SCEV
*Candidate
) {
10096 const SCEV
*MaybeMaxExpr
= MatchNotExpr(MaybeMinExpr
);
10100 return IsMaxConsistingOf
<MaxExprType
>(MaybeMaxExpr
, SE
.getNotSCEV(Candidate
));
10103 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution
&SE
,
10104 ICmpInst::Predicate Pred
,
10105 const SCEV
*LHS
, const SCEV
*RHS
) {
10106 // If both sides are affine addrecs for the same loop, with equal
10107 // steps, and we know the recurrences don't wrap, then we only
10108 // need to check the predicate on the starting values.
10110 if (!ICmpInst::isRelational(Pred
))
10113 const SCEVAddRecExpr
*LAR
= dyn_cast
<SCEVAddRecExpr
>(LHS
);
10116 const SCEVAddRecExpr
*RAR
= dyn_cast
<SCEVAddRecExpr
>(RHS
);
10119 if (LAR
->getLoop() != RAR
->getLoop())
10121 if (!LAR
->isAffine() || !RAR
->isAffine())
10124 if (LAR
->getStepRecurrence(SE
) != RAR
->getStepRecurrence(SE
))
10127 SCEV::NoWrapFlags NW
= ICmpInst::isSigned(Pred
) ?
10128 SCEV::FlagNSW
: SCEV::FlagNUW
;
10129 if (!LAR
->getNoWrapFlags(NW
) || !RAR
->getNoWrapFlags(NW
))
10132 return SE
.isKnownPredicate(Pred
, LAR
->getStart(), RAR
->getStart());
10135 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
10137 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution
&SE
,
10138 ICmpInst::Predicate Pred
,
10139 const SCEV
*LHS
, const SCEV
*RHS
) {
10144 case ICmpInst::ICMP_SGE
:
10145 std::swap(LHS
, RHS
);
10147 case ICmpInst::ICMP_SLE
:
10149 // min(A, ...) <= A
10150 IsMinConsistingOf
<SCEVSMaxExpr
>(SE
, LHS
, RHS
) ||
10151 // A <= max(A, ...)
10152 IsMaxConsistingOf
<SCEVSMaxExpr
>(RHS
, LHS
);
10154 case ICmpInst::ICMP_UGE
:
10155 std::swap(LHS
, RHS
);
10157 case ICmpInst::ICMP_ULE
:
10159 // min(A, ...) <= A
10160 IsMinConsistingOf
<SCEVUMaxExpr
>(SE
, LHS
, RHS
) ||
10161 // A <= max(A, ...)
10162 IsMaxConsistingOf
<SCEVUMaxExpr
>(RHS
, LHS
);
10165 llvm_unreachable("covered switch fell through?!");
10168 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred
,
10169 const SCEV
*LHS
, const SCEV
*RHS
,
10170 const SCEV
*FoundLHS
,
10171 const SCEV
*FoundRHS
,
10173 assert(getTypeSizeInBits(LHS
->getType()) ==
10174 getTypeSizeInBits(RHS
->getType()) &&
10175 "LHS and RHS have different sizes?");
10176 assert(getTypeSizeInBits(FoundLHS
->getType()) ==
10177 getTypeSizeInBits(FoundRHS
->getType()) &&
10178 "FoundLHS and FoundRHS have different sizes?");
10179 // We want to avoid hurting the compile time with analysis of too big trees.
10180 if (Depth
> MaxSCEVOperationsImplicationDepth
)
10182 // We only want to work with ICMP_SGT comparison so far.
10183 // TODO: Extend to ICMP_UGT?
10184 if (Pred
== ICmpInst::ICMP_SLT
) {
10185 Pred
= ICmpInst::ICMP_SGT
;
10186 std::swap(LHS
, RHS
);
10187 std::swap(FoundLHS
, FoundRHS
);
10189 if (Pred
!= ICmpInst::ICMP_SGT
)
10192 auto GetOpFromSExt
= [&](const SCEV
*S
) {
10193 if (auto *Ext
= dyn_cast
<SCEVSignExtendExpr
>(S
))
10194 return Ext
->getOperand();
10195 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
10196 // the constant in some cases.
10200 // Acquire values from extensions.
10201 auto *OrigLHS
= LHS
;
10202 auto *OrigFoundLHS
= FoundLHS
;
10203 LHS
= GetOpFromSExt(LHS
);
10204 FoundLHS
= GetOpFromSExt(FoundLHS
);
10206 // Is the SGT predicate can be proved trivially or using the found context.
10207 auto IsSGTViaContext
= [&](const SCEV
*S1
, const SCEV
*S2
) {
10208 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT
, S1
, S2
) ||
10209 isImpliedViaOperations(ICmpInst::ICMP_SGT
, S1
, S2
, OrigFoundLHS
,
10210 FoundRHS
, Depth
+ 1);
10213 if (auto *LHSAddExpr
= dyn_cast
<SCEVAddExpr
>(LHS
)) {
10214 // We want to avoid creation of any new non-constant SCEV. Since we are
10215 // going to compare the operands to RHS, we should be certain that we don't
10216 // need any size extensions for this. So let's decline all cases when the
10217 // sizes of types of LHS and RHS do not match.
10218 // TODO: Maybe try to get RHS from sext to catch more cases?
10219 if (getTypeSizeInBits(LHS
->getType()) != getTypeSizeInBits(RHS
->getType()))
10222 // Should not overflow.
10223 if (!LHSAddExpr
->hasNoSignedWrap())
10226 auto *LL
= LHSAddExpr
->getOperand(0);
10227 auto *LR
= LHSAddExpr
->getOperand(1);
10228 auto *MinusOne
= getNegativeSCEV(getOne(RHS
->getType()));
10230 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
10231 auto IsSumGreaterThanRHS
= [&](const SCEV
*S1
, const SCEV
*S2
) {
10232 return IsSGTViaContext(S1
, MinusOne
) && IsSGTViaContext(S2
, RHS
);
10234 // Try to prove the following rule:
10235 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
10236 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
10237 if (IsSumGreaterThanRHS(LL
, LR
) || IsSumGreaterThanRHS(LR
, LL
))
10239 } else if (auto *LHSUnknownExpr
= dyn_cast
<SCEVUnknown
>(LHS
)) {
10241 // FIXME: Once we have SDiv implemented, we can get rid of this matching.
10243 using namespace llvm::PatternMatch
;
10245 if (match(LHSUnknownExpr
->getValue(), m_SDiv(m_Value(LL
), m_Value(LR
)))) {
10246 // Rules for division.
10247 // We are going to perform some comparisons with Denominator and its
10248 // derivative expressions. In general case, creating a SCEV for it may
10249 // lead to a complex analysis of the entire graph, and in particular it
10250 // can request trip count recalculation for the same loop. This would
10251 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
10252 // this, we only want to create SCEVs that are constants in this section.
10253 // So we bail if Denominator is not a constant.
10254 if (!isa
<ConstantInt
>(LR
))
10257 auto *Denominator
= cast
<SCEVConstant
>(getSCEV(LR
));
10259 // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
10260 // then a SCEV for the numerator already exists and matches with FoundLHS.
10261 auto *Numerator
= getExistingSCEV(LL
);
10262 if (!Numerator
|| Numerator
->getType() != FoundLHS
->getType())
10265 // Make sure that the numerator matches with FoundLHS and the denominator
10267 if (!HasSameValue(Numerator
, FoundLHS
) || !isKnownPositive(Denominator
))
10270 auto *DTy
= Denominator
->getType();
10271 auto *FRHSTy
= FoundRHS
->getType();
10272 if (DTy
->isPointerTy() != FRHSTy
->isPointerTy())
10273 // One of types is a pointer and another one is not. We cannot extend
10274 // them properly to a wider type, so let us just reject this case.
10275 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
10276 // to avoid this check.
10280 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
10281 auto *WTy
= getWiderType(DTy
, FRHSTy
);
10282 auto *DenominatorExt
= getNoopOrSignExtend(Denominator
, WTy
);
10283 auto *FoundRHSExt
= getNoopOrSignExtend(FoundRHS
, WTy
);
10285 // Try to prove the following rule:
10286 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
10287 // For example, given that FoundLHS > 2. It means that FoundLHS is at
10288 // least 3. If we divide it by Denominator < 4, we will have at least 1.
10289 auto *DenomMinusTwo
= getMinusSCEV(DenominatorExt
, getConstant(WTy
, 2));
10290 if (isKnownNonPositive(RHS
) &&
10291 IsSGTViaContext(FoundRHSExt
, DenomMinusTwo
))
10294 // Try to prove the following rule:
10295 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
10296 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
10297 // If we divide it by Denominator > 2, then:
10298 // 1. If FoundLHS is negative, then the result is 0.
10299 // 2. If FoundLHS is non-negative, then the result is non-negative.
10300 // Anyways, the result is non-negative.
10301 auto *MinusOne
= getNegativeSCEV(getOne(WTy
));
10302 auto *NegDenomMinusOne
= getMinusSCEV(MinusOne
, DenominatorExt
);
10303 if (isKnownNegative(RHS
) &&
10304 IsSGTViaContext(FoundRHSExt
, NegDenomMinusOne
))
10309 // If our expression contained SCEVUnknown Phis, and we split it down and now
10310 // need to prove something for them, try to prove the predicate for every
10311 // possible incoming values of those Phis.
10312 if (isImpliedViaMerge(Pred
, OrigLHS
, RHS
, OrigFoundLHS
, FoundRHS
, Depth
+ 1))
10319 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred
,
10320 const SCEV
*LHS
, const SCEV
*RHS
) {
10321 return isKnownPredicateViaConstantRanges(Pred
, LHS
, RHS
) ||
10322 IsKnownPredicateViaMinOrMax(*this, Pred
, LHS
, RHS
) ||
10323 IsKnownPredicateViaAddRecStart(*this, Pred
, LHS
, RHS
) ||
10324 isKnownPredicateViaNoOverflow(Pred
, LHS
, RHS
);
10328 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred
,
10329 const SCEV
*LHS
, const SCEV
*RHS
,
10330 const SCEV
*FoundLHS
,
10331 const SCEV
*FoundRHS
) {
10333 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
10334 case ICmpInst::ICMP_EQ
:
10335 case ICmpInst::ICMP_NE
:
10336 if (HasSameValue(LHS
, FoundLHS
) && HasSameValue(RHS
, FoundRHS
))
10339 case ICmpInst::ICMP_SLT
:
10340 case ICmpInst::ICMP_SLE
:
10341 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE
, LHS
, FoundLHS
) &&
10342 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE
, RHS
, FoundRHS
))
10345 case ICmpInst::ICMP_SGT
:
10346 case ICmpInst::ICMP_SGE
:
10347 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE
, LHS
, FoundLHS
) &&
10348 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE
, RHS
, FoundRHS
))
10351 case ICmpInst::ICMP_ULT
:
10352 case ICmpInst::ICMP_ULE
:
10353 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE
, LHS
, FoundLHS
) &&
10354 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE
, RHS
, FoundRHS
))
10357 case ICmpInst::ICMP_UGT
:
10358 case ICmpInst::ICMP_UGE
:
10359 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE
, LHS
, FoundLHS
) &&
10360 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE
, RHS
, FoundRHS
))
10365 // Maybe it can be proved via operations?
10366 if (isImpliedViaOperations(Pred
, LHS
, RHS
, FoundLHS
, FoundRHS
))
10372 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred
,
10375 const SCEV
*FoundLHS
,
10376 const SCEV
*FoundRHS
) {
10377 if (!isa
<SCEVConstant
>(RHS
) || !isa
<SCEVConstant
>(FoundRHS
))
10378 // The restriction on `FoundRHS` be lifted easily -- it exists only to
10379 // reduce the compile time impact of this optimization.
10382 Optional
<APInt
> Addend
= computeConstantDifference(LHS
, FoundLHS
);
10386 const APInt
&ConstFoundRHS
= cast
<SCEVConstant
>(FoundRHS
)->getAPInt();
10388 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
10389 // antecedent "`FoundLHS` `Pred` `FoundRHS`".
10390 ConstantRange FoundLHSRange
=
10391 ConstantRange::makeAllowedICmpRegion(Pred
, ConstFoundRHS
);
10393 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
10394 ConstantRange LHSRange
= FoundLHSRange
.add(ConstantRange(*Addend
));
10396 // We can also compute the range of values for `LHS` that satisfy the
10397 // consequent, "`LHS` `Pred` `RHS`":
10398 const APInt
&ConstRHS
= cast
<SCEVConstant
>(RHS
)->getAPInt();
10399 ConstantRange SatisfyingLHSRange
=
10400 ConstantRange::makeSatisfyingICmpRegion(Pred
, ConstRHS
);
10402 // The antecedent implies the consequent if every value of `LHS` that
10403 // satisfies the antecedent also satisfies the consequent.
10404 return SatisfyingLHSRange
.contains(LHSRange
);
10407 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV
*RHS
, const SCEV
*Stride
,
10408 bool IsSigned
, bool NoWrap
) {
10409 assert(isKnownPositive(Stride
) && "Positive stride expected!");
10411 if (NoWrap
) return false;
10413 unsigned BitWidth
= getTypeSizeInBits(RHS
->getType());
10414 const SCEV
*One
= getOne(Stride
->getType());
10417 APInt MaxRHS
= getSignedRangeMax(RHS
);
10418 APInt MaxValue
= APInt::getSignedMaxValue(BitWidth
);
10419 APInt MaxStrideMinusOne
= getSignedRangeMax(getMinusSCEV(Stride
, One
));
10421 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
10422 return (std::move(MaxValue
) - MaxStrideMinusOne
).slt(MaxRHS
);
10425 APInt MaxRHS
= getUnsignedRangeMax(RHS
);
10426 APInt MaxValue
= APInt::getMaxValue(BitWidth
);
10427 APInt MaxStrideMinusOne
= getUnsignedRangeMax(getMinusSCEV(Stride
, One
));
10429 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
10430 return (std::move(MaxValue
) - MaxStrideMinusOne
).ult(MaxRHS
);
10433 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV
*RHS
, const SCEV
*Stride
,
10434 bool IsSigned
, bool NoWrap
) {
10435 if (NoWrap
) return false;
10437 unsigned BitWidth
= getTypeSizeInBits(RHS
->getType());
10438 const SCEV
*One
= getOne(Stride
->getType());
10441 APInt MinRHS
= getSignedRangeMin(RHS
);
10442 APInt MinValue
= APInt::getSignedMinValue(BitWidth
);
10443 APInt MaxStrideMinusOne
= getSignedRangeMax(getMinusSCEV(Stride
, One
));
10445 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
10446 return (std::move(MinValue
) + MaxStrideMinusOne
).sgt(MinRHS
);
10449 APInt MinRHS
= getUnsignedRangeMin(RHS
);
10450 APInt MinValue
= APInt::getMinValue(BitWidth
);
10451 APInt MaxStrideMinusOne
= getUnsignedRangeMax(getMinusSCEV(Stride
, One
));
10453 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
10454 return (std::move(MinValue
) + MaxStrideMinusOne
).ugt(MinRHS
);
10457 const SCEV
*ScalarEvolution::computeBECount(const SCEV
*Delta
, const SCEV
*Step
,
10459 const SCEV
*One
= getOne(Step
->getType());
10460 Delta
= Equality
? getAddExpr(Delta
, Step
)
10461 : getAddExpr(Delta
, getMinusSCEV(Step
, One
));
10462 return getUDivExpr(Delta
, Step
);
10465 const SCEV
*ScalarEvolution::computeMaxBECountForLT(const SCEV
*Start
,
10466 const SCEV
*Stride
,
10471 assert(!isKnownNonPositive(Stride
) &&
10472 "Stride is expected strictly positive!");
10473 // Calculate the maximum backedge count based on the range of values
10474 // permitted by Start, End, and Stride.
10475 const SCEV
*MaxBECount
;
10477 IsSigned
? getSignedRangeMin(Start
) : getUnsignedRangeMin(Start
);
10479 APInt StrideForMaxBECount
=
10480 IsSigned
? getSignedRangeMin(Stride
) : getUnsignedRangeMin(Stride
);
10482 // We already know that the stride is positive, so we paper over conservatism
10483 // in our range computation by forcing StrideForMaxBECount to be at least one.
10484 // In theory this is unnecessary, but we expect MaxBECount to be a
10485 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there
10486 // is nothing to constant fold it to).
10487 APInt
One(BitWidth
, 1, IsSigned
);
10488 StrideForMaxBECount
= APIntOps::smax(One
, StrideForMaxBECount
);
10490 APInt MaxValue
= IsSigned
? APInt::getSignedMaxValue(BitWidth
)
10491 : APInt::getMaxValue(BitWidth
);
10492 APInt Limit
= MaxValue
- (StrideForMaxBECount
- 1);
10494 // Although End can be a MAX expression we estimate MaxEnd considering only
10495 // the case End = RHS of the loop termination condition. This is safe because
10496 // in the other case (End - Start) is zero, leading to a zero maximum backedge
10498 APInt MaxEnd
= IsSigned
? APIntOps::smin(getSignedRangeMax(End
), Limit
)
10499 : APIntOps::umin(getUnsignedRangeMax(End
), Limit
);
10501 MaxBECount
= computeBECount(getConstant(MaxEnd
- MinStart
) /* Delta */,
10502 getConstant(StrideForMaxBECount
) /* Step */,
10503 false /* Equality */);
10508 ScalarEvolution::ExitLimit
10509 ScalarEvolution::howManyLessThans(const SCEV
*LHS
, const SCEV
*RHS
,
10510 const Loop
*L
, bool IsSigned
,
10511 bool ControlsExit
, bool AllowPredicates
) {
10512 SmallPtrSet
<const SCEVPredicate
*, 4> Predicates
;
10514 const SCEVAddRecExpr
*IV
= dyn_cast
<SCEVAddRecExpr
>(LHS
);
10515 bool PredicatedIV
= false;
10517 if (!IV
&& AllowPredicates
) {
10518 // Try to make this an AddRec using runtime tests, in the first X
10519 // iterations of this loop, where X is the SCEV expression found by the
10520 // algorithm below.
10521 IV
= convertSCEVToAddRecWithPredicates(LHS
, L
, Predicates
);
10522 PredicatedIV
= true;
10525 // Avoid weird loops
10526 if (!IV
|| IV
->getLoop() != L
|| !IV
->isAffine())
10527 return getCouldNotCompute();
10529 bool NoWrap
= ControlsExit
&&
10530 IV
->getNoWrapFlags(IsSigned
? SCEV::FlagNSW
: SCEV::FlagNUW
);
10532 const SCEV
*Stride
= IV
->getStepRecurrence(*this);
10534 bool PositiveStride
= isKnownPositive(Stride
);
10536 // Avoid negative or zero stride values.
10537 if (!PositiveStride
) {
10538 // We can compute the correct backedge taken count for loops with unknown
10539 // strides if we can prove that the loop is not an infinite loop with side
10540 // effects. Here's the loop structure we are trying to handle -
10546 // } while (i < end);
10548 // The backedge taken count for such loops is evaluated as -
10549 // (max(end, start + stride) - start - 1) /u stride
10551 // The additional preconditions that we need to check to prove correctness
10552 // of the above formula is as follows -
10554 // a) IV is either nuw or nsw depending upon signedness (indicated by the
10556 // b) loop is single exit with no side effects.
10559 // Precondition a) implies that if the stride is negative, this is a single
10560 // trip loop. The backedge taken count formula reduces to zero in this case.
10562 // Precondition b) implies that the unknown stride cannot be zero otherwise
10565 // The positive stride case is the same as isKnownPositive(Stride) returning
10566 // true (original behavior of the function).
10568 // We want to make sure that the stride is truly unknown as there are edge
10569 // cases where ScalarEvolution propagates no wrap flags to the
10570 // post-increment/decrement IV even though the increment/decrement operation
10571 // itself is wrapping. The computed backedge taken count may be wrong in
10572 // such cases. This is prevented by checking that the stride is not known to
10573 // be either positive or non-positive. For example, no wrap flags are
10574 // propagated to the post-increment IV of this loop with a trip count of 2 -
10576 // unsigned char i;
10577 // for(i=127; i<128; i+=129)
10580 if (PredicatedIV
|| !NoWrap
|| isKnownNonPositive(Stride
) ||
10581 !loopHasNoSideEffects(L
))
10582 return getCouldNotCompute();
10583 } else if (!Stride
->isOne() &&
10584 doesIVOverflowOnLT(RHS
, Stride
, IsSigned
, NoWrap
))
10585 // Avoid proven overflow cases: this will ensure that the backedge taken
10586 // count will not generate any unsigned overflow. Relaxed no-overflow
10587 // conditions exploit NoWrapFlags, allowing to optimize in presence of
10588 // undefined behaviors like the case of C language.
10589 return getCouldNotCompute();
10591 ICmpInst::Predicate Cond
= IsSigned
? ICmpInst::ICMP_SLT
10592 : ICmpInst::ICMP_ULT
;
10593 const SCEV
*Start
= IV
->getStart();
10594 const SCEV
*End
= RHS
;
10595 // When the RHS is not invariant, we do not know the end bound of the loop and
10596 // cannot calculate the ExactBECount needed by ExitLimit. However, we can
10597 // calculate the MaxBECount, given the start, stride and max value for the end
10598 // bound of the loop (RHS), and the fact that IV does not overflow (which is
10600 if (!isLoopInvariant(RHS
, L
)) {
10601 const SCEV
*MaxBECount
= computeMaxBECountForLT(
10602 Start
, Stride
, RHS
, getTypeSizeInBits(LHS
->getType()), IsSigned
);
10603 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount
,
10604 false /*MaxOrZero*/, Predicates
);
10606 // If the backedge is taken at least once, then it will be taken
10607 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
10608 // is the LHS value of the less-than comparison the first time it is evaluated
10609 // and End is the RHS.
10610 const SCEV
*BECountIfBackedgeTaken
=
10611 computeBECount(getMinusSCEV(End
, Start
), Stride
, false);
10612 // If the loop entry is guarded by the result of the backedge test of the
10613 // first loop iteration, then we know the backedge will be taken at least
10614 // once and so the backedge taken count is as above. If not then we use the
10615 // expression (max(End,Start)-Start)/Stride to describe the backedge count,
10616 // as if the backedge is taken at least once max(End,Start) is End and so the
10617 // result is as above, and if not max(End,Start) is Start so we get a backedge
10619 const SCEV
*BECount
;
10620 if (isLoopEntryGuardedByCond(L
, Cond
, getMinusSCEV(Start
, Stride
), RHS
))
10621 BECount
= BECountIfBackedgeTaken
;
10623 End
= IsSigned
? getSMaxExpr(RHS
, Start
) : getUMaxExpr(RHS
, Start
);
10624 BECount
= computeBECount(getMinusSCEV(End
, Start
), Stride
, false);
10627 const SCEV
*MaxBECount
;
10628 bool MaxOrZero
= false;
10629 if (isa
<SCEVConstant
>(BECount
))
10630 MaxBECount
= BECount
;
10631 else if (isa
<SCEVConstant
>(BECountIfBackedgeTaken
)) {
10632 // If we know exactly how many times the backedge will be taken if it's
10633 // taken at least once, then the backedge count will either be that or
10635 MaxBECount
= BECountIfBackedgeTaken
;
10638 MaxBECount
= computeMaxBECountForLT(
10639 Start
, Stride
, RHS
, getTypeSizeInBits(LHS
->getType()), IsSigned
);
10642 if (isa
<SCEVCouldNotCompute
>(MaxBECount
) &&
10643 !isa
<SCEVCouldNotCompute
>(BECount
))
10644 MaxBECount
= getConstant(getUnsignedRangeMax(BECount
));
10646 return ExitLimit(BECount
, MaxBECount
, MaxOrZero
, Predicates
);
10649 ScalarEvolution::ExitLimit
10650 ScalarEvolution::howManyGreaterThans(const SCEV
*LHS
, const SCEV
*RHS
,
10651 const Loop
*L
, bool IsSigned
,
10652 bool ControlsExit
, bool AllowPredicates
) {
10653 SmallPtrSet
<const SCEVPredicate
*, 4> Predicates
;
10654 // We handle only IV > Invariant
10655 if (!isLoopInvariant(RHS
, L
))
10656 return getCouldNotCompute();
10658 const SCEVAddRecExpr
*IV
= dyn_cast
<SCEVAddRecExpr
>(LHS
);
10659 if (!IV
&& AllowPredicates
)
10660 // Try to make this an AddRec using runtime tests, in the first X
10661 // iterations of this loop, where X is the SCEV expression found by the
10662 // algorithm below.
10663 IV
= convertSCEVToAddRecWithPredicates(LHS
, L
, Predicates
);
10665 // Avoid weird loops
10666 if (!IV
|| IV
->getLoop() != L
|| !IV
->isAffine())
10667 return getCouldNotCompute();
10669 bool NoWrap
= ControlsExit
&&
10670 IV
->getNoWrapFlags(IsSigned
? SCEV::FlagNSW
: SCEV::FlagNUW
);
10672 const SCEV
*Stride
= getNegativeSCEV(IV
->getStepRecurrence(*this));
10674 // Avoid negative or zero stride values
10675 if (!isKnownPositive(Stride
))
10676 return getCouldNotCompute();
10678 // Avoid proven overflow cases: this will ensure that the backedge taken count
10679 // will not generate any unsigned overflow. Relaxed no-overflow conditions
10680 // exploit NoWrapFlags, allowing to optimize in presence of undefined
10681 // behaviors like the case of C language.
10682 if (!Stride
->isOne() && doesIVOverflowOnGT(RHS
, Stride
, IsSigned
, NoWrap
))
10683 return getCouldNotCompute();
10685 ICmpInst::Predicate Cond
= IsSigned
? ICmpInst::ICMP_SGT
10686 : ICmpInst::ICMP_UGT
;
10688 const SCEV
*Start
= IV
->getStart();
10689 const SCEV
*End
= RHS
;
10690 if (!isLoopEntryGuardedByCond(L
, Cond
, getAddExpr(Start
, Stride
), RHS
))
10691 End
= IsSigned
? getSMinExpr(RHS
, Start
) : getUMinExpr(RHS
, Start
);
10693 const SCEV
*BECount
= computeBECount(getMinusSCEV(Start
, End
), Stride
, false);
10695 APInt MaxStart
= IsSigned
? getSignedRangeMax(Start
)
10696 : getUnsignedRangeMax(Start
);
10698 APInt MinStride
= IsSigned
? getSignedRangeMin(Stride
)
10699 : getUnsignedRangeMin(Stride
);
10701 unsigned BitWidth
= getTypeSizeInBits(LHS
->getType());
10702 APInt Limit
= IsSigned
? APInt::getSignedMinValue(BitWidth
) + (MinStride
- 1)
10703 : APInt::getMinValue(BitWidth
) + (MinStride
- 1);
10705 // Although End can be a MIN expression we estimate MinEnd considering only
10706 // the case End = RHS. This is safe because in the other case (Start - End)
10707 // is zero, leading to a zero maximum backedge taken count.
10709 IsSigned
? APIntOps::smax(getSignedRangeMin(RHS
), Limit
)
10710 : APIntOps::umax(getUnsignedRangeMin(RHS
), Limit
);
10713 const SCEV
*MaxBECount
= getCouldNotCompute();
10714 if (isa
<SCEVConstant
>(BECount
))
10715 MaxBECount
= BECount
;
10717 MaxBECount
= computeBECount(getConstant(MaxStart
- MinEnd
),
10718 getConstant(MinStride
), false);
10720 if (isa
<SCEVCouldNotCompute
>(MaxBECount
))
10721 MaxBECount
= BECount
;
10723 return ExitLimit(BECount
, MaxBECount
, false, Predicates
);
10726 const SCEV
*SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange
&Range
,
10727 ScalarEvolution
&SE
) const {
10728 if (Range
.isFullSet()) // Infinite loop.
10729 return SE
.getCouldNotCompute();
10731 // If the start is a non-zero constant, shift the range to simplify things.
10732 if (const SCEVConstant
*SC
= dyn_cast
<SCEVConstant
>(getStart()))
10733 if (!SC
->getValue()->isZero()) {
10734 SmallVector
<const SCEV
*, 4> Operands(op_begin(), op_end());
10735 Operands
[0] = SE
.getZero(SC
->getType());
10736 const SCEV
*Shifted
= SE
.getAddRecExpr(Operands
, getLoop(),
10737 getNoWrapFlags(FlagNW
));
10738 if (const auto *ShiftedAddRec
= dyn_cast
<SCEVAddRecExpr
>(Shifted
))
10739 return ShiftedAddRec
->getNumIterationsInRange(
10740 Range
.subtract(SC
->getAPInt()), SE
);
10741 // This is strange and shouldn't happen.
10742 return SE
.getCouldNotCompute();
10745 // The only time we can solve this is when we have all constant indices.
10746 // Otherwise, we cannot determine the overflow conditions.
10747 if (any_of(operands(), [](const SCEV
*Op
) { return !isa
<SCEVConstant
>(Op
); }))
10748 return SE
.getCouldNotCompute();
10750 // Okay at this point we know that all elements of the chrec are constants and
10751 // that the start element is zero.
10753 // First check to see if the range contains zero. If not, the first
10754 // iteration exits.
10755 unsigned BitWidth
= SE
.getTypeSizeInBits(getType());
10756 if (!Range
.contains(APInt(BitWidth
, 0)))
10757 return SE
.getZero(getType());
10760 // If this is an affine expression then we have this situation:
10761 // Solve {0,+,A} in Range === Ax in Range
10763 // We know that zero is in the range. If A is positive then we know that
10764 // the upper value of the range must be the first possible exit value.
10765 // If A is negative then the lower of the range is the last possible loop
10766 // value. Also note that we already checked for a full range.
10767 APInt A
= cast
<SCEVConstant
>(getOperand(1))->getAPInt();
10768 APInt End
= A
.sge(1) ? (Range
.getUpper() - 1) : Range
.getLower();
10770 // The exit value should be (End+A)/A.
10771 APInt ExitVal
= (End
+ A
).udiv(A
);
10772 ConstantInt
*ExitValue
= ConstantInt::get(SE
.getContext(), ExitVal
);
10774 // Evaluate at the exit value. If we really did fall out of the valid
10775 // range, then we computed our trip count, otherwise wrap around or other
10776 // things must have happened.
10777 ConstantInt
*Val
= EvaluateConstantChrecAtConstant(this, ExitValue
, SE
);
10778 if (Range
.contains(Val
->getValue()))
10779 return SE
.getCouldNotCompute(); // Something strange happened
10781 // Ensure that the previous value is in the range. This is a sanity check.
10782 assert(Range
.contains(
10783 EvaluateConstantChrecAtConstant(this,
10784 ConstantInt::get(SE
.getContext(), ExitVal
- 1), SE
)->getValue()) &&
10785 "Linear scev computation is off in a bad way!");
10786 return SE
.getConstant(ExitValue
);
10789 if (isQuadratic()) {
10790 if (auto S
= SolveQuadraticAddRecRange(this, Range
, SE
))
10791 return SE
.getConstant(S
.getValue());
10794 return SE
.getCouldNotCompute();
10797 const SCEVAddRecExpr
*
10798 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution
&SE
) const {
10799 assert(getNumOperands() > 1 && "AddRec with zero step?");
10800 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
10801 // but in this case we cannot guarantee that the value returned will be an
10802 // AddRec because SCEV does not have a fixed point where it stops
10803 // simplification: it is legal to return ({rec1} + {rec2}). For example, it
10804 // may happen if we reach arithmetic depth limit while simplifying. So we
10805 // construct the returned value explicitly.
10806 SmallVector
<const SCEV
*, 3> Ops
;
10807 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
10808 // (this + Step) is {A+B,+,B+C,+...,+,N}.
10809 for (unsigned i
= 0, e
= getNumOperands() - 1; i
< e
; ++i
)
10810 Ops
.push_back(SE
.getAddExpr(getOperand(i
), getOperand(i
+ 1)));
10811 // We know that the last operand is not a constant zero (otherwise it would
10812 // have been popped out earlier). This guarantees us that if the result has
10813 // the same last operand, then it will also not be popped out, meaning that
10814 // the returned value will be an AddRec.
10815 const SCEV
*Last
= getOperand(getNumOperands() - 1);
10816 assert(!Last
->isZero() && "Recurrency with zero step?");
10817 Ops
.push_back(Last
);
10818 return cast
<SCEVAddRecExpr
>(SE
.getAddRecExpr(Ops
, getLoop(),
10819 SCEV::FlagAnyWrap
));
10822 // Return true when S contains at least an undef value.
10823 static inline bool containsUndefs(const SCEV
*S
) {
10824 return SCEVExprContains(S
, [](const SCEV
*S
) {
10825 if (const auto *SU
= dyn_cast
<SCEVUnknown
>(S
))
10826 return isa
<UndefValue
>(SU
->getValue());
10827 else if (const auto *SC
= dyn_cast
<SCEVConstant
>(S
))
10828 return isa
<UndefValue
>(SC
->getValue());
10835 // Collect all steps of SCEV expressions.
10836 struct SCEVCollectStrides
{
10837 ScalarEvolution
&SE
;
10838 SmallVectorImpl
<const SCEV
*> &Strides
;
10840 SCEVCollectStrides(ScalarEvolution
&SE
, SmallVectorImpl
<const SCEV
*> &S
)
10841 : SE(SE
), Strides(S
) {}
10843 bool follow(const SCEV
*S
) {
10844 if (const SCEVAddRecExpr
*AR
= dyn_cast
<SCEVAddRecExpr
>(S
))
10845 Strides
.push_back(AR
->getStepRecurrence(SE
));
10849 bool isDone() const { return false; }
10852 // Collect all SCEVUnknown and SCEVMulExpr expressions.
10853 struct SCEVCollectTerms
{
10854 SmallVectorImpl
<const SCEV
*> &Terms
;
10856 SCEVCollectTerms(SmallVectorImpl
<const SCEV
*> &T
) : Terms(T
) {}
10858 bool follow(const SCEV
*S
) {
10859 if (isa
<SCEVUnknown
>(S
) || isa
<SCEVMulExpr
>(S
) ||
10860 isa
<SCEVSignExtendExpr
>(S
)) {
10861 if (!containsUndefs(S
))
10862 Terms
.push_back(S
);
10864 // Stop recursion: once we collected a term, do not walk its operands.
10872 bool isDone() const { return false; }
10875 // Check if a SCEV contains an AddRecExpr.
10876 struct SCEVHasAddRec
{
10877 bool &ContainsAddRec
;
10879 SCEVHasAddRec(bool &ContainsAddRec
) : ContainsAddRec(ContainsAddRec
) {
10880 ContainsAddRec
= false;
10883 bool follow(const SCEV
*S
) {
10884 if (isa
<SCEVAddRecExpr
>(S
)) {
10885 ContainsAddRec
= true;
10887 // Stop recursion: once we collected a term, do not walk its operands.
10895 bool isDone() const { return false; }
10898 // Find factors that are multiplied with an expression that (possibly as a
10899 // subexpression) contains an AddRecExpr. In the expression:
10901 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop))
10903 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
10904 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
10905 // parameters as they form a product with an induction variable.
10907 // This collector expects all array size parameters to be in the same MulExpr.
10908 // It might be necessary to later add support for collecting parameters that are
10909 // spread over different nested MulExpr.
10910 struct SCEVCollectAddRecMultiplies
{
10911 SmallVectorImpl
<const SCEV
*> &Terms
;
10912 ScalarEvolution
&SE
;
10914 SCEVCollectAddRecMultiplies(SmallVectorImpl
<const SCEV
*> &T
, ScalarEvolution
&SE
)
10915 : Terms(T
), SE(SE
) {}
10917 bool follow(const SCEV
*S
) {
10918 if (auto *Mul
= dyn_cast
<SCEVMulExpr
>(S
)) {
10919 bool HasAddRec
= false;
10920 SmallVector
<const SCEV
*, 0> Operands
;
10921 for (auto Op
: Mul
->operands()) {
10922 const SCEVUnknown
*Unknown
= dyn_cast
<SCEVUnknown
>(Op
);
10923 if (Unknown
&& !isa
<CallInst
>(Unknown
->getValue())) {
10924 Operands
.push_back(Op
);
10925 } else if (Unknown
) {
10928 bool ContainsAddRec
;
10929 SCEVHasAddRec
ContiansAddRec(ContainsAddRec
);
10930 visitAll(Op
, ContiansAddRec
);
10931 HasAddRec
|= ContainsAddRec
;
10934 if (Operands
.size() == 0)
10940 Terms
.push_back(SE
.getMulExpr(Operands
));
10941 // Stop recursion: once we collected a term, do not walk its operands.
10949 bool isDone() const { return false; }
10952 } // end anonymous namespace
10954 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
10956 /// 1) The strides of AddRec expressions.
10957 /// 2) Unknowns that are multiplied with AddRec expressions.
10958 void ScalarEvolution::collectParametricTerms(const SCEV
*Expr
,
10959 SmallVectorImpl
<const SCEV
*> &Terms
) {
10960 SmallVector
<const SCEV
*, 4> Strides
;
10961 SCEVCollectStrides
StrideCollector(*this, Strides
);
10962 visitAll(Expr
, StrideCollector
);
10965 dbgs() << "Strides:\n";
10966 for (const SCEV
*S
: Strides
)
10967 dbgs() << *S
<< "\n";
10970 for (const SCEV
*S
: Strides
) {
10971 SCEVCollectTerms
TermCollector(Terms
);
10972 visitAll(S
, TermCollector
);
10976 dbgs() << "Terms:\n";
10977 for (const SCEV
*T
: Terms
)
10978 dbgs() << *T
<< "\n";
10981 SCEVCollectAddRecMultiplies
MulCollector(Terms
, *this);
10982 visitAll(Expr
, MulCollector
);
10985 static bool findArrayDimensionsRec(ScalarEvolution
&SE
,
10986 SmallVectorImpl
<const SCEV
*> &Terms
,
10987 SmallVectorImpl
<const SCEV
*> &Sizes
) {
10988 int Last
= Terms
.size() - 1;
10989 const SCEV
*Step
= Terms
[Last
];
10991 // End of recursion.
10993 if (const SCEVMulExpr
*M
= dyn_cast
<SCEVMulExpr
>(Step
)) {
10994 SmallVector
<const SCEV
*, 2> Qs
;
10995 for (const SCEV
*Op
: M
->operands())
10996 if (!isa
<SCEVConstant
>(Op
))
10999 Step
= SE
.getMulExpr(Qs
);
11002 Sizes
.push_back(Step
);
11006 for (const SCEV
*&Term
: Terms
) {
11007 // Normalize the terms before the next call to findArrayDimensionsRec.
11009 SCEVDivision::divide(SE
, Term
, Step
, &Q
, &R
);
11011 // Bail out when GCD does not evenly divide one of the terms.
11018 // Remove all SCEVConstants.
11020 remove_if(Terms
, [](const SCEV
*E
) { return isa
<SCEVConstant
>(E
); }),
11023 if (Terms
.size() > 0)
11024 if (!findArrayDimensionsRec(SE
, Terms
, Sizes
))
11027 Sizes
.push_back(Step
);
11031 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
11032 static inline bool containsParameters(SmallVectorImpl
<const SCEV
*> &Terms
) {
11033 for (const SCEV
*T
: Terms
)
11034 if (SCEVExprContains(T
, isa
<SCEVUnknown
, const SCEV
*>))
11039 // Return the number of product terms in S.
11040 static inline int numberOfTerms(const SCEV
*S
) {
11041 if (const SCEVMulExpr
*Expr
= dyn_cast
<SCEVMulExpr
>(S
))
11042 return Expr
->getNumOperands();
11046 static const SCEV
*removeConstantFactors(ScalarEvolution
&SE
, const SCEV
*T
) {
11047 if (isa
<SCEVConstant
>(T
))
11050 if (isa
<SCEVUnknown
>(T
))
11053 if (const SCEVMulExpr
*M
= dyn_cast
<SCEVMulExpr
>(T
)) {
11054 SmallVector
<const SCEV
*, 2> Factors
;
11055 for (const SCEV
*Op
: M
->operands())
11056 if (!isa
<SCEVConstant
>(Op
))
11057 Factors
.push_back(Op
);
11059 return SE
.getMulExpr(Factors
);
11065 /// Return the size of an element read or written by Inst.
11066 const SCEV
*ScalarEvolution::getElementSize(Instruction
*Inst
) {
11068 if (StoreInst
*Store
= dyn_cast
<StoreInst
>(Inst
))
11069 Ty
= Store
->getValueOperand()->getType();
11070 else if (LoadInst
*Load
= dyn_cast
<LoadInst
>(Inst
))
11071 Ty
= Load
->getType();
11075 Type
*ETy
= getEffectiveSCEVType(PointerType::getUnqual(Ty
));
11076 return getSizeOfExpr(ETy
, Ty
);
11079 void ScalarEvolution::findArrayDimensions(SmallVectorImpl
<const SCEV
*> &Terms
,
11080 SmallVectorImpl
<const SCEV
*> &Sizes
,
11081 const SCEV
*ElementSize
) {
11082 if (Terms
.size() < 1 || !ElementSize
)
11085 // Early return when Terms do not contain parameters: we do not delinearize
11086 // non parametric SCEVs.
11087 if (!containsParameters(Terms
))
11091 dbgs() << "Terms:\n";
11092 for (const SCEV
*T
: Terms
)
11093 dbgs() << *T
<< "\n";
11096 // Remove duplicates.
11097 array_pod_sort(Terms
.begin(), Terms
.end());
11098 Terms
.erase(std::unique(Terms
.begin(), Terms
.end()), Terms
.end());
11100 // Put larger terms first.
11101 llvm::sort(Terms
, [](const SCEV
*LHS
, const SCEV
*RHS
) {
11102 return numberOfTerms(LHS
) > numberOfTerms(RHS
);
11105 // Try to divide all terms by the element size. If term is not divisible by
11106 // element size, proceed with the original term.
11107 for (const SCEV
*&Term
: Terms
) {
11109 SCEVDivision::divide(*this, Term
, ElementSize
, &Q
, &R
);
11114 SmallVector
<const SCEV
*, 4> NewTerms
;
11116 // Remove constant factors.
11117 for (const SCEV
*T
: Terms
)
11118 if (const SCEV
*NewT
= removeConstantFactors(*this, T
))
11119 NewTerms
.push_back(NewT
);
11122 dbgs() << "Terms after sorting:\n";
11123 for (const SCEV
*T
: NewTerms
)
11124 dbgs() << *T
<< "\n";
11127 if (NewTerms
.empty() || !findArrayDimensionsRec(*this, NewTerms
, Sizes
)) {
11132 // The last element to be pushed into Sizes is the size of an element.
11133 Sizes
.push_back(ElementSize
);
11136 dbgs() << "Sizes:\n";
11137 for (const SCEV
*S
: Sizes
)
11138 dbgs() << *S
<< "\n";
11142 void ScalarEvolution::computeAccessFunctions(
11143 const SCEV
*Expr
, SmallVectorImpl
<const SCEV
*> &Subscripts
,
11144 SmallVectorImpl
<const SCEV
*> &Sizes
) {
11145 // Early exit in case this SCEV is not an affine multivariate function.
11149 if (auto *AR
= dyn_cast
<SCEVAddRecExpr
>(Expr
))
11150 if (!AR
->isAffine())
11153 const SCEV
*Res
= Expr
;
11154 int Last
= Sizes
.size() - 1;
11155 for (int i
= Last
; i
>= 0; i
--) {
11157 SCEVDivision::divide(*this, Res
, Sizes
[i
], &Q
, &R
);
11160 dbgs() << "Res: " << *Res
<< "\n";
11161 dbgs() << "Sizes[i]: " << *Sizes
[i
] << "\n";
11162 dbgs() << "Res divided by Sizes[i]:\n";
11163 dbgs() << "Quotient: " << *Q
<< "\n";
11164 dbgs() << "Remainder: " << *R
<< "\n";
11169 // Do not record the last subscript corresponding to the size of elements in
11173 // Bail out if the remainder is too complex.
11174 if (isa
<SCEVAddRecExpr
>(R
)) {
11175 Subscripts
.clear();
11183 // Record the access function for the current subscript.
11184 Subscripts
.push_back(R
);
11187 // Also push in last position the remainder of the last division: it will be
11188 // the access function of the innermost dimension.
11189 Subscripts
.push_back(Res
);
11191 std::reverse(Subscripts
.begin(), Subscripts
.end());
11194 dbgs() << "Subscripts:\n";
11195 for (const SCEV
*S
: Subscripts
)
11196 dbgs() << *S
<< "\n";
11200 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
11201 /// sizes of an array access. Returns the remainder of the delinearization that
11202 /// is the offset start of the array. The SCEV->delinearize algorithm computes
11203 /// the multiples of SCEV coefficients: that is a pattern matching of sub
11204 /// expressions in the stride and base of a SCEV corresponding to the
11205 /// computation of a GCD (greatest common divisor) of base and stride. When
11206 /// SCEV->delinearize fails, it returns the SCEV unchanged.
11208 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
11210 /// void foo(long n, long m, long o, double A[n][m][o]) {
11212 /// for (long i = 0; i < n; i++)
11213 /// for (long j = 0; j < m; j++)
11214 /// for (long k = 0; k < o; k++)
11215 /// A[i][j][k] = 1.0;
11218 /// the delinearization input is the following AddRec SCEV:
11220 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
11222 /// From this SCEV, we are able to say that the base offset of the access is %A
11223 /// because it appears as an offset that does not divide any of the strides in
11226 /// CHECK: Base offset: %A
11228 /// and then SCEV->delinearize determines the size of some of the dimensions of
11229 /// the array as these are the multiples by which the strides are happening:
11231 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
11233 /// Note that the outermost dimension remains of UnknownSize because there are
11234 /// no strides that would help identifying the size of the last dimension: when
11235 /// the array has been statically allocated, one could compute the size of that
11236 /// dimension by dividing the overall size of the array by the size of the known
11237 /// dimensions: %m * %o * 8.
11239 /// Finally delinearize provides the access functions for the array reference
11240 /// that does correspond to A[i][j][k] of the above C testcase:
11242 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
11244 /// The testcases are checking the output of a function pass:
11245 /// DelinearizationPass that walks through all loads and stores of a function
11246 /// asking for the SCEV of the memory access with respect to all enclosing
11247 /// loops, calling SCEV->delinearize on that and printing the results.
11248 void ScalarEvolution::delinearize(const SCEV
*Expr
,
11249 SmallVectorImpl
<const SCEV
*> &Subscripts
,
11250 SmallVectorImpl
<const SCEV
*> &Sizes
,
11251 const SCEV
*ElementSize
) {
11252 // First step: collect parametric terms.
11253 SmallVector
<const SCEV
*, 4> Terms
;
11254 collectParametricTerms(Expr
, Terms
);
11259 // Second step: find subscript sizes.
11260 findArrayDimensions(Terms
, Sizes
, ElementSize
);
11265 // Third step: compute the access functions for each subscript.
11266 computeAccessFunctions(Expr
, Subscripts
, Sizes
);
11268 if (Subscripts
.empty())
11272 dbgs() << "succeeded to delinearize " << *Expr
<< "\n";
11273 dbgs() << "ArrayDecl[UnknownSize]";
11274 for (const SCEV
*S
: Sizes
)
11275 dbgs() << "[" << *S
<< "]";
11277 dbgs() << "\nArrayRef";
11278 for (const SCEV
*S
: Subscripts
)
11279 dbgs() << "[" << *S
<< "]";
11284 //===----------------------------------------------------------------------===//
11285 // SCEVCallbackVH Class Implementation
11286 //===----------------------------------------------------------------------===//
11288 void ScalarEvolution::SCEVCallbackVH::deleted() {
11289 assert(SE
&& "SCEVCallbackVH called with a null ScalarEvolution!");
11290 if (PHINode
*PN
= dyn_cast
<PHINode
>(getValPtr()))
11291 SE
->ConstantEvolutionLoopExitValue
.erase(PN
);
11292 SE
->eraseValueFromMap(getValPtr());
11293 // this now dangles!
11296 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value
*V
) {
11297 assert(SE
&& "SCEVCallbackVH called with a null ScalarEvolution!");
11299 // Forget all the expressions associated with users of the old value,
11300 // so that future queries will recompute the expressions using the new
11302 Value
*Old
= getValPtr();
11303 SmallVector
<User
*, 16> Worklist(Old
->user_begin(), Old
->user_end());
11304 SmallPtrSet
<User
*, 8> Visited
;
11305 while (!Worklist
.empty()) {
11306 User
*U
= Worklist
.pop_back_val();
11307 // Deleting the Old value will cause this to dangle. Postpone
11308 // that until everything else is done.
11311 if (!Visited
.insert(U
).second
)
11313 if (PHINode
*PN
= dyn_cast
<PHINode
>(U
))
11314 SE
->ConstantEvolutionLoopExitValue
.erase(PN
);
11315 SE
->eraseValueFromMap(U
);
11316 Worklist
.insert(Worklist
.end(), U
->user_begin(), U
->user_end());
11318 // Delete the Old value.
11319 if (PHINode
*PN
= dyn_cast
<PHINode
>(Old
))
11320 SE
->ConstantEvolutionLoopExitValue
.erase(PN
);
11321 SE
->eraseValueFromMap(Old
);
11322 // this now dangles!
11325 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value
*V
, ScalarEvolution
*se
)
11326 : CallbackVH(V
), SE(se
) {}
11328 //===----------------------------------------------------------------------===//
11329 // ScalarEvolution Class Implementation
11330 //===----------------------------------------------------------------------===//
11332 ScalarEvolution::ScalarEvolution(Function
&F
, TargetLibraryInfo
&TLI
,
11333 AssumptionCache
&AC
, DominatorTree
&DT
,
11335 : F(F
), TLI(TLI
), AC(AC
), DT(DT
), LI(LI
),
11336 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
11337 LoopDispositions(64), BlockDispositions(64) {
11338 // To use guards for proving predicates, we need to scan every instruction in
11339 // relevant basic blocks, and not just terminators. Doing this is a waste of
11340 // time if the IR does not actually contain any calls to
11341 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
11343 // This pessimizes the case where a pass that preserves ScalarEvolution wants
11344 // to _add_ guards to the module when there weren't any before, and wants
11345 // ScalarEvolution to optimize based on those guards. For now we prefer to be
11346 // efficient in lieu of being smart in that rather obscure case.
11348 auto *GuardDecl
= F
.getParent()->getFunction(
11349 Intrinsic::getName(Intrinsic::experimental_guard
));
11350 HasGuards
= GuardDecl
&& !GuardDecl
->use_empty();
11353 ScalarEvolution::ScalarEvolution(ScalarEvolution
&&Arg
)
11354 : F(Arg
.F
), HasGuards(Arg
.HasGuards
), TLI(Arg
.TLI
), AC(Arg
.AC
), DT(Arg
.DT
),
11355 LI(Arg
.LI
), CouldNotCompute(std::move(Arg
.CouldNotCompute
)),
11356 ValueExprMap(std::move(Arg
.ValueExprMap
)),
11357 PendingLoopPredicates(std::move(Arg
.PendingLoopPredicates
)),
11358 PendingPhiRanges(std::move(Arg
.PendingPhiRanges
)),
11359 PendingMerges(std::move(Arg
.PendingMerges
)),
11360 MinTrailingZerosCache(std::move(Arg
.MinTrailingZerosCache
)),
11361 BackedgeTakenCounts(std::move(Arg
.BackedgeTakenCounts
)),
11362 PredicatedBackedgeTakenCounts(
11363 std::move(Arg
.PredicatedBackedgeTakenCounts
)),
11364 ConstantEvolutionLoopExitValue(
11365 std::move(Arg
.ConstantEvolutionLoopExitValue
)),
11366 ValuesAtScopes(std::move(Arg
.ValuesAtScopes
)),
11367 LoopDispositions(std::move(Arg
.LoopDispositions
)),
11368 LoopPropertiesCache(std::move(Arg
.LoopPropertiesCache
)),
11369 BlockDispositions(std::move(Arg
.BlockDispositions
)),
11370 UnsignedRanges(std::move(Arg
.UnsignedRanges
)),
11371 SignedRanges(std::move(Arg
.SignedRanges
)),
11372 UniqueSCEVs(std::move(Arg
.UniqueSCEVs
)),
11373 UniquePreds(std::move(Arg
.UniquePreds
)),
11374 SCEVAllocator(std::move(Arg
.SCEVAllocator
)),
11375 LoopUsers(std::move(Arg
.LoopUsers
)),
11376 PredicatedSCEVRewrites(std::move(Arg
.PredicatedSCEVRewrites
)),
11377 FirstUnknown(Arg
.FirstUnknown
) {
11378 Arg
.FirstUnknown
= nullptr;
11381 ScalarEvolution::~ScalarEvolution() {
11382 // Iterate through all the SCEVUnknown instances and call their
11383 // destructors, so that they release their references to their values.
11384 for (SCEVUnknown
*U
= FirstUnknown
; U
;) {
11385 SCEVUnknown
*Tmp
= U
;
11387 Tmp
->~SCEVUnknown();
11389 FirstUnknown
= nullptr;
11391 ExprValueMap
.clear();
11392 ValueExprMap
.clear();
11395 // Free any extra memory created for ExitNotTakenInfo in the unlikely event
11396 // that a loop had multiple computable exits.
11397 for (auto &BTCI
: BackedgeTakenCounts
)
11398 BTCI
.second
.clear();
11399 for (auto &BTCI
: PredicatedBackedgeTakenCounts
)
11400 BTCI
.second
.clear();
11402 assert(PendingLoopPredicates
.empty() && "isImpliedCond garbage");
11403 assert(PendingPhiRanges
.empty() && "getRangeRef garbage");
11404 assert(PendingMerges
.empty() && "isImpliedViaMerge garbage");
11405 assert(!WalkingBEDominatingConds
&& "isLoopBackedgeGuardedByCond garbage!");
11406 assert(!ProvingSplitPredicate
&& "ProvingSplitPredicate garbage!");
11409 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop
*L
) {
11410 return !isa
<SCEVCouldNotCompute
>(getBackedgeTakenCount(L
));
11413 static void PrintLoopInfo(raw_ostream
&OS
, ScalarEvolution
*SE
,
11415 // Print all inner loops first
11417 PrintLoopInfo(OS
, SE
, I
);
11420 L
->getHeader()->printAsOperand(OS
, /*PrintType=*/false);
11423 SmallVector
<BasicBlock
*, 8> ExitBlocks
;
11424 L
->getExitBlocks(ExitBlocks
);
11425 if (ExitBlocks
.size() != 1)
11426 OS
<< "<multiple exits> ";
11428 if (SE
->hasLoopInvariantBackedgeTakenCount(L
)) {
11429 OS
<< "backedge-taken count is " << *SE
->getBackedgeTakenCount(L
);
11431 OS
<< "Unpredictable backedge-taken count. ";
11436 L
->getHeader()->printAsOperand(OS
, /*PrintType=*/false);
11439 if (!isa
<SCEVCouldNotCompute
>(SE
->getMaxBackedgeTakenCount(L
))) {
11440 OS
<< "max backedge-taken count is " << *SE
->getMaxBackedgeTakenCount(L
);
11441 if (SE
->isBackedgeTakenCountMaxOrZero(L
))
11442 OS
<< ", actual taken count either this or zero.";
11444 OS
<< "Unpredictable max backedge-taken count. ";
11449 L
->getHeader()->printAsOperand(OS
, /*PrintType=*/false);
11452 SCEVUnionPredicate Pred
;
11453 auto PBT
= SE
->getPredicatedBackedgeTakenCount(L
, Pred
);
11454 if (!isa
<SCEVCouldNotCompute
>(PBT
)) {
11455 OS
<< "Predicated backedge-taken count is " << *PBT
<< "\n";
11456 OS
<< " Predicates:\n";
11459 OS
<< "Unpredictable predicated backedge-taken count. ";
11463 if (SE
->hasLoopInvariantBackedgeTakenCount(L
)) {
11465 L
->getHeader()->printAsOperand(OS
, /*PrintType=*/false);
11467 OS
<< "Trip multiple is " << SE
->getSmallConstantTripMultiple(L
) << "\n";
11471 static StringRef
loopDispositionToStr(ScalarEvolution::LoopDisposition LD
) {
11473 case ScalarEvolution::LoopVariant
:
11475 case ScalarEvolution::LoopInvariant
:
11476 return "Invariant";
11477 case ScalarEvolution::LoopComputable
:
11478 return "Computable";
11480 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
11483 void ScalarEvolution::print(raw_ostream
&OS
) const {
11484 // ScalarEvolution's implementation of the print method is to print
11485 // out SCEV values of all instructions that are interesting. Doing
11486 // this potentially causes it to create new SCEV objects though,
11487 // which technically conflicts with the const qualifier. This isn't
11488 // observable from outside the class though, so casting away the
11489 // const isn't dangerous.
11490 ScalarEvolution
&SE
= *const_cast<ScalarEvolution
*>(this);
11492 OS
<< "Classifying expressions for: ";
11493 F
.printAsOperand(OS
, /*PrintType=*/false);
11495 for (Instruction
&I
: instructions(F
))
11496 if (isSCEVable(I
.getType()) && !isa
<CmpInst
>(I
)) {
11499 const SCEV
*SV
= SE
.getSCEV(&I
);
11501 if (!isa
<SCEVCouldNotCompute
>(SV
)) {
11503 SE
.getUnsignedRange(SV
).print(OS
);
11505 SE
.getSignedRange(SV
).print(OS
);
11508 const Loop
*L
= LI
.getLoopFor(I
.getParent());
11510 const SCEV
*AtUse
= SE
.getSCEVAtScope(SV
, L
);
11514 if (!isa
<SCEVCouldNotCompute
>(AtUse
)) {
11516 SE
.getUnsignedRange(AtUse
).print(OS
);
11518 SE
.getSignedRange(AtUse
).print(OS
);
11523 OS
<< "\t\t" "Exits: ";
11524 const SCEV
*ExitValue
= SE
.getSCEVAtScope(SV
, L
->getParentLoop());
11525 if (!SE
.isLoopInvariant(ExitValue
, L
)) {
11526 OS
<< "<<Unknown>>";
11532 for (auto *Iter
= L
; Iter
; Iter
= Iter
->getParentLoop()) {
11534 OS
<< "\t\t" "LoopDispositions: { ";
11540 Iter
->getHeader()->printAsOperand(OS
, /*PrintType=*/false);
11541 OS
<< ": " << loopDispositionToStr(SE
.getLoopDisposition(SV
, Iter
));
11544 for (auto *InnerL
: depth_first(L
)) {
11548 OS
<< "\t\t" "LoopDispositions: { ";
11554 InnerL
->getHeader()->printAsOperand(OS
, /*PrintType=*/false);
11555 OS
<< ": " << loopDispositionToStr(SE
.getLoopDisposition(SV
, InnerL
));
11564 OS
<< "Determining loop execution counts for: ";
11565 F
.printAsOperand(OS
, /*PrintType=*/false);
11568 PrintLoopInfo(OS
, &SE
, I
);
11571 ScalarEvolution::LoopDisposition
11572 ScalarEvolution::getLoopDisposition(const SCEV
*S
, const Loop
*L
) {
11573 auto &Values
= LoopDispositions
[S
];
11574 for (auto &V
: Values
) {
11575 if (V
.getPointer() == L
)
11578 Values
.emplace_back(L
, LoopVariant
);
11579 LoopDisposition D
= computeLoopDisposition(S
, L
);
11580 auto &Values2
= LoopDispositions
[S
];
11581 for (auto &V
: make_range(Values2
.rbegin(), Values2
.rend())) {
11582 if (V
.getPointer() == L
) {
11590 ScalarEvolution::LoopDisposition
11591 ScalarEvolution::computeLoopDisposition(const SCEV
*S
, const Loop
*L
) {
11592 switch (static_cast<SCEVTypes
>(S
->getSCEVType())) {
11594 return LoopInvariant
;
11598 return getLoopDisposition(cast
<SCEVCastExpr
>(S
)->getOperand(), L
);
11599 case scAddRecExpr
: {
11600 const SCEVAddRecExpr
*AR
= cast
<SCEVAddRecExpr
>(S
);
11602 // If L is the addrec's loop, it's computable.
11603 if (AR
->getLoop() == L
)
11604 return LoopComputable
;
11606 // Add recurrences are never invariant in the function-body (null loop).
11608 return LoopVariant
;
11610 // Everything that is not defined at loop entry is variant.
11611 if (DT
.dominates(L
->getHeader(), AR
->getLoop()->getHeader()))
11612 return LoopVariant
;
11613 assert(!L
->contains(AR
->getLoop()) && "Containing loop's header does not"
11614 " dominate the contained loop's header?");
11616 // This recurrence is invariant w.r.t. L if AR's loop contains L.
11617 if (AR
->getLoop()->contains(L
))
11618 return LoopInvariant
;
11620 // This recurrence is variant w.r.t. L if any of its operands
11622 for (auto *Op
: AR
->operands())
11623 if (!isLoopInvariant(Op
, L
))
11624 return LoopVariant
;
11626 // Otherwise it's loop-invariant.
11627 return LoopInvariant
;
11633 bool HasVarying
= false;
11634 for (auto *Op
: cast
<SCEVNAryExpr
>(S
)->operands()) {
11635 LoopDisposition D
= getLoopDisposition(Op
, L
);
11636 if (D
== LoopVariant
)
11637 return LoopVariant
;
11638 if (D
== LoopComputable
)
11641 return HasVarying
? LoopComputable
: LoopInvariant
;
11644 const SCEVUDivExpr
*UDiv
= cast
<SCEVUDivExpr
>(S
);
11645 LoopDisposition LD
= getLoopDisposition(UDiv
->getLHS(), L
);
11646 if (LD
== LoopVariant
)
11647 return LoopVariant
;
11648 LoopDisposition RD
= getLoopDisposition(UDiv
->getRHS(), L
);
11649 if (RD
== LoopVariant
)
11650 return LoopVariant
;
11651 return (LD
== LoopInvariant
&& RD
== LoopInvariant
) ?
11652 LoopInvariant
: LoopComputable
;
11655 // All non-instruction values are loop invariant. All instructions are loop
11656 // invariant if they are not contained in the specified loop.
11657 // Instructions are never considered invariant in the function body
11658 // (null loop) because they are defined within the "loop".
11659 if (auto *I
= dyn_cast
<Instruction
>(cast
<SCEVUnknown
>(S
)->getValue()))
11660 return (L
&& !L
->contains(I
)) ? LoopInvariant
: LoopVariant
;
11661 return LoopInvariant
;
11662 case scCouldNotCompute
:
11663 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
11665 llvm_unreachable("Unknown SCEV kind!");
11668 bool ScalarEvolution::isLoopInvariant(const SCEV
*S
, const Loop
*L
) {
11669 return getLoopDisposition(S
, L
) == LoopInvariant
;
11672 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV
*S
, const Loop
*L
) {
11673 return getLoopDisposition(S
, L
) == LoopComputable
;
11676 ScalarEvolution::BlockDisposition
11677 ScalarEvolution::getBlockDisposition(const SCEV
*S
, const BasicBlock
*BB
) {
11678 auto &Values
= BlockDispositions
[S
];
11679 for (auto &V
: Values
) {
11680 if (V
.getPointer() == BB
)
11683 Values
.emplace_back(BB
, DoesNotDominateBlock
);
11684 BlockDisposition D
= computeBlockDisposition(S
, BB
);
11685 auto &Values2
= BlockDispositions
[S
];
11686 for (auto &V
: make_range(Values2
.rbegin(), Values2
.rend())) {
11687 if (V
.getPointer() == BB
) {
11695 ScalarEvolution::BlockDisposition
11696 ScalarEvolution::computeBlockDisposition(const SCEV
*S
, const BasicBlock
*BB
) {
11697 switch (static_cast<SCEVTypes
>(S
->getSCEVType())) {
11699 return ProperlyDominatesBlock
;
11703 return getBlockDisposition(cast
<SCEVCastExpr
>(S
)->getOperand(), BB
);
11704 case scAddRecExpr
: {
11705 // This uses a "dominates" query instead of "properly dominates" query
11706 // to test for proper dominance too, because the instruction which
11707 // produces the addrec's value is a PHI, and a PHI effectively properly
11708 // dominates its entire containing block.
11709 const SCEVAddRecExpr
*AR
= cast
<SCEVAddRecExpr
>(S
);
11710 if (!DT
.dominates(AR
->getLoop()->getHeader(), BB
))
11711 return DoesNotDominateBlock
;
11713 // Fall through into SCEVNAryExpr handling.
11720 const SCEVNAryExpr
*NAry
= cast
<SCEVNAryExpr
>(S
);
11721 bool Proper
= true;
11722 for (const SCEV
*NAryOp
: NAry
->operands()) {
11723 BlockDisposition D
= getBlockDisposition(NAryOp
, BB
);
11724 if (D
== DoesNotDominateBlock
)
11725 return DoesNotDominateBlock
;
11726 if (D
== DominatesBlock
)
11729 return Proper
? ProperlyDominatesBlock
: DominatesBlock
;
11732 const SCEVUDivExpr
*UDiv
= cast
<SCEVUDivExpr
>(S
);
11733 const SCEV
*LHS
= UDiv
->getLHS(), *RHS
= UDiv
->getRHS();
11734 BlockDisposition LD
= getBlockDisposition(LHS
, BB
);
11735 if (LD
== DoesNotDominateBlock
)
11736 return DoesNotDominateBlock
;
11737 BlockDisposition RD
= getBlockDisposition(RHS
, BB
);
11738 if (RD
== DoesNotDominateBlock
)
11739 return DoesNotDominateBlock
;
11740 return (LD
== ProperlyDominatesBlock
&& RD
== ProperlyDominatesBlock
) ?
11741 ProperlyDominatesBlock
: DominatesBlock
;
11744 if (Instruction
*I
=
11745 dyn_cast
<Instruction
>(cast
<SCEVUnknown
>(S
)->getValue())) {
11746 if (I
->getParent() == BB
)
11747 return DominatesBlock
;
11748 if (DT
.properlyDominates(I
->getParent(), BB
))
11749 return ProperlyDominatesBlock
;
11750 return DoesNotDominateBlock
;
11752 return ProperlyDominatesBlock
;
11753 case scCouldNotCompute
:
11754 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
11756 llvm_unreachable("Unknown SCEV kind!");
11759 bool ScalarEvolution::dominates(const SCEV
*S
, const BasicBlock
*BB
) {
11760 return getBlockDisposition(S
, BB
) >= DominatesBlock
;
11763 bool ScalarEvolution::properlyDominates(const SCEV
*S
, const BasicBlock
*BB
) {
11764 return getBlockDisposition(S
, BB
) == ProperlyDominatesBlock
;
11767 bool ScalarEvolution::hasOperand(const SCEV
*S
, const SCEV
*Op
) const {
11768 return SCEVExprContains(S
, [&](const SCEV
*Expr
) { return Expr
== Op
; });
11771 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV
*S
) const {
11772 auto IsS
= [&](const SCEV
*X
) { return S
== X
; };
11773 auto ContainsS
= [&](const SCEV
*X
) {
11774 return !isa
<SCEVCouldNotCompute
>(X
) && SCEVExprContains(X
, IsS
);
11776 return ContainsS(ExactNotTaken
) || ContainsS(MaxNotTaken
);
11780 ScalarEvolution::forgetMemoizedResults(const SCEV
*S
) {
11781 ValuesAtScopes
.erase(S
);
11782 LoopDispositions
.erase(S
);
11783 BlockDispositions
.erase(S
);
11784 UnsignedRanges
.erase(S
);
11785 SignedRanges
.erase(S
);
11786 ExprValueMap
.erase(S
);
11787 HasRecMap
.erase(S
);
11788 MinTrailingZerosCache
.erase(S
);
11790 for (auto I
= PredicatedSCEVRewrites
.begin();
11791 I
!= PredicatedSCEVRewrites
.end();) {
11792 std::pair
<const SCEV
*, const Loop
*> Entry
= I
->first
;
11793 if (Entry
.first
== S
)
11794 PredicatedSCEVRewrites
.erase(I
++);
11799 auto RemoveSCEVFromBackedgeMap
=
11800 [S
, this](DenseMap
<const Loop
*, BackedgeTakenInfo
> &Map
) {
11801 for (auto I
= Map
.begin(), E
= Map
.end(); I
!= E
;) {
11802 BackedgeTakenInfo
&BEInfo
= I
->second
;
11803 if (BEInfo
.hasOperand(S
, this)) {
11811 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts
);
11812 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts
);
11816 ScalarEvolution::getUsedLoops(const SCEV
*S
,
11817 SmallPtrSetImpl
<const Loop
*> &LoopsUsed
) {
11818 struct FindUsedLoops
{
11819 FindUsedLoops(SmallPtrSetImpl
<const Loop
*> &LoopsUsed
)
11820 : LoopsUsed(LoopsUsed
) {}
11821 SmallPtrSetImpl
<const Loop
*> &LoopsUsed
;
11822 bool follow(const SCEV
*S
) {
11823 if (auto *AR
= dyn_cast
<SCEVAddRecExpr
>(S
))
11824 LoopsUsed
.insert(AR
->getLoop());
11828 bool isDone() const { return false; }
11831 FindUsedLoops
F(LoopsUsed
);
11832 SCEVTraversal
<FindUsedLoops
>(F
).visitAll(S
);
11835 void ScalarEvolution::addToLoopUseLists(const SCEV
*S
) {
11836 SmallPtrSet
<const Loop
*, 8> LoopsUsed
;
11837 getUsedLoops(S
, LoopsUsed
);
11838 for (auto *L
: LoopsUsed
)
11839 LoopUsers
[L
].push_back(S
);
11842 void ScalarEvolution::verify() const {
11843 ScalarEvolution
&SE
= *const_cast<ScalarEvolution
*>(this);
11844 ScalarEvolution
SE2(F
, TLI
, AC
, DT
, LI
);
11846 SmallVector
<Loop
*, 8> LoopStack(LI
.begin(), LI
.end());
11848 // Map's SCEV expressions from one ScalarEvolution "universe" to another.
11849 struct SCEVMapper
: public SCEVRewriteVisitor
<SCEVMapper
> {
11850 SCEVMapper(ScalarEvolution
&SE
) : SCEVRewriteVisitor
<SCEVMapper
>(SE
) {}
11852 const SCEV
*visitConstant(const SCEVConstant
*Constant
) {
11853 return SE
.getConstant(Constant
->getAPInt());
11856 const SCEV
*visitUnknown(const SCEVUnknown
*Expr
) {
11857 return SE
.getUnknown(Expr
->getValue());
11860 const SCEV
*visitCouldNotCompute(const SCEVCouldNotCompute
*Expr
) {
11861 return SE
.getCouldNotCompute();
11865 SCEVMapper
SCM(SE2
);
11867 while (!LoopStack
.empty()) {
11868 auto *L
= LoopStack
.pop_back_val();
11869 LoopStack
.insert(LoopStack
.end(), L
->begin(), L
->end());
11871 auto *CurBECount
= SCM
.visit(
11872 const_cast<ScalarEvolution
*>(this)->getBackedgeTakenCount(L
));
11873 auto *NewBECount
= SE2
.getBackedgeTakenCount(L
);
11875 if (CurBECount
== SE2
.getCouldNotCompute() ||
11876 NewBECount
== SE2
.getCouldNotCompute()) {
11877 // NB! This situation is legal, but is very suspicious -- whatever pass
11878 // change the loop to make a trip count go from could not compute to
11879 // computable or vice-versa *should have* invalidated SCEV. However, we
11880 // choose not to assert here (for now) since we don't want false
11885 if (containsUndefs(CurBECount
) || containsUndefs(NewBECount
)) {
11886 // SCEV treats "undef" as an unknown but consistent value (i.e. it does
11887 // not propagate undef aggressively). This means we can (and do) fail
11888 // verification in cases where a transform makes the trip count of a loop
11889 // go from "undef" to "undef+1" (say). The transform is fine, since in
11890 // both cases the loop iterates "undef" times, but SCEV thinks we
11891 // increased the trip count of the loop by 1 incorrectly.
11895 if (SE
.getTypeSizeInBits(CurBECount
->getType()) >
11896 SE
.getTypeSizeInBits(NewBECount
->getType()))
11897 NewBECount
= SE2
.getZeroExtendExpr(NewBECount
, CurBECount
->getType());
11898 else if (SE
.getTypeSizeInBits(CurBECount
->getType()) <
11899 SE
.getTypeSizeInBits(NewBECount
->getType()))
11900 CurBECount
= SE2
.getZeroExtendExpr(CurBECount
, NewBECount
->getType());
11902 auto *ConstantDelta
=
11903 dyn_cast
<SCEVConstant
>(SE2
.getMinusSCEV(CurBECount
, NewBECount
));
11905 if (ConstantDelta
&& ConstantDelta
->getAPInt() != 0) {
11906 dbgs() << "Trip Count Changed!\n";
11907 dbgs() << "Old: " << *CurBECount
<< "\n";
11908 dbgs() << "New: " << *NewBECount
<< "\n";
11909 dbgs() << "Delta: " << *ConstantDelta
<< "\n";
11915 bool ScalarEvolution::invalidate(
11916 Function
&F
, const PreservedAnalyses
&PA
,
11917 FunctionAnalysisManager::Invalidator
&Inv
) {
11918 // Invalidate the ScalarEvolution object whenever it isn't preserved or one
11919 // of its dependencies is invalidated.
11920 auto PAC
= PA
.getChecker
<ScalarEvolutionAnalysis
>();
11921 return !(PAC
.preserved() || PAC
.preservedSet
<AllAnalysesOn
<Function
>>()) ||
11922 Inv
.invalidate
<AssumptionAnalysis
>(F
, PA
) ||
11923 Inv
.invalidate
<DominatorTreeAnalysis
>(F
, PA
) ||
11924 Inv
.invalidate
<LoopAnalysis
>(F
, PA
);
11927 AnalysisKey
ScalarEvolutionAnalysis::Key
;
11929 ScalarEvolution
ScalarEvolutionAnalysis::run(Function
&F
,
11930 FunctionAnalysisManager
&AM
) {
11931 return ScalarEvolution(F
, AM
.getResult
<TargetLibraryAnalysis
>(F
),
11932 AM
.getResult
<AssumptionAnalysis
>(F
),
11933 AM
.getResult
<DominatorTreeAnalysis
>(F
),
11934 AM
.getResult
<LoopAnalysis
>(F
));
11938 ScalarEvolutionPrinterPass::run(Function
&F
, FunctionAnalysisManager
&AM
) {
11939 AM
.getResult
<ScalarEvolutionAnalysis
>(F
).print(OS
);
11940 return PreservedAnalyses::all();
11943 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass
, "scalar-evolution",
11944 "Scalar Evolution Analysis", false, true)
11945 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker
)
11946 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass
)
11947 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass
)
11948 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass
)
11949 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass
, "scalar-evolution",
11950 "Scalar Evolution Analysis", false, true)
11952 char ScalarEvolutionWrapperPass::ID
= 0;
11954 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID
) {
11955 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
11958 bool ScalarEvolutionWrapperPass::runOnFunction(Function
&F
) {
11959 SE
.reset(new ScalarEvolution(
11960 F
, getAnalysis
<TargetLibraryInfoWrapperPass
>().getTLI(),
11961 getAnalysis
<AssumptionCacheTracker
>().getAssumptionCache(F
),
11962 getAnalysis
<DominatorTreeWrapperPass
>().getDomTree(),
11963 getAnalysis
<LoopInfoWrapperPass
>().getLoopInfo()));
11967 void ScalarEvolutionWrapperPass::releaseMemory() { SE
.reset(); }
11969 void ScalarEvolutionWrapperPass::print(raw_ostream
&OS
, const Module
*) const {
11973 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
11980 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage
&AU
) const {
11981 AU
.setPreservesAll();
11982 AU
.addRequiredTransitive
<AssumptionCacheTracker
>();
11983 AU
.addRequiredTransitive
<LoopInfoWrapperPass
>();
11984 AU
.addRequiredTransitive
<DominatorTreeWrapperPass
>();
11985 AU
.addRequiredTransitive
<TargetLibraryInfoWrapperPass
>();
11988 const SCEVPredicate
*ScalarEvolution::getEqualPredicate(const SCEV
*LHS
,
11990 FoldingSetNodeID ID
;
11991 assert(LHS
->getType() == RHS
->getType() &&
11992 "Type mismatch between LHS and RHS");
11993 // Unique this node based on the arguments
11994 ID
.AddInteger(SCEVPredicate::P_Equal
);
11995 ID
.AddPointer(LHS
);
11996 ID
.AddPointer(RHS
);
11997 void *IP
= nullptr;
11998 if (const auto *S
= UniquePreds
.FindNodeOrInsertPos(ID
, IP
))
12000 SCEVEqualPredicate
*Eq
= new (SCEVAllocator
)
12001 SCEVEqualPredicate(ID
.Intern(SCEVAllocator
), LHS
, RHS
);
12002 UniquePreds
.InsertNode(Eq
, IP
);
12006 const SCEVPredicate
*ScalarEvolution::getWrapPredicate(
12007 const SCEVAddRecExpr
*AR
,
12008 SCEVWrapPredicate::IncrementWrapFlags AddedFlags
) {
12009 FoldingSetNodeID ID
;
12010 // Unique this node based on the arguments
12011 ID
.AddInteger(SCEVPredicate::P_Wrap
);
12013 ID
.AddInteger(AddedFlags
);
12014 void *IP
= nullptr;
12015 if (const auto *S
= UniquePreds
.FindNodeOrInsertPos(ID
, IP
))
12017 auto *OF
= new (SCEVAllocator
)
12018 SCEVWrapPredicate(ID
.Intern(SCEVAllocator
), AR
, AddedFlags
);
12019 UniquePreds
.InsertNode(OF
, IP
);
12025 class SCEVPredicateRewriter
: public SCEVRewriteVisitor
<SCEVPredicateRewriter
> {
12028 /// Rewrites \p S in the context of a loop L and the SCEV predication
12029 /// infrastructure.
12031 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
12032 /// equivalences present in \p Pred.
12034 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
12035 /// \p NewPreds such that the result will be an AddRecExpr.
12036 static const SCEV
*rewrite(const SCEV
*S
, const Loop
*L
, ScalarEvolution
&SE
,
12037 SmallPtrSetImpl
<const SCEVPredicate
*> *NewPreds
,
12038 SCEVUnionPredicate
*Pred
) {
12039 SCEVPredicateRewriter
Rewriter(L
, SE
, NewPreds
, Pred
);
12040 return Rewriter
.visit(S
);
12043 const SCEV
*visitUnknown(const SCEVUnknown
*Expr
) {
12045 auto ExprPreds
= Pred
->getPredicatesForExpr(Expr
);
12046 for (auto *Pred
: ExprPreds
)
12047 if (const auto *IPred
= dyn_cast
<SCEVEqualPredicate
>(Pred
))
12048 if (IPred
->getLHS() == Expr
)
12049 return IPred
->getRHS();
12051 return convertToAddRecWithPreds(Expr
);
12054 const SCEV
*visitZeroExtendExpr(const SCEVZeroExtendExpr
*Expr
) {
12055 const SCEV
*Operand
= visit(Expr
->getOperand());
12056 const SCEVAddRecExpr
*AR
= dyn_cast
<SCEVAddRecExpr
>(Operand
);
12057 if (AR
&& AR
->getLoop() == L
&& AR
->isAffine()) {
12058 // This couldn't be folded because the operand didn't have the nuw
12059 // flag. Add the nusw flag as an assumption that we could make.
12060 const SCEV
*Step
= AR
->getStepRecurrence(SE
);
12061 Type
*Ty
= Expr
->getType();
12062 if (addOverflowAssumption(AR
, SCEVWrapPredicate::IncrementNUSW
))
12063 return SE
.getAddRecExpr(SE
.getZeroExtendExpr(AR
->getStart(), Ty
),
12064 SE
.getSignExtendExpr(Step
, Ty
), L
,
12065 AR
->getNoWrapFlags());
12067 return SE
.getZeroExtendExpr(Operand
, Expr
->getType());
12070 const SCEV
*visitSignExtendExpr(const SCEVSignExtendExpr
*Expr
) {
12071 const SCEV
*Operand
= visit(Expr
->getOperand());
12072 const SCEVAddRecExpr
*AR
= dyn_cast
<SCEVAddRecExpr
>(Operand
);
12073 if (AR
&& AR
->getLoop() == L
&& AR
->isAffine()) {
12074 // This couldn't be folded because the operand didn't have the nsw
12075 // flag. Add the nssw flag as an assumption that we could make.
12076 const SCEV
*Step
= AR
->getStepRecurrence(SE
);
12077 Type
*Ty
= Expr
->getType();
12078 if (addOverflowAssumption(AR
, SCEVWrapPredicate::IncrementNSSW
))
12079 return SE
.getAddRecExpr(SE
.getSignExtendExpr(AR
->getStart(), Ty
),
12080 SE
.getSignExtendExpr(Step
, Ty
), L
,
12081 AR
->getNoWrapFlags());
12083 return SE
.getSignExtendExpr(Operand
, Expr
->getType());
12087 explicit SCEVPredicateRewriter(const Loop
*L
, ScalarEvolution
&SE
,
12088 SmallPtrSetImpl
<const SCEVPredicate
*> *NewPreds
,
12089 SCEVUnionPredicate
*Pred
)
12090 : SCEVRewriteVisitor(SE
), NewPreds(NewPreds
), Pred(Pred
), L(L
) {}
12092 bool addOverflowAssumption(const SCEVPredicate
*P
) {
12094 // Check if we've already made this assumption.
12095 return Pred
&& Pred
->implies(P
);
12097 NewPreds
->insert(P
);
12101 bool addOverflowAssumption(const SCEVAddRecExpr
*AR
,
12102 SCEVWrapPredicate::IncrementWrapFlags AddedFlags
) {
12103 auto *A
= SE
.getWrapPredicate(AR
, AddedFlags
);
12104 return addOverflowAssumption(A
);
12107 // If \p Expr represents a PHINode, we try to see if it can be represented
12108 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
12109 // to add this predicate as a runtime overflow check, we return the AddRec.
12110 // If \p Expr does not meet these conditions (is not a PHI node, or we
12111 // couldn't create an AddRec for it, or couldn't add the predicate), we just
12113 const SCEV
*convertToAddRecWithPreds(const SCEVUnknown
*Expr
) {
12114 if (!isa
<PHINode
>(Expr
->getValue()))
12116 Optional
<std::pair
<const SCEV
*, SmallVector
<const SCEVPredicate
*, 3>>>
12117 PredicatedRewrite
= SE
.createAddRecFromPHIWithCasts(Expr
);
12118 if (!PredicatedRewrite
)
12120 for (auto *P
: PredicatedRewrite
->second
){
12121 // Wrap predicates from outer loops are not supported.
12122 if (auto *WP
= dyn_cast
<const SCEVWrapPredicate
>(P
)) {
12123 auto *AR
= cast
<const SCEVAddRecExpr
>(WP
->getExpr());
12124 if (L
!= AR
->getLoop())
12127 if (!addOverflowAssumption(P
))
12130 return PredicatedRewrite
->first
;
12133 SmallPtrSetImpl
<const SCEVPredicate
*> *NewPreds
;
12134 SCEVUnionPredicate
*Pred
;
12138 } // end anonymous namespace
12140 const SCEV
*ScalarEvolution::rewriteUsingPredicate(const SCEV
*S
, const Loop
*L
,
12141 SCEVUnionPredicate
&Preds
) {
12142 return SCEVPredicateRewriter::rewrite(S
, L
, *this, nullptr, &Preds
);
12145 const SCEVAddRecExpr
*ScalarEvolution::convertSCEVToAddRecWithPredicates(
12146 const SCEV
*S
, const Loop
*L
,
12147 SmallPtrSetImpl
<const SCEVPredicate
*> &Preds
) {
12148 SmallPtrSet
<const SCEVPredicate
*, 4> TransformPreds
;
12149 S
= SCEVPredicateRewriter::rewrite(S
, L
, *this, &TransformPreds
, nullptr);
12150 auto *AddRec
= dyn_cast
<SCEVAddRecExpr
>(S
);
12155 // Since the transformation was successful, we can now transfer the SCEV
12157 for (auto *P
: TransformPreds
)
12163 /// SCEV predicates
12164 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID
,
12165 SCEVPredicateKind Kind
)
12166 : FastID(ID
), Kind(Kind
) {}
12168 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID
,
12169 const SCEV
*LHS
, const SCEV
*RHS
)
12170 : SCEVPredicate(ID
, P_Equal
), LHS(LHS
), RHS(RHS
) {
12171 assert(LHS
->getType() == RHS
->getType() && "LHS and RHS types don't match");
12172 assert(LHS
!= RHS
&& "LHS and RHS are the same SCEV");
12175 bool SCEVEqualPredicate::implies(const SCEVPredicate
*N
) const {
12176 const auto *Op
= dyn_cast
<SCEVEqualPredicate
>(N
);
12181 return Op
->LHS
== LHS
&& Op
->RHS
== RHS
;
12184 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
12186 const SCEV
*SCEVEqualPredicate::getExpr() const { return LHS
; }
12188 void SCEVEqualPredicate::print(raw_ostream
&OS
, unsigned Depth
) const {
12189 OS
.indent(Depth
) << "Equal predicate: " << *LHS
<< " == " << *RHS
<< "\n";
12192 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID
,
12193 const SCEVAddRecExpr
*AR
,
12194 IncrementWrapFlags Flags
)
12195 : SCEVPredicate(ID
, P_Wrap
), AR(AR
), Flags(Flags
) {}
12197 const SCEV
*SCEVWrapPredicate::getExpr() const { return AR
; }
12199 bool SCEVWrapPredicate::implies(const SCEVPredicate
*N
) const {
12200 const auto *Op
= dyn_cast
<SCEVWrapPredicate
>(N
);
12202 return Op
&& Op
->AR
== AR
&& setFlags(Flags
, Op
->Flags
) == Flags
;
12205 bool SCEVWrapPredicate::isAlwaysTrue() const {
12206 SCEV::NoWrapFlags ScevFlags
= AR
->getNoWrapFlags();
12207 IncrementWrapFlags IFlags
= Flags
;
12209 if (ScalarEvolution::setFlags(ScevFlags
, SCEV::FlagNSW
) == ScevFlags
)
12210 IFlags
= clearFlags(IFlags
, IncrementNSSW
);
12212 return IFlags
== IncrementAnyWrap
;
12215 void SCEVWrapPredicate::print(raw_ostream
&OS
, unsigned Depth
) const {
12216 OS
.indent(Depth
) << *getExpr() << " Added Flags: ";
12217 if (SCEVWrapPredicate::IncrementNUSW
& getFlags())
12219 if (SCEVWrapPredicate::IncrementNSSW
& getFlags())
12224 SCEVWrapPredicate::IncrementWrapFlags
12225 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr
*AR
,
12226 ScalarEvolution
&SE
) {
12227 IncrementWrapFlags ImpliedFlags
= IncrementAnyWrap
;
12228 SCEV::NoWrapFlags StaticFlags
= AR
->getNoWrapFlags();
12230 // We can safely transfer the NSW flag as NSSW.
12231 if (ScalarEvolution::setFlags(StaticFlags
, SCEV::FlagNSW
) == StaticFlags
)
12232 ImpliedFlags
= IncrementNSSW
;
12234 if (ScalarEvolution::setFlags(StaticFlags
, SCEV::FlagNUW
) == StaticFlags
) {
12235 // If the increment is positive, the SCEV NUW flag will also imply the
12236 // WrapPredicate NUSW flag.
12237 if (const auto *Step
= dyn_cast
<SCEVConstant
>(AR
->getStepRecurrence(SE
)))
12238 if (Step
->getValue()->getValue().isNonNegative())
12239 ImpliedFlags
= setFlags(ImpliedFlags
, IncrementNUSW
);
12242 return ImpliedFlags
;
12245 /// Union predicates don't get cached so create a dummy set ID for it.
12246 SCEVUnionPredicate::SCEVUnionPredicate()
12247 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union
) {}
12249 bool SCEVUnionPredicate::isAlwaysTrue() const {
12250 return all_of(Preds
,
12251 [](const SCEVPredicate
*I
) { return I
->isAlwaysTrue(); });
12254 ArrayRef
<const SCEVPredicate
*>
12255 SCEVUnionPredicate::getPredicatesForExpr(const SCEV
*Expr
) {
12256 auto I
= SCEVToPreds
.find(Expr
);
12257 if (I
== SCEVToPreds
.end())
12258 return ArrayRef
<const SCEVPredicate
*>();
12262 bool SCEVUnionPredicate::implies(const SCEVPredicate
*N
) const {
12263 if (const auto *Set
= dyn_cast
<SCEVUnionPredicate
>(N
))
12264 return all_of(Set
->Preds
,
12265 [this](const SCEVPredicate
*I
) { return this->implies(I
); });
12267 auto ScevPredsIt
= SCEVToPreds
.find(N
->getExpr());
12268 if (ScevPredsIt
== SCEVToPreds
.end())
12270 auto &SCEVPreds
= ScevPredsIt
->second
;
12272 return any_of(SCEVPreds
,
12273 [N
](const SCEVPredicate
*I
) { return I
->implies(N
); });
12276 const SCEV
*SCEVUnionPredicate::getExpr() const { return nullptr; }
12278 void SCEVUnionPredicate::print(raw_ostream
&OS
, unsigned Depth
) const {
12279 for (auto Pred
: Preds
)
12280 Pred
->print(OS
, Depth
);
12283 void SCEVUnionPredicate::add(const SCEVPredicate
*N
) {
12284 if (const auto *Set
= dyn_cast
<SCEVUnionPredicate
>(N
)) {
12285 for (auto Pred
: Set
->Preds
)
12293 const SCEV
*Key
= N
->getExpr();
12294 assert(Key
&& "Only SCEVUnionPredicate doesn't have an "
12295 " associated expression!");
12297 SCEVToPreds
[Key
].push_back(N
);
12298 Preds
.push_back(N
);
12301 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution
&SE
,
12305 const SCEV
*PredicatedScalarEvolution::getSCEV(Value
*V
) {
12306 const SCEV
*Expr
= SE
.getSCEV(V
);
12307 RewriteEntry
&Entry
= RewriteMap
[Expr
];
12309 // If we already have an entry and the version matches, return it.
12310 if (Entry
.second
&& Generation
== Entry
.first
)
12311 return Entry
.second
;
12313 // We found an entry but it's stale. Rewrite the stale entry
12314 // according to the current predicate.
12316 Expr
= Entry
.second
;
12318 const SCEV
*NewSCEV
= SE
.rewriteUsingPredicate(Expr
, &L
, Preds
);
12319 Entry
= {Generation
, NewSCEV
};
12324 const SCEV
*PredicatedScalarEvolution::getBackedgeTakenCount() {
12325 if (!BackedgeCount
) {
12326 SCEVUnionPredicate BackedgePred
;
12327 BackedgeCount
= SE
.getPredicatedBackedgeTakenCount(&L
, BackedgePred
);
12328 addPredicate(BackedgePred
);
12330 return BackedgeCount
;
12333 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate
&Pred
) {
12334 if (Preds
.implies(&Pred
))
12337 updateGeneration();
12340 const SCEVUnionPredicate
&PredicatedScalarEvolution::getUnionPredicate() const {
12344 void PredicatedScalarEvolution::updateGeneration() {
12345 // If the generation number wrapped recompute everything.
12346 if (++Generation
== 0) {
12347 for (auto &II
: RewriteMap
) {
12348 const SCEV
*Rewritten
= II
.second
.second
;
12349 II
.second
= {Generation
, SE
.rewriteUsingPredicate(Rewritten
, &L
, Preds
)};
12354 void PredicatedScalarEvolution::setNoOverflow(
12355 Value
*V
, SCEVWrapPredicate::IncrementWrapFlags Flags
) {
12356 const SCEV
*Expr
= getSCEV(V
);
12357 const auto *AR
= cast
<SCEVAddRecExpr
>(Expr
);
12359 auto ImpliedFlags
= SCEVWrapPredicate::getImpliedFlags(AR
, SE
);
12361 // Clear the statically implied flags.
12362 Flags
= SCEVWrapPredicate::clearFlags(Flags
, ImpliedFlags
);
12363 addPredicate(*SE
.getWrapPredicate(AR
, Flags
));
12365 auto II
= FlagsMap
.insert({V
, Flags
});
12367 II
.first
->second
= SCEVWrapPredicate::setFlags(Flags
, II
.first
->second
);
12370 bool PredicatedScalarEvolution::hasNoOverflow(
12371 Value
*V
, SCEVWrapPredicate::IncrementWrapFlags Flags
) {
12372 const SCEV
*Expr
= getSCEV(V
);
12373 const auto *AR
= cast
<SCEVAddRecExpr
>(Expr
);
12375 Flags
= SCEVWrapPredicate::clearFlags(
12376 Flags
, SCEVWrapPredicate::getImpliedFlags(AR
, SE
));
12378 auto II
= FlagsMap
.find(V
);
12380 if (II
!= FlagsMap
.end())
12381 Flags
= SCEVWrapPredicate::clearFlags(Flags
, II
->second
);
12383 return Flags
== SCEVWrapPredicate::IncrementAnyWrap
;
12386 const SCEVAddRecExpr
*PredicatedScalarEvolution::getAsAddRec(Value
*V
) {
12387 const SCEV
*Expr
= this->getSCEV(V
);
12388 SmallPtrSet
<const SCEVPredicate
*, 4> NewPreds
;
12389 auto *New
= SE
.convertSCEVToAddRecWithPredicates(Expr
, &L
, NewPreds
);
12394 for (auto *P
: NewPreds
)
12397 updateGeneration();
12398 RewriteMap
[SE
.getSCEV(V
)] = {Generation
, New
};
12402 PredicatedScalarEvolution::PredicatedScalarEvolution(
12403 const PredicatedScalarEvolution
&Init
)
12404 : RewriteMap(Init
.RewriteMap
), SE(Init
.SE
), L(Init
.L
), Preds(Init
.Preds
),
12405 Generation(Init
.Generation
), BackedgeCount(Init
.BackedgeCount
) {
12406 for (const auto &I
: Init
.FlagsMap
)
12407 FlagsMap
.insert(I
);
12410 void PredicatedScalarEvolution::print(raw_ostream
&OS
, unsigned Depth
) const {
12412 for (auto *BB
: L
.getBlocks())
12413 for (auto &I
: *BB
) {
12414 if (!SE
.isSCEVable(I
.getType()))
12417 auto *Expr
= SE
.getSCEV(&I
);
12418 auto II
= RewriteMap
.find(Expr
);
12420 if (II
== RewriteMap
.end())
12423 // Don't print things that are not interesting.
12424 if (II
->second
.second
== Expr
)
12427 OS
.indent(Depth
) << "[PSE]" << I
<< ":\n";
12428 OS
.indent(Depth
+ 2) << *Expr
<< "\n";
12429 OS
.indent(Depth
+ 2) << "--> " << *II
->second
.second
<< "\n";
12433 // Match the mathematical pattern A - (A / B) * B, where A and B can be
12434 // arbitrary expressions.
12435 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is
12436 // 4, A / B becomes X / 8).
12437 bool ScalarEvolution::matchURem(const SCEV
*Expr
, const SCEV
*&LHS
,
12438 const SCEV
*&RHS
) {
12439 const auto *Add
= dyn_cast
<SCEVAddExpr
>(Expr
);
12440 if (Add
== nullptr || Add
->getNumOperands() != 2)
12443 const SCEV
*A
= Add
->getOperand(1);
12444 const auto *Mul
= dyn_cast
<SCEVMulExpr
>(Add
->getOperand(0));
12446 if (Mul
== nullptr)
12449 const auto MatchURemWithDivisor
= [&](const SCEV
*B
) {
12450 // (SomeExpr + (-(SomeExpr / B) * B)).
12451 if (Expr
== getURemExpr(A
, B
)) {
12459 // (SomeExpr + (-1 * (SomeExpr / B) * B)).
12460 if (Mul
->getNumOperands() == 3 && isa
<SCEVConstant
>(Mul
->getOperand(0)))
12461 return MatchURemWithDivisor(Mul
->getOperand(1)) ||
12462 MatchURemWithDivisor(Mul
->getOperand(2));
12464 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)).
12465 if (Mul
->getNumOperands() == 2)
12466 return MatchURemWithDivisor(Mul
->getOperand(1)) ||
12467 MatchURemWithDivisor(Mul
->getOperand(0)) ||
12468 MatchURemWithDivisor(getNegativeSCEV(Mul
->getOperand(1))) ||
12469 MatchURemWithDivisor(getNegativeSCEV(Mul
->getOperand(0)));