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/Pass.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Function.h"
27 #include "llvm/Operator.h"
28 #include "llvm/Support/DataTypes.h"
29 #include "llvm/Support/ValueHandle.h"
30 #include "llvm/Support/Allocator.h"
31 #include "llvm/Support/ConstantRange.h"
32 #include "llvm/ADT/FoldingSet.h"
33 #include "llvm/ADT/DenseMap.h"
42 class ScalarEvolution;
44 class TargetLibraryInfo;
51 template<> struct FoldingSetTrait<SCEV>;
53 /// SCEV - This class represents an analyzed expression in the program. These
54 /// are opaque objects that the client is not allowed to do much with
57 class SCEV : public FoldingSetNode {
58 friend struct FoldingSetTrait<SCEV>;
60 /// FastID - A reference to an Interned FoldingSetNodeID for this node.
61 /// The ScalarEvolution's BumpPtrAllocator holds the data.
62 FoldingSetNodeIDRef FastID;
64 // The SCEV baseclass this node corresponds to
65 const unsigned short SCEVType;
68 /// SubclassData - This field is initialized to zero and may be used in
69 /// subclasses to store miscellaneous information.
70 unsigned short SubclassData;
73 SCEV(const SCEV &); // DO NOT IMPLEMENT
74 void operator=(const SCEV &); // DO NOT IMPLEMENT
77 /// NoWrapFlags are bitfield indices into SubclassData.
79 /// Add and Mul expressions may have no-unsigned-wrap <NUW> or
80 /// no-signed-wrap <NSW> properties, which are derived from the IR
81 /// operator. NSW is a misnomer that we use to mean no signed overflow or
84 /// AddRec expression may have a no-self-wraparound <NW> property if the
85 /// result can never reach the start value. This property is independent of
86 /// the actual start value and step direction. Self-wraparound is defined
87 /// purely in terms of the recurrence's loop, step size, and
88 /// bitwidth. Formally, a recurrence with no self-wraparound satisfies:
89 /// abs(step) * max-iteration(loop) <= unsigned-max(bitwidth).
91 /// Note that NUW and NSW are also valid properties of a recurrence, and
92 /// either implies NW. For convenience, NW will be set for a recurrence
93 /// whenever either NUW or NSW are set.
94 enum NoWrapFlags { FlagAnyWrap = 0, // No guarantee.
95 FlagNW = (1 << 0), // No self-wrap.
96 FlagNUW = (1 << 1), // No unsigned wrap.
97 FlagNSW = (1 << 2), // No signed wrap.
98 NoWrapMask = (1 << 3) -1 };
100 explicit SCEV(const FoldingSetNodeIDRef ID, unsigned SCEVTy) :
101 FastID(ID), SCEVType(SCEVTy), SubclassData(0) {}
103 unsigned getSCEVType() const { return SCEVType; }
105 /// getType - Return the LLVM type of this SCEV expression.
107 Type *getType() const;
109 /// isZero - Return true if the expression is a constant zero.
113 /// isOne - Return true if the expression is a constant one.
117 /// isAllOnesValue - Return true if the expression is a constant
120 bool isAllOnesValue() const;
122 /// print - Print out the internal representation of this scalar to the
123 /// specified stream. This should really only be used for debugging
125 void print(raw_ostream &OS) const;
127 /// dump - This method is used for debugging.
132 // Specialize FoldingSetTrait for SCEV to avoid needing to compute
133 // temporary FoldingSetNodeID values.
134 template<> struct FoldingSetTrait<SCEV> : DefaultFoldingSetTrait<SCEV> {
135 static void Profile(const SCEV &X, FoldingSetNodeID& ID) {
138 static bool Equals(const SCEV &X, const FoldingSetNodeID &ID,
139 FoldingSetNodeID &TempID) {
140 return ID == X.FastID;
142 static unsigned ComputeHash(const SCEV &X, FoldingSetNodeID &TempID) {
143 return X.FastID.ComputeHash();
147 inline raw_ostream &operator<<(raw_ostream &OS, const SCEV &S) {
152 /// SCEVCouldNotCompute - An object of this class is returned by queries that
153 /// could not be answered. For example, if you ask for the number of
154 /// iterations of a linked-list traversal loop, you will get one of these.
155 /// None of the standard SCEV operations are valid on this class, it is just a
157 struct SCEVCouldNotCompute : public SCEV {
158 SCEVCouldNotCompute();
160 /// Methods for support type inquiry through isa, cast, and dyn_cast:
161 static inline bool classof(const SCEVCouldNotCompute *S) { return true; }
162 static bool classof(const SCEV *S);
165 /// ScalarEvolution - This class is the main scalar evolution driver. Because
166 /// client code (intentionally) can't do much with the SCEV objects directly,
167 /// they must ask this class for services.
169 class ScalarEvolution : public FunctionPass {
171 /// LoopDisposition - An enum describing the relationship between a
173 enum LoopDisposition {
174 LoopVariant, ///< The SCEV is loop-variant (unknown).
175 LoopInvariant, ///< The SCEV is loop-invariant.
176 LoopComputable ///< The SCEV varies predictably with the loop.
179 /// BlockDisposition - An enum describing the relationship between a
180 /// SCEV and a basic block.
181 enum BlockDisposition {
182 DoesNotDominateBlock, ///< The SCEV does not dominate the block.
183 DominatesBlock, ///< The SCEV dominates the block.
184 ProperlyDominatesBlock ///< The SCEV properly dominates the block.
187 /// Convenient NoWrapFlags manipulation that hides enum casts and is
188 /// visible in the ScalarEvolution name space.
189 static SCEV::NoWrapFlags maskFlags(SCEV::NoWrapFlags Flags, int Mask) {
190 return (SCEV::NoWrapFlags)(Flags & Mask);
192 static SCEV::NoWrapFlags setFlags(SCEV::NoWrapFlags Flags,
193 SCEV::NoWrapFlags OnFlags) {
194 return (SCEV::NoWrapFlags)(Flags | OnFlags);
196 static SCEV::NoWrapFlags clearFlags(SCEV::NoWrapFlags Flags,
197 SCEV::NoWrapFlags OffFlags) {
198 return (SCEV::NoWrapFlags)(Flags & ~OffFlags);
202 /// SCEVCallbackVH - A CallbackVH to arrange for ScalarEvolution to be
203 /// notified whenever a Value is deleted.
204 class SCEVCallbackVH : public CallbackVH {
206 virtual void deleted();
207 virtual void allUsesReplacedWith(Value *New);
209 SCEVCallbackVH(Value *V, ScalarEvolution *SE = 0);
212 friend class SCEVCallbackVH;
213 friend class SCEVExpander;
214 friend class SCEVUnknown;
216 /// F - The function we are analyzing.
220 /// LI - The loop information for the function we are currently analyzing.
224 /// TD - The target data information for the target we are targeting.
228 /// TLI - The target library information for the target we are targeting.
230 TargetLibraryInfo *TLI;
232 /// DT - The dominator tree.
236 /// CouldNotCompute - This SCEV is used to represent unknown trip
237 /// counts and things.
238 SCEVCouldNotCompute CouldNotCompute;
240 /// ValueExprMapType - The typedef for ValueExprMap.
242 typedef DenseMap<SCEVCallbackVH, const SCEV *, DenseMapInfo<Value *> >
245 /// ValueExprMap - This is a cache of the values we have analyzed so far.
247 ValueExprMapType ValueExprMap;
249 /// ExitLimit - Information about the number of loop iterations for
250 /// which a loop exit's branch condition evaluates to the not-taken path.
251 /// This is a temporary pair of exact and max expressions that are
252 /// eventually summarized in ExitNotTakenInfo and BackedgeTakenInfo.
257 /*implicit*/ ExitLimit(const SCEV *E) : Exact(E), Max(E) {}
259 ExitLimit(const SCEV *E, const SCEV *M) : Exact(E), Max(M) {}
261 /// hasAnyInfo - Test whether this ExitLimit contains any computed
262 /// information, or whether it's all SCEVCouldNotCompute values.
263 bool hasAnyInfo() const {
264 return !isa<SCEVCouldNotCompute>(Exact) ||
265 !isa<SCEVCouldNotCompute>(Max);
269 /// ExitNotTakenInfo - Information about the number of times a particular
270 /// loop exit may be reached before exiting the loop.
271 struct ExitNotTakenInfo {
272 AssertingVH<BasicBlock> ExitingBlock;
273 const SCEV *ExactNotTaken;
274 PointerIntPair<ExitNotTakenInfo*, 1> NextExit;
276 ExitNotTakenInfo() : ExitingBlock(0), ExactNotTaken(0) {}
278 /// isCompleteList - Return true if all loop exits are computable.
279 bool isCompleteList() const {
280 return NextExit.getInt() == 0;
283 void setIncomplete() { NextExit.setInt(1); }
285 /// getNextExit - Return a pointer to the next exit's not-taken info.
286 ExitNotTakenInfo *getNextExit() const {
287 return NextExit.getPointer();
290 void setNextExit(ExitNotTakenInfo *ENT) { NextExit.setPointer(ENT); }
293 /// BackedgeTakenInfo - Information about the backedge-taken count
294 /// of a loop. This currently includes an exact count and a maximum count.
296 class BackedgeTakenInfo {
297 /// ExitNotTaken - A list of computable exits and their not-taken counts.
298 /// Loops almost never have more than one computable exit.
299 ExitNotTakenInfo ExitNotTaken;
301 /// Max - An expression indicating the least maximum backedge-taken
302 /// count of the loop that is known, or a SCEVCouldNotCompute.
306 BackedgeTakenInfo() : Max(0) {}
308 /// Initialize BackedgeTakenInfo from a list of exact exit counts.
310 SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts,
311 bool Complete, const SCEV *MaxCount);
313 /// hasAnyInfo - Test whether this BackedgeTakenInfo contains any
314 /// computed information, or whether it's all SCEVCouldNotCompute
316 bool hasAnyInfo() const {
317 return ExitNotTaken.ExitingBlock || !isa<SCEVCouldNotCompute>(Max);
320 /// getExact - Return an expression indicating the exact backedge-taken
321 /// count of the loop if it is known, or SCEVCouldNotCompute
322 /// otherwise. This is the number of times the loop header can be
323 /// guaranteed to execute, minus one.
324 const SCEV *getExact(ScalarEvolution *SE) const;
326 /// getExact - Return the number of times this loop exit may fall through
327 /// to the back edge, or SCEVCouldNotCompute. The loop is guaranteed not
328 /// to exit via this block before this number of iterations, but may exit
329 /// via another block.
330 const SCEV *getExact(BasicBlock *ExitingBlock, ScalarEvolution *SE) const;
332 /// getMax - Get the max backedge taken count for the loop.
333 const SCEV *getMax(ScalarEvolution *SE) const;
335 /// clear - Invalidate this result and free associated memory.
339 /// BackedgeTakenCounts - Cache the backedge-taken count of the loops for
340 /// this function as they are computed.
341 DenseMap<const Loop*, BackedgeTakenInfo> BackedgeTakenCounts;
343 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
344 /// the PHI instructions that we attempt to compute constant evolutions for.
345 /// This allows us to avoid potentially expensive recomputation of these
346 /// properties. An instruction maps to null if we are unable to compute its
348 DenseMap<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
350 /// ValuesAtScopes - This map contains entries for all the expressions
351 /// that we attempt to compute getSCEVAtScope information for, which can
352 /// be expensive in extreme cases.
353 DenseMap<const SCEV *,
354 std::map<const Loop *, const SCEV *> > ValuesAtScopes;
356 /// LoopDispositions - Memoized computeLoopDisposition results.
357 DenseMap<const SCEV *,
358 std::map<const Loop *, LoopDisposition> > LoopDispositions;
360 /// computeLoopDisposition - Compute a LoopDisposition value.
361 LoopDisposition computeLoopDisposition(const SCEV *S, const Loop *L);
363 /// BlockDispositions - Memoized computeBlockDisposition results.
364 DenseMap<const SCEV *,
365 std::map<const BasicBlock *, BlockDisposition> > BlockDispositions;
367 /// computeBlockDisposition - Compute a BlockDisposition value.
368 BlockDisposition computeBlockDisposition(const SCEV *S, const BasicBlock *BB);
370 /// UnsignedRanges - Memoized results from getUnsignedRange
371 DenseMap<const SCEV *, ConstantRange> UnsignedRanges;
373 /// SignedRanges - Memoized results from getSignedRange
374 DenseMap<const SCEV *, ConstantRange> SignedRanges;
376 /// setUnsignedRange - Set the memoized unsigned range for the given SCEV.
377 const ConstantRange &setUnsignedRange(const SCEV *S,
378 const ConstantRange &CR) {
379 std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair =
380 UnsignedRanges.insert(std::make_pair(S, CR));
382 Pair.first->second = CR;
383 return Pair.first->second;
386 /// setUnsignedRange - Set the memoized signed range for the given SCEV.
387 const ConstantRange &setSignedRange(const SCEV *S,
388 const ConstantRange &CR) {
389 std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair =
390 SignedRanges.insert(std::make_pair(S, CR));
392 Pair.first->second = CR;
393 return Pair.first->second;
396 /// createSCEV - We know that there is no SCEV for the specified value.
397 /// Analyze the expression.
398 const SCEV *createSCEV(Value *V);
400 /// createNodeForPHI - Provide the special handling we need to analyze PHI
402 const SCEV *createNodeForPHI(PHINode *PN);
404 /// createNodeForGEP - Provide the special handling we need to analyze GEP
406 const SCEV *createNodeForGEP(GEPOperator *GEP);
408 /// computeSCEVAtScope - Implementation code for getSCEVAtScope; called
409 /// at most once for each SCEV+Loop pair.
411 const SCEV *computeSCEVAtScope(const SCEV *S, const Loop *L);
413 /// ForgetSymbolicValue - This looks up computed SCEV values for all
414 /// instructions that depend on the given instruction and removes them from
415 /// the ValueExprMap map if they reference SymName. This is used during PHI
417 void ForgetSymbolicName(Instruction *I, const SCEV *SymName);
419 /// getBECount - Subtract the end and start values and divide by the step,
420 /// rounding up, to get the number of times the backedge is executed. Return
421 /// CouldNotCompute if an intermediate computation overflows.
422 const SCEV *getBECount(const SCEV *Start,
427 /// getBackedgeTakenInfo - Return the BackedgeTakenInfo for the given
428 /// loop, lazily computing new values if the loop hasn't been analyzed
430 const BackedgeTakenInfo &getBackedgeTakenInfo(const Loop *L);
432 /// ComputeBackedgeTakenCount - Compute the number of times the specified
433 /// loop will iterate.
434 BackedgeTakenInfo ComputeBackedgeTakenCount(const Loop *L);
436 /// ComputeExitLimit - Compute the number of times the backedge of the
437 /// specified loop will execute if it exits via the specified block.
438 ExitLimit ComputeExitLimit(const Loop *L, BasicBlock *ExitingBlock);
440 /// ComputeExitLimitFromCond - Compute the number of times the backedge of
441 /// the specified loop will execute if its exit condition were a conditional
442 /// branch of ExitCond, TBB, and FBB.
443 ExitLimit ComputeExitLimitFromCond(const Loop *L,
448 /// ComputeExitLimitFromICmp - Compute the number of times the backedge of
449 /// the specified loop will execute if its exit condition were a conditional
450 /// branch of the ICmpInst ExitCond, TBB, and FBB.
451 ExitLimit ComputeExitLimitFromICmp(const Loop *L,
456 /// ComputeLoadConstantCompareExitLimit - Given an exit condition
457 /// of 'icmp op load X, cst', try to see if we can compute the
458 /// backedge-taken count.
459 ExitLimit ComputeLoadConstantCompareExitLimit(LoadInst *LI,
462 ICmpInst::Predicate p);
464 /// ComputeExitCountExhaustively - If the loop is known to execute a
465 /// constant number of times (the condition evolves only from constants),
466 /// try to evaluate a few iterations of the loop until we get the exit
467 /// condition gets a value of ExitWhen (true or false). If we cannot
468 /// evaluate the exit count of the loop, return CouldNotCompute.
469 const SCEV *ComputeExitCountExhaustively(const Loop *L,
473 /// HowFarToZero - Return the number of times an exit condition comparing
474 /// the specified value to zero will execute. If not computable, return
476 ExitLimit HowFarToZero(const SCEV *V, const Loop *L);
478 /// HowFarToNonZero - Return the number of times an exit condition checking
479 /// the specified value for nonzero will execute. If not computable, return
481 ExitLimit HowFarToNonZero(const SCEV *V, const Loop *L);
483 /// HowManyLessThans - Return the number of times an exit condition
484 /// containing the specified less-than comparison will execute. If not
485 /// computable, return CouldNotCompute. isSigned specifies whether the
486 /// less-than is signed.
487 ExitLimit HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
488 const Loop *L, bool isSigned);
490 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
491 /// (which may not be an immediate predecessor) which has exactly one
492 /// successor from which BB is reachable, or null if no such block is
494 std::pair<BasicBlock *, BasicBlock *>
495 getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
497 /// isImpliedCond - Test whether the condition described by Pred, LHS, and
498 /// RHS is true whenever the given FoundCondValue value evaluates to true.
499 bool isImpliedCond(ICmpInst::Predicate Pred,
500 const SCEV *LHS, const SCEV *RHS,
501 Value *FoundCondValue,
504 /// isImpliedCondOperands - Test whether the condition described by Pred,
505 /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
506 /// and FoundRHS is true.
507 bool isImpliedCondOperands(ICmpInst::Predicate Pred,
508 const SCEV *LHS, const SCEV *RHS,
509 const SCEV *FoundLHS, const SCEV *FoundRHS);
511 /// isImpliedCondOperandsHelper - Test whether the condition described by
512 /// Pred, LHS, and RHS is true whenever the condition described by Pred,
513 /// FoundLHS, and FoundRHS is true.
514 bool isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
515 const SCEV *LHS, const SCEV *RHS,
516 const SCEV *FoundLHS,
517 const SCEV *FoundRHS);
519 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
520 /// in the header of its containing loop, we know the loop executes a
521 /// constant number of times, and the PHI node is just a recurrence
522 /// involving constants, fold it.
523 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs,
526 /// isKnownPredicateWithRanges - Test if the given expression is known to
527 /// satisfy the condition described by Pred and the known constant ranges
530 bool isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
531 const SCEV *LHS, const SCEV *RHS);
533 /// forgetMemoizedResults - Drop memoized information computed for S.
534 void forgetMemoizedResults(const SCEV *S);
537 static char ID; // Pass identification, replacement for typeid
540 LLVMContext &getContext() const { return F->getContext(); }
542 /// isSCEVable - Test if values of the given type are analyzable within
543 /// the SCEV framework. This primarily includes integer types, and it
544 /// can optionally include pointer types if the ScalarEvolution class
545 /// has access to target-specific information.
546 bool isSCEVable(Type *Ty) const;
548 /// getTypeSizeInBits - Return the size in bits of the specified type,
549 /// for which isSCEVable must return true.
550 uint64_t getTypeSizeInBits(Type *Ty) const;
552 /// getEffectiveSCEVType - Return a type with the same bitwidth as
553 /// the given type and which represents how SCEV will treat the given
554 /// type, for which isSCEVable must return true. For pointer types,
555 /// this is the pointer-sized integer type.
556 Type *getEffectiveSCEVType(Type *Ty) const;
558 /// getSCEV - Return a SCEV expression for the full generality of the
559 /// specified expression.
560 const SCEV *getSCEV(Value *V);
562 const SCEV *getConstant(ConstantInt *V);
563 const SCEV *getConstant(const APInt& Val);
564 const SCEV *getConstant(Type *Ty, uint64_t V, bool isSigned = false);
565 const SCEV *getTruncateExpr(const SCEV *Op, Type *Ty);
566 const SCEV *getZeroExtendExpr(const SCEV *Op, Type *Ty);
567 const SCEV *getSignExtendExpr(const SCEV *Op, Type *Ty);
568 const SCEV *getAnyExtendExpr(const SCEV *Op, Type *Ty);
569 const SCEV *getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
570 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
571 const SCEV *getAddExpr(const SCEV *LHS, const SCEV *RHS,
572 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
573 SmallVector<const SCEV *, 2> Ops;
576 return getAddExpr(Ops, Flags);
578 const SCEV *getAddExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
579 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
580 SmallVector<const SCEV *, 3> Ops;
584 return getAddExpr(Ops, Flags);
586 const SCEV *getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
587 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
588 const SCEV *getMulExpr(const SCEV *LHS, const SCEV *RHS,
589 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap)
591 SmallVector<const SCEV *, 2> Ops;
594 return getMulExpr(Ops, Flags);
596 const SCEV *getMulExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
597 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
598 SmallVector<const SCEV *, 3> Ops;
602 return getMulExpr(Ops, Flags);
604 const SCEV *getUDivExpr(const SCEV *LHS, const SCEV *RHS);
605 const SCEV *getAddRecExpr(const SCEV *Start, const SCEV *Step,
606 const Loop *L, SCEV::NoWrapFlags Flags);
607 const SCEV *getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
608 const Loop *L, SCEV::NoWrapFlags Flags);
609 const SCEV *getAddRecExpr(const SmallVectorImpl<const SCEV *> &Operands,
610 const Loop *L, SCEV::NoWrapFlags Flags) {
611 SmallVector<const SCEV *, 4> NewOp(Operands.begin(), Operands.end());
612 return getAddRecExpr(NewOp, L, Flags);
614 const SCEV *getSMaxExpr(const SCEV *LHS, const SCEV *RHS);
615 const SCEV *getSMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
616 const SCEV *getUMaxExpr(const SCEV *LHS, const SCEV *RHS);
617 const SCEV *getUMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
618 const SCEV *getSMinExpr(const SCEV *LHS, const SCEV *RHS);
619 const SCEV *getUMinExpr(const SCEV *LHS, const SCEV *RHS);
620 const SCEV *getUnknown(Value *V);
621 const SCEV *getCouldNotCompute();
623 /// getSizeOfExpr - Return an expression for sizeof on the given type.
625 const SCEV *getSizeOfExpr(Type *AllocTy);
627 /// getAlignOfExpr - Return an expression for alignof on the given type.
629 const SCEV *getAlignOfExpr(Type *AllocTy);
631 /// getOffsetOfExpr - Return an expression for offsetof on the given field.
633 const SCEV *getOffsetOfExpr(StructType *STy, unsigned FieldNo);
635 /// getOffsetOfExpr - Return an expression for offsetof on the given field.
637 const SCEV *getOffsetOfExpr(Type *CTy, Constant *FieldNo);
639 /// getNegativeSCEV - Return the SCEV object corresponding to -V.
641 const SCEV *getNegativeSCEV(const SCEV *V);
643 /// getNotSCEV - Return the SCEV object corresponding to ~V.
645 const SCEV *getNotSCEV(const SCEV *V);
647 /// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
648 const SCEV *getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
649 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
651 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
652 /// of the input value to the specified type. If the type must be
653 /// extended, it is zero extended.
654 const SCEV *getTruncateOrZeroExtend(const SCEV *V, Type *Ty);
656 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
657 /// of the input value to the specified type. If the type must be
658 /// extended, it is sign extended.
659 const SCEV *getTruncateOrSignExtend(const SCEV *V, Type *Ty);
661 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of
662 /// the input value to the specified type. If the type must be extended,
663 /// it is zero extended. The conversion must not be narrowing.
664 const SCEV *getNoopOrZeroExtend(const SCEV *V, Type *Ty);
666 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of
667 /// the input value to the specified type. If the type must be extended,
668 /// it is sign extended. The conversion must not be narrowing.
669 const SCEV *getNoopOrSignExtend(const SCEV *V, Type *Ty);
671 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
672 /// the input value to the specified type. If the type must be extended,
673 /// it is extended with unspecified bits. The conversion must not be
675 const SCEV *getNoopOrAnyExtend(const SCEV *V, Type *Ty);
677 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
678 /// input value to the specified type. The conversion must not be
680 const SCEV *getTruncateOrNoop(const SCEV *V, Type *Ty);
682 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
683 /// the types using zero-extension, and then perform a umax operation
685 const SCEV *getUMaxFromMismatchedTypes(const SCEV *LHS,
688 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
689 /// the types using zero-extension, and then perform a umin operation
691 const SCEV *getUMinFromMismatchedTypes(const SCEV *LHS,
694 /// getPointerBase - Transitively follow the chain of pointer-type operands
695 /// until reaching a SCEV that does not have a single pointer operand. This
696 /// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
697 /// but corner cases do exist.
698 const SCEV *getPointerBase(const SCEV *V);
700 /// getSCEVAtScope - Return a SCEV expression for the specified value
701 /// at the specified scope in the program. The L value specifies a loop
702 /// nest to evaluate the expression at, where null is the top-level or a
703 /// specified loop is immediately inside of the loop.
705 /// This method can be used to compute the exit value for a variable defined
706 /// in a loop by querying what the value will hold in the parent loop.
708 /// In the case that a relevant loop exit value cannot be computed, the
709 /// original value V is returned.
710 const SCEV *getSCEVAtScope(const SCEV *S, const Loop *L);
712 /// getSCEVAtScope - This is a convenience function which does
713 /// getSCEVAtScope(getSCEV(V), L).
714 const SCEV *getSCEVAtScope(Value *V, const Loop *L);
716 /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
717 /// by a conditional between LHS and RHS. This is used to help avoid max
718 /// expressions in loop trip counts, and to eliminate casts.
719 bool isLoopEntryGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
720 const SCEV *LHS, const SCEV *RHS);
722 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
723 /// protected by a conditional between LHS and RHS. This is used to
724 /// to eliminate casts.
725 bool isLoopBackedgeGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
726 const SCEV *LHS, const SCEV *RHS);
728 /// getSmallConstantTripCount - Returns the maximum trip count of this loop
729 /// as a normal unsigned value, if possible. Returns 0 if the trip count is
730 /// unknown or not constant.
731 unsigned getSmallConstantTripCount(Loop *L, BasicBlock *ExitBlock);
733 /// getSmallConstantTripMultiple - Returns the largest constant divisor of
734 /// the trip count of this loop as a normal unsigned value, if
735 /// possible. This means that the actual trip count is always a multiple of
736 /// the returned value (don't forget the trip count could very well be zero
738 unsigned getSmallConstantTripMultiple(Loop *L, BasicBlock *ExitBlock);
740 // getExitCount - Get the expression for the number of loop iterations for
741 // which this loop is guaranteed not to exit via ExitingBlock. Otherwise
742 // return SCEVCouldNotCompute.
743 const SCEV *getExitCount(Loop *L, BasicBlock *ExitingBlock);
745 /// getBackedgeTakenCount - If the specified loop has a predictable
746 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
747 /// object. The backedge-taken count is the number of times the loop header
748 /// will be branched to from within the loop. This is one less than the
749 /// trip count of the loop, since it doesn't count the first iteration,
750 /// when the header is branched to from outside the loop.
752 /// Note that it is not valid to call this method on a loop without a
753 /// loop-invariant backedge-taken count (see
754 /// hasLoopInvariantBackedgeTakenCount).
756 const SCEV *getBackedgeTakenCount(const Loop *L);
758 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
759 /// return the least SCEV value that is known never to be less than the
760 /// actual backedge taken count.
761 const SCEV *getMaxBackedgeTakenCount(const Loop *L);
763 /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop
764 /// has an analyzable loop-invariant backedge-taken count.
765 bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
767 /// forgetLoop - This method should be called by the client when it has
768 /// changed a loop in a way that may effect ScalarEvolution's ability to
769 /// compute a trip count, or if the loop is deleted.
770 void forgetLoop(const Loop *L);
772 /// forgetValue - This method should be called by the client when it has
773 /// changed a value in a way that may effect its value, or which may
774 /// disconnect it from a def-use chain linking it to a loop.
775 void forgetValue(Value *V);
777 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S
778 /// is guaranteed to end in (at every loop iteration). It is, at the same
779 /// time, the minimum number of times S is divisible by 2. For example,
780 /// given {4,+,8} it returns 2. If S is guaranteed to be 0, it returns the
782 uint32_t GetMinTrailingZeros(const SCEV *S);
784 /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
786 ConstantRange getUnsignedRange(const SCEV *S);
788 /// getSignedRange - Determine the signed range for a particular SCEV.
790 ConstantRange getSignedRange(const SCEV *S);
792 /// isKnownNegative - Test if the given expression is known to be negative.
794 bool isKnownNegative(const SCEV *S);
796 /// isKnownPositive - Test if the given expression is known to be positive.
798 bool isKnownPositive(const SCEV *S);
800 /// isKnownNonNegative - Test if the given expression is known to be
803 bool isKnownNonNegative(const SCEV *S);
805 /// isKnownNonPositive - Test if the given expression is known to be
808 bool isKnownNonPositive(const SCEV *S);
810 /// isKnownNonZero - Test if the given expression is known to be
813 bool isKnownNonZero(const SCEV *S);
815 /// isKnownPredicate - Test if the given expression is known to satisfy
816 /// the condition described by Pred, LHS, and RHS.
818 bool isKnownPredicate(ICmpInst::Predicate Pred,
819 const SCEV *LHS, const SCEV *RHS);
821 /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
822 /// predicate Pred. Return true iff any changes were made. If the
823 /// operands are provably equal or inequal, LHS and RHS are set to
824 /// the same value and Pred is set to either ICMP_EQ or ICMP_NE.
826 bool SimplifyICmpOperands(ICmpInst::Predicate &Pred,
830 /// getLoopDisposition - Return the "disposition" of the given SCEV with
831 /// respect to the given loop.
832 LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L);
834 /// isLoopInvariant - Return true if the value of the given SCEV is
835 /// unchanging in the specified loop.
836 bool isLoopInvariant(const SCEV *S, const Loop *L);
838 /// hasComputableLoopEvolution - Return true if the given SCEV changes value
839 /// in a known way in the specified loop. This property being true implies
840 /// that the value is variant in the loop AND that we can emit an expression
841 /// to compute the value of the expression at any particular loop iteration.
842 bool hasComputableLoopEvolution(const SCEV *S, const Loop *L);
844 /// getLoopDisposition - Return the "disposition" of the given SCEV with
845 /// respect to the given block.
846 BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB);
848 /// dominates - Return true if elements that makes up the given SCEV
849 /// dominate the specified basic block.
850 bool dominates(const SCEV *S, const BasicBlock *BB);
852 /// properlyDominates - Return true if elements that makes up the given SCEV
853 /// properly dominate the specified basic block.
854 bool properlyDominates(const SCEV *S, const BasicBlock *BB);
856 /// hasOperand - Test whether the given SCEV has Op as a direct or
857 /// indirect operand.
858 bool hasOperand(const SCEV *S, const SCEV *Op) const;
860 virtual bool runOnFunction(Function &F);
861 virtual void releaseMemory();
862 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
863 virtual void print(raw_ostream &OS, const Module* = 0) const;
866 FoldingSet<SCEV> UniqueSCEVs;
867 BumpPtrAllocator SCEVAllocator;
869 /// FirstUnknown - The head of a linked list of all SCEVUnknown
870 /// values that have been allocated. This is used by releaseMemory
871 /// to locate them all and call their destructors.
872 SCEVUnknown *FirstUnknown;