Home | History | Annotate | Download | only in Analysis
      1 //===- llvm/Analysis/ScalarEvolution.h - Scalar Evolution -------*- C++ -*-===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     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.
     15 //
     16 // This analysis is primarily useful for induction variable substitution and
     17 // strength reduction.
     18 //
     19 //===----------------------------------------------------------------------===//
     20 
     21 #ifndef LLVM_ANALYSIS_SCALAREVOLUTION_H
     22 #define LLVM_ANALYSIS_SCALAREVOLUTION_H
     23 
     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"
     34 #include <map>
     35 
     36 namespace llvm {
     37   class APInt;
     38   class Constant;
     39   class ConstantInt;
     40   class DominatorTree;
     41   class Type;
     42   class ScalarEvolution;
     43   class TargetData;
     44   class LLVMContext;
     45   class Loop;
     46   class LoopInfo;
     47   class Operator;
     48   class SCEVUnknown;
     49   class SCEV;
     50   template<> struct FoldingSetTrait<SCEV>;
     51 
     52   /// SCEV - This class represents an analyzed expression in the program.  These
     53   /// are opaque objects that the client is not allowed to do much with
     54   /// directly.
     55   ///
     56   class SCEV : public FoldingSetNode {
     57     friend struct FoldingSetTrait<SCEV>;
     58 
     59     /// FastID - A reference to an Interned FoldingSetNodeID for this node.
     60     /// The ScalarEvolution's BumpPtrAllocator holds the data.
     61     FoldingSetNodeIDRef FastID;
     62 
     63     // The SCEV baseclass this node corresponds to
     64     const unsigned short SCEVType;
     65 
     66   protected:
     67     /// SubclassData - This field is initialized to zero and may be used in
     68     /// subclasses to store miscellaneous information.
     69     unsigned short SubclassData;
     70 
     71   private:
     72     SCEV(const SCEV &);            // DO NOT IMPLEMENT
     73     void operator=(const SCEV &);  // DO NOT IMPLEMENT
     74 
     75   public:
     76     /// NoWrapFlags are bitfield indices into SubclassData.
     77     ///
     78     /// Add and Mul expressions may have no-unsigned-wrap <NUW> or
     79     /// no-signed-wrap <NSW> properties, which are derived from the IR
     80     /// operator. NSW is a misnomer that we use to mean no signed overflow or
     81     /// underflow.
     82     ///
     83     /// AddRec expression may have a no-self-wraparound <NW> property if the
     84     /// result can never reach the start value. This property is independent of
     85     /// the actual start value and step direction. Self-wraparound is defined
     86     /// purely in terms of the recurrence's loop, step size, and
     87     /// bitwidth. Formally, a recurrence with no self-wraparound satisfies:
     88     /// abs(step) * max-iteration(loop) <= unsigned-max(bitwidth).
     89     ///
     90     /// Note that NUW and NSW are also valid properties of a recurrence, and
     91     /// either implies NW. For convenience, NW will be set for a recurrence
     92     /// whenever either NUW or NSW are set.
     93     enum NoWrapFlags { FlagAnyWrap = 0,          // No guarantee.
     94                        FlagNW      = (1 << 0),   // No self-wrap.
     95                        FlagNUW     = (1 << 1),   // No unsigned wrap.
     96                        FlagNSW     = (1 << 2),   // No signed wrap.
     97                        NoWrapMask  = (1 << 3) -1 };
     98 
     99     explicit SCEV(const FoldingSetNodeIDRef ID, unsigned SCEVTy) :
    100       FastID(ID), SCEVType(SCEVTy), SubclassData(0) {}
    101 
    102     unsigned getSCEVType() const { return SCEVType; }
    103 
    104     /// getType - Return the LLVM type of this SCEV expression.
    105     ///
    106     Type *getType() const;
    107 
    108     /// isZero - Return true if the expression is a constant zero.
    109     ///
    110     bool isZero() const;
    111 
    112     /// isOne - Return true if the expression is a constant one.
    113     ///
    114     bool isOne() const;
    115 
    116     /// isAllOnesValue - Return true if the expression is a constant
    117     /// all-ones value.
    118     ///
    119     bool isAllOnesValue() const;
    120 
    121     /// print - Print out the internal representation of this scalar to the
    122     /// specified stream.  This should really only be used for debugging
    123     /// purposes.
    124     void print(raw_ostream &OS) const;
    125 
    126     /// dump - This method is used for debugging.
    127     ///
    128     void dump() const;
    129   };
    130 
    131   // Specialize FoldingSetTrait for SCEV to avoid needing to compute
    132   // temporary FoldingSetNodeID values.
    133   template<> struct FoldingSetTrait<SCEV> : DefaultFoldingSetTrait<SCEV> {
    134     static void Profile(const SCEV &X, FoldingSetNodeID& ID) {
    135       ID = X.FastID;
    136     }
    137     static bool Equals(const SCEV &X, const FoldingSetNodeID &ID,
    138                        FoldingSetNodeID &TempID) {
    139       return ID == X.FastID;
    140     }
    141     static unsigned ComputeHash(const SCEV &X, FoldingSetNodeID &TempID) {
    142       return X.FastID.ComputeHash();
    143     }
    144   };
    145 
    146   inline raw_ostream &operator<<(raw_ostream &OS, const SCEV &S) {
    147     S.print(OS);
    148     return OS;
    149   }
    150 
    151   /// SCEVCouldNotCompute - An object of this class is returned by queries that
    152   /// could not be answered.  For example, if you ask for the number of
    153   /// iterations of a linked-list traversal loop, you will get one of these.
    154   /// None of the standard SCEV operations are valid on this class, it is just a
    155   /// marker.
    156   struct SCEVCouldNotCompute : public SCEV {
    157     SCEVCouldNotCompute();
    158 
    159     /// Methods for support type inquiry through isa, cast, and dyn_cast:
    160     static inline bool classof(const SCEVCouldNotCompute *S) { return true; }
    161     static bool classof(const SCEV *S);
    162   };
    163 
    164   /// ScalarEvolution - This class is the main scalar evolution driver.  Because
    165   /// client code (intentionally) can't do much with the SCEV objects directly,
    166   /// they must ask this class for services.
    167   ///
    168   class ScalarEvolution : public FunctionPass {
    169   public:
    170     /// LoopDisposition - An enum describing the relationship between a
    171     /// SCEV and a loop.
    172     enum LoopDisposition {
    173       LoopVariant,    ///< The SCEV is loop-variant (unknown).
    174       LoopInvariant,  ///< The SCEV is loop-invariant.
    175       LoopComputable  ///< The SCEV varies predictably with the loop.
    176     };
    177 
    178     /// BlockDisposition - An enum describing the relationship between a
    179     /// SCEV and a basic block.
    180     enum BlockDisposition {
    181       DoesNotDominateBlock,  ///< The SCEV does not dominate the block.
    182       DominatesBlock,        ///< The SCEV dominates the block.
    183       ProperlyDominatesBlock ///< The SCEV properly dominates the block.
    184     };
    185 
    186     /// Convenient NoWrapFlags manipulation that hides enum casts and is
    187     /// visible in the ScalarEvolution name space.
    188     static SCEV::NoWrapFlags maskFlags(SCEV::NoWrapFlags Flags, int Mask) {
    189       return (SCEV::NoWrapFlags)(Flags & Mask);
    190     }
    191     static SCEV::NoWrapFlags setFlags(SCEV::NoWrapFlags Flags,
    192                                       SCEV::NoWrapFlags OnFlags) {
    193       return (SCEV::NoWrapFlags)(Flags | OnFlags);
    194     }
    195     static SCEV::NoWrapFlags clearFlags(SCEV::NoWrapFlags Flags,
    196                                         SCEV::NoWrapFlags OffFlags) {
    197       return (SCEV::NoWrapFlags)(Flags & ~OffFlags);
    198     }
    199 
    200   private:
    201     /// SCEVCallbackVH - A CallbackVH to arrange for ScalarEvolution to be
    202     /// notified whenever a Value is deleted.
    203     class SCEVCallbackVH : public CallbackVH {
    204       ScalarEvolution *SE;
    205       virtual void deleted();
    206       virtual void allUsesReplacedWith(Value *New);
    207     public:
    208       SCEVCallbackVH(Value *V, ScalarEvolution *SE = 0);
    209     };
    210 
    211     friend class SCEVCallbackVH;
    212     friend class SCEVExpander;
    213     friend class SCEVUnknown;
    214 
    215     /// F - The function we are analyzing.
    216     ///
    217     Function *F;
    218 
    219     /// LI - The loop information for the function we are currently analyzing.
    220     ///
    221     LoopInfo *LI;
    222 
    223     /// TD - The target data information for the target we are targeting.
    224     ///
    225     TargetData *TD;
    226 
    227     /// DT - The dominator tree.
    228     ///
    229     DominatorTree *DT;
    230 
    231     /// CouldNotCompute - This SCEV is used to represent unknown trip
    232     /// counts and things.
    233     SCEVCouldNotCompute CouldNotCompute;
    234 
    235     /// ValueExprMapType - The typedef for ValueExprMap.
    236     ///
    237     typedef DenseMap<SCEVCallbackVH, const SCEV *, DenseMapInfo<Value *> >
    238       ValueExprMapType;
    239 
    240     /// ValueExprMap - This is a cache of the values we have analyzed so far.
    241     ///
    242     ValueExprMapType ValueExprMap;
    243 
    244     /// BackedgeTakenInfo - Information about the backedge-taken count
    245     /// of a loop. This currently includes an exact count and a maximum count.
    246     ///
    247     struct BackedgeTakenInfo {
    248       /// Exact - An expression indicating the exact backedge-taken count of
    249       /// the loop if it is known, or a SCEVCouldNotCompute otherwise.
    250       const SCEV *Exact;
    251 
    252       /// Max - An expression indicating the least maximum backedge-taken
    253       /// count of the loop that is known, or a SCEVCouldNotCompute.
    254       const SCEV *Max;
    255 
    256       /*implicit*/ BackedgeTakenInfo(const SCEV *exact) :
    257         Exact(exact), Max(exact) {}
    258 
    259       BackedgeTakenInfo(const SCEV *exact, const SCEV *max) :
    260         Exact(exact), Max(max) {}
    261 
    262       /// hasAnyInfo - Test whether this BackedgeTakenInfo contains any
    263       /// computed information, or whether it's all SCEVCouldNotCompute
    264       /// values.
    265       bool hasAnyInfo() const {
    266         return !isa<SCEVCouldNotCompute>(Exact) ||
    267                !isa<SCEVCouldNotCompute>(Max);
    268       }
    269     };
    270 
    271     /// BackedgeTakenCounts - Cache the backedge-taken count of the loops for
    272     /// this function as they are computed.
    273     DenseMap<const Loop*, BackedgeTakenInfo> BackedgeTakenCounts;
    274 
    275     /// ConstantEvolutionLoopExitValue - This map contains entries for all of
    276     /// the PHI instructions that we attempt to compute constant evolutions for.
    277     /// This allows us to avoid potentially expensive recomputation of these
    278     /// properties.  An instruction maps to null if we are unable to compute its
    279     /// exit value.
    280     DenseMap<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
    281 
    282     /// ValuesAtScopes - This map contains entries for all the expressions
    283     /// that we attempt to compute getSCEVAtScope information for, which can
    284     /// be expensive in extreme cases.
    285     DenseMap<const SCEV *,
    286              std::map<const Loop *, const SCEV *> > ValuesAtScopes;
    287 
    288     /// LoopDispositions - Memoized computeLoopDisposition results.
    289     DenseMap<const SCEV *,
    290              std::map<const Loop *, LoopDisposition> > LoopDispositions;
    291 
    292     /// computeLoopDisposition - Compute a LoopDisposition value.
    293     LoopDisposition computeLoopDisposition(const SCEV *S, const Loop *L);
    294 
    295     /// BlockDispositions - Memoized computeBlockDisposition results.
    296     DenseMap<const SCEV *,
    297              std::map<const BasicBlock *, BlockDisposition> > BlockDispositions;
    298 
    299     /// computeBlockDisposition - Compute a BlockDisposition value.
    300     BlockDisposition computeBlockDisposition(const SCEV *S, const BasicBlock *BB);
    301 
    302     /// UnsignedRanges - Memoized results from getUnsignedRange
    303     DenseMap<const SCEV *, ConstantRange> UnsignedRanges;
    304 
    305     /// SignedRanges - Memoized results from getSignedRange
    306     DenseMap<const SCEV *, ConstantRange> SignedRanges;
    307 
    308     /// setUnsignedRange - Set the memoized unsigned range for the given SCEV.
    309     const ConstantRange &setUnsignedRange(const SCEV *S,
    310                                           const ConstantRange &CR) {
    311       std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair =
    312         UnsignedRanges.insert(std::make_pair(S, CR));
    313       if (!Pair.second)
    314         Pair.first->second = CR;
    315       return Pair.first->second;
    316     }
    317 
    318     /// setUnsignedRange - Set the memoized signed range for the given SCEV.
    319     const ConstantRange &setSignedRange(const SCEV *S,
    320                                         const ConstantRange &CR) {
    321       std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair =
    322         SignedRanges.insert(std::make_pair(S, CR));
    323       if (!Pair.second)
    324         Pair.first->second = CR;
    325       return Pair.first->second;
    326     }
    327 
    328     /// createSCEV - We know that there is no SCEV for the specified value.
    329     /// Analyze the expression.
    330     const SCEV *createSCEV(Value *V);
    331 
    332     /// createNodeForPHI - Provide the special handling we need to analyze PHI
    333     /// SCEVs.
    334     const SCEV *createNodeForPHI(PHINode *PN);
    335 
    336     /// createNodeForGEP - Provide the special handling we need to analyze GEP
    337     /// SCEVs.
    338     const SCEV *createNodeForGEP(GEPOperator *GEP);
    339 
    340     /// computeSCEVAtScope - Implementation code for getSCEVAtScope; called
    341     /// at most once for each SCEV+Loop pair.
    342     ///
    343     const SCEV *computeSCEVAtScope(const SCEV *S, const Loop *L);
    344 
    345     /// ForgetSymbolicValue - This looks up computed SCEV values for all
    346     /// instructions that depend on the given instruction and removes them from
    347     /// the ValueExprMap map if they reference SymName. This is used during PHI
    348     /// resolution.
    349     void ForgetSymbolicName(Instruction *I, const SCEV *SymName);
    350 
    351     /// getBECount - Subtract the end and start values and divide by the step,
    352     /// rounding up, to get the number of times the backedge is executed. Return
    353     /// CouldNotCompute if an intermediate computation overflows.
    354     const SCEV *getBECount(const SCEV *Start,
    355                            const SCEV *End,
    356                            const SCEV *Step,
    357                            bool NoWrap);
    358 
    359     /// getBackedgeTakenInfo - Return the BackedgeTakenInfo for the given
    360     /// loop, lazily computing new values if the loop hasn't been analyzed
    361     /// yet.
    362     const BackedgeTakenInfo &getBackedgeTakenInfo(const Loop *L);
    363 
    364     /// ComputeBackedgeTakenCount - Compute the number of times the specified
    365     /// loop will iterate.
    366     BackedgeTakenInfo ComputeBackedgeTakenCount(const Loop *L);
    367 
    368     /// ComputeBackedgeTakenCountFromExit - Compute the number of times the
    369     /// backedge of the specified loop will execute if it exits via the
    370     /// specified block.
    371     BackedgeTakenInfo ComputeBackedgeTakenCountFromExit(const Loop *L,
    372                                                       BasicBlock *ExitingBlock);
    373 
    374     /// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
    375     /// backedge of the specified loop will execute if its exit condition
    376     /// were a conditional branch of ExitCond, TBB, and FBB.
    377     BackedgeTakenInfo
    378       ComputeBackedgeTakenCountFromExitCond(const Loop *L,
    379                                             Value *ExitCond,
    380                                             BasicBlock *TBB,
    381                                             BasicBlock *FBB);
    382 
    383     /// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of
    384     /// times the backedge of the specified loop will execute if its exit
    385     /// condition were a conditional branch of the ICmpInst ExitCond, TBB,
    386     /// and FBB.
    387     BackedgeTakenInfo
    388       ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
    389                                                 ICmpInst *ExitCond,
    390                                                 BasicBlock *TBB,
    391                                                 BasicBlock *FBB);
    392 
    393     /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition
    394     /// of 'icmp op load X, cst', try to see if we can compute the
    395     /// backedge-taken count.
    396     BackedgeTakenInfo
    397       ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI,
    398                                                    Constant *RHS,
    399                                                    const Loop *L,
    400                                                    ICmpInst::Predicate p);
    401 
    402     /// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute
    403     /// a constant number of times (the condition evolves only from constants),
    404     /// try to evaluate a few iterations of the loop until we get the exit
    405     /// condition gets a value of ExitWhen (true or false).  If we cannot
    406     /// evaluate the backedge-taken count of the loop, return CouldNotCompute.
    407     const SCEV *ComputeBackedgeTakenCountExhaustively(const Loop *L,
    408                                                       Value *Cond,
    409                                                       bool ExitWhen);
    410 
    411     /// HowFarToZero - Return the number of times a backedge comparing the
    412     /// specified value to zero will execute.  If not computable, return
    413     /// CouldNotCompute.
    414     BackedgeTakenInfo HowFarToZero(const SCEV *V, const Loop *L);
    415 
    416     /// HowFarToNonZero - Return the number of times a backedge checking the
    417     /// specified value for nonzero will execute.  If not computable, return
    418     /// CouldNotCompute.
    419     BackedgeTakenInfo HowFarToNonZero(const SCEV *V, const Loop *L);
    420 
    421     /// HowManyLessThans - Return the number of times a backedge containing the
    422     /// specified less-than comparison will execute.  If not computable, return
    423     /// CouldNotCompute. isSigned specifies whether the less-than is signed.
    424     BackedgeTakenInfo HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
    425                                        const Loop *L, bool isSigned);
    426 
    427     /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
    428     /// (which may not be an immediate predecessor) which has exactly one
    429     /// successor from which BB is reachable, or null if no such block is
    430     /// found.
    431     std::pair<BasicBlock *, BasicBlock *>
    432     getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
    433 
    434     /// isImpliedCond - Test whether the condition described by Pred, LHS, and
    435     /// RHS is true whenever the given FoundCondValue value evaluates to true.
    436     bool isImpliedCond(ICmpInst::Predicate Pred,
    437                        const SCEV *LHS, const SCEV *RHS,
    438                        Value *FoundCondValue,
    439                        bool Inverse);
    440 
    441     /// isImpliedCondOperands - Test whether the condition described by Pred,
    442     /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
    443     /// and FoundRHS is true.
    444     bool isImpliedCondOperands(ICmpInst::Predicate Pred,
    445                                const SCEV *LHS, const SCEV *RHS,
    446                                const SCEV *FoundLHS, const SCEV *FoundRHS);
    447 
    448     /// isImpliedCondOperandsHelper - Test whether the condition described by
    449     /// Pred, LHS, and RHS is true whenever the condition described by Pred,
    450     /// FoundLHS, and FoundRHS is true.
    451     bool isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
    452                                      const SCEV *LHS, const SCEV *RHS,
    453                                      const SCEV *FoundLHS, const SCEV *FoundRHS);
    454 
    455     /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
    456     /// in the header of its containing loop, we know the loop executes a
    457     /// constant number of times, and the PHI node is just a recurrence
    458     /// involving constants, fold it.
    459     Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs,
    460                                                 const Loop *L);
    461 
    462     /// isKnownPredicateWithRanges - Test if the given expression is known to
    463     /// satisfy the condition described by Pred and the known constant ranges
    464     /// of LHS and RHS.
    465     ///
    466     bool isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
    467                                     const SCEV *LHS, const SCEV *RHS);
    468 
    469     /// forgetMemoizedResults - Drop memoized information computed for S.
    470     void forgetMemoizedResults(const SCEV *S);
    471 
    472   public:
    473     static char ID; // Pass identification, replacement for typeid
    474     ScalarEvolution();
    475 
    476     LLVMContext &getContext() const { return F->getContext(); }
    477 
    478     /// isSCEVable - Test if values of the given type are analyzable within
    479     /// the SCEV framework. This primarily includes integer types, and it
    480     /// can optionally include pointer types if the ScalarEvolution class
    481     /// has access to target-specific information.
    482     bool isSCEVable(Type *Ty) const;
    483 
    484     /// getTypeSizeInBits - Return the size in bits of the specified type,
    485     /// for which isSCEVable must return true.
    486     uint64_t getTypeSizeInBits(Type *Ty) const;
    487 
    488     /// getEffectiveSCEVType - Return a type with the same bitwidth as
    489     /// the given type and which represents how SCEV will treat the given
    490     /// type, for which isSCEVable must return true. For pointer types,
    491     /// this is the pointer-sized integer type.
    492     Type *getEffectiveSCEVType(Type *Ty) const;
    493 
    494     /// getSCEV - Return a SCEV expression for the full generality of the
    495     /// specified expression.
    496     const SCEV *getSCEV(Value *V);
    497 
    498     const SCEV *getConstant(ConstantInt *V);
    499     const SCEV *getConstant(const APInt& Val);
    500     const SCEV *getConstant(Type *Ty, uint64_t V, bool isSigned = false);
    501     const SCEV *getTruncateExpr(const SCEV *Op, Type *Ty);
    502     const SCEV *getZeroExtendExpr(const SCEV *Op, Type *Ty);
    503     const SCEV *getSignExtendExpr(const SCEV *Op, Type *Ty);
    504     const SCEV *getAnyExtendExpr(const SCEV *Op, Type *Ty);
    505     const SCEV *getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
    506                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
    507     const SCEV *getAddExpr(const SCEV *LHS, const SCEV *RHS,
    508                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
    509       SmallVector<const SCEV *, 2> Ops;
    510       Ops.push_back(LHS);
    511       Ops.push_back(RHS);
    512       return getAddExpr(Ops, Flags);
    513     }
    514     const SCEV *getAddExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
    515                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
    516       SmallVector<const SCEV *, 3> Ops;
    517       Ops.push_back(Op0);
    518       Ops.push_back(Op1);
    519       Ops.push_back(Op2);
    520       return getAddExpr(Ops, Flags);
    521     }
    522     const SCEV *getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
    523                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
    524     const SCEV *getMulExpr(const SCEV *LHS, const SCEV *RHS,
    525                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap)
    526     {
    527       SmallVector<const SCEV *, 2> Ops;
    528       Ops.push_back(LHS);
    529       Ops.push_back(RHS);
    530       return getMulExpr(Ops, Flags);
    531     }
    532     const SCEV *getUDivExpr(const SCEV *LHS, const SCEV *RHS);
    533     const SCEV *getAddRecExpr(const SCEV *Start, const SCEV *Step,
    534                               const Loop *L, SCEV::NoWrapFlags Flags);
    535     const SCEV *getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
    536                               const Loop *L, SCEV::NoWrapFlags Flags);
    537     const SCEV *getAddRecExpr(const SmallVectorImpl<const SCEV *> &Operands,
    538                               const Loop *L, SCEV::NoWrapFlags Flags) {
    539       SmallVector<const SCEV *, 4> NewOp(Operands.begin(), Operands.end());
    540       return getAddRecExpr(NewOp, L, Flags);
    541     }
    542     const SCEV *getSMaxExpr(const SCEV *LHS, const SCEV *RHS);
    543     const SCEV *getSMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
    544     const SCEV *getUMaxExpr(const SCEV *LHS, const SCEV *RHS);
    545     const SCEV *getUMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
    546     const SCEV *getSMinExpr(const SCEV *LHS, const SCEV *RHS);
    547     const SCEV *getUMinExpr(const SCEV *LHS, const SCEV *RHS);
    548     const SCEV *getUnknown(Value *V);
    549     const SCEV *getCouldNotCompute();
    550 
    551     /// getSizeOfExpr - Return an expression for sizeof on the given type.
    552     ///
    553     const SCEV *getSizeOfExpr(Type *AllocTy);
    554 
    555     /// getAlignOfExpr - Return an expression for alignof on the given type.
    556     ///
    557     const SCEV *getAlignOfExpr(Type *AllocTy);
    558 
    559     /// getOffsetOfExpr - Return an expression for offsetof on the given field.
    560     ///
    561     const SCEV *getOffsetOfExpr(StructType *STy, unsigned FieldNo);
    562 
    563     /// getOffsetOfExpr - Return an expression for offsetof on the given field.
    564     ///
    565     const SCEV *getOffsetOfExpr(Type *CTy, Constant *FieldNo);
    566 
    567     /// getNegativeSCEV - Return the SCEV object corresponding to -V.
    568     ///
    569     const SCEV *getNegativeSCEV(const SCEV *V);
    570 
    571     /// getNotSCEV - Return the SCEV object corresponding to ~V.
    572     ///
    573     const SCEV *getNotSCEV(const SCEV *V);
    574 
    575     /// getMinusSCEV - Return LHS-RHS.  Minus is represented in SCEV as A+B*-1.
    576     const SCEV *getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
    577                              SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
    578 
    579     /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
    580     /// of the input value to the specified type.  If the type must be
    581     /// extended, it is zero extended.
    582     const SCEV *getTruncateOrZeroExtend(const SCEV *V, Type *Ty);
    583 
    584     /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
    585     /// of the input value to the specified type.  If the type must be
    586     /// extended, it is sign extended.
    587     const SCEV *getTruncateOrSignExtend(const SCEV *V, Type *Ty);
    588 
    589     /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of
    590     /// the input value to the specified type.  If the type must be extended,
    591     /// it is zero extended.  The conversion must not be narrowing.
    592     const SCEV *getNoopOrZeroExtend(const SCEV *V, Type *Ty);
    593 
    594     /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of
    595     /// the input value to the specified type.  If the type must be extended,
    596     /// it is sign extended.  The conversion must not be narrowing.
    597     const SCEV *getNoopOrSignExtend(const SCEV *V, Type *Ty);
    598 
    599     /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
    600     /// the input value to the specified type. If the type must be extended,
    601     /// it is extended with unspecified bits. The conversion must not be
    602     /// narrowing.
    603     const SCEV *getNoopOrAnyExtend(const SCEV *V, Type *Ty);
    604 
    605     /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
    606     /// input value to the specified type.  The conversion must not be
    607     /// widening.
    608     const SCEV *getTruncateOrNoop(const SCEV *V, Type *Ty);
    609 
    610     /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
    611     /// the types using zero-extension, and then perform a umax operation
    612     /// with them.
    613     const SCEV *getUMaxFromMismatchedTypes(const SCEV *LHS,
    614                                            const SCEV *RHS);
    615 
    616     /// getUMinFromMismatchedTypes - Promote the operands to the wider of
    617     /// the types using zero-extension, and then perform a umin operation
    618     /// with them.
    619     const SCEV *getUMinFromMismatchedTypes(const SCEV *LHS,
    620                                            const SCEV *RHS);
    621 
    622     /// getPointerBase - Transitively follow the chain of pointer-type operands
    623     /// until reaching a SCEV that does not have a single pointer operand. This
    624     /// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
    625     /// but corner cases do exist.
    626     const SCEV *getPointerBase(const SCEV *V);
    627 
    628     /// getSCEVAtScope - Return a SCEV expression for the specified value
    629     /// at the specified scope in the program.  The L value specifies a loop
    630     /// nest to evaluate the expression at, where null is the top-level or a
    631     /// specified loop is immediately inside of the loop.
    632     ///
    633     /// This method can be used to compute the exit value for a variable defined
    634     /// in a loop by querying what the value will hold in the parent loop.
    635     ///
    636     /// In the case that a relevant loop exit value cannot be computed, the
    637     /// original value V is returned.
    638     const SCEV *getSCEVAtScope(const SCEV *S, const Loop *L);
    639 
    640     /// getSCEVAtScope - This is a convenience function which does
    641     /// getSCEVAtScope(getSCEV(V), L).
    642     const SCEV *getSCEVAtScope(Value *V, const Loop *L);
    643 
    644     /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
    645     /// by a conditional between LHS and RHS.  This is used to help avoid max
    646     /// expressions in loop trip counts, and to eliminate casts.
    647     bool isLoopEntryGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
    648                                   const SCEV *LHS, const SCEV *RHS);
    649 
    650     /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
    651     /// protected by a conditional between LHS and RHS.  This is used to
    652     /// to eliminate casts.
    653     bool isLoopBackedgeGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
    654                                      const SCEV *LHS, const SCEV *RHS);
    655 
    656     /// getBackedgeTakenCount - If the specified loop has a predictable
    657     /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
    658     /// object. The backedge-taken count is the number of times the loop header
    659     /// will be branched to from within the loop. This is one less than the
    660     /// trip count of the loop, since it doesn't count the first iteration,
    661     /// when the header is branched to from outside the loop.
    662     ///
    663     /// Note that it is not valid to call this method on a loop without a
    664     /// loop-invariant backedge-taken count (see
    665     /// hasLoopInvariantBackedgeTakenCount).
    666     ///
    667     const SCEV *getBackedgeTakenCount(const Loop *L);
    668 
    669     /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
    670     /// return the least SCEV value that is known never to be less than the
    671     /// actual backedge taken count.
    672     const SCEV *getMaxBackedgeTakenCount(const Loop *L);
    673 
    674     /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop
    675     /// has an analyzable loop-invariant backedge-taken count.
    676     bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
    677 
    678     /// forgetLoop - This method should be called by the client when it has
    679     /// changed a loop in a way that may effect ScalarEvolution's ability to
    680     /// compute a trip count, or if the loop is deleted.
    681     void forgetLoop(const Loop *L);
    682 
    683     /// forgetValue - This method should be called by the client when it has
    684     /// changed a value in a way that may effect its value, or which may
    685     /// disconnect it from a def-use chain linking it to a loop.
    686     void forgetValue(Value *V);
    687 
    688     /// GetMinTrailingZeros - Determine the minimum number of zero bits that S
    689     /// is guaranteed to end in (at every loop iteration).  It is, at the same
    690     /// time, the minimum number of times S is divisible by 2.  For example,
    691     /// given {4,+,8} it returns 2.  If S is guaranteed to be 0, it returns the
    692     /// bitwidth of S.
    693     uint32_t GetMinTrailingZeros(const SCEV *S);
    694 
    695     /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
    696     ///
    697     ConstantRange getUnsignedRange(const SCEV *S);
    698 
    699     /// getSignedRange - Determine the signed range for a particular SCEV.
    700     ///
    701     ConstantRange getSignedRange(const SCEV *S);
    702 
    703     /// isKnownNegative - Test if the given expression is known to be negative.
    704     ///
    705     bool isKnownNegative(const SCEV *S);
    706 
    707     /// isKnownPositive - Test if the given expression is known to be positive.
    708     ///
    709     bool isKnownPositive(const SCEV *S);
    710 
    711     /// isKnownNonNegative - Test if the given expression is known to be
    712     /// non-negative.
    713     ///
    714     bool isKnownNonNegative(const SCEV *S);
    715 
    716     /// isKnownNonPositive - Test if the given expression is known to be
    717     /// non-positive.
    718     ///
    719     bool isKnownNonPositive(const SCEV *S);
    720 
    721     /// isKnownNonZero - Test if the given expression is known to be
    722     /// non-zero.
    723     ///
    724     bool isKnownNonZero(const SCEV *S);
    725 
    726     /// isKnownPredicate - Test if the given expression is known to satisfy
    727     /// the condition described by Pred, LHS, and RHS.
    728     ///
    729     bool isKnownPredicate(ICmpInst::Predicate Pred,
    730                           const SCEV *LHS, const SCEV *RHS);
    731 
    732     /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
    733     /// predicate Pred. Return true iff any changes were made. If the
    734     /// operands are provably equal or inequal, LHS and RHS are set to
    735     /// the same value and Pred is set to either ICMP_EQ or ICMP_NE.
    736     ///
    737     bool SimplifyICmpOperands(ICmpInst::Predicate &Pred,
    738                               const SCEV *&LHS,
    739                               const SCEV *&RHS);
    740 
    741     /// getLoopDisposition - Return the "disposition" of the given SCEV with
    742     /// respect to the given loop.
    743     LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L);
    744 
    745     /// isLoopInvariant - Return true if the value of the given SCEV is
    746     /// unchanging in the specified loop.
    747     bool isLoopInvariant(const SCEV *S, const Loop *L);
    748 
    749     /// hasComputableLoopEvolution - Return true if the given SCEV changes value
    750     /// in a known way in the specified loop.  This property being true implies
    751     /// that the value is variant in the loop AND that we can emit an expression
    752     /// to compute the value of the expression at any particular loop iteration.
    753     bool hasComputableLoopEvolution(const SCEV *S, const Loop *L);
    754 
    755     /// getLoopDisposition - Return the "disposition" of the given SCEV with
    756     /// respect to the given block.
    757     BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB);
    758 
    759     /// dominates - Return true if elements that makes up the given SCEV
    760     /// dominate the specified basic block.
    761     bool dominates(const SCEV *S, const BasicBlock *BB);
    762 
    763     /// properlyDominates - Return true if elements that makes up the given SCEV
    764     /// properly dominate the specified basic block.
    765     bool properlyDominates(const SCEV *S, const BasicBlock *BB);
    766 
    767     /// hasOperand - Test whether the given SCEV has Op as a direct or
    768     /// indirect operand.
    769     bool hasOperand(const SCEV *S, const SCEV *Op) const;
    770 
    771     virtual bool runOnFunction(Function &F);
    772     virtual void releaseMemory();
    773     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
    774     virtual void print(raw_ostream &OS, const Module* = 0) const;
    775 
    776   private:
    777     FoldingSet<SCEV> UniqueSCEVs;
    778     BumpPtrAllocator SCEVAllocator;
    779 
    780     /// FirstUnknown - The head of a linked list of all SCEVUnknown
    781     /// values that have been allocated. This is used by releaseMemory
    782     /// to locate them all and call their destructors.
    783     SCEVUnknown *FirstUnknown;
    784   };
    785 }
    786 
    787 #endif
    788