LLVM API Documentation

ScalarEvolution.h
Go to the documentation of this file.
00001 //===- llvm/Analysis/ScalarEvolution.h - Scalar Evolution -------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // The ScalarEvolution class is an LLVM pass which can be used to analyze and
00011 // categorize scalar expressions in loops.  It specializes in recognizing
00012 // general induction variables, representing them with the abstract and opaque
00013 // SCEV class.  Given this analysis, trip counts of loops and other important
00014 // properties can be obtained.
00015 //
00016 // This analysis is primarily useful for induction variable substitution and
00017 // strength reduction.
00018 //
00019 //===----------------------------------------------------------------------===//
00020 
00021 #ifndef LLVM_ANALYSIS_SCALAREVOLUTION_H
00022 #define LLVM_ANALYSIS_SCALAREVOLUTION_H
00023 
00024 #include "llvm/ADT/DenseSet.h"
00025 #include "llvm/ADT/FoldingSet.h"
00026 #include "llvm/IR/Function.h"
00027 #include "llvm/IR/Instructions.h"
00028 #include "llvm/IR/Operator.h"
00029 #include "llvm/Pass.h"
00030 #include "llvm/Support/Allocator.h"
00031 #include "llvm/Support/ConstantRange.h"
00032 #include "llvm/Support/DataTypes.h"
00033 #include "llvm/Support/ValueHandle.h"
00034 #include <map>
00035 
00036 namespace llvm {
00037   class APInt;
00038   class Constant;
00039   class ConstantInt;
00040   class DominatorTree;
00041   class Type;
00042   class ScalarEvolution;
00043   class DataLayout;
00044   class TargetLibraryInfo;
00045   class LLVMContext;
00046   class Loop;
00047   class LoopInfo;
00048   class Operator;
00049   class SCEVUnknown;
00050   class SCEV;
00051   template<> struct FoldingSetTrait<SCEV>;
00052 
00053   /// SCEV - This class represents an analyzed expression in the program.  These
00054   /// are opaque objects that the client is not allowed to do much with
00055   /// directly.
00056   ///
00057   class SCEV : public FoldingSetNode {
00058     friend struct FoldingSetTrait<SCEV>;
00059 
00060     /// FastID - A reference to an Interned FoldingSetNodeID for this node.
00061     /// The ScalarEvolution's BumpPtrAllocator holds the data.
00062     FoldingSetNodeIDRef FastID;
00063 
00064     // The SCEV baseclass this node corresponds to
00065     const unsigned short SCEVType;
00066 
00067   protected:
00068     /// SubclassData - This field is initialized to zero and may be used in
00069     /// subclasses to store miscellaneous information.
00070     unsigned short SubclassData;
00071 
00072   private:
00073     SCEV(const SCEV &) LLVM_DELETED_FUNCTION;
00074     void operator=(const SCEV &) LLVM_DELETED_FUNCTION;
00075 
00076   public:
00077     /// NoWrapFlags are bitfield indices into SubclassData.
00078     ///
00079     /// Add and Mul expressions may have no-unsigned-wrap <NUW> or
00080     /// no-signed-wrap <NSW> properties, which are derived from the IR
00081     /// operator. NSW is a misnomer that we use to mean no signed overflow or
00082     /// underflow.
00083     ///
00084     /// AddRec expression may have a no-self-wraparound <NW> property if the
00085     /// result can never reach the start value. This property is independent of
00086     /// the actual start value and step direction. Self-wraparound is defined
00087     /// purely in terms of the recurrence's loop, step size, and
00088     /// bitwidth. Formally, a recurrence with no self-wraparound satisfies:
00089     /// abs(step) * max-iteration(loop) <= unsigned-max(bitwidth).
00090     ///
00091     /// Note that NUW and NSW are also valid properties of a recurrence, and
00092     /// either implies NW. For convenience, NW will be set for a recurrence
00093     /// whenever either NUW or NSW are set.
00094     enum NoWrapFlags { FlagAnyWrap = 0,          // No guarantee.
00095                        FlagNW      = (1 << 0),   // No self-wrap.
00096                        FlagNUW     = (1 << 1),   // No unsigned wrap.
00097                        FlagNSW     = (1 << 2),   // No signed wrap.
00098                        NoWrapMask  = (1 << 3) -1 };
00099 
00100     explicit SCEV(const FoldingSetNodeIDRef ID, unsigned SCEVTy) :
00101       FastID(ID), SCEVType(SCEVTy), SubclassData(0) {}
00102 
00103     unsigned getSCEVType() const { return SCEVType; }
00104 
00105     /// getType - Return the LLVM type of this SCEV expression.
00106     ///
00107     Type *getType() const;
00108 
00109     /// isZero - Return true if the expression is a constant zero.
00110     ///
00111     bool isZero() const;
00112 
00113     /// isOne - Return true if the expression is a constant one.
00114     ///
00115     bool isOne() const;
00116 
00117     /// isAllOnesValue - Return true if the expression is a constant
00118     /// all-ones value.
00119     ///
00120     bool isAllOnesValue() const;
00121 
00122     /// isNonConstantNegative - Return true if the specified scev is negated,
00123     /// but not a constant.
00124     bool isNonConstantNegative() const;
00125 
00126     /// print - Print out the internal representation of this scalar to the
00127     /// specified stream.  This should really only be used for debugging
00128     /// purposes.
00129     void print(raw_ostream &OS) const;
00130 
00131     /// dump - This method is used for debugging.
00132     ///
00133     void dump() const;
00134   };
00135 
00136   // Specialize FoldingSetTrait for SCEV to avoid needing to compute
00137   // temporary FoldingSetNodeID values.
00138   template<> struct FoldingSetTrait<SCEV> : DefaultFoldingSetTrait<SCEV> {
00139     static void Profile(const SCEV &X, FoldingSetNodeID& ID) {
00140       ID = X.FastID;
00141     }
00142     static bool Equals(const SCEV &X, const FoldingSetNodeID &ID,
00143                        unsigned IDHash, FoldingSetNodeID &TempID) {
00144       return ID == X.FastID;
00145     }
00146     static unsigned ComputeHash(const SCEV &X, FoldingSetNodeID &TempID) {
00147       return X.FastID.ComputeHash();
00148     }
00149   };
00150 
00151   inline raw_ostream &operator<<(raw_ostream &OS, const SCEV &S) {
00152     S.print(OS);
00153     return OS;
00154   }
00155 
00156   /// SCEVCouldNotCompute - An object of this class is returned by queries that
00157   /// could not be answered.  For example, if you ask for the number of
00158   /// iterations of a linked-list traversal loop, you will get one of these.
00159   /// None of the standard SCEV operations are valid on this class, it is just a
00160   /// marker.
00161   struct SCEVCouldNotCompute : public SCEV {
00162     SCEVCouldNotCompute();
00163 
00164     /// Methods for support type inquiry through isa, cast, and dyn_cast:
00165     static bool classof(const SCEV *S);
00166   };
00167 
00168   /// ScalarEvolution - This class is the main scalar evolution driver.  Because
00169   /// client code (intentionally) can't do much with the SCEV objects directly,
00170   /// they must ask this class for services.
00171   ///
00172   class ScalarEvolution : public FunctionPass {
00173   public:
00174     /// LoopDisposition - An enum describing the relationship between a
00175     /// SCEV and a loop.
00176     enum LoopDisposition {
00177       LoopVariant,    ///< The SCEV is loop-variant (unknown).
00178       LoopInvariant,  ///< The SCEV is loop-invariant.
00179       LoopComputable  ///< The SCEV varies predictably with the loop.
00180     };
00181 
00182     /// BlockDisposition - An enum describing the relationship between a
00183     /// SCEV and a basic block.
00184     enum BlockDisposition {
00185       DoesNotDominateBlock,  ///< The SCEV does not dominate the block.
00186       DominatesBlock,        ///< The SCEV dominates the block.
00187       ProperlyDominatesBlock ///< The SCEV properly dominates the block.
00188     };
00189 
00190     /// Convenient NoWrapFlags manipulation that hides enum casts and is
00191     /// visible in the ScalarEvolution name space.
00192     static SCEV::NoWrapFlags maskFlags(SCEV::NoWrapFlags Flags, int Mask) {
00193       return (SCEV::NoWrapFlags)(Flags & Mask);
00194     }
00195     static SCEV::NoWrapFlags setFlags(SCEV::NoWrapFlags Flags,
00196                                       SCEV::NoWrapFlags OnFlags) {
00197       return (SCEV::NoWrapFlags)(Flags | OnFlags);
00198     }
00199     static SCEV::NoWrapFlags clearFlags(SCEV::NoWrapFlags Flags,
00200                                         SCEV::NoWrapFlags OffFlags) {
00201       return (SCEV::NoWrapFlags)(Flags & ~OffFlags);
00202     }
00203 
00204   private:
00205     /// SCEVCallbackVH - A CallbackVH to arrange for ScalarEvolution to be
00206     /// notified whenever a Value is deleted.
00207     class SCEVCallbackVH : public CallbackVH {
00208       ScalarEvolution *SE;
00209       virtual void deleted();
00210       virtual void allUsesReplacedWith(Value *New);
00211     public:
00212       SCEVCallbackVH(Value *V, ScalarEvolution *SE = 0);
00213     };
00214 
00215     friend class SCEVCallbackVH;
00216     friend class SCEVExpander;
00217     friend class SCEVUnknown;
00218 
00219     /// F - The function we are analyzing.
00220     ///
00221     Function *F;
00222 
00223     /// LI - The loop information for the function we are currently analyzing.
00224     ///
00225     LoopInfo *LI;
00226 
00227     /// TD - The target data information for the target we are targeting.
00228     ///
00229     DataLayout *TD;
00230 
00231     /// TLI - The target library information for the target we are targeting.
00232     ///
00233     TargetLibraryInfo *TLI;
00234 
00235     /// DT - The dominator tree.
00236     ///
00237     DominatorTree *DT;
00238 
00239     /// CouldNotCompute - This SCEV is used to represent unknown trip
00240     /// counts and things.
00241     SCEVCouldNotCompute CouldNotCompute;
00242 
00243     /// ValueExprMapType - The typedef for ValueExprMap.
00244     ///
00245     typedef DenseMap<SCEVCallbackVH, const SCEV *, DenseMapInfo<Value *> >
00246       ValueExprMapType;
00247 
00248     /// ValueExprMap - This is a cache of the values we have analyzed so far.
00249     ///
00250     ValueExprMapType ValueExprMap;
00251 
00252     /// Mark predicate values currently being processed by isImpliedCond.
00253     DenseSet<Value*> PendingLoopPredicates;
00254 
00255     /// ExitLimit - Information about the number of loop iterations for
00256     /// which a loop exit's branch condition evaluates to the not-taken path.
00257     /// This is a temporary pair of exact and max expressions that are
00258     /// eventually summarized in ExitNotTakenInfo and BackedgeTakenInfo.
00259     struct ExitLimit {
00260       const SCEV *Exact;
00261       const SCEV *Max;
00262 
00263       /*implicit*/ ExitLimit(const SCEV *E) : Exact(E), Max(E) {}
00264 
00265       ExitLimit(const SCEV *E, const SCEV *M) : Exact(E), Max(M) {}
00266 
00267       /// hasAnyInfo - Test whether this ExitLimit contains any computed
00268       /// information, or whether it's all SCEVCouldNotCompute values.
00269       bool hasAnyInfo() const {
00270         return !isa<SCEVCouldNotCompute>(Exact) ||
00271           !isa<SCEVCouldNotCompute>(Max);
00272       }
00273     };
00274 
00275     /// ExitNotTakenInfo - Information about the number of times a particular
00276     /// loop exit may be reached before exiting the loop.
00277     struct ExitNotTakenInfo {
00278       AssertingVH<BasicBlock> ExitingBlock;
00279       const SCEV *ExactNotTaken;
00280       PointerIntPair<ExitNotTakenInfo*, 1> NextExit;
00281 
00282       ExitNotTakenInfo() : ExitingBlock(0), ExactNotTaken(0) {}
00283 
00284       /// isCompleteList - Return true if all loop exits are computable.
00285       bool isCompleteList() const {
00286         return NextExit.getInt() == 0;
00287       }
00288 
00289       void setIncomplete() { NextExit.setInt(1); }
00290 
00291       /// getNextExit - Return a pointer to the next exit's not-taken info.
00292       ExitNotTakenInfo *getNextExit() const {
00293         return NextExit.getPointer();
00294       }
00295 
00296       void setNextExit(ExitNotTakenInfo *ENT) { NextExit.setPointer(ENT); }
00297     };
00298 
00299     /// BackedgeTakenInfo - Information about the backedge-taken count
00300     /// of a loop. This currently includes an exact count and a maximum count.
00301     ///
00302     class BackedgeTakenInfo {
00303       /// ExitNotTaken - A list of computable exits and their not-taken counts.
00304       /// Loops almost never have more than one computable exit.
00305       ExitNotTakenInfo ExitNotTaken;
00306 
00307       /// Max - An expression indicating the least maximum backedge-taken
00308       /// count of the loop that is known, or a SCEVCouldNotCompute.
00309       const SCEV *Max;
00310 
00311     public:
00312       BackedgeTakenInfo() : Max(0) {}
00313 
00314       /// Initialize BackedgeTakenInfo from a list of exact exit counts.
00315       BackedgeTakenInfo(
00316         SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts,
00317         bool Complete, const SCEV *MaxCount);
00318 
00319       /// hasAnyInfo - Test whether this BackedgeTakenInfo contains any
00320       /// computed information, or whether it's all SCEVCouldNotCompute
00321       /// values.
00322       bool hasAnyInfo() const {
00323         return ExitNotTaken.ExitingBlock || !isa<SCEVCouldNotCompute>(Max);
00324       }
00325 
00326       /// getExact - Return an expression indicating the exact backedge-taken
00327       /// count of the loop if it is known, or SCEVCouldNotCompute
00328       /// otherwise. This is the number of times the loop header can be
00329       /// guaranteed to execute, minus one.
00330       const SCEV *getExact(ScalarEvolution *SE) const;
00331 
00332       /// getExact - Return the number of times this loop exit may fall through
00333       /// to the back edge, or SCEVCouldNotCompute. The loop is guaranteed not
00334       /// to exit via this block before this number of iterations, but may exit
00335       /// via another block.
00336       const SCEV *getExact(BasicBlock *ExitingBlock, ScalarEvolution *SE) const;
00337 
00338       /// getMax - Get the max backedge taken count for the loop.
00339       const SCEV *getMax(ScalarEvolution *SE) const;
00340 
00341       /// Return true if any backedge taken count expressions refer to the given
00342       /// subexpression.
00343       bool hasOperand(const SCEV *S, ScalarEvolution *SE) const;
00344 
00345       /// clear - Invalidate this result and free associated memory.
00346       void clear();
00347     };
00348 
00349     /// BackedgeTakenCounts - Cache the backedge-taken count of the loops for
00350     /// this function as they are computed.
00351     DenseMap<const Loop*, BackedgeTakenInfo> BackedgeTakenCounts;
00352 
00353     /// ConstantEvolutionLoopExitValue - This map contains entries for all of
00354     /// the PHI instructions that we attempt to compute constant evolutions for.
00355     /// This allows us to avoid potentially expensive recomputation of these
00356     /// properties.  An instruction maps to null if we are unable to compute its
00357     /// exit value.
00358     DenseMap<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
00359 
00360     /// ValuesAtScopes - This map contains entries for all the expressions
00361     /// that we attempt to compute getSCEVAtScope information for, which can
00362     /// be expensive in extreme cases.
00363     DenseMap<const SCEV *,
00364              std::map<const Loop *, const SCEV *> > ValuesAtScopes;
00365 
00366     /// LoopDispositions - Memoized computeLoopDisposition results.
00367     DenseMap<const SCEV *,
00368              std::map<const Loop *, LoopDisposition> > LoopDispositions;
00369 
00370     /// computeLoopDisposition - Compute a LoopDisposition value.
00371     LoopDisposition computeLoopDisposition(const SCEV *S, const Loop *L);
00372 
00373     /// BlockDispositions - Memoized computeBlockDisposition results.
00374     DenseMap<const SCEV *,
00375              std::map<const BasicBlock *, BlockDisposition> > BlockDispositions;
00376 
00377     /// computeBlockDisposition - Compute a BlockDisposition value.
00378     BlockDisposition computeBlockDisposition(const SCEV *S, const BasicBlock *BB);
00379 
00380     /// UnsignedRanges - Memoized results from getUnsignedRange
00381     DenseMap<const SCEV *, ConstantRange> UnsignedRanges;
00382 
00383     /// SignedRanges - Memoized results from getSignedRange
00384     DenseMap<const SCEV *, ConstantRange> SignedRanges;
00385 
00386     /// setUnsignedRange - Set the memoized unsigned range for the given SCEV.
00387     const ConstantRange &setUnsignedRange(const SCEV *S,
00388                                           const ConstantRange &CR) {
00389       std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair =
00390         UnsignedRanges.insert(std::make_pair(S, CR));
00391       if (!Pair.second)
00392         Pair.first->second = CR;
00393       return Pair.first->second;
00394     }
00395 
00396     /// setUnsignedRange - Set the memoized signed range for the given SCEV.
00397     const ConstantRange &setSignedRange(const SCEV *S,
00398                                         const ConstantRange &CR) {
00399       std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair =
00400         SignedRanges.insert(std::make_pair(S, CR));
00401       if (!Pair.second)
00402         Pair.first->second = CR;
00403       return Pair.first->second;
00404     }
00405 
00406     /// createSCEV - We know that there is no SCEV for the specified value.
00407     /// Analyze the expression.
00408     const SCEV *createSCEV(Value *V);
00409 
00410     /// createNodeForPHI - Provide the special handling we need to analyze PHI
00411     /// SCEVs.
00412     const SCEV *createNodeForPHI(PHINode *PN);
00413 
00414     /// createNodeForGEP - Provide the special handling we need to analyze GEP
00415     /// SCEVs.
00416     const SCEV *createNodeForGEP(GEPOperator *GEP);
00417 
00418     /// computeSCEVAtScope - Implementation code for getSCEVAtScope; called
00419     /// at most once for each SCEV+Loop pair.
00420     ///
00421     const SCEV *computeSCEVAtScope(const SCEV *S, const Loop *L);
00422 
00423     /// ForgetSymbolicValue - This looks up computed SCEV values for all
00424     /// instructions that depend on the given instruction and removes them from
00425     /// the ValueExprMap map if they reference SymName. This is used during PHI
00426     /// resolution.
00427     void ForgetSymbolicName(Instruction *I, const SCEV *SymName);
00428 
00429     /// getBECount - Subtract the end and start values and divide by the step,
00430     /// rounding up, to get the number of times the backedge is executed. Return
00431     /// CouldNotCompute if an intermediate computation overflows.
00432     const SCEV *getBECount(const SCEV *Start,
00433                            const SCEV *End,
00434                            const SCEV *Step,
00435                            bool NoWrap);
00436 
00437     /// getBackedgeTakenInfo - Return the BackedgeTakenInfo for the given
00438     /// loop, lazily computing new values if the loop hasn't been analyzed
00439     /// yet.
00440     const BackedgeTakenInfo &getBackedgeTakenInfo(const Loop *L);
00441 
00442     /// ComputeBackedgeTakenCount - Compute the number of times the specified
00443     /// loop will iterate.
00444     BackedgeTakenInfo ComputeBackedgeTakenCount(const Loop *L);
00445 
00446     /// ComputeExitLimit - Compute the number of times the backedge of the
00447     /// specified loop will execute if it exits via the specified block.
00448     ExitLimit ComputeExitLimit(const Loop *L, BasicBlock *ExitingBlock);
00449 
00450     /// ComputeExitLimitFromCond - Compute the number of times the backedge of
00451     /// the specified loop will execute if its exit condition were a conditional
00452     /// branch of ExitCond, TBB, and FBB.
00453     ExitLimit ComputeExitLimitFromCond(const Loop *L,
00454                                        Value *ExitCond,
00455                                        BasicBlock *TBB,
00456                                        BasicBlock *FBB);
00457 
00458     /// ComputeExitLimitFromICmp - Compute the number of times the backedge of
00459     /// the specified loop will execute if its exit condition were a conditional
00460     /// branch of the ICmpInst ExitCond, TBB, and FBB.
00461     ExitLimit ComputeExitLimitFromICmp(const Loop *L,
00462                                        ICmpInst *ExitCond,
00463                                        BasicBlock *TBB,
00464                                        BasicBlock *FBB);
00465 
00466     /// ComputeLoadConstantCompareExitLimit - Given an exit condition
00467     /// of 'icmp op load X, cst', try to see if we can compute the
00468     /// backedge-taken count.
00469     ExitLimit ComputeLoadConstantCompareExitLimit(LoadInst *LI,
00470                                                   Constant *RHS,
00471                                                   const Loop *L,
00472                                                   ICmpInst::Predicate p);
00473 
00474     /// ComputeExitCountExhaustively - If the loop is known to execute a
00475     /// constant number of times (the condition evolves only from constants),
00476     /// try to evaluate a few iterations of the loop until we get the exit
00477     /// condition gets a value of ExitWhen (true or false).  If we cannot
00478     /// evaluate the exit count of the loop, return CouldNotCompute.
00479     const SCEV *ComputeExitCountExhaustively(const Loop *L,
00480                                              Value *Cond,
00481                                              bool ExitWhen);
00482 
00483     /// HowFarToZero - Return the number of times an exit condition comparing
00484     /// the specified value to zero will execute.  If not computable, return
00485     /// CouldNotCompute.
00486     ExitLimit HowFarToZero(const SCEV *V, const Loop *L);
00487 
00488     /// HowFarToNonZero - Return the number of times an exit condition checking
00489     /// the specified value for nonzero will execute.  If not computable, return
00490     /// CouldNotCompute.
00491     ExitLimit HowFarToNonZero(const SCEV *V, const Loop *L);
00492 
00493     /// HowManyLessThans - Return the number of times an exit condition
00494     /// containing the specified less-than comparison will execute.  If not
00495     /// computable, return CouldNotCompute. isSigned specifies whether the
00496     /// less-than is signed.
00497     ExitLimit HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
00498                                const Loop *L, bool isSigned);
00499 
00500     /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
00501     /// (which may not be an immediate predecessor) which has exactly one
00502     /// successor from which BB is reachable, or null if no such block is
00503     /// found.
00504     std::pair<BasicBlock *, BasicBlock *>
00505     getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
00506 
00507     /// isImpliedCond - Test whether the condition described by Pred, LHS, and
00508     /// RHS is true whenever the given FoundCondValue value evaluates to true.
00509     bool isImpliedCond(ICmpInst::Predicate Pred,
00510                        const SCEV *LHS, const SCEV *RHS,
00511                        Value *FoundCondValue,
00512                        bool Inverse);
00513 
00514     /// isImpliedCondOperands - Test whether the condition described by Pred,
00515     /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
00516     /// and FoundRHS is true.
00517     bool isImpliedCondOperands(ICmpInst::Predicate Pred,
00518                                const SCEV *LHS, const SCEV *RHS,
00519                                const SCEV *FoundLHS, const SCEV *FoundRHS);
00520 
00521     /// isImpliedCondOperandsHelper - Test whether the condition described by
00522     /// Pred, LHS, and RHS is true whenever the condition described by Pred,
00523     /// FoundLHS, and FoundRHS is true.
00524     bool isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
00525                                      const SCEV *LHS, const SCEV *RHS,
00526                                      const SCEV *FoundLHS,
00527                                      const SCEV *FoundRHS);
00528 
00529     /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
00530     /// in the header of its containing loop, we know the loop executes a
00531     /// constant number of times, and the PHI node is just a recurrence
00532     /// involving constants, fold it.
00533     Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs,
00534                                                 const Loop *L);
00535 
00536     /// isKnownPredicateWithRanges - Test if the given expression is known to
00537     /// satisfy the condition described by Pred and the known constant ranges
00538     /// of LHS and RHS.
00539     ///
00540     bool isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
00541                                     const SCEV *LHS, const SCEV *RHS);
00542 
00543     /// forgetMemoizedResults - Drop memoized information computed for S.
00544     void forgetMemoizedResults(const SCEV *S);
00545 
00546   public:
00547     static char ID; // Pass identification, replacement for typeid
00548     ScalarEvolution();
00549 
00550     LLVMContext &getContext() const { return F->getContext(); }
00551 
00552     /// isSCEVable - Test if values of the given type are analyzable within
00553     /// the SCEV framework. This primarily includes integer types, and it
00554     /// can optionally include pointer types if the ScalarEvolution class
00555     /// has access to target-specific information.
00556     bool isSCEVable(Type *Ty) const;
00557 
00558     /// getTypeSizeInBits - Return the size in bits of the specified type,
00559     /// for which isSCEVable must return true.
00560     uint64_t getTypeSizeInBits(Type *Ty) const;
00561 
00562     /// getEffectiveSCEVType - Return a type with the same bitwidth as
00563     /// the given type and which represents how SCEV will treat the given
00564     /// type, for which isSCEVable must return true. For pointer types,
00565     /// this is the pointer-sized integer type.
00566     Type *getEffectiveSCEVType(Type *Ty) const;
00567 
00568     /// getSCEV - Return a SCEV expression for the full generality of the
00569     /// specified expression.
00570     const SCEV *getSCEV(Value *V);
00571 
00572     const SCEV *getConstant(ConstantInt *V);
00573     const SCEV *getConstant(const APInt& Val);
00574     const SCEV *getConstant(Type *Ty, uint64_t V, bool isSigned = false);
00575     const SCEV *getTruncateExpr(const SCEV *Op, Type *Ty);
00576     const SCEV *getZeroExtendExpr(const SCEV *Op, Type *Ty);
00577     const SCEV *getSignExtendExpr(const SCEV *Op, Type *Ty);
00578     const SCEV *getAnyExtendExpr(const SCEV *Op, Type *Ty);
00579     const SCEV *getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
00580                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
00581     const SCEV *getAddExpr(const SCEV *LHS, const SCEV *RHS,
00582                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
00583       SmallVector<const SCEV *, 2> Ops;
00584       Ops.push_back(LHS);
00585       Ops.push_back(RHS);
00586       return getAddExpr(Ops, Flags);
00587     }
00588     const SCEV *getAddExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
00589                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
00590       SmallVector<const SCEV *, 3> Ops;
00591       Ops.push_back(Op0);
00592       Ops.push_back(Op1);
00593       Ops.push_back(Op2);
00594       return getAddExpr(Ops, Flags);
00595     }
00596     const SCEV *getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
00597                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
00598     const SCEV *getMulExpr(const SCEV *LHS, const SCEV *RHS,
00599                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap)
00600     {
00601       SmallVector<const SCEV *, 2> Ops;
00602       Ops.push_back(LHS);
00603       Ops.push_back(RHS);
00604       return getMulExpr(Ops, Flags);
00605     }
00606     const SCEV *getMulExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
00607                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
00608       SmallVector<const SCEV *, 3> Ops;
00609       Ops.push_back(Op0);
00610       Ops.push_back(Op1);
00611       Ops.push_back(Op2);
00612       return getMulExpr(Ops, Flags);
00613     }
00614     const SCEV *getUDivExpr(const SCEV *LHS, const SCEV *RHS);
00615     const SCEV *getAddRecExpr(const SCEV *Start, const SCEV *Step,
00616                               const Loop *L, SCEV::NoWrapFlags Flags);
00617     const SCEV *getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
00618                               const Loop *L, SCEV::NoWrapFlags Flags);
00619     const SCEV *getAddRecExpr(const SmallVectorImpl<const SCEV *> &Operands,
00620                               const Loop *L, SCEV::NoWrapFlags Flags) {
00621       SmallVector<const SCEV *, 4> NewOp(Operands.begin(), Operands.end());
00622       return getAddRecExpr(NewOp, L, Flags);
00623     }
00624     const SCEV *getSMaxExpr(const SCEV *LHS, const SCEV *RHS);
00625     const SCEV *getSMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
00626     const SCEV *getUMaxExpr(const SCEV *LHS, const SCEV *RHS);
00627     const SCEV *getUMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
00628     const SCEV *getSMinExpr(const SCEV *LHS, const SCEV *RHS);
00629     const SCEV *getUMinExpr(const SCEV *LHS, const SCEV *RHS);
00630     const SCEV *getUnknown(Value *V);
00631     const SCEV *getCouldNotCompute();
00632 
00633     /// getSizeOfExpr - Return an expression for sizeof on the given type.
00634     ///
00635     const SCEV *getSizeOfExpr(Type *AllocTy);
00636 
00637     /// getAlignOfExpr - Return an expression for alignof on the given type.
00638     ///
00639     const SCEV *getAlignOfExpr(Type *AllocTy);
00640 
00641     /// getOffsetOfExpr - Return an expression for offsetof on the given field.
00642     ///
00643     const SCEV *getOffsetOfExpr(StructType *STy, unsigned FieldNo);
00644 
00645     /// getOffsetOfExpr - Return an expression for offsetof on the given field.
00646     ///
00647     const SCEV *getOffsetOfExpr(Type *CTy, Constant *FieldNo);
00648 
00649     /// getNegativeSCEV - Return the SCEV object corresponding to -V.
00650     ///
00651     const SCEV *getNegativeSCEV(const SCEV *V);
00652 
00653     /// getNotSCEV - Return the SCEV object corresponding to ~V.
00654     ///
00655     const SCEV *getNotSCEV(const SCEV *V);
00656 
00657     /// getMinusSCEV - Return LHS-RHS.  Minus is represented in SCEV as A+B*-1.
00658     const SCEV *getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
00659                              SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
00660 
00661     /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
00662     /// of the input value to the specified type.  If the type must be
00663     /// extended, it is zero extended.
00664     const SCEV *getTruncateOrZeroExtend(const SCEV *V, Type *Ty);
00665 
00666     /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
00667     /// of the input value to the specified type.  If the type must be
00668     /// extended, it is sign extended.
00669     const SCEV *getTruncateOrSignExtend(const SCEV *V, Type *Ty);
00670 
00671     /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of
00672     /// the input value to the specified type.  If the type must be extended,
00673     /// it is zero extended.  The conversion must not be narrowing.
00674     const SCEV *getNoopOrZeroExtend(const SCEV *V, Type *Ty);
00675 
00676     /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of
00677     /// the input value to the specified type.  If the type must be extended,
00678     /// it is sign extended.  The conversion must not be narrowing.
00679     const SCEV *getNoopOrSignExtend(const SCEV *V, Type *Ty);
00680 
00681     /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
00682     /// the input value to the specified type. If the type must be extended,
00683     /// it is extended with unspecified bits. The conversion must not be
00684     /// narrowing.
00685     const SCEV *getNoopOrAnyExtend(const SCEV *V, Type *Ty);
00686 
00687     /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
00688     /// input value to the specified type.  The conversion must not be
00689     /// widening.
00690     const SCEV *getTruncateOrNoop(const SCEV *V, Type *Ty);
00691 
00692     /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
00693     /// the types using zero-extension, and then perform a umax operation
00694     /// with them.
00695     const SCEV *getUMaxFromMismatchedTypes(const SCEV *LHS,
00696                                            const SCEV *RHS);
00697 
00698     /// getUMinFromMismatchedTypes - Promote the operands to the wider of
00699     /// the types using zero-extension, and then perform a umin operation
00700     /// with them.
00701     const SCEV *getUMinFromMismatchedTypes(const SCEV *LHS,
00702                                            const SCEV *RHS);
00703 
00704     /// getPointerBase - Transitively follow the chain of pointer-type operands
00705     /// until reaching a SCEV that does not have a single pointer operand. This
00706     /// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
00707     /// but corner cases do exist.
00708     const SCEV *getPointerBase(const SCEV *V);
00709 
00710     /// getSCEVAtScope - Return a SCEV expression for the specified value
00711     /// at the specified scope in the program.  The L value specifies a loop
00712     /// nest to evaluate the expression at, where null is the top-level or a
00713     /// specified loop is immediately inside of the loop.
00714     ///
00715     /// This method can be used to compute the exit value for a variable defined
00716     /// in a loop by querying what the value will hold in the parent loop.
00717     ///
00718     /// In the case that a relevant loop exit value cannot be computed, the
00719     /// original value V is returned.
00720     const SCEV *getSCEVAtScope(const SCEV *S, const Loop *L);
00721 
00722     /// getSCEVAtScope - This is a convenience function which does
00723     /// getSCEVAtScope(getSCEV(V), L).
00724     const SCEV *getSCEVAtScope(Value *V, const Loop *L);
00725 
00726     /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
00727     /// by a conditional between LHS and RHS.  This is used to help avoid max
00728     /// expressions in loop trip counts, and to eliminate casts.
00729     bool isLoopEntryGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
00730                                   const SCEV *LHS, const SCEV *RHS);
00731 
00732     /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
00733     /// protected by a conditional between LHS and RHS.  This is used to
00734     /// to eliminate casts.
00735     bool isLoopBackedgeGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
00736                                      const SCEV *LHS, const SCEV *RHS);
00737 
00738     /// getSmallConstantTripCount - Returns the maximum trip count of this loop
00739     /// as a normal unsigned value. Returns 0 if the trip count is unknown or
00740     /// not constant. This "trip count" assumes that control exits via
00741     /// ExitingBlock. More precisely, it is the number of times that control may
00742     /// reach ExitingBlock before taking the branch. For loops with multiple
00743     /// exits, it may not be the number times that the loop header executes if
00744     /// the loop exits prematurely via another branch.
00745     unsigned getSmallConstantTripCount(Loop *L, BasicBlock *ExitingBlock);
00746 
00747     /// getSmallConstantTripMultiple - Returns the largest constant divisor of
00748     /// the trip count of this loop as a normal unsigned value, if
00749     /// possible. This means that the actual trip count is always a multiple of
00750     /// the returned value (don't forget the trip count could very well be zero
00751     /// as well!). As explained in the comments for getSmallConstantTripCount,
00752     /// this assumes that control exits the loop via ExitingBlock.
00753     unsigned getSmallConstantTripMultiple(Loop *L, BasicBlock *ExitingBlock);
00754 
00755     // getExitCount - Get the expression for the number of loop iterations for
00756     // which this loop is guaranteed not to exit via ExitingBlock. Otherwise
00757     // return SCEVCouldNotCompute.
00758     const SCEV *getExitCount(Loop *L, BasicBlock *ExitingBlock);
00759 
00760     /// getBackedgeTakenCount - If the specified loop has a predictable
00761     /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
00762     /// object. The backedge-taken count is the number of times the loop header
00763     /// will be branched to from within the loop. This is one less than the
00764     /// trip count of the loop, since it doesn't count the first iteration,
00765     /// when the header is branched to from outside the loop.
00766     ///
00767     /// Note that it is not valid to call this method on a loop without a
00768     /// loop-invariant backedge-taken count (see
00769     /// hasLoopInvariantBackedgeTakenCount).
00770     ///
00771     const SCEV *getBackedgeTakenCount(const Loop *L);
00772 
00773     /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
00774     /// return the least SCEV value that is known never to be less than the
00775     /// actual backedge taken count.
00776     const SCEV *getMaxBackedgeTakenCount(const Loop *L);
00777 
00778     /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop
00779     /// has an analyzable loop-invariant backedge-taken count.
00780     bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
00781 
00782     /// forgetLoop - This method should be called by the client when it has
00783     /// changed a loop in a way that may effect ScalarEvolution's ability to
00784     /// compute a trip count, or if the loop is deleted.
00785     void forgetLoop(const Loop *L);
00786 
00787     /// forgetValue - This method should be called by the client when it has
00788     /// changed a value in a way that may effect its value, or which may
00789     /// disconnect it from a def-use chain linking it to a loop.
00790     void forgetValue(Value *V);
00791 
00792     /// GetMinTrailingZeros - Determine the minimum number of zero bits that S
00793     /// is guaranteed to end in (at every loop iteration).  It is, at the same
00794     /// time, the minimum number of times S is divisible by 2.  For example,
00795     /// given {4,+,8} it returns 2.  If S is guaranteed to be 0, it returns the
00796     /// bitwidth of S.
00797     uint32_t GetMinTrailingZeros(const SCEV *S);
00798 
00799     /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
00800     ///
00801     ConstantRange getUnsignedRange(const SCEV *S);
00802 
00803     /// getSignedRange - Determine the signed range for a particular SCEV.
00804     ///
00805     ConstantRange getSignedRange(const SCEV *S);
00806 
00807     /// isKnownNegative - Test if the given expression is known to be negative.
00808     ///
00809     bool isKnownNegative(const SCEV *S);
00810 
00811     /// isKnownPositive - Test if the given expression is known to be positive.
00812     ///
00813     bool isKnownPositive(const SCEV *S);
00814 
00815     /// isKnownNonNegative - Test if the given expression is known to be
00816     /// non-negative.
00817     ///
00818     bool isKnownNonNegative(const SCEV *S);
00819 
00820     /// isKnownNonPositive - Test if the given expression is known to be
00821     /// non-positive.
00822     ///
00823     bool isKnownNonPositive(const SCEV *S);
00824 
00825     /// isKnownNonZero - Test if the given expression is known to be
00826     /// non-zero.
00827     ///
00828     bool isKnownNonZero(const SCEV *S);
00829 
00830     /// isKnownPredicate - Test if the given expression is known to satisfy
00831     /// the condition described by Pred, LHS, and RHS.
00832     ///
00833     bool isKnownPredicate(ICmpInst::Predicate Pred,
00834                           const SCEV *LHS, const SCEV *RHS);
00835 
00836     /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
00837     /// predicate Pred. Return true iff any changes were made. If the
00838     /// operands are provably equal or unequal, LHS and RHS are set to
00839     /// the same value and Pred is set to either ICMP_EQ or ICMP_NE.
00840     ///
00841     bool SimplifyICmpOperands(ICmpInst::Predicate &Pred,
00842                               const SCEV *&LHS,
00843                               const SCEV *&RHS,
00844                               unsigned Depth = 0);
00845 
00846     /// getLoopDisposition - Return the "disposition" of the given SCEV with
00847     /// respect to the given loop.
00848     LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L);
00849 
00850     /// isLoopInvariant - Return true if the value of the given SCEV is
00851     /// unchanging in the specified loop.
00852     bool isLoopInvariant(const SCEV *S, const Loop *L);
00853 
00854     /// hasComputableLoopEvolution - Return true if the given SCEV changes value
00855     /// in a known way in the specified loop.  This property being true implies
00856     /// that the value is variant in the loop AND that we can emit an expression
00857     /// to compute the value of the expression at any particular loop iteration.
00858     bool hasComputableLoopEvolution(const SCEV *S, const Loop *L);
00859 
00860     /// getLoopDisposition - Return the "disposition" of the given SCEV with
00861     /// respect to the given block.
00862     BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB);
00863 
00864     /// dominates - Return true if elements that makes up the given SCEV
00865     /// dominate the specified basic block.
00866     bool dominates(const SCEV *S, const BasicBlock *BB);
00867 
00868     /// properlyDominates - Return true if elements that makes up the given SCEV
00869     /// properly dominate the specified basic block.
00870     bool properlyDominates(const SCEV *S, const BasicBlock *BB);
00871 
00872     /// hasOperand - Test whether the given SCEV has Op as a direct or
00873     /// indirect operand.
00874     bool hasOperand(const SCEV *S, const SCEV *Op) const;
00875 
00876     virtual bool runOnFunction(Function &F);
00877     virtual void releaseMemory();
00878     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
00879     virtual void print(raw_ostream &OS, const Module* = 0) const;
00880     virtual void verifyAnalysis() const;
00881 
00882   private:
00883     FoldingSet<SCEV> UniqueSCEVs;
00884     BumpPtrAllocator SCEVAllocator;
00885 
00886     /// FirstUnknown - The head of a linked list of all SCEVUnknown
00887     /// values that have been allocated. This is used by releaseMemory
00888     /// to locate them all and call their destructors.
00889     SCEVUnknown *FirstUnknown;
00890   };
00891 }
00892 
00893 #endif