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