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 AssumptionTracker;
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 &) LLVM_DELETED_FUNCTION;
75 void operator=(const SCEV &) LLVM_DELETED_FUNCTION;
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 expression may have a no-self-wraparound <NW> property if the
86 /// result can never reach the start value. This property is independent of
87 /// the actual start value and step direction. Self-wraparound is defined
88 /// purely in terms of the recurrence's loop, step size, and
89 /// bitwidth. Formally, a recurrence with no self-wraparound satisfies:
90 /// abs(step) * max-iteration(loop) <= unsigned-max(bitwidth).
92 /// Note that NUW and NSW are also valid properties of a recurrence, and
93 /// either implies NW. For convenience, NW will be set for a recurrence
94 /// whenever either NUW or NSW are set.
95 enum NoWrapFlags { FlagAnyWrap = 0, // No guarantee.
96 FlagNW = (1 << 0), // No self-wrap.
97 FlagNUW = (1 << 1), // No unsigned wrap.
98 FlagNSW = (1 << 2), // No signed wrap.
99 NoWrapMask = (1 << 3) -1 };
101 explicit SCEV(const FoldingSetNodeIDRef ID, unsigned SCEVTy) :
102 FastID(ID), SCEVType(SCEVTy), SubclassData(0) {}
104 unsigned getSCEVType() const { return SCEVType; }
106 /// getType - Return the LLVM type of this SCEV expression.
108 Type *getType() const;
110 /// isZero - Return true if the expression is a constant zero.
114 /// isOne - Return true if the expression is a constant one.
118 /// isAllOnesValue - Return true if the expression is a constant
121 bool isAllOnesValue() const;
123 /// isNonConstantNegative - Return true if the specified scev is negated,
124 /// but not a constant.
125 bool isNonConstantNegative() const;
127 /// print - Print out the internal representation of this scalar to the
128 /// specified stream. This should really only be used for debugging
130 void print(raw_ostream &OS) const;
132 /// dump - This method is used for debugging.
137 // Specialize FoldingSetTrait for SCEV to avoid needing to compute
138 // temporary FoldingSetNodeID values.
139 template<> struct FoldingSetTrait<SCEV> : DefaultFoldingSetTrait<SCEV> {
140 static void Profile(const SCEV &X, FoldingSetNodeID& ID) {
143 static bool Equals(const SCEV &X, const FoldingSetNodeID &ID,
144 unsigned IDHash, FoldingSetNodeID &TempID) {
145 return ID == X.FastID;
147 static unsigned ComputeHash(const SCEV &X, FoldingSetNodeID &TempID) {
148 return X.FastID.ComputeHash();
152 inline raw_ostream &operator<<(raw_ostream &OS, const SCEV &S) {
157 /// SCEVCouldNotCompute - An object of this class is returned by queries that
158 /// could not be answered. For example, if you ask for the number of
159 /// iterations of a linked-list traversal loop, you will get one of these.
160 /// None of the standard SCEV operations are valid on this class, it is just a
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 /// ScalarEvolution - This class is the main scalar evolution driver. Because
170 /// client code (intentionally) can't do much with the SCEV objects directly,
171 /// they must ask this class for services.
173 class ScalarEvolution : public FunctionPass {
175 /// LoopDisposition - An enum describing the relationship between a
177 enum LoopDisposition {
178 LoopVariant, ///< The SCEV is loop-variant (unknown).
179 LoopInvariant, ///< The SCEV is loop-invariant.
180 LoopComputable ///< The SCEV varies predictably with the loop.
183 /// BlockDisposition - An enum describing the relationship between a
184 /// SCEV and a basic block.
185 enum BlockDisposition {
186 DoesNotDominateBlock, ///< The SCEV does not dominate the block.
187 DominatesBlock, ///< The SCEV dominates the block.
188 ProperlyDominatesBlock ///< The SCEV properly dominates the block.
191 /// Convenient NoWrapFlags manipulation that hides enum casts and is
192 /// visible in the ScalarEvolution name space.
193 static SCEV::NoWrapFlags LLVM_ATTRIBUTE_UNUSED_RESULT
194 maskFlags(SCEV::NoWrapFlags Flags, int Mask) {
195 return (SCEV::NoWrapFlags)(Flags & Mask);
197 static SCEV::NoWrapFlags LLVM_ATTRIBUTE_UNUSED_RESULT
198 setFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OnFlags) {
199 return (SCEV::NoWrapFlags)(Flags | OnFlags);
201 static SCEV::NoWrapFlags LLVM_ATTRIBUTE_UNUSED_RESULT
202 clearFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OffFlags) {
203 return (SCEV::NoWrapFlags)(Flags & ~OffFlags);
207 /// SCEVCallbackVH - A CallbackVH to arrange for ScalarEvolution to be
208 /// notified whenever a Value is deleted.
209 class SCEVCallbackVH : public CallbackVH {
211 void deleted() override;
212 void allUsesReplacedWith(Value *New) override;
214 SCEVCallbackVH(Value *V, ScalarEvolution *SE = nullptr);
217 friend class SCEVCallbackVH;
218 friend class SCEVExpander;
219 friend class SCEVUnknown;
221 /// F - The function we are analyzing.
225 /// The tracker for @llvm.assume intrinsics in this function.
226 AssumptionTracker *AT;
228 /// LI - The loop information for the function we are currently analyzing.
232 /// The DataLayout information for the target we are targeting.
234 const DataLayout *DL;
236 /// TLI - The target library information for the target we are targeting.
238 TargetLibraryInfo *TLI;
240 /// DT - The dominator tree.
244 /// CouldNotCompute - This SCEV is used to represent unknown trip
245 /// counts and things.
246 SCEVCouldNotCompute CouldNotCompute;
248 /// ValueExprMapType - The typedef for ValueExprMap.
250 typedef DenseMap<SCEVCallbackVH, const SCEV *, DenseMapInfo<Value *> >
253 /// ValueExprMap - This is a cache of the values we have analyzed so far.
255 ValueExprMapType ValueExprMap;
257 /// Mark predicate values currently being processed by isImpliedCond.
258 DenseSet<Value*> PendingLoopPredicates;
260 /// ExitLimit - Information about the number of loop iterations for which a
261 /// loop exit's branch condition evaluates to the not-taken path. This is a
262 /// temporary pair of exact and max expressions that are eventually
263 /// summarized in ExitNotTakenInfo and BackedgeTakenInfo.
265 /// If MustExit is true, then the exit must be taken when the BECount
266 /// reaches Exact (and before surpassing Max). If MustExit is false, then
267 /// BECount may exceed Exact or Max if the loop exits via another branch. In
268 /// either case, the loop may exit early via another branch.
270 /// MustExit is true for most cases. However, an exit guarded by an
271 /// (in)equality on a nonunit stride may be skipped.
277 /*implicit*/ ExitLimit(const SCEV *E)
278 : Exact(E), Max(E), MustExit(true) {}
280 ExitLimit(const SCEV *E, const SCEV *M, bool MustExit)
281 : Exact(E), Max(M), MustExit(MustExit) {}
283 /// hasAnyInfo - Test whether this ExitLimit contains any computed
284 /// information, or whether it's all SCEVCouldNotCompute values.
285 bool hasAnyInfo() const {
286 return !isa<SCEVCouldNotCompute>(Exact) ||
287 !isa<SCEVCouldNotCompute>(Max);
291 /// ExitNotTakenInfo - Information about the number of times a particular
292 /// loop exit may be reached before exiting the loop.
293 struct ExitNotTakenInfo {
294 AssertingVH<BasicBlock> ExitingBlock;
295 const SCEV *ExactNotTaken;
296 PointerIntPair<ExitNotTakenInfo*, 1> NextExit;
298 ExitNotTakenInfo() : ExitingBlock(nullptr), ExactNotTaken(nullptr) {}
300 /// isCompleteList - Return true if all loop exits are computable.
301 bool isCompleteList() const {
302 return NextExit.getInt() == 0;
305 void setIncomplete() { NextExit.setInt(1); }
307 /// getNextExit - Return a pointer to the next exit's not-taken info.
308 ExitNotTakenInfo *getNextExit() const {
309 return NextExit.getPointer();
312 void setNextExit(ExitNotTakenInfo *ENT) { NextExit.setPointer(ENT); }
315 /// BackedgeTakenInfo - Information about the backedge-taken count
316 /// of a loop. This currently includes an exact count and a maximum count.
318 class BackedgeTakenInfo {
319 /// ExitNotTaken - A list of computable exits and their not-taken counts.
320 /// Loops almost never have more than one computable exit.
321 ExitNotTakenInfo ExitNotTaken;
323 /// Max - An expression indicating the least maximum backedge-taken
324 /// count of the loop that is known, or a SCEVCouldNotCompute.
328 BackedgeTakenInfo() : Max(nullptr) {}
330 /// Initialize BackedgeTakenInfo from a list of exact exit counts.
332 SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts,
333 bool Complete, const SCEV *MaxCount);
335 /// hasAnyInfo - Test whether this BackedgeTakenInfo contains any
336 /// computed information, or whether it's all SCEVCouldNotCompute
338 bool hasAnyInfo() const {
339 return ExitNotTaken.ExitingBlock || !isa<SCEVCouldNotCompute>(Max);
342 /// getExact - Return an expression indicating the exact backedge-taken
343 /// count of the loop if it is known, or SCEVCouldNotCompute
344 /// otherwise. This is the number of times the loop header can be
345 /// guaranteed to execute, minus one.
346 const SCEV *getExact(ScalarEvolution *SE) const;
348 /// getExact - Return the number of times this loop exit may fall through
349 /// to the back edge, or SCEVCouldNotCompute. The loop is guaranteed not
350 /// to exit via this block before this number of iterations, but may exit
351 /// via another block.
352 const SCEV *getExact(BasicBlock *ExitingBlock, ScalarEvolution *SE) const;
354 /// getMax - Get the max backedge taken count for the loop.
355 const SCEV *getMax(ScalarEvolution *SE) const;
357 /// Return true if any backedge taken count expressions refer to the given
359 bool hasOperand(const SCEV *S, ScalarEvolution *SE) const;
361 /// clear - Invalidate this result and free associated memory.
365 /// BackedgeTakenCounts - Cache the backedge-taken count of the loops for
366 /// this function as they are computed.
367 DenseMap<const Loop*, BackedgeTakenInfo> BackedgeTakenCounts;
369 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
370 /// the PHI instructions that we attempt to compute constant evolutions for.
371 /// This allows us to avoid potentially expensive recomputation of these
372 /// properties. An instruction maps to null if we are unable to compute its
374 DenseMap<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
376 /// ValuesAtScopes - This map contains entries for all the expressions
377 /// that we attempt to compute getSCEVAtScope information for, which can
378 /// be expensive in extreme cases.
379 DenseMap<const SCEV *,
380 SmallVector<std::pair<const Loop *, const SCEV *>, 2> > ValuesAtScopes;
382 /// LoopDispositions - Memoized computeLoopDisposition results.
383 DenseMap<const SCEV *,
384 SmallVector<std::pair<const Loop *, LoopDisposition>, 2> > LoopDispositions;
386 /// computeLoopDisposition - Compute a LoopDisposition value.
387 LoopDisposition computeLoopDisposition(const SCEV *S, const Loop *L);
389 /// BlockDispositions - Memoized computeBlockDisposition results.
390 DenseMap<const SCEV *,
391 SmallVector<std::pair<const BasicBlock *, BlockDisposition>, 2> > BlockDispositions;
393 /// computeBlockDisposition - Compute a BlockDisposition value.
394 BlockDisposition computeBlockDisposition(const SCEV *S, const BasicBlock *BB);
396 /// UnsignedRanges - Memoized results from getUnsignedRange
397 DenseMap<const SCEV *, ConstantRange> UnsignedRanges;
399 /// SignedRanges - Memoized results from getSignedRange
400 DenseMap<const SCEV *, ConstantRange> SignedRanges;
402 /// setUnsignedRange - Set the memoized unsigned range for the given SCEV.
403 const ConstantRange &setUnsignedRange(const SCEV *S,
404 const ConstantRange &CR) {
405 std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair =
406 UnsignedRanges.insert(std::make_pair(S, CR));
408 Pair.first->second = CR;
409 return Pair.first->second;
412 /// setUnsignedRange - Set the memoized signed range for the given SCEV.
413 const ConstantRange &setSignedRange(const SCEV *S,
414 const ConstantRange &CR) {
415 std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair =
416 SignedRanges.insert(std::make_pair(S, CR));
418 Pair.first->second = CR;
419 return Pair.first->second;
422 /// createSCEV - We know that there is no SCEV for the specified value.
423 /// Analyze the expression.
424 const SCEV *createSCEV(Value *V);
426 /// createNodeForPHI - Provide the special handling we need to analyze PHI
428 const SCEV *createNodeForPHI(PHINode *PN);
430 /// createNodeForGEP - Provide the special handling we need to analyze GEP
432 const SCEV *createNodeForGEP(GEPOperator *GEP);
434 /// computeSCEVAtScope - Implementation code for getSCEVAtScope; called
435 /// at most once for each SCEV+Loop pair.
437 const SCEV *computeSCEVAtScope(const SCEV *S, const Loop *L);
439 /// ForgetSymbolicValue - This looks up computed SCEV values for all
440 /// instructions that depend on the given instruction and removes them from
441 /// the ValueExprMap map if they reference SymName. This is used during PHI
443 void ForgetSymbolicName(Instruction *I, const SCEV *SymName);
445 /// getBackedgeTakenInfo - Return the BackedgeTakenInfo for the given
446 /// loop, lazily computing new values if the loop hasn't been analyzed
448 const BackedgeTakenInfo &getBackedgeTakenInfo(const Loop *L);
450 /// ComputeBackedgeTakenCount - Compute the number of times the specified
451 /// loop will iterate.
452 BackedgeTakenInfo ComputeBackedgeTakenCount(const Loop *L);
454 /// ComputeExitLimit - Compute the number of times the backedge of the
455 /// specified loop will execute if it exits via the specified block.
456 ExitLimit ComputeExitLimit(const Loop *L, BasicBlock *ExitingBlock);
458 /// ComputeExitLimitFromCond - Compute the number of times the backedge of
459 /// the specified loop will execute if its exit condition were a conditional
460 /// branch of ExitCond, TBB, and FBB.
461 ExitLimit ComputeExitLimitFromCond(const Loop *L,
467 /// ComputeExitLimitFromICmp - Compute the number of times the backedge of
468 /// the specified loop will execute if its exit condition were a conditional
469 /// branch of the ICmpInst ExitCond, TBB, and FBB.
470 ExitLimit ComputeExitLimitFromICmp(const Loop *L,
476 /// ComputeExitLimitFromSingleExitSwitch - Compute the number of times the
477 /// backedge of the specified loop will execute if its exit condition were a
478 /// switch with a single exiting case to ExitingBB.
480 ComputeExitLimitFromSingleExitSwitch(const Loop *L, SwitchInst *Switch,
481 BasicBlock *ExitingBB, bool IsSubExpr);
483 /// ComputeLoadConstantCompareExitLimit - Given an exit condition
484 /// of 'icmp op load X, cst', try to see if we can compute the
485 /// backedge-taken count.
486 ExitLimit ComputeLoadConstantCompareExitLimit(LoadInst *LI,
489 ICmpInst::Predicate p);
491 /// ComputeExitCountExhaustively - If the loop is known to execute a
492 /// constant number of times (the condition evolves only from constants),
493 /// try to evaluate a few iterations of the loop until we get the exit
494 /// condition gets a value of ExitWhen (true or false). If we cannot
495 /// evaluate the exit count of the loop, return CouldNotCompute.
496 const SCEV *ComputeExitCountExhaustively(const Loop *L,
500 /// HowFarToZero - Return the number of times an exit condition comparing
501 /// the specified value to zero will execute. If not computable, return
503 ExitLimit HowFarToZero(const SCEV *V, const Loop *L, bool IsSubExpr);
505 /// HowFarToNonZero - Return the number of times an exit condition checking
506 /// the specified value for nonzero will execute. If not computable, return
508 ExitLimit HowFarToNonZero(const SCEV *V, const Loop *L);
510 /// HowManyLessThans - Return the number of times an exit condition
511 /// containing the specified less-than comparison will execute. If not
512 /// computable, return CouldNotCompute. isSigned specifies whether the
513 /// less-than is signed.
514 ExitLimit HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
515 const Loop *L, bool isSigned, bool IsSubExpr);
516 ExitLimit HowManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
517 const Loop *L, bool isSigned, bool IsSubExpr);
519 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
520 /// (which may not be an immediate predecessor) which has exactly one
521 /// successor from which BB is reachable, or null if no such block is
523 std::pair<BasicBlock *, BasicBlock *>
524 getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
526 /// isImpliedCond - Test whether the condition described by Pred, LHS, and
527 /// RHS is true whenever the given FoundCondValue value evaluates to true.
528 bool isImpliedCond(ICmpInst::Predicate Pred,
529 const SCEV *LHS, const SCEV *RHS,
530 Value *FoundCondValue,
533 /// isImpliedCondOperands - Test whether the condition described by Pred,
534 /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
535 /// and FoundRHS is true.
536 bool isImpliedCondOperands(ICmpInst::Predicate Pred,
537 const SCEV *LHS, const SCEV *RHS,
538 const SCEV *FoundLHS, const SCEV *FoundRHS);
540 /// isImpliedCondOperandsHelper - Test whether the condition described by
541 /// Pred, LHS, and RHS is true whenever the condition described by Pred,
542 /// FoundLHS, and FoundRHS is true.
543 bool isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
544 const SCEV *LHS, const SCEV *RHS,
545 const SCEV *FoundLHS,
546 const SCEV *FoundRHS);
548 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
549 /// in the header of its containing loop, we know the loop executes a
550 /// constant number of times, and the PHI node is just a recurrence
551 /// involving constants, fold it.
552 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs,
555 /// isKnownPredicateWithRanges - Test if the given expression is known to
556 /// satisfy the condition described by Pred and the known constant ranges
559 bool isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
560 const SCEV *LHS, const SCEV *RHS);
562 /// forgetMemoizedResults - Drop memoized information computed for S.
563 void forgetMemoizedResults(const SCEV *S);
565 /// Return false iff given SCEV contains a SCEVUnknown with NULL value-
567 bool checkValidity(const SCEV *S) const;
570 static char ID; // Pass identification, replacement for typeid
573 LLVMContext &getContext() const { return F->getContext(); }
575 /// isSCEVable - Test if values of the given type are analyzable within
576 /// the SCEV framework. This primarily includes integer types, and it
577 /// can optionally include pointer types if the ScalarEvolution class
578 /// has access to target-specific information.
579 bool isSCEVable(Type *Ty) const;
581 /// getTypeSizeInBits - Return the size in bits of the specified type,
582 /// for which isSCEVable must return true.
583 uint64_t getTypeSizeInBits(Type *Ty) const;
585 /// getEffectiveSCEVType - Return a type with the same bitwidth as
586 /// the given type and which represents how SCEV will treat the given
587 /// type, for which isSCEVable must return true. For pointer types,
588 /// this is the pointer-sized integer type.
589 Type *getEffectiveSCEVType(Type *Ty) const;
591 /// getSCEV - Return a SCEV expression for the full generality of the
592 /// specified expression.
593 const SCEV *getSCEV(Value *V);
595 const SCEV *getConstant(ConstantInt *V);
596 const SCEV *getConstant(const APInt& Val);
597 const SCEV *getConstant(Type *Ty, uint64_t V, bool isSigned = false);
598 const SCEV *getTruncateExpr(const SCEV *Op, Type *Ty);
599 const SCEV *getZeroExtendExpr(const SCEV *Op, Type *Ty);
600 const SCEV *getSignExtendExpr(const SCEV *Op, Type *Ty);
601 const SCEV *getAnyExtendExpr(const SCEV *Op, Type *Ty);
602 const SCEV *getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
603 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
604 const SCEV *getAddExpr(const SCEV *LHS, const SCEV *RHS,
605 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
606 SmallVector<const SCEV *, 2> Ops;
609 return getAddExpr(Ops, Flags);
611 const SCEV *getAddExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
612 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
613 SmallVector<const SCEV *, 3> Ops;
617 return getAddExpr(Ops, Flags);
619 const SCEV *getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
620 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
621 const SCEV *getMulExpr(const SCEV *LHS, const SCEV *RHS,
622 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap)
624 SmallVector<const SCEV *, 2> Ops;
627 return getMulExpr(Ops, Flags);
629 const SCEV *getMulExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
630 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
631 SmallVector<const SCEV *, 3> Ops;
635 return getMulExpr(Ops, Flags);
637 const SCEV *getUDivExpr(const SCEV *LHS, const SCEV *RHS);
638 const SCEV *getUDivExactExpr(const SCEV *LHS, const SCEV *RHS);
639 const SCEV *getAddRecExpr(const SCEV *Start, const SCEV *Step,
640 const Loop *L, SCEV::NoWrapFlags Flags);
641 const SCEV *getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
642 const Loop *L, SCEV::NoWrapFlags Flags);
643 const SCEV *getAddRecExpr(const SmallVectorImpl<const SCEV *> &Operands,
644 const Loop *L, SCEV::NoWrapFlags Flags) {
645 SmallVector<const SCEV *, 4> NewOp(Operands.begin(), Operands.end());
646 return getAddRecExpr(NewOp, L, Flags);
648 const SCEV *getSMaxExpr(const SCEV *LHS, const SCEV *RHS);
649 const SCEV *getSMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
650 const SCEV *getUMaxExpr(const SCEV *LHS, const SCEV *RHS);
651 const SCEV *getUMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
652 const SCEV *getSMinExpr(const SCEV *LHS, const SCEV *RHS);
653 const SCEV *getUMinExpr(const SCEV *LHS, const SCEV *RHS);
654 const SCEV *getUnknown(Value *V);
655 const SCEV *getCouldNotCompute();
657 /// getSizeOfExpr - Return an expression for sizeof AllocTy that is type
660 const SCEV *getSizeOfExpr(Type *IntTy, Type *AllocTy);
662 /// getOffsetOfExpr - Return an expression for offsetof on the given field
665 const SCEV *getOffsetOfExpr(Type *IntTy, StructType *STy, unsigned FieldNo);
667 /// getNegativeSCEV - Return the SCEV object corresponding to -V.
669 const SCEV *getNegativeSCEV(const SCEV *V);
671 /// getNotSCEV - Return the SCEV object corresponding to ~V.
673 const SCEV *getNotSCEV(const SCEV *V);
675 /// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
676 const SCEV *getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
677 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
679 /// getTruncateOrZeroExtend - 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 zero extended.
682 const SCEV *getTruncateOrZeroExtend(const SCEV *V, Type *Ty);
684 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
685 /// of the input value to the specified type. If the type must be
686 /// extended, it is sign extended.
687 const SCEV *getTruncateOrSignExtend(const SCEV *V, Type *Ty);
689 /// getNoopOrZeroExtend - 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 zero extended. The conversion must not be narrowing.
692 const SCEV *getNoopOrZeroExtend(const SCEV *V, Type *Ty);
694 /// getNoopOrSignExtend - 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 sign extended. The conversion must not be narrowing.
697 const SCEV *getNoopOrSignExtend(const SCEV *V, Type *Ty);
699 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
700 /// the input value to the specified type. If the type must be extended,
701 /// it is extended with unspecified bits. The conversion must not be
703 const SCEV *getNoopOrAnyExtend(const SCEV *V, Type *Ty);
705 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
706 /// input value to the specified type. The conversion must not be
708 const SCEV *getTruncateOrNoop(const SCEV *V, Type *Ty);
710 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
711 /// the types using zero-extension, and then perform a umax operation
713 const SCEV *getUMaxFromMismatchedTypes(const SCEV *LHS,
716 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
717 /// the types using zero-extension, and then perform a umin operation
719 const SCEV *getUMinFromMismatchedTypes(const SCEV *LHS,
722 /// getPointerBase - Transitively follow the chain of pointer-type operands
723 /// until reaching a SCEV that does not have a single pointer operand. This
724 /// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
725 /// but corner cases do exist.
726 const SCEV *getPointerBase(const SCEV *V);
728 /// getSCEVAtScope - Return a SCEV expression for the specified value
729 /// at the specified scope in the program. The L value specifies a loop
730 /// nest to evaluate the expression at, where null is the top-level or a
731 /// specified loop is immediately inside of the loop.
733 /// This method can be used to compute the exit value for a variable defined
734 /// in a loop by querying what the value will hold in the parent loop.
736 /// In the case that a relevant loop exit value cannot be computed, the
737 /// original value V is returned.
738 const SCEV *getSCEVAtScope(const SCEV *S, const Loop *L);
740 /// getSCEVAtScope - This is a convenience function which does
741 /// getSCEVAtScope(getSCEV(V), L).
742 const SCEV *getSCEVAtScope(Value *V, const Loop *L);
744 /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
745 /// by a conditional between LHS and RHS. This is used to help avoid max
746 /// expressions in loop trip counts, and to eliminate casts.
747 bool isLoopEntryGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
748 const SCEV *LHS, const SCEV *RHS);
750 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
751 /// protected by a conditional between LHS and RHS. This is used to
752 /// to eliminate casts.
753 bool isLoopBackedgeGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
754 const SCEV *LHS, const SCEV *RHS);
756 /// getSmallConstantTripCount - Returns the maximum trip count of this loop
757 /// as a normal unsigned value. Returns 0 if the trip count is unknown or
758 /// not constant. This "trip count" assumes that control exits via
759 /// ExitingBlock. More precisely, it is the number of times that control may
760 /// reach ExitingBlock before taking the branch. For loops with multiple
761 /// exits, it may not be the number times that the loop header executes if
762 /// the loop exits prematurely via another branch.
763 unsigned getSmallConstantTripCount(Loop *L, BasicBlock *ExitingBlock);
765 /// getSmallConstantTripMultiple - Returns the largest constant divisor of
766 /// the trip count of this loop as a normal unsigned value, if
767 /// possible. This means that the actual trip count is always a multiple of
768 /// the returned value (don't forget the trip count could very well be zero
769 /// as well!). As explained in the comments for getSmallConstantTripCount,
770 /// this assumes that control exits the loop via ExitingBlock.
771 unsigned getSmallConstantTripMultiple(Loop *L, BasicBlock *ExitingBlock);
773 // getExitCount - Get the expression for the number of loop iterations for
774 // which this loop is guaranteed not to exit via ExitingBlock. Otherwise
775 // return SCEVCouldNotCompute.
776 const SCEV *getExitCount(Loop *L, BasicBlock *ExitingBlock);
778 /// getBackedgeTakenCount - If the specified loop has a predictable
779 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
780 /// object. The backedge-taken count is the number of times the loop header
781 /// will be branched to from within the loop. This is one less than the
782 /// trip count of the loop, since it doesn't count the first iteration,
783 /// when the header is branched to from outside the loop.
785 /// Note that it is not valid to call this method on a loop without a
786 /// loop-invariant backedge-taken count (see
787 /// hasLoopInvariantBackedgeTakenCount).
789 const SCEV *getBackedgeTakenCount(const Loop *L);
791 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
792 /// return the least SCEV value that is known never to be less than the
793 /// actual backedge taken count.
794 const SCEV *getMaxBackedgeTakenCount(const Loop *L);
796 /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop
797 /// has an analyzable loop-invariant backedge-taken count.
798 bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
800 /// forgetLoop - This method should be called by the client when it has
801 /// changed a loop in a way that may effect ScalarEvolution's ability to
802 /// compute a trip count, or if the loop is deleted. This call is
803 /// potentially expensive for large loop bodies.
804 void forgetLoop(const Loop *L);
806 /// forgetValue - This method should be called by the client when it has
807 /// changed a value in a way that may effect its value, or which may
808 /// disconnect it from a def-use chain linking it to a loop.
809 void forgetValue(Value *V);
811 /// \brief Called when the client has changed the disposition of values in
814 /// We don't have a way to invalidate per-loop dispositions. Clear and
815 /// recompute is simpler.
816 void forgetLoopDispositions(const Loop *L) { LoopDispositions.clear(); }
818 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S
819 /// is guaranteed to end in (at every loop iteration). It is, at the same
820 /// time, the minimum number of times S is divisible by 2. For example,
821 /// given {4,+,8} it returns 2. If S is guaranteed to be 0, it returns the
823 uint32_t GetMinTrailingZeros(const SCEV *S);
825 /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
827 ConstantRange getUnsignedRange(const SCEV *S);
829 /// getSignedRange - Determine the signed range for a particular SCEV.
831 ConstantRange getSignedRange(const SCEV *S);
833 /// isKnownNegative - Test if the given expression is known to be negative.
835 bool isKnownNegative(const SCEV *S);
837 /// isKnownPositive - Test if the given expression is known to be positive.
839 bool isKnownPositive(const SCEV *S);
841 /// isKnownNonNegative - Test if the given expression is known to be
844 bool isKnownNonNegative(const SCEV *S);
846 /// isKnownNonPositive - Test if the given expression is known to be
849 bool isKnownNonPositive(const SCEV *S);
851 /// isKnownNonZero - Test if the given expression is known to be
854 bool isKnownNonZero(const SCEV *S);
856 /// isKnownPredicate - Test if the given expression is known to satisfy
857 /// the condition described by Pred, LHS, and RHS.
859 bool isKnownPredicate(ICmpInst::Predicate Pred,
860 const SCEV *LHS, const SCEV *RHS);
862 /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
863 /// predicate Pred. Return true iff any changes were made. If the
864 /// operands are provably equal or unequal, LHS and RHS are set to
865 /// the same value and Pred is set to either ICMP_EQ or ICMP_NE.
867 bool SimplifyICmpOperands(ICmpInst::Predicate &Pred,
872 /// getLoopDisposition - Return the "disposition" of the given SCEV with
873 /// respect to the given loop.
874 LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L);
876 /// isLoopInvariant - Return true if the value of the given SCEV is
877 /// unchanging in the specified loop.
878 bool isLoopInvariant(const SCEV *S, const Loop *L);
880 /// hasComputableLoopEvolution - Return true if the given SCEV changes value
881 /// in a known way in the specified loop. This property being true implies
882 /// that the value is variant in the loop AND that we can emit an expression
883 /// to compute the value of the expression at any particular loop iteration.
884 bool hasComputableLoopEvolution(const SCEV *S, const Loop *L);
886 /// getLoopDisposition - Return the "disposition" of the given SCEV with
887 /// respect to the given block.
888 BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB);
890 /// dominates - Return true if elements that makes up the given SCEV
891 /// dominate the specified basic block.
892 bool dominates(const SCEV *S, const BasicBlock *BB);
894 /// properlyDominates - Return true if elements that makes up the given SCEV
895 /// properly dominate the specified basic block.
896 bool properlyDominates(const SCEV *S, const BasicBlock *BB);
898 /// hasOperand - Test whether the given SCEV has Op as a direct or
899 /// indirect operand.
900 bool hasOperand(const SCEV *S, const SCEV *Op) const;
902 /// Return the size of an element read or written by Inst.
903 const SCEV *getElementSize(Instruction *Inst);
905 /// Compute the array dimensions Sizes from the set of Terms extracted from
906 /// the memory access function of this SCEVAddRecExpr.
907 void findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
908 SmallVectorImpl<const SCEV *> &Sizes,
909 const SCEV *ElementSize) const;
911 bool runOnFunction(Function &F) override;
912 void releaseMemory() override;
913 void getAnalysisUsage(AnalysisUsage &AU) const override;
914 void print(raw_ostream &OS, const Module* = nullptr) const override;
915 void verifyAnalysis() const override;
918 /// Compute the backedge taken count knowing the interval difference, the
919 /// stride and presence of the equality in the comparison.
920 const SCEV *computeBECount(const SCEV *Delta, const SCEV *Stride,
923 /// Verify if an linear IV with positive stride can overflow when in a
924 /// less-than comparison, knowing the invariant term of the comparison,
925 /// the stride and the knowledge of NSW/NUW flags on the recurrence.
926 bool doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
927 bool IsSigned, bool NoWrap);
929 /// Verify if an linear IV with negative stride can overflow when in a
930 /// greater-than comparison, knowing the invariant term of the comparison,
931 /// the stride and the knowledge of NSW/NUW flags on the recurrence.
932 bool doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
933 bool IsSigned, bool NoWrap);
936 FoldingSet<SCEV> UniqueSCEVs;
937 BumpPtrAllocator SCEVAllocator;
939 /// FirstUnknown - The head of a linked list of all SCEVUnknown
940 /// values that have been allocated. This is used by releaseMemory
941 /// to locate them all and call their destructors.
942 SCEVUnknown *FirstUnknown;