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