1 //===- llvm/Analysis/ScalarEvolution.h - Scalar Evolution -------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // The ScalarEvolution class is an LLVM pass which can be used to analyze and
11 // categorize scalar expressions in loops. It specializes in recognizing
12 // general induction variables, representing them with the abstract and opaque
13 // SCEV class. Given this analysis, trip counts of loops and other important
14 // properties can be obtained.
16 // This analysis is primarily useful for induction variable substitution and
17 // strength reduction.
19 //===----------------------------------------------------------------------===//
21 #ifndef LLVM_ANALYSIS_SCALAREVOLUTION_H
22 #define LLVM_ANALYSIS_SCALAREVOLUTION_H
24 #include "llvm/ADT/DenseSet.h"
25 #include "llvm/ADT/FoldingSet.h"
26 #include "llvm/IR/ConstantRange.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/Operator.h"
30 #include "llvm/IR/PassManager.h"
31 #include "llvm/IR/ValueHandle.h"
32 #include "llvm/Pass.h"
33 #include "llvm/Support/Allocator.h"
34 #include "llvm/Support/DataTypes.h"
39 class AssumptionCache;
44 class ScalarEvolution;
46 class TargetLibraryInfo;
54 template<> struct FoldingSetTrait<SCEV>;
56 /// This class represents an analyzed expression in the program. These are
57 /// opaque objects that the client is not allowed to do much with directly.
59 class SCEV : public FoldingSetNode {
60 friend struct FoldingSetTrait<SCEV>;
62 /// A reference to an Interned FoldingSetNodeID for this node. The
63 /// ScalarEvolution's BumpPtrAllocator holds the data.
64 FoldingSetNodeIDRef FastID;
66 // The SCEV baseclass this node corresponds to
67 const unsigned short SCEVType;
70 /// This field is initialized to zero and may be used in subclasses to store
71 /// miscellaneous information.
72 unsigned short SubclassData;
75 SCEV(const SCEV &) = delete;
76 void operator=(const SCEV &) = delete;
79 /// NoWrapFlags are bitfield indices into SubclassData.
81 /// Add and Mul expressions may have no-unsigned-wrap <NUW> or
82 /// no-signed-wrap <NSW> properties, which are derived from the IR
83 /// operator. NSW is a misnomer that we use to mean no signed overflow or
86 /// AddRec expressions may have a no-self-wraparound <NW> property if, in
87 /// the integer domain, abs(step) * max-iteration(loop) <=
88 /// unsigned-max(bitwidth). This means that the recurrence will never reach
89 /// its start value if the step is non-zero. Computing the same value on
90 /// each iteration is not considered wrapping, and recurrences with step = 0
91 /// are trivially <NW>. <NW> is independent of the sign of step and the
92 /// value the add recurrence starts with.
94 /// Note that NUW and NSW are also valid properties of a recurrence, and
95 /// either implies NW. For convenience, NW will be set for a recurrence
96 /// whenever either NUW or NSW are set.
97 enum NoWrapFlags { FlagAnyWrap = 0, // No guarantee.
98 FlagNW = (1 << 0), // No self-wrap.
99 FlagNUW = (1 << 1), // No unsigned wrap.
100 FlagNSW = (1 << 2), // No signed wrap.
101 NoWrapMask = (1 << 3) -1 };
103 explicit SCEV(const FoldingSetNodeIDRef ID, unsigned SCEVTy) :
104 FastID(ID), SCEVType(SCEVTy), SubclassData(0) {}
106 unsigned getSCEVType() const { return SCEVType; }
108 /// Return the LLVM type of this SCEV expression.
110 Type *getType() const;
112 /// Return true if the expression is a constant zero.
116 /// Return true if the expression is a constant one.
120 /// Return true if the expression is a constant all-ones value.
122 bool isAllOnesValue() const;
124 /// Return true if the specified scev is negated, but not a constant.
125 bool isNonConstantNegative() const;
127 /// Print out the internal representation of this scalar to the specified
128 /// stream. This should really only be used for debugging purposes.
129 void print(raw_ostream &OS) const;
131 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
132 /// This method is used for debugging.
138 // Specialize FoldingSetTrait for SCEV to avoid needing to compute
139 // temporary FoldingSetNodeID values.
140 template<> struct FoldingSetTrait<SCEV> : DefaultFoldingSetTrait<SCEV> {
141 static void Profile(const SCEV &X, FoldingSetNodeID& ID) {
144 static bool Equals(const SCEV &X, const FoldingSetNodeID &ID,
145 unsigned IDHash, FoldingSetNodeID &TempID) {
146 return ID == X.FastID;
148 static unsigned ComputeHash(const SCEV &X, FoldingSetNodeID &TempID) {
149 return X.FastID.ComputeHash();
153 inline raw_ostream &operator<<(raw_ostream &OS, const SCEV &S) {
158 /// An object of this class is returned by queries that could not be answered.
159 /// For example, if you ask for the number of iterations of a linked-list
160 /// traversal loop, you will get one of these. None of the standard SCEV
161 /// operations are valid on this class, it is just a marker.
162 struct SCEVCouldNotCompute : public SCEV {
163 SCEVCouldNotCompute();
165 /// Methods for support type inquiry through isa, cast, and dyn_cast:
166 static bool classof(const SCEV *S);
169 /// The main scalar evolution driver. Because client code (intentionally)
170 /// can't do much with the SCEV objects directly, they must ask this class
172 class ScalarEvolution {
174 /// An enum describing the relationship between a SCEV and a loop.
175 enum LoopDisposition {
176 LoopVariant, ///< The SCEV is loop-variant (unknown).
177 LoopInvariant, ///< The SCEV is loop-invariant.
178 LoopComputable ///< The SCEV varies predictably with the loop.
181 /// An enum describing the relationship between a SCEV and a basic block.
182 enum BlockDisposition {
183 DoesNotDominateBlock, ///< The SCEV does not dominate the block.
184 DominatesBlock, ///< The SCEV dominates the block.
185 ProperlyDominatesBlock ///< The SCEV properly dominates the block.
188 /// Convenient NoWrapFlags manipulation that hides enum casts and is
189 /// visible in the ScalarEvolution name space.
190 static SCEV::NoWrapFlags LLVM_ATTRIBUTE_UNUSED_RESULT
191 maskFlags(SCEV::NoWrapFlags Flags, int Mask) {
192 return (SCEV::NoWrapFlags)(Flags & Mask);
194 static SCEV::NoWrapFlags LLVM_ATTRIBUTE_UNUSED_RESULT
195 setFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OnFlags) {
196 return (SCEV::NoWrapFlags)(Flags | OnFlags);
198 static SCEV::NoWrapFlags LLVM_ATTRIBUTE_UNUSED_RESULT
199 clearFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OffFlags) {
200 return (SCEV::NoWrapFlags)(Flags & ~OffFlags);
204 /// A CallbackVH to arrange for ScalarEvolution to be notified whenever a
205 /// Value is deleted.
206 class SCEVCallbackVH final : public CallbackVH {
208 void deleted() override;
209 void allUsesReplacedWith(Value *New) override;
211 SCEVCallbackVH(Value *V, ScalarEvolution *SE = nullptr);
214 friend class SCEVCallbackVH;
215 friend class SCEVExpander;
216 friend class SCEVUnknown;
218 /// The function we are analyzing.
222 /// The target library information for the target we are targeting.
224 TargetLibraryInfo &TLI;
226 /// The tracker for @llvm.assume intrinsics in this function.
229 /// The dominator tree.
233 /// The loop information for the function we are currently analyzing.
237 /// This SCEV is used to represent unknown trip counts and things.
238 std::unique_ptr<SCEVCouldNotCompute> CouldNotCompute;
240 /// The typedef for ValueExprMap.
242 typedef DenseMap<SCEVCallbackVH, const SCEV *, DenseMapInfo<Value *> >
245 /// This is a cache of the values we have analyzed so far.
247 ValueExprMapType ValueExprMap;
249 /// Mark predicate values currently being processed by isImpliedCond.
250 DenseSet<Value*> PendingLoopPredicates;
252 /// Set to true by isLoopBackedgeGuardedByCond when we're walking the set of
253 /// conditions dominating the backedge of a loop.
254 bool WalkingBEDominatingConds;
256 /// Set to true by isKnownPredicateViaSplitting when we're trying to prove a
257 /// predicate by splitting it into a set of independent predicates.
258 bool ProvingSplitPredicate;
260 /// Information about the number of loop iterations for which a loop exit's
261 /// branch condition evaluates to the not-taken path. This is a temporary
262 /// pair of exact and max expressions that are eventually summarized in
263 /// ExitNotTakenInfo and BackedgeTakenInfo.
268 /*implicit*/ ExitLimit(const SCEV *E) : Exact(E), Max(E) {}
270 ExitLimit(const SCEV *E, const SCEV *M) : Exact(E), Max(M) {}
272 /// Test whether this ExitLimit contains any computed information, or
273 /// whether it's all SCEVCouldNotCompute values.
274 bool hasAnyInfo() const {
275 return !isa<SCEVCouldNotCompute>(Exact) ||
276 !isa<SCEVCouldNotCompute>(Max);
280 /// Information about the number of times a particular loop exit may be
281 /// reached before exiting the loop.
282 struct ExitNotTakenInfo {
283 AssertingVH<BasicBlock> ExitingBlock;
284 const SCEV *ExactNotTaken;
285 PointerIntPair<ExitNotTakenInfo*, 1> NextExit;
287 ExitNotTakenInfo() : ExitingBlock(nullptr), ExactNotTaken(nullptr) {}
289 /// Return true if all loop exits are computable.
290 bool isCompleteList() const {
291 return NextExit.getInt() == 0;
294 void setIncomplete() { NextExit.setInt(1); }
296 /// Return a pointer to the next exit's not-taken info.
297 ExitNotTakenInfo *getNextExit() const {
298 return NextExit.getPointer();
301 void setNextExit(ExitNotTakenInfo *ENT) { NextExit.setPointer(ENT); }
304 /// Information about the backedge-taken count of a loop. This currently
305 /// includes an exact count and a maximum count.
307 class BackedgeTakenInfo {
308 /// A list of computable exits and their not-taken counts. Loops almost
309 /// never have more than one computable exit.
310 ExitNotTakenInfo ExitNotTaken;
312 /// An expression indicating the least maximum backedge-taken count of the
313 /// loop that is known, or a SCEVCouldNotCompute.
317 BackedgeTakenInfo() : Max(nullptr) {}
319 /// Initialize BackedgeTakenInfo from a list of exact exit counts.
321 SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts,
322 bool Complete, const SCEV *MaxCount);
324 /// Test whether this BackedgeTakenInfo contains any computed information,
325 /// or whether it's all SCEVCouldNotCompute values.
326 bool hasAnyInfo() const {
327 return ExitNotTaken.ExitingBlock || !isa<SCEVCouldNotCompute>(Max);
330 /// Return an expression indicating the exact backedge-taken count of the
331 /// loop if it is known, or SCEVCouldNotCompute otherwise. This is the
332 /// number of times the loop header can be guaranteed to execute, minus
334 const SCEV *getExact(ScalarEvolution *SE) const;
336 /// Return the number of times this loop exit may fall through to the back
337 /// edge, or SCEVCouldNotCompute. The loop is guaranteed not to exit via
338 /// this block before this number of iterations, but may exit via another
340 const SCEV *getExact(BasicBlock *ExitingBlock, ScalarEvolution *SE) const;
342 /// Get the max backedge taken count for the loop.
343 const SCEV *getMax(ScalarEvolution *SE) const;
345 /// Return true if any backedge taken count expressions refer to the given
347 bool hasOperand(const SCEV *S, ScalarEvolution *SE) const;
349 /// Invalidate this result and free associated memory.
353 /// Cache the backedge-taken count of the loops for this function as they
355 DenseMap<const Loop*, BackedgeTakenInfo> BackedgeTakenCounts;
357 /// This map contains entries for all of the PHI instructions that we
358 /// attempt to compute constant evolutions for. This allows us to avoid
359 /// potentially expensive recomputation of these properties. An instruction
360 /// maps to null if we are unable to compute its exit value.
361 DenseMap<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
363 /// This map contains entries for all the expressions that we attempt to
364 /// compute getSCEVAtScope information for, which can be expensive in
366 DenseMap<const SCEV *,
367 SmallVector<std::pair<const Loop *, const SCEV *>, 2> > ValuesAtScopes;
369 /// Memoized computeLoopDisposition results.
370 DenseMap<const SCEV *,
371 SmallVector<PointerIntPair<const Loop *, 2, LoopDisposition>, 2>>
374 /// Compute a LoopDisposition value.
375 LoopDisposition computeLoopDisposition(const SCEV *S, const Loop *L);
377 /// Memoized computeBlockDisposition results.
380 SmallVector<PointerIntPair<const BasicBlock *, 2, BlockDisposition>, 2>>
383 /// Compute a BlockDisposition value.
384 BlockDisposition computeBlockDisposition(const SCEV *S, const BasicBlock *BB);
386 /// Memoized results from getRange
387 DenseMap<const SCEV *, ConstantRange> UnsignedRanges;
389 /// Memoized results from getRange
390 DenseMap<const SCEV *, ConstantRange> SignedRanges;
392 /// Used to parameterize getRange
393 enum RangeSignHint { HINT_RANGE_UNSIGNED, HINT_RANGE_SIGNED };
395 /// Set the memoized range for the given SCEV.
396 const ConstantRange &setRange(const SCEV *S, RangeSignHint Hint,
397 const ConstantRange &CR) {
398 DenseMap<const SCEV *, ConstantRange> &Cache =
399 Hint == HINT_RANGE_UNSIGNED ? UnsignedRanges : SignedRanges;
401 std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair =
402 Cache.insert(std::make_pair(S, CR));
404 Pair.first->second = CR;
405 return Pair.first->second;
408 /// Determine the range for a particular SCEV.
409 ConstantRange getRange(const SCEV *S, RangeSignHint Hint);
411 /// We know that there is no SCEV for the specified value. Analyze the
413 const SCEV *createSCEV(Value *V);
415 /// Provide the special handling we need to analyze PHI SCEVs.
416 const SCEV *createNodeForPHI(PHINode *PN);
418 /// Provide special handling for a select-like instruction (currently this
419 /// is either a select instruction or a phi node). \p I is the instruction
420 /// being processed, and it is assumed equivalent to "Cond ? TrueVal :
422 const SCEV *createNodeForSelect(Instruction *I, Value *Cond, Value *TrueVal,
425 /// Provide the special handling we need to analyze GEP SCEVs.
426 const SCEV *createNodeForGEP(GEPOperator *GEP);
428 /// Implementation code for getSCEVAtScope; called at most once for each
431 const SCEV *computeSCEVAtScope(const SCEV *S, const Loop *L);
433 /// This looks up computed SCEV values for all instructions that depend on
434 /// the given instruction and removes them from the ValueExprMap map if they
435 /// reference SymName. This is used during PHI resolution.
436 void ForgetSymbolicName(Instruction *I, const SCEV *SymName);
438 /// Return the BackedgeTakenInfo for the given loop, lazily computing new
439 /// values if the loop hasn't been analyzed yet.
440 const BackedgeTakenInfo &getBackedgeTakenInfo(const Loop *L);
442 /// Compute the number of times the specified loop will iterate.
443 BackedgeTakenInfo ComputeBackedgeTakenCount(const Loop *L);
445 /// Compute the number of times the backedge of the specified loop will
446 /// execute if it exits via the specified block.
447 ExitLimit ComputeExitLimit(const Loop *L, BasicBlock *ExitingBlock);
449 /// Compute the number of times the backedge of the specified loop will
450 /// execute if its exit condition were a conditional branch of ExitCond,
452 ExitLimit ComputeExitLimitFromCond(const Loop *L,
458 /// Compute the number of times the backedge of the specified loop will
459 /// execute if its exit condition were a conditional branch of the ICmpInst
460 /// ExitCond, TBB, and FBB.
461 ExitLimit ComputeExitLimitFromICmp(const Loop *L,
467 /// Compute the number of times the backedge of the specified loop will
468 /// execute if its exit condition were a switch with a single exiting case
471 ComputeExitLimitFromSingleExitSwitch(const Loop *L, SwitchInst *Switch,
472 BasicBlock *ExitingBB, bool IsSubExpr);
474 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
475 /// compute the backedge-taken count.
476 ExitLimit ComputeLoadConstantCompareExitLimit(LoadInst *LI,
479 ICmpInst::Predicate p);
481 /// If the loop is known to execute a constant number of times (the
482 /// condition evolves only from constants), try to evaluate a few iterations
483 /// of the loop until we get the exit condition gets a value of ExitWhen
484 /// (true or false). If we cannot evaluate the exit count of the loop,
485 /// return CouldNotCompute.
486 const SCEV *ComputeExitCountExhaustively(const Loop *L,
490 /// Return the number of times an exit condition comparing the specified
491 /// value to zero will execute. If not computable, return CouldNotCompute.
492 ExitLimit HowFarToZero(const SCEV *V, const Loop *L, bool IsSubExpr);
494 /// Return the number of times an exit condition checking the specified
495 /// value for nonzero will execute. If not computable, return
497 ExitLimit HowFarToNonZero(const SCEV *V, const Loop *L);
499 /// Return the number of times an exit condition containing the specified
500 /// less-than comparison will execute. If not computable, return
501 /// CouldNotCompute. isSigned specifies whether the less-than is signed.
502 ExitLimit HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
503 const Loop *L, bool isSigned, bool IsSubExpr);
504 ExitLimit HowManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
505 const Loop *L, bool isSigned, bool IsSubExpr);
507 /// Return a predecessor of BB (which may not be an immediate predecessor)
508 /// which has exactly one successor from which BB is reachable, or null if
509 /// no such block is found.
510 std::pair<BasicBlock *, BasicBlock *>
511 getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
513 /// Test whether the condition described by Pred, LHS, and RHS is true
514 /// whenever the given FoundCondValue value evaluates to true.
515 bool isImpliedCond(ICmpInst::Predicate Pred,
516 const SCEV *LHS, const SCEV *RHS,
517 Value *FoundCondValue,
520 /// Test whether the condition described by Pred, LHS, and RHS is true
521 /// whenever the condition described by FoundPred, FoundLHS, FoundRHS is
523 bool isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
524 const SCEV *RHS, ICmpInst::Predicate FoundPred,
525 const SCEV *FoundLHS, const SCEV *FoundRHS);
527 /// Test whether the condition described by Pred, LHS, and RHS is true
528 /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
530 bool isImpliedCondOperands(ICmpInst::Predicate Pred,
531 const SCEV *LHS, const SCEV *RHS,
532 const SCEV *FoundLHS, const SCEV *FoundRHS);
534 /// Test whether the condition described by Pred, LHS, and RHS is true
535 /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
537 bool isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
538 const SCEV *LHS, const SCEV *RHS,
539 const SCEV *FoundLHS,
540 const SCEV *FoundRHS);
542 /// Test whether the condition described by Pred, LHS, and RHS is true
543 /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
544 /// true. Utility function used by isImpliedCondOperands.
545 bool isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
546 const SCEV *LHS, const SCEV *RHS,
547 const SCEV *FoundLHS,
548 const SCEV *FoundRHS);
550 /// Test whether the condition described by Pred, LHS, and RHS is true
551 /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
554 /// This routine tries to rule out certain kinds of integer overflow, and
555 /// then tries to reason about arithmetic properties of the predicates.
556 bool isImpliedCondOperandsViaNoOverflow(ICmpInst::Predicate Pred,
557 const SCEV *LHS, const SCEV *RHS,
558 const SCEV *FoundLHS,
559 const SCEV *FoundRHS);
561 /// If we know that the specified Phi is in the header of its containing
562 /// loop, we know the loop executes a constant number of times, and the PHI
563 /// node is just a recurrence involving constants, fold it.
564 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs,
567 /// Test if the given expression is known to satisfy the condition described
568 /// by Pred and the known constant ranges of LHS and RHS.
570 bool isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
571 const SCEV *LHS, const SCEV *RHS);
573 /// Try to split Pred LHS RHS into logical conjunctions (and's) and try to
574 /// prove them individually.
575 bool isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, const SCEV *LHS,
578 /// Drop memoized information computed for S.
579 void forgetMemoizedResults(const SCEV *S);
581 /// Return an existing SCEV for V if there is one, otherwise return nullptr.
582 const SCEV *getExistingSCEV(Value *V);
584 /// Return false iff given SCEV contains a SCEVUnknown with NULL value-
586 bool checkValidity(const SCEV *S) const;
588 /// Return true if `ExtendOpTy`({`Start`,+,`Step`}) can be proved to be
589 /// equal to {`ExtendOpTy`(`Start`),+,`ExtendOpTy`(`Step`)}. This is
590 /// equivalent to proving no signed (resp. unsigned) wrap in
591 /// {`Start`,+,`Step`} if `ExtendOpTy` is `SCEVSignExtendExpr`
592 /// (resp. `SCEVZeroExtendExpr`).
594 template<typename ExtendOpTy>
595 bool proveNoWrapByVaryingStart(const SCEV *Start, const SCEV *Step,
598 bool isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
599 ICmpInst::Predicate Pred, bool &Increasing);
601 /// Return true if, for all loop invariant X, the predicate "LHS `Pred` X"
602 /// is monotonically increasing or decreasing. In the former case set
603 /// `Increasing` to true and in the latter case set `Increasing` to false.
605 /// A predicate is said to be monotonically increasing if may go from being
606 /// false to being true as the loop iterates, but never the other way
607 /// around. A predicate is said to be monotonically decreasing if may go
608 /// from being true to being false as the loop iterates, but never the other
610 bool isMonotonicPredicate(const SCEVAddRecExpr *LHS,
611 ICmpInst::Predicate Pred, bool &Increasing);
613 // Return SCEV no-wrap flags that can be proven based on reasoning
614 // about how poison produced from no-wrap flags on this value
615 // (e.g. a nuw add) would trigger undefined behavior on overflow.
616 SCEV::NoWrapFlags getNoWrapFlagsFromUB(const Value *V);
619 ScalarEvolution(Function &F, TargetLibraryInfo &TLI, AssumptionCache &AC,
620 DominatorTree &DT, LoopInfo &LI);
622 ScalarEvolution(ScalarEvolution &&Arg);
624 LLVMContext &getContext() const { return F.getContext(); }
626 /// Test if values of the given type are analyzable within the SCEV
627 /// framework. This primarily includes integer types, and it can optionally
628 /// include pointer types if the ScalarEvolution class has access to
629 /// target-specific information.
630 bool isSCEVable(Type *Ty) const;
632 /// Return the size in bits of the specified type, for which isSCEVable must
634 uint64_t getTypeSizeInBits(Type *Ty) const;
636 /// Return a type with the same bitwidth as the given type and which
637 /// represents how SCEV will treat the given type, for which isSCEVable must
638 /// return true. For pointer types, this is the pointer-sized integer type.
639 Type *getEffectiveSCEVType(Type *Ty) const;
641 /// Return a SCEV expression for the full generality of the specified
643 const SCEV *getSCEV(Value *V);
645 const SCEV *getConstant(ConstantInt *V);
646 const SCEV *getConstant(const APInt& Val);
647 const SCEV *getConstant(Type *Ty, uint64_t V, bool isSigned = false);
648 const SCEV *getTruncateExpr(const SCEV *Op, Type *Ty);
649 const SCEV *getZeroExtendExpr(const SCEV *Op, Type *Ty);
650 const SCEV *getSignExtendExpr(const SCEV *Op, Type *Ty);
651 const SCEV *getAnyExtendExpr(const SCEV *Op, Type *Ty);
652 const SCEV *getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
653 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
654 const SCEV *getAddExpr(const SCEV *LHS, const SCEV *RHS,
655 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
656 SmallVector<const SCEV *, 2> Ops;
659 return getAddExpr(Ops, Flags);
661 const SCEV *getAddExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
662 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
663 SmallVector<const SCEV *, 3> Ops;
667 return getAddExpr(Ops, Flags);
669 const SCEV *getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
670 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
671 const SCEV *getMulExpr(const SCEV *LHS, const SCEV *RHS,
672 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap)
674 SmallVector<const SCEV *, 2> Ops;
677 return getMulExpr(Ops, Flags);
679 const SCEV *getMulExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
680 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
681 SmallVector<const SCEV *, 3> Ops;
685 return getMulExpr(Ops, Flags);
687 const SCEV *getUDivExpr(const SCEV *LHS, const SCEV *RHS);
688 const SCEV *getUDivExactExpr(const SCEV *LHS, const SCEV *RHS);
689 const SCEV *getAddRecExpr(const SCEV *Start, const SCEV *Step,
690 const Loop *L, SCEV::NoWrapFlags Flags);
691 const SCEV *getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
692 const Loop *L, SCEV::NoWrapFlags Flags);
693 const SCEV *getAddRecExpr(const SmallVectorImpl<const SCEV *> &Operands,
694 const Loop *L, SCEV::NoWrapFlags Flags) {
695 SmallVector<const SCEV *, 4> NewOp(Operands.begin(), Operands.end());
696 return getAddRecExpr(NewOp, L, Flags);
698 /// \brief Returns an expression for a GEP
700 /// \p PointeeType The type used as the basis for the pointer arithmetics
701 /// \p BaseExpr The expression for the pointer operand.
702 /// \p IndexExprs The expressions for the indices.
703 /// \p InBounds Whether the GEP is in bounds.
704 const SCEV *getGEPExpr(Type *PointeeType, const SCEV *BaseExpr,
705 const SmallVectorImpl<const SCEV *> &IndexExprs,
706 bool InBounds = false);
707 const SCEV *getSMaxExpr(const SCEV *LHS, const SCEV *RHS);
708 const SCEV *getSMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
709 const SCEV *getUMaxExpr(const SCEV *LHS, const SCEV *RHS);
710 const SCEV *getUMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
711 const SCEV *getSMinExpr(const SCEV *LHS, const SCEV *RHS);
712 const SCEV *getUMinExpr(const SCEV *LHS, const SCEV *RHS);
713 const SCEV *getUnknown(Value *V);
714 const SCEV *getCouldNotCompute();
716 /// \brief Return a SCEV for the constant 0 of a specific type.
717 const SCEV *getZero(Type *Ty) { return getConstant(Ty, 0); }
719 /// \brief Return a SCEV for the constant 1 of a specific type.
720 const SCEV *getOne(Type *Ty) { return getConstant(Ty, 1); }
722 /// Return an expression for sizeof AllocTy that is type IntTy
724 const SCEV *getSizeOfExpr(Type *IntTy, Type *AllocTy);
726 /// Return an expression for offsetof on the given field with type IntTy
728 const SCEV *getOffsetOfExpr(Type *IntTy, StructType *STy, unsigned FieldNo);
730 /// Return the SCEV object corresponding to -V.
732 const SCEV *getNegativeSCEV(const SCEV *V,
733 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
735 /// Return the SCEV object corresponding to ~V.
737 const SCEV *getNotSCEV(const SCEV *V);
739 /// Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
740 const SCEV *getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
741 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
743 /// Return a SCEV corresponding to a conversion of the input value to the
744 /// specified type. If the type must be extended, it is zero extended.
745 const SCEV *getTruncateOrZeroExtend(const SCEV *V, Type *Ty);
747 /// Return a SCEV corresponding to a conversion of the input value to the
748 /// specified type. If the type must be extended, it is sign extended.
749 const SCEV *getTruncateOrSignExtend(const SCEV *V, Type *Ty);
751 /// Return a SCEV corresponding to a conversion of the input value to the
752 /// specified type. If the type must be extended, it is zero extended. The
753 /// conversion must not be narrowing.
754 const SCEV *getNoopOrZeroExtend(const SCEV *V, Type *Ty);
756 /// Return a SCEV corresponding to a conversion of the input value to the
757 /// specified type. If the type must be extended, it is sign extended. The
758 /// conversion must not be narrowing.
759 const SCEV *getNoopOrSignExtend(const SCEV *V, Type *Ty);
761 /// Return a SCEV corresponding to a conversion of the input value to the
762 /// specified type. If the type must be extended, it is extended with
763 /// unspecified bits. The conversion must not be narrowing.
764 const SCEV *getNoopOrAnyExtend(const SCEV *V, Type *Ty);
766 /// Return a SCEV corresponding to a conversion of the input value to the
767 /// specified type. The conversion must not be widening.
768 const SCEV *getTruncateOrNoop(const SCEV *V, Type *Ty);
770 /// Promote the operands to the wider of the types using zero-extension, and
771 /// then perform a umax operation with them.
772 const SCEV *getUMaxFromMismatchedTypes(const SCEV *LHS,
775 /// Promote the operands to the wider of the types using zero-extension, and
776 /// then perform a umin operation with them.
777 const SCEV *getUMinFromMismatchedTypes(const SCEV *LHS,
780 /// Transitively follow the chain of pointer-type operands until reaching a
781 /// SCEV that does not have a single pointer operand. This returns a
782 /// SCEVUnknown pointer for well-formed pointer-type expressions, but corner
784 const SCEV *getPointerBase(const SCEV *V);
786 /// Return a SCEV expression for the specified value at the specified scope
787 /// in the program. The L value specifies a loop nest to evaluate the
788 /// expression at, where null is the top-level or a specified loop is
789 /// immediately inside of the loop.
791 /// This method can be used to compute the exit value for a variable defined
792 /// in a loop by querying what the value will hold in the parent loop.
794 /// In the case that a relevant loop exit value cannot be computed, the
795 /// original value V is returned.
796 const SCEV *getSCEVAtScope(const SCEV *S, const Loop *L);
798 /// This is a convenience function which does getSCEVAtScope(getSCEV(V), L).
799 const SCEV *getSCEVAtScope(Value *V, const Loop *L);
801 /// Test whether entry to the loop is protected by a conditional between LHS
802 /// and RHS. This is used to help avoid max expressions in loop trip
803 /// counts, and to eliminate casts.
804 bool isLoopEntryGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
805 const SCEV *LHS, const SCEV *RHS);
807 /// Test whether the backedge of the loop is protected by a conditional
808 /// between LHS and RHS. This is used to to eliminate casts.
809 bool isLoopBackedgeGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
810 const SCEV *LHS, const SCEV *RHS);
812 /// \brief Returns the maximum trip count of the loop if it is a single-exit
813 /// loop and we can compute a small maximum for that loop.
815 /// Implemented in terms of the \c getSmallConstantTripCount overload with
816 /// the single exiting block passed to it. See that routine for details.
817 unsigned getSmallConstantTripCount(Loop *L);
819 /// Returns the maximum trip count of this loop as a normal unsigned
820 /// value. Returns 0 if the trip count is unknown or not constant. This
821 /// "trip count" assumes that control exits via ExitingBlock. More
822 /// precisely, it is the number of times that control may reach ExitingBlock
823 /// before taking the branch. For loops with multiple exits, it may not be
824 /// the number times that the loop header executes if the loop exits
825 /// prematurely via another branch.
826 unsigned getSmallConstantTripCount(Loop *L, BasicBlock *ExitingBlock);
828 /// \brief Returns the largest constant divisor of the trip count of the
829 /// loop if it is a single-exit loop and we can compute a small maximum for
832 /// Implemented in terms of the \c getSmallConstantTripMultiple overload with
833 /// the single exiting block passed to it. See that routine for details.
834 unsigned getSmallConstantTripMultiple(Loop *L);
836 /// Returns the largest constant divisor of the trip count of this loop as a
837 /// normal unsigned value, if possible. This means that the actual trip
838 /// count is always a multiple of the returned value (don't forget the trip
839 /// count could very well be zero as well!). As explained in the comments
840 /// for getSmallConstantTripCount, this assumes that control exits the loop
841 /// via ExitingBlock.
842 unsigned getSmallConstantTripMultiple(Loop *L, BasicBlock *ExitingBlock);
844 /// Get the expression for the number of loop iterations for which this loop
845 /// is guaranteed not to exit via ExitingBlock. Otherwise return
846 /// SCEVCouldNotCompute.
847 const SCEV *getExitCount(Loop *L, BasicBlock *ExitingBlock);
849 /// If the specified loop has a predictable backedge-taken count, return it,
850 /// otherwise return a SCEVCouldNotCompute object. The backedge-taken count
851 /// is the number of times the loop header will be branched to from within
852 /// the loop. This is one less than the trip count of the loop, since it
853 /// doesn't count the first iteration, when the header is branched to from
854 /// outside the loop.
856 /// Note that it is not valid to call this method on a loop without a
857 /// loop-invariant backedge-taken count (see
858 /// hasLoopInvariantBackedgeTakenCount).
860 const SCEV *getBackedgeTakenCount(const Loop *L);
862 /// Similar to getBackedgeTakenCount, except return the least SCEV value
863 /// that is known never to be less than the actual backedge taken count.
864 const SCEV *getMaxBackedgeTakenCount(const Loop *L);
866 /// Return true if the specified loop has an analyzable loop-invariant
867 /// backedge-taken count.
868 bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
870 /// This method should be called by the client when it has changed a loop in
871 /// a way that may effect ScalarEvolution's ability to compute a trip count,
872 /// or if the loop is deleted. This call is potentially expensive for large
874 void forgetLoop(const Loop *L);
876 /// This method should be called by the client when it has changed a value
877 /// in a way that may effect its value, or which may disconnect it from a
878 /// def-use chain linking it to a loop.
879 void forgetValue(Value *V);
881 /// \brief Called when the client has changed the disposition of values in
884 /// We don't have a way to invalidate per-loop dispositions. Clear and
885 /// recompute is simpler.
886 void forgetLoopDispositions(const Loop *L) { LoopDispositions.clear(); }
888 /// Determine the minimum number of zero bits that S is guaranteed to end in
889 /// (at every loop iteration). It is, at the same time, the minimum number
890 /// of times S is divisible by 2. For example, given {4,+,8} it returns 2.
891 /// If S is guaranteed to be 0, it returns the bitwidth of S.
892 uint32_t GetMinTrailingZeros(const SCEV *S);
894 /// Determine the unsigned range for a particular SCEV.
896 ConstantRange getUnsignedRange(const SCEV *S) {
897 return getRange(S, HINT_RANGE_UNSIGNED);
900 /// Determine the signed range for a particular SCEV.
902 ConstantRange getSignedRange(const SCEV *S) {
903 return getRange(S, HINT_RANGE_SIGNED);
906 /// Test if the given expression is known to be negative.
908 bool isKnownNegative(const SCEV *S);
910 /// Test if the given expression is known to be positive.
912 bool isKnownPositive(const SCEV *S);
914 /// Test if the given expression is known to be non-negative.
916 bool isKnownNonNegative(const SCEV *S);
918 /// Test if the given expression is known to be non-positive.
920 bool isKnownNonPositive(const SCEV *S);
922 /// Test if the given expression is known to be non-zero.
924 bool isKnownNonZero(const SCEV *S);
926 /// Test if the given expression is known to satisfy the condition described
927 /// by Pred, LHS, and RHS.
929 bool isKnownPredicate(ICmpInst::Predicate Pred,
930 const SCEV *LHS, const SCEV *RHS);
932 /// Return true if the result of the predicate LHS `Pred` RHS is loop
933 /// invariant with respect to L. Set InvariantPred, InvariantLHS and
934 /// InvariantLHS so that InvariantLHS `InvariantPred` InvariantRHS is the
935 /// loop invariant form of LHS `Pred` RHS.
936 bool isLoopInvariantPredicate(ICmpInst::Predicate Pred, const SCEV *LHS,
937 const SCEV *RHS, const Loop *L,
938 ICmpInst::Predicate &InvariantPred,
939 const SCEV *&InvariantLHS,
940 const SCEV *&InvariantRHS);
942 /// Simplify LHS and RHS in a comparison with predicate Pred. Return true
943 /// iff any changes were made. If the operands are provably equal or
944 /// unequal, LHS and RHS are set to the same value and Pred is set to either
945 /// ICMP_EQ or ICMP_NE.
947 bool SimplifyICmpOperands(ICmpInst::Predicate &Pred,
952 /// Return the "disposition" of the given SCEV with respect to the given
954 LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L);
956 /// Return true if the value of the given SCEV is unchanging in the
958 bool isLoopInvariant(const SCEV *S, const Loop *L);
960 /// Return true if the given SCEV changes value in a known way in the
961 /// specified loop. This property being true implies that the value is
962 /// variant in the loop AND that we can emit an expression to compute the
963 /// value of the expression at any particular loop iteration.
964 bool hasComputableLoopEvolution(const SCEV *S, const Loop *L);
966 /// Return the "disposition" of the given SCEV with respect to the given
968 BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB);
970 /// Return true if elements that makes up the given SCEV dominate the
971 /// specified basic block.
972 bool dominates(const SCEV *S, const BasicBlock *BB);
974 /// Return true if elements that makes up the given SCEV properly dominate
975 /// the specified basic block.
976 bool properlyDominates(const SCEV *S, const BasicBlock *BB);
978 /// Test whether the given SCEV has Op as a direct or indirect operand.
979 bool hasOperand(const SCEV *S, const SCEV *Op) const;
981 /// Return the size of an element read or written by Inst.
982 const SCEV *getElementSize(Instruction *Inst);
984 /// Compute the array dimensions Sizes from the set of Terms extracted from
985 /// the memory access function of this SCEVAddRecExpr.
986 void findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
987 SmallVectorImpl<const SCEV *> &Sizes,
988 const SCEV *ElementSize) const;
990 void print(raw_ostream &OS) const;
993 /// Collect parametric terms occurring in step expressions.
994 void collectParametricTerms(const SCEV *Expr,
995 SmallVectorImpl<const SCEV *> &Terms);
999 /// Return in Subscripts the access functions for each dimension in Sizes.
1000 void computeAccessFunctions(const SCEV *Expr,
1001 SmallVectorImpl<const SCEV *> &Subscripts,
1002 SmallVectorImpl<const SCEV *> &Sizes);
1004 /// Split this SCEVAddRecExpr into two vectors of SCEVs representing the
1005 /// subscripts and sizes of an array access.
1007 /// The delinearization is a 3 step process: the first two steps compute the
1008 /// sizes of each subscript and the third step computes the access functions
1009 /// for the delinearized array:
1011 /// 1. Find the terms in the step functions
1012 /// 2. Compute the array size
1013 /// 3. Compute the access function: divide the SCEV by the array size
1014 /// starting with the innermost dimensions found in step 2. The Quotient
1015 /// is the SCEV to be divided in the next step of the recursion. The
1016 /// Remainder is the subscript of the innermost dimension. Loop over all
1017 /// array dimensions computed in step 2.
1019 /// To compute a uniform array size for several memory accesses to the same
1020 /// object, one can collect in step 1 all the step terms for all the memory
1021 /// accesses, and compute in step 2 a unique array shape. This guarantees
1022 /// that the array shape will be the same across all memory accesses.
1024 /// FIXME: We could derive the result of steps 1 and 2 from a description of
1025 /// the array shape given in metadata.
1034 /// A[j+k][2i][5i] =
1036 /// The initial SCEV:
1038 /// A[{{{0,+,2*m+5}_i, +, n*m}_j, +, n*m}_k]
1040 /// 1. Find the different terms in the step functions:
1041 /// -> [2*m, 5, n*m, n*m]
1043 /// 2. Compute the array size: sort and unique them
1044 /// -> [n*m, 2*m, 5]
1045 /// find the GCD of all the terms = 1
1046 /// divide by the GCD and erase constant terms
1049 /// divide by GCD -> [n, 2]
1050 /// remove constant terms
1052 /// size of the array is A[unknown][n][m]
1054 /// 3. Compute the access function
1055 /// a. Divide {{{0,+,2*m+5}_i, +, n*m}_j, +, n*m}_k by the innermost size m
1056 /// Quotient: {{{0,+,2}_i, +, n}_j, +, n}_k
1057 /// Remainder: {{{0,+,5}_i, +, 0}_j, +, 0}_k
1058 /// The remainder is the subscript of the innermost array dimension: [5i].
1060 /// b. Divide Quotient: {{{0,+,2}_i, +, n}_j, +, n}_k by next outer size n
1061 /// Quotient: {{{0,+,0}_i, +, 1}_j, +, 1}_k
1062 /// Remainder: {{{0,+,2}_i, +, 0}_j, +, 0}_k
1063 /// The Remainder is the subscript of the next array dimension: [2i].
1065 /// The subscript of the outermost dimension is the Quotient: [j+k].
1067 /// Overall, we have: A[][n][m], and the access function: A[j+k][2i][5i].
1068 void delinearize(const SCEV *Expr,
1069 SmallVectorImpl<const SCEV *> &Subscripts,
1070 SmallVectorImpl<const SCEV *> &Sizes,
1071 const SCEV *ElementSize);
1074 /// Compute the backedge taken count knowing the interval difference, the
1075 /// stride and presence of the equality in the comparison.
1076 const SCEV *computeBECount(const SCEV *Delta, const SCEV *Stride,
1079 /// Verify if an linear IV with positive stride can overflow when in a
1080 /// less-than comparison, knowing the invariant term of the comparison,
1081 /// the stride and the knowledge of NSW/NUW flags on the recurrence.
1082 bool doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
1083 bool IsSigned, bool NoWrap);
1085 /// Verify if an linear IV with negative stride can overflow when in a
1086 /// greater-than comparison, knowing the invariant term of the comparison,
1087 /// the stride and the knowledge of NSW/NUW flags on the recurrence.
1088 bool doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
1089 bool IsSigned, bool NoWrap);
1092 FoldingSet<SCEV> UniqueSCEVs;
1093 BumpPtrAllocator SCEVAllocator;
1095 /// The head of a linked list of all SCEVUnknown values that have been
1096 /// allocated. This is used by releaseMemory to locate them all and call
1097 /// their destructors.
1098 SCEVUnknown *FirstUnknown;
1101 /// \brief Analysis pass that exposes the \c ScalarEvolution for a function.
1102 class ScalarEvolutionAnalysis {
1106 typedef ScalarEvolution Result;
1108 /// \brief Opaque, unique identifier for this analysis pass.
1109 static void *ID() { return (void *)&PassID; }
1111 /// \brief Provide a name for the analysis for debugging and logging.
1112 static StringRef name() { return "ScalarEvolutionAnalysis"; }
1114 ScalarEvolution run(Function &F, AnalysisManager<Function> *AM);
1117 /// \brief Printer pass for the \c ScalarEvolutionAnalysis results.
1118 class ScalarEvolutionPrinterPass {
1122 explicit ScalarEvolutionPrinterPass(raw_ostream &OS) : OS(OS) {}
1123 PreservedAnalyses run(Function &F, AnalysisManager<Function> *AM);
1125 static StringRef name() { return "ScalarEvolutionPrinterPass"; }
1128 class ScalarEvolutionWrapperPass : public FunctionPass {
1129 std::unique_ptr<ScalarEvolution> SE;
1134 ScalarEvolutionWrapperPass();
1136 ScalarEvolution &getSE() { return *SE; }
1137 const ScalarEvolution &getSE() const { return *SE; }
1139 bool runOnFunction(Function &F) override;
1140 void releaseMemory() override;
1141 void getAnalysisUsage(AnalysisUsage &AU) const override;
1142 void print(raw_ostream &OS, const Module * = nullptr) const override;
1143 void verifyAnalysis() const override;