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