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/ValueHandle.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Support/Allocator.h"
33 #include "llvm/Support/DataTypes.h"
38 class AssumptionCache;
43 class ScalarEvolution;
45 class TargetLibraryInfo;
52 template<> struct FoldingSetTrait<SCEV>;
54 /// SCEV - This class represents an analyzed expression in the program. These
55 /// are opaque objects that the client is not allowed to do much with
58 class SCEV : public FoldingSetNode {
59 friend struct FoldingSetTrait<SCEV>;
61 /// FastID - A reference to an Interned FoldingSetNodeID for this node.
62 /// The ScalarEvolution's BumpPtrAllocator holds the data.
63 FoldingSetNodeIDRef FastID;
65 // The SCEV baseclass this node corresponds to
66 const unsigned short SCEVType;
69 /// SubclassData - This field is initialized to zero and may be used in
70 /// subclasses to store miscellaneous information.
71 unsigned short SubclassData;
74 SCEV(const SCEV &) = delete;
75 void operator=(const SCEV &) = delete;
78 /// NoWrapFlags are bitfield indices into SubclassData.
80 /// Add and Mul expressions may have no-unsigned-wrap <NUW> or
81 /// no-signed-wrap <NSW> properties, which are derived from the IR
82 /// operator. NSW is a misnomer that we use to mean no signed overflow or
85 /// AddRec expressions may have a no-self-wraparound <NW> property if, in
86 /// the integer domain, abs(step) * max-iteration(loop) <=
87 /// unsigned-max(bitwidth). This means that the recurrence will never reach
88 /// its start value if the step is non-zero. Computing the same value on
89 /// each iteration is not considered wrapping, and recurrences with step = 0
90 /// are trivially <NW>. <NW> is independent of the sign of step and the
91 /// value the add recurrence starts with.
93 /// Note that NUW and NSW are also valid properties of a recurrence, and
94 /// either implies NW. For convenience, NW will be set for a recurrence
95 /// whenever either NUW or NSW are set.
96 enum NoWrapFlags { FlagAnyWrap = 0, // No guarantee.
97 FlagNW = (1 << 0), // No self-wrap.
98 FlagNUW = (1 << 1), // No unsigned wrap.
99 FlagNSW = (1 << 2), // No signed wrap.
100 NoWrapMask = (1 << 3) -1 };
102 explicit SCEV(const FoldingSetNodeIDRef ID, unsigned SCEVTy) :
103 FastID(ID), SCEVType(SCEVTy), SubclassData(0) {}
105 unsigned getSCEVType() const { return SCEVType; }
107 /// getType - Return the LLVM type of this SCEV expression.
109 Type *getType() const;
111 /// isZero - Return true if the expression is a constant zero.
115 /// isOne - Return true if the expression is a constant one.
119 /// isAllOnesValue - Return true if the expression is a constant
122 bool isAllOnesValue() const;
124 /// isNonConstantNegative - Return true if the specified scev is negated,
125 /// but not a constant.
126 bool isNonConstantNegative() const;
128 /// print - Print out the internal representation of this scalar to the
129 /// specified stream. This should really only be used for debugging
131 void print(raw_ostream &OS) const;
133 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
134 /// dump - This method is used for debugging.
140 // Specialize FoldingSetTrait for SCEV to avoid needing to compute
141 // temporary FoldingSetNodeID values.
142 template<> struct FoldingSetTrait<SCEV> : DefaultFoldingSetTrait<SCEV> {
143 static void Profile(const SCEV &X, FoldingSetNodeID& ID) {
146 static bool Equals(const SCEV &X, const FoldingSetNodeID &ID,
147 unsigned IDHash, FoldingSetNodeID &TempID) {
148 return ID == X.FastID;
150 static unsigned ComputeHash(const SCEV &X, FoldingSetNodeID &TempID) {
151 return X.FastID.ComputeHash();
155 inline raw_ostream &operator<<(raw_ostream &OS, const SCEV &S) {
160 /// SCEVCouldNotCompute - An object of this class is returned by queries that
161 /// could not be answered. For example, if you ask for the number of
162 /// iterations of a linked-list traversal loop, you will get one of these.
163 /// None of the standard SCEV operations are valid on this class, it is just a
165 struct SCEVCouldNotCompute : public SCEV {
166 SCEVCouldNotCompute();
168 /// Methods for support type inquiry through isa, cast, and dyn_cast:
169 static bool classof(const SCEV *S);
172 /// ScalarEvolution - This class is the main scalar evolution driver. Because
173 /// client code (intentionally) can't do much with the SCEV objects directly,
174 /// they must ask this class for services.
176 class ScalarEvolution : public FunctionPass {
178 /// LoopDisposition - An enum describing the relationship between a
180 enum LoopDisposition {
181 LoopVariant, ///< The SCEV is loop-variant (unknown).
182 LoopInvariant, ///< The SCEV is loop-invariant.
183 LoopComputable ///< The SCEV varies predictably with the loop.
186 /// BlockDisposition - An enum describing the relationship between a
187 /// SCEV and a basic block.
188 enum BlockDisposition {
189 DoesNotDominateBlock, ///< The SCEV does not dominate the block.
190 DominatesBlock, ///< The SCEV dominates the block.
191 ProperlyDominatesBlock ///< The SCEV properly dominates the block.
194 /// Convenient NoWrapFlags manipulation that hides enum casts and is
195 /// visible in the ScalarEvolution name space.
196 static SCEV::NoWrapFlags LLVM_ATTRIBUTE_UNUSED_RESULT
197 maskFlags(SCEV::NoWrapFlags Flags, int Mask) {
198 return (SCEV::NoWrapFlags)(Flags & Mask);
200 static SCEV::NoWrapFlags LLVM_ATTRIBUTE_UNUSED_RESULT
201 setFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OnFlags) {
202 return (SCEV::NoWrapFlags)(Flags | OnFlags);
204 static SCEV::NoWrapFlags LLVM_ATTRIBUTE_UNUSED_RESULT
205 clearFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OffFlags) {
206 return (SCEV::NoWrapFlags)(Flags & ~OffFlags);
210 /// SCEVCallbackVH - A CallbackVH to arrange for ScalarEvolution to be
211 /// notified whenever a Value is deleted.
212 class SCEVCallbackVH : public CallbackVH {
214 void deleted() override;
215 void allUsesReplacedWith(Value *New) override;
217 SCEVCallbackVH(Value *V, ScalarEvolution *SE = nullptr);
220 friend class SCEVCallbackVH;
221 friend class SCEVExpander;
222 friend class SCEVUnknown;
224 /// F - The function we are analyzing.
228 /// The tracker for @llvm.assume intrinsics in this function.
231 /// LI - The loop information for the function we are currently analyzing.
235 /// The DataLayout information for the target we are targeting.
237 const DataLayout *DL;
239 /// TLI - The target library information for the target we are targeting.
241 TargetLibraryInfo *TLI;
243 /// DT - The dominator tree.
247 /// CouldNotCompute - This SCEV is used to represent unknown trip
248 /// counts and things.
249 SCEVCouldNotCompute CouldNotCompute;
251 /// ValueExprMapType - The typedef for ValueExprMap.
253 typedef DenseMap<SCEVCallbackVH, const SCEV *, DenseMapInfo<Value *> >
256 /// ValueExprMap - This is a cache of the values we have analyzed so far.
258 ValueExprMapType ValueExprMap;
260 /// Mark predicate values currently being processed by isImpliedCond.
261 DenseSet<Value*> PendingLoopPredicates;
263 /// ExitLimit - Information about the number of loop iterations for which a
264 /// loop exit's branch condition evaluates to the not-taken path. This is a
265 /// temporary pair of exact and max expressions that are eventually
266 /// summarized in ExitNotTakenInfo and BackedgeTakenInfo.
271 /*implicit*/ ExitLimit(const SCEV *E) : Exact(E), Max(E) {}
273 ExitLimit(const SCEV *E, const SCEV *M) : Exact(E), Max(M) {}
275 /// hasAnyInfo - Test whether this ExitLimit contains any computed
276 /// information, or whether it's all SCEVCouldNotCompute values.
277 bool hasAnyInfo() const {
278 return !isa<SCEVCouldNotCompute>(Exact) ||
279 !isa<SCEVCouldNotCompute>(Max);
283 /// ExitNotTakenInfo - Information about the number of times a particular
284 /// loop exit may be reached before exiting the loop.
285 struct ExitNotTakenInfo {
286 AssertingVH<BasicBlock> ExitingBlock;
287 const SCEV *ExactNotTaken;
288 PointerIntPair<ExitNotTakenInfo*, 1> NextExit;
290 ExitNotTakenInfo() : ExitingBlock(nullptr), ExactNotTaken(nullptr) {}
292 /// isCompleteList - Return true if all loop exits are computable.
293 bool isCompleteList() const {
294 return NextExit.getInt() == 0;
297 void setIncomplete() { NextExit.setInt(1); }
299 /// getNextExit - Return a pointer to the next exit's not-taken info.
300 ExitNotTakenInfo *getNextExit() const {
301 return NextExit.getPointer();
304 void setNextExit(ExitNotTakenInfo *ENT) { NextExit.setPointer(ENT); }
307 /// BackedgeTakenInfo - Information about the backedge-taken count
308 /// of a loop. This currently includes an exact count and a maximum count.
310 class BackedgeTakenInfo {
311 /// ExitNotTaken - A list of computable exits and their not-taken counts.
312 /// Loops almost never have more than one computable exit.
313 ExitNotTakenInfo ExitNotTaken;
315 /// Max - An expression indicating the least maximum backedge-taken
316 /// count of the loop that is known, or a SCEVCouldNotCompute.
320 BackedgeTakenInfo() : Max(nullptr) {}
322 /// Initialize BackedgeTakenInfo from a list of exact exit counts.
324 SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts,
325 bool Complete, const SCEV *MaxCount);
327 /// hasAnyInfo - Test whether this BackedgeTakenInfo contains any
328 /// computed information, or whether it's all SCEVCouldNotCompute
330 bool hasAnyInfo() const {
331 return ExitNotTaken.ExitingBlock || !isa<SCEVCouldNotCompute>(Max);
334 /// getExact - Return an expression indicating the exact backedge-taken
335 /// count of the loop if it is known, or SCEVCouldNotCompute
336 /// otherwise. This is the number of times the loop header can be
337 /// guaranteed to execute, minus one.
338 const SCEV *getExact(ScalarEvolution *SE) const;
340 /// getExact - Return the number of times this loop exit may fall through
341 /// to the back edge, or SCEVCouldNotCompute. The loop is guaranteed not
342 /// to exit via this block before this number of iterations, but may exit
343 /// via another block.
344 const SCEV *getExact(BasicBlock *ExitingBlock, ScalarEvolution *SE) const;
346 /// getMax - Get the max backedge taken count for the loop.
347 const SCEV *getMax(ScalarEvolution *SE) const;
349 /// Return true if any backedge taken count expressions refer to the given
351 bool hasOperand(const SCEV *S, ScalarEvolution *SE) const;
353 /// clear - Invalidate this result and free associated memory.
357 /// BackedgeTakenCounts - Cache the backedge-taken count of the loops for
358 /// this function as they are computed.
359 DenseMap<const Loop*, BackedgeTakenInfo> BackedgeTakenCounts;
361 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
362 /// the PHI instructions that we attempt to compute constant evolutions for.
363 /// This allows us to avoid potentially expensive recomputation of these
364 /// properties. An instruction maps to null if we are unable to compute its
366 DenseMap<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
368 /// ValuesAtScopes - This map contains entries for all the expressions
369 /// that we attempt to compute getSCEVAtScope information for, which can
370 /// be expensive in extreme cases.
371 DenseMap<const SCEV *,
372 SmallVector<std::pair<const Loop *, const SCEV *>, 2> > ValuesAtScopes;
374 /// LoopDispositions - Memoized computeLoopDisposition results.
375 DenseMap<const SCEV *,
376 SmallVector<PointerIntPair<const Loop *, 2, LoopDisposition>, 2>>
379 /// computeLoopDisposition - Compute a LoopDisposition value.
380 LoopDisposition computeLoopDisposition(const SCEV *S, const Loop *L);
382 /// BlockDispositions - Memoized computeBlockDisposition results.
385 SmallVector<PointerIntPair<const BasicBlock *, 2, BlockDisposition>, 2>>
388 /// computeBlockDisposition - Compute a BlockDisposition value.
389 BlockDisposition computeBlockDisposition(const SCEV *S, const BasicBlock *BB);
391 /// UnsignedRanges - Memoized results from getUnsignedRange
392 DenseMap<const SCEV *, ConstantRange> UnsignedRanges;
394 /// SignedRanges - Memoized results from getSignedRange
395 DenseMap<const SCEV *, ConstantRange> SignedRanges;
397 /// setUnsignedRange - Set the memoized unsigned range for the given SCEV.
398 const ConstantRange &setUnsignedRange(const SCEV *S,
399 const ConstantRange &CR) {
400 std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair =
401 UnsignedRanges.insert(std::make_pair(S, CR));
403 Pair.first->second = CR;
404 return Pair.first->second;
407 /// setUnsignedRange - Set the memoized signed range for the given SCEV.
408 const ConstantRange &setSignedRange(const SCEV *S,
409 const ConstantRange &CR) {
410 std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair =
411 SignedRanges.insert(std::make_pair(S, CR));
413 Pair.first->second = CR;
414 return Pair.first->second;
417 /// createSCEV - We know that there is no SCEV for the specified value.
418 /// Analyze the expression.
419 const SCEV *createSCEV(Value *V);
421 /// createNodeForPHI - Provide the special handling we need to analyze PHI
423 const SCEV *createNodeForPHI(PHINode *PN);
425 /// createNodeForGEP - Provide the special handling we need to analyze GEP
427 const SCEV *createNodeForGEP(GEPOperator *GEP);
429 /// computeSCEVAtScope - Implementation code for getSCEVAtScope; called
430 /// at most once for each SCEV+Loop pair.
432 const SCEV *computeSCEVAtScope(const SCEV *S, const Loop *L);
434 /// ForgetSymbolicValue - This looks up computed SCEV values for all
435 /// instructions that depend on the given instruction and removes them from
436 /// the ValueExprMap map if they reference SymName. This is used during PHI
438 void ForgetSymbolicName(Instruction *I, const SCEV *SymName);
440 /// getBackedgeTakenInfo - Return the BackedgeTakenInfo for the given
441 /// loop, lazily computing new values if the loop hasn't been analyzed
443 const BackedgeTakenInfo &getBackedgeTakenInfo(const Loop *L);
445 /// ComputeBackedgeTakenCount - Compute the number of times the specified
446 /// loop will iterate.
447 BackedgeTakenInfo ComputeBackedgeTakenCount(const Loop *L);
449 /// ComputeExitLimit - Compute the number of times the backedge of the
450 /// specified loop will execute if it exits via the specified block.
451 ExitLimit ComputeExitLimit(const Loop *L, BasicBlock *ExitingBlock);
453 /// ComputeExitLimitFromCond - Compute the number of times the backedge of
454 /// the specified loop will execute if its exit condition were a conditional
455 /// branch of ExitCond, TBB, and FBB.
456 ExitLimit ComputeExitLimitFromCond(const Loop *L,
462 /// ComputeExitLimitFromICmp - Compute the number of times the backedge of
463 /// the specified loop will execute if its exit condition were a conditional
464 /// branch of the ICmpInst ExitCond, TBB, and FBB.
465 ExitLimit ComputeExitLimitFromICmp(const Loop *L,
471 /// ComputeExitLimitFromSingleExitSwitch - Compute the number of times the
472 /// backedge of the specified loop will execute if its exit condition were a
473 /// switch with a single exiting case to ExitingBB.
475 ComputeExitLimitFromSingleExitSwitch(const Loop *L, SwitchInst *Switch,
476 BasicBlock *ExitingBB, bool IsSubExpr);
478 /// ComputeLoadConstantCompareExitLimit - Given an exit condition
479 /// of 'icmp op load X, cst', try to see if we can compute the
480 /// backedge-taken count.
481 ExitLimit ComputeLoadConstantCompareExitLimit(LoadInst *LI,
484 ICmpInst::Predicate p);
486 /// ComputeExitCountExhaustively - If the loop is known to execute a
487 /// constant number of times (the condition evolves only from constants),
488 /// try to evaluate a few iterations of the loop until we get the exit
489 /// condition gets a value of ExitWhen (true or false). If we cannot
490 /// evaluate the exit count of the loop, return CouldNotCompute.
491 const SCEV *ComputeExitCountExhaustively(const Loop *L,
495 /// HowFarToZero - Return the number of times an exit condition comparing
496 /// the specified value to zero will execute. If not computable, return
498 ExitLimit HowFarToZero(const SCEV *V, const Loop *L, bool IsSubExpr);
500 /// HowFarToNonZero - Return the number of times an exit condition checking
501 /// the specified value for nonzero will execute. If not computable, return
503 ExitLimit HowFarToNonZero(const SCEV *V, const Loop *L);
505 /// HowManyLessThans - Return the number of times an exit condition
506 /// containing the specified less-than comparison will execute. If not
507 /// computable, return CouldNotCompute. isSigned specifies whether the
508 /// less-than is signed.
509 ExitLimit HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
510 const Loop *L, bool isSigned, bool IsSubExpr);
511 ExitLimit HowManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
512 const Loop *L, bool isSigned, bool IsSubExpr);
514 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
515 /// (which may not be an immediate predecessor) which has exactly one
516 /// successor from which BB is reachable, or null if no such block is
518 std::pair<BasicBlock *, BasicBlock *>
519 getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
521 /// isImpliedCond - Test whether the condition described by Pred, LHS, and
522 /// RHS is true whenever the given FoundCondValue value evaluates to true.
523 bool isImpliedCond(ICmpInst::Predicate Pred,
524 const SCEV *LHS, const SCEV *RHS,
525 Value *FoundCondValue,
528 /// isImpliedCondOperands - Test whether the condition described by Pred,
529 /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
530 /// and FoundRHS is true.
531 bool isImpliedCondOperands(ICmpInst::Predicate Pred,
532 const SCEV *LHS, const SCEV *RHS,
533 const SCEV *FoundLHS, const SCEV *FoundRHS);
535 /// isImpliedCondOperandsHelper - Test whether the condition described by
536 /// Pred, LHS, and RHS is true whenever the condition described by Pred,
537 /// FoundLHS, and FoundRHS is true.
538 bool isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
539 const SCEV *LHS, const SCEV *RHS,
540 const SCEV *FoundLHS,
541 const SCEV *FoundRHS);
543 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
544 /// in the header of its containing loop, we know the loop executes a
545 /// constant number of times, and the PHI node is just a recurrence
546 /// involving constants, fold it.
547 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs,
550 /// isKnownPredicateWithRanges - Test if the given expression is known to
551 /// satisfy the condition described by Pred and the known constant ranges
554 bool isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
555 const SCEV *LHS, const SCEV *RHS);
557 /// forgetMemoizedResults - Drop memoized information computed for S.
558 void forgetMemoizedResults(const SCEV *S);
560 /// Return false iff given SCEV contains a SCEVUnknown with NULL value-
562 bool checkValidity(const SCEV *S) const;
565 static char ID; // Pass identification, replacement for typeid
568 LLVMContext &getContext() const { return F->getContext(); }
570 /// isSCEVable - Test if values of the given type are analyzable within
571 /// the SCEV framework. This primarily includes integer types, and it
572 /// can optionally include pointer types if the ScalarEvolution class
573 /// has access to target-specific information.
574 bool isSCEVable(Type *Ty) const;
576 /// getTypeSizeInBits - Return the size in bits of the specified type,
577 /// for which isSCEVable must return true.
578 uint64_t getTypeSizeInBits(Type *Ty) const;
580 /// getEffectiveSCEVType - Return a type with the same bitwidth as
581 /// the given type and which represents how SCEV will treat the given
582 /// type, for which isSCEVable must return true. For pointer types,
583 /// this is the pointer-sized integer type.
584 Type *getEffectiveSCEVType(Type *Ty) const;
586 /// getSCEV - Return a SCEV expression for the full generality of the
587 /// specified expression.
588 const SCEV *getSCEV(Value *V);
590 const SCEV *getConstant(ConstantInt *V);
591 const SCEV *getConstant(const APInt& Val);
592 const SCEV *getConstant(Type *Ty, uint64_t V, bool isSigned = false);
593 const SCEV *getTruncateExpr(const SCEV *Op, Type *Ty);
594 const SCEV *getZeroExtendExpr(const SCEV *Op, Type *Ty);
595 const SCEV *getSignExtendExpr(const SCEV *Op, Type *Ty);
596 const SCEV *getAnyExtendExpr(const SCEV *Op, Type *Ty);
597 const SCEV *getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
598 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
599 const SCEV *getAddExpr(const SCEV *LHS, const SCEV *RHS,
600 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
601 SmallVector<const SCEV *, 2> Ops;
604 return getAddExpr(Ops, Flags);
606 const SCEV *getAddExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
607 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
608 SmallVector<const SCEV *, 3> Ops;
612 return getAddExpr(Ops, Flags);
614 const SCEV *getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
615 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
616 const SCEV *getMulExpr(const SCEV *LHS, const SCEV *RHS,
617 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap)
619 SmallVector<const SCEV *, 2> Ops;
622 return getMulExpr(Ops, Flags);
624 const SCEV *getMulExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
625 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
626 SmallVector<const SCEV *, 3> Ops;
630 return getMulExpr(Ops, Flags);
632 const SCEV *getUDivExpr(const SCEV *LHS, const SCEV *RHS);
633 const SCEV *getUDivExactExpr(const SCEV *LHS, const SCEV *RHS);
634 const SCEV *getAddRecExpr(const SCEV *Start, const SCEV *Step,
635 const Loop *L, SCEV::NoWrapFlags Flags);
636 const SCEV *getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
637 const Loop *L, SCEV::NoWrapFlags Flags);
638 const SCEV *getAddRecExpr(const SmallVectorImpl<const SCEV *> &Operands,
639 const Loop *L, SCEV::NoWrapFlags Flags) {
640 SmallVector<const SCEV *, 4> NewOp(Operands.begin(), Operands.end());
641 return getAddRecExpr(NewOp, L, Flags);
643 const SCEV *getSMaxExpr(const SCEV *LHS, const SCEV *RHS);
644 const SCEV *getSMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
645 const SCEV *getUMaxExpr(const SCEV *LHS, const SCEV *RHS);
646 const SCEV *getUMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
647 const SCEV *getSMinExpr(const SCEV *LHS, const SCEV *RHS);
648 const SCEV *getUMinExpr(const SCEV *LHS, const SCEV *RHS);
649 const SCEV *getUnknown(Value *V);
650 const SCEV *getCouldNotCompute();
652 /// getSizeOfExpr - Return an expression for sizeof AllocTy that is type
655 const SCEV *getSizeOfExpr(Type *IntTy, Type *AllocTy);
657 /// getOffsetOfExpr - Return an expression for offsetof on the given field
660 const SCEV *getOffsetOfExpr(Type *IntTy, StructType *STy, unsigned FieldNo);
662 /// getNegativeSCEV - Return the SCEV object corresponding to -V.
664 const SCEV *getNegativeSCEV(const SCEV *V);
666 /// getNotSCEV - Return the SCEV object corresponding to ~V.
668 const SCEV *getNotSCEV(const SCEV *V);
670 /// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
671 const SCEV *getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
672 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
674 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
675 /// of the input value to the specified type. If the type must be
676 /// extended, it is zero extended.
677 const SCEV *getTruncateOrZeroExtend(const SCEV *V, Type *Ty);
679 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
680 /// of the input value to the specified type. If the type must be
681 /// extended, it is sign extended.
682 const SCEV *getTruncateOrSignExtend(const SCEV *V, Type *Ty);
684 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of
685 /// the input value to the specified type. If the type must be extended,
686 /// it is zero extended. The conversion must not be narrowing.
687 const SCEV *getNoopOrZeroExtend(const SCEV *V, Type *Ty);
689 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of
690 /// the input value to the specified type. If the type must be extended,
691 /// it is sign extended. The conversion must not be narrowing.
692 const SCEV *getNoopOrSignExtend(const SCEV *V, Type *Ty);
694 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
695 /// the input value to the specified type. If the type must be extended,
696 /// it is extended with unspecified bits. The conversion must not be
698 const SCEV *getNoopOrAnyExtend(const SCEV *V, Type *Ty);
700 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
701 /// input value to the specified type. The conversion must not be
703 const SCEV *getTruncateOrNoop(const SCEV *V, Type *Ty);
705 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
706 /// the types using zero-extension, and then perform a umax operation
708 const SCEV *getUMaxFromMismatchedTypes(const SCEV *LHS,
711 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
712 /// the types using zero-extension, and then perform a umin operation
714 const SCEV *getUMinFromMismatchedTypes(const SCEV *LHS,
717 /// getPointerBase - Transitively follow the chain of pointer-type operands
718 /// until reaching a SCEV that does not have a single pointer operand. This
719 /// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
720 /// but corner cases do exist.
721 const SCEV *getPointerBase(const SCEV *V);
723 /// getSCEVAtScope - Return a SCEV expression for the specified value
724 /// at the specified scope in the program. The L value specifies a loop
725 /// nest to evaluate the expression at, where null is the top-level or a
726 /// specified loop is immediately inside of the loop.
728 /// This method can be used to compute the exit value for a variable defined
729 /// in a loop by querying what the value will hold in the parent loop.
731 /// In the case that a relevant loop exit value cannot be computed, the
732 /// original value V is returned.
733 const SCEV *getSCEVAtScope(const SCEV *S, const Loop *L);
735 /// getSCEVAtScope - This is a convenience function which does
736 /// getSCEVAtScope(getSCEV(V), L).
737 const SCEV *getSCEVAtScope(Value *V, const Loop *L);
739 /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
740 /// by a conditional between LHS and RHS. This is used to help avoid max
741 /// expressions in loop trip counts, and to eliminate casts.
742 bool isLoopEntryGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
743 const SCEV *LHS, const SCEV *RHS);
745 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
746 /// protected by a conditional between LHS and RHS. This is used to
747 /// to eliminate casts.
748 bool isLoopBackedgeGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
749 const SCEV *LHS, const SCEV *RHS);
751 /// \brief Returns the maximum trip count of the loop if it is a single-exit
752 /// loop and we can compute a small maximum for that loop.
754 /// Implemented in terms of the \c getSmallConstantTripCount overload with
755 /// the single exiting block passed to it. See that routine for details.
756 unsigned getSmallConstantTripCount(Loop *L);
758 /// getSmallConstantTripCount - Returns the maximum trip count of this loop
759 /// as a normal unsigned value. Returns 0 if the trip count is unknown or
760 /// not constant. This "trip count" assumes that control exits via
761 /// ExitingBlock. More precisely, it is the number of times that control may
762 /// reach ExitingBlock before taking the branch. For loops with multiple
763 /// exits, it may not be the number times that the loop header executes if
764 /// the loop exits prematurely via another branch.
765 unsigned getSmallConstantTripCount(Loop *L, BasicBlock *ExitingBlock);
767 /// \brief Returns the largest constant divisor of the trip count of the
768 /// loop if it is a single-exit loop and we can compute a small maximum for
771 /// Implemented in terms of the \c getSmallConstantTripMultiple overload with
772 /// the single exiting block passed to it. See that routine for details.
773 unsigned getSmallConstantTripMultiple(Loop *L);
775 /// getSmallConstantTripMultiple - Returns the largest constant divisor of
776 /// the trip count of this loop as a normal unsigned value, if
777 /// possible. This means that the actual trip count is always a multiple of
778 /// the returned value (don't forget the trip count could very well be zero
779 /// as well!). As explained in the comments for getSmallConstantTripCount,
780 /// this assumes that control exits the loop via ExitingBlock.
781 unsigned getSmallConstantTripMultiple(Loop *L, BasicBlock *ExitingBlock);
783 // getExitCount - Get the expression for the number of loop iterations for
784 // which this loop is guaranteed not to exit via ExitingBlock. Otherwise
785 // return SCEVCouldNotCompute.
786 const SCEV *getExitCount(Loop *L, BasicBlock *ExitingBlock);
788 /// getBackedgeTakenCount - If the specified loop has a predictable
789 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
790 /// object. The backedge-taken count is the number of times the loop header
791 /// will be branched to from within the loop. This is one less than the
792 /// trip count of the loop, since it doesn't count the first iteration,
793 /// when the header is branched to from outside the loop.
795 /// Note that it is not valid to call this method on a loop without a
796 /// loop-invariant backedge-taken count (see
797 /// hasLoopInvariantBackedgeTakenCount).
799 const SCEV *getBackedgeTakenCount(const Loop *L);
801 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
802 /// return the least SCEV value that is known never to be less than the
803 /// actual backedge taken count.
804 const SCEV *getMaxBackedgeTakenCount(const Loop *L);
806 /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop
807 /// has an analyzable loop-invariant backedge-taken count.
808 bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
810 /// forgetLoop - This method should be called by the client when it has
811 /// changed a loop in a way that may effect ScalarEvolution's ability to
812 /// compute a trip count, or if the loop is deleted. This call is
813 /// potentially expensive for large loop bodies.
814 void forgetLoop(const Loop *L);
816 /// forgetValue - This method should be called by the client when it has
817 /// changed a value in a way that may effect its value, or which may
818 /// disconnect it from a def-use chain linking it to a loop.
819 void forgetValue(Value *V);
821 /// \brief Called when the client has changed the disposition of values in
824 /// We don't have a way to invalidate per-loop dispositions. Clear and
825 /// recompute is simpler.
826 void forgetLoopDispositions(const Loop *L) { LoopDispositions.clear(); }
828 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S
829 /// is guaranteed to end in (at every loop iteration). It is, at the same
830 /// time, the minimum number of times S is divisible by 2. For example,
831 /// given {4,+,8} it returns 2. If S is guaranteed to be 0, it returns the
833 uint32_t GetMinTrailingZeros(const SCEV *S);
835 /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
837 ConstantRange getUnsignedRange(const SCEV *S);
839 /// getSignedRange - Determine the signed range for a particular SCEV.
841 ConstantRange getSignedRange(const SCEV *S);
843 /// isKnownNegative - Test if the given expression is known to be negative.
845 bool isKnownNegative(const SCEV *S);
847 /// isKnownPositive - Test if the given expression is known to be positive.
849 bool isKnownPositive(const SCEV *S);
851 /// isKnownNonNegative - Test if the given expression is known to be
854 bool isKnownNonNegative(const SCEV *S);
856 /// isKnownNonPositive - Test if the given expression is known to be
859 bool isKnownNonPositive(const SCEV *S);
861 /// isKnownNonZero - Test if the given expression is known to be
864 bool isKnownNonZero(const SCEV *S);
866 /// isKnownPredicate - Test if the given expression is known to satisfy
867 /// the condition described by Pred, LHS, and RHS.
869 bool isKnownPredicate(ICmpInst::Predicate Pred,
870 const SCEV *LHS, const SCEV *RHS);
872 /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
873 /// predicate Pred. Return true iff any changes were made. If the
874 /// operands are provably equal or unequal, LHS and RHS are set to
875 /// the same value and Pred is set to either ICMP_EQ or ICMP_NE.
877 bool SimplifyICmpOperands(ICmpInst::Predicate &Pred,
882 /// getLoopDisposition - Return the "disposition" of the given SCEV with
883 /// respect to the given loop.
884 LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L);
886 /// isLoopInvariant - Return true if the value of the given SCEV is
887 /// unchanging in the specified loop.
888 bool isLoopInvariant(const SCEV *S, const Loop *L);
890 /// hasComputableLoopEvolution - Return true if the given SCEV changes value
891 /// in a known way in the specified loop. This property being true implies
892 /// that the value is variant in the loop AND that we can emit an expression
893 /// to compute the value of the expression at any particular loop iteration.
894 bool hasComputableLoopEvolution(const SCEV *S, const Loop *L);
896 /// getLoopDisposition - Return the "disposition" of the given SCEV with
897 /// respect to the given block.
898 BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB);
900 /// dominates - Return true if elements that makes up the given SCEV
901 /// dominate the specified basic block.
902 bool dominates(const SCEV *S, const BasicBlock *BB);
904 /// properlyDominates - Return true if elements that makes up the given SCEV
905 /// properly dominate the specified basic block.
906 bool properlyDominates(const SCEV *S, const BasicBlock *BB);
908 /// hasOperand - Test whether the given SCEV has Op as a direct or
909 /// indirect operand.
910 bool hasOperand(const SCEV *S, const SCEV *Op) const;
912 /// Return the size of an element read or written by Inst.
913 const SCEV *getElementSize(Instruction *Inst);
915 /// Compute the array dimensions Sizes from the set of Terms extracted from
916 /// the memory access function of this SCEVAddRecExpr.
917 void findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
918 SmallVectorImpl<const SCEV *> &Sizes,
919 const SCEV *ElementSize) const;
921 bool runOnFunction(Function &F) override;
922 void releaseMemory() override;
923 void getAnalysisUsage(AnalysisUsage &AU) const override;
924 void print(raw_ostream &OS, const Module* = nullptr) const override;
925 void verifyAnalysis() const override;
928 /// Compute the backedge taken count knowing the interval difference, the
929 /// stride and presence of the equality in the comparison.
930 const SCEV *computeBECount(const SCEV *Delta, const SCEV *Stride,
933 /// Verify if an linear IV with positive stride can overflow when in a
934 /// less-than comparison, knowing the invariant term of the comparison,
935 /// the stride and the knowledge of NSW/NUW flags on the recurrence.
936 bool doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
937 bool IsSigned, bool NoWrap);
939 /// Verify if an linear IV with negative stride can overflow when in a
940 /// greater-than comparison, knowing the invariant term of the comparison,
941 /// the stride and the knowledge of NSW/NUW flags on the recurrence.
942 bool doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
943 bool IsSigned, bool NoWrap);
946 FoldingSet<SCEV> UniqueSCEVs;
947 BumpPtrAllocator SCEVAllocator;
949 /// FirstUnknown - The head of a linked list of all SCEVUnknown
950 /// values that have been allocated. This is used by releaseMemory
951 /// to locate them all and call their destructors.
952 SCEVUnknown *FirstUnknown;