ScalarEvolution.h revision b0b046848faad8e87d02c82d03b5b7b1ba74e041
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// catagorize 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/Analysis/LoopInfo.h"
26#include "llvm/Support/DataTypes.h"
27#include <iosfwd>
28
29namespace llvm {
30  class APInt;
31  class ConstantInt;
32  class Instruction;
33  class Type;
34  class ConstantRange;
35  class SCEVHandle;
36  class ScalarEvolution;
37
38  /// SCEV - This class represent an analyzed expression in the program.  These
39  /// are reference counted opaque objects that the client is not allowed to
40  /// do much with directly.
41  ///
42  class SCEV {
43    const unsigned SCEVType;      // The SCEV baseclass this node corresponds to
44    mutable unsigned RefCount;
45
46    friend class SCEVHandle;
47    void addRef() const { ++RefCount; }
48    void dropRef() const {
49      if (--RefCount == 0)
50        delete this;
51    }
52
53    SCEV(const SCEV &);            // DO NOT IMPLEMENT
54    void operator=(const SCEV &);  // DO NOT IMPLEMENT
55  protected:
56    virtual ~SCEV();
57  public:
58    explicit SCEV(unsigned SCEVTy) : SCEVType(SCEVTy), RefCount(0) {}
59
60    unsigned getSCEVType() const { return SCEVType; }
61
62    /// isLoopInvariant - Return true if the value of this SCEV is unchanging in
63    /// the specified loop.
64    virtual bool isLoopInvariant(const Loop *L) const = 0;
65
66    /// hasComputableLoopEvolution - Return true if this SCEV changes value in a
67    /// known way in the specified loop.  This property being true implies that
68    /// the value is variant in the loop AND that we can emit an expression to
69    /// compute the value of the expression at any particular loop iteration.
70    virtual bool hasComputableLoopEvolution(const Loop *L) const = 0;
71
72    /// getType - Return the LLVM type of this SCEV expression.
73    ///
74    virtual const Type *getType() const = 0;
75
76    /// getBitWidth - Get the bit width of the type, if it has one, 0 otherwise.
77    ///
78    uint32_t getBitWidth() const;
79
80    /// isZero - Return true if the expression is a constant zero.
81    ///
82    bool isZero() const;
83
84    /// replaceSymbolicValuesWithConcrete - If this SCEV internally references
85    /// the symbolic value "Sym", construct and return a new SCEV that produces
86    /// the same value, but which uses the concrete value Conc instead of the
87    /// symbolic value.  If this SCEV does not use the symbolic value, it
88    /// returns itself.
89    virtual SCEVHandle
90    replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
91                                      const SCEVHandle &Conc,
92                                      ScalarEvolution &SE) const = 0;
93
94    /// print - Print out the internal representation of this scalar to the
95    /// specified stream.  This should really only be used for debugging
96    /// purposes.
97    virtual void print(std::ostream &OS) const = 0;
98    void print(std::ostream *OS) const { if (OS) print(*OS); }
99
100    /// dump - This method is used for debugging.
101    ///
102    void dump() const;
103  };
104
105  inline std::ostream &operator<<(std::ostream &OS, const SCEV &S) {
106    S.print(OS);
107    return OS;
108  }
109
110  /// SCEVCouldNotCompute - An object of this class is returned by queries that
111  /// could not be answered.  For example, if you ask for the number of
112  /// iterations of a linked-list traversal loop, you will get one of these.
113  /// None of the standard SCEV operations are valid on this class, it is just a
114  /// marker.
115  struct SCEVCouldNotCompute : public SCEV {
116    SCEVCouldNotCompute();
117
118    // None of these methods are valid for this object.
119    virtual bool isLoopInvariant(const Loop *L) const;
120    virtual const Type *getType() const;
121    virtual bool hasComputableLoopEvolution(const Loop *L) const;
122    virtual void print(std::ostream &OS) const;
123    void print(std::ostream *OS) const { if (OS) print(*OS); }
124    virtual SCEVHandle
125    replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
126                                      const SCEVHandle &Conc,
127                                      ScalarEvolution &SE) const;
128
129    /// Methods for support type inquiry through isa, cast, and dyn_cast:
130    static inline bool classof(const SCEVCouldNotCompute *S) { return true; }
131    static bool classof(const SCEV *S);
132  };
133
134  /// SCEVHandle - This class is used to maintain the SCEV object's refcounts,
135  /// freeing the objects when the last reference is dropped.
136  class SCEVHandle {
137    SCEV *S;
138    SCEVHandle();  // DO NOT IMPLEMENT
139  public:
140    SCEVHandle(const SCEV *s) : S(const_cast<SCEV*>(s)) {
141      assert(S && "Cannot create a handle to a null SCEV!");
142      S->addRef();
143    }
144    SCEVHandle(const SCEVHandle &RHS) : S(RHS.S) {
145      S->addRef();
146    }
147    ~SCEVHandle() { S->dropRef(); }
148
149    operator SCEV*() const { return S; }
150
151    SCEV &operator*() const { return *S; }
152    SCEV *operator->() const { return S; }
153
154    bool operator==(SCEV *RHS) const { return S == RHS; }
155    bool operator!=(SCEV *RHS) const { return S != RHS; }
156
157    const SCEVHandle &operator=(SCEV *RHS) {
158      if (S != RHS) {
159        S->dropRef();
160        S = RHS;
161        S->addRef();
162      }
163      return *this;
164    }
165
166    const SCEVHandle &operator=(const SCEVHandle &RHS) {
167      if (S != RHS.S) {
168        S->dropRef();
169        S = RHS.S;
170        S->addRef();
171      }
172      return *this;
173    }
174  };
175
176  template<typename From> struct simplify_type;
177  template<> struct simplify_type<const SCEVHandle> {
178    typedef SCEV* SimpleType;
179    static SimpleType getSimplifiedValue(const SCEVHandle &Node) {
180      return Node;
181    }
182  };
183  template<> struct simplify_type<SCEVHandle>
184    : public simplify_type<const SCEVHandle> {};
185
186  /// ScalarEvolution - This class is the main scalar evolution driver.  Because
187  /// client code (intentionally) can't do much with the SCEV objects directly,
188  /// they must ask this class for services.
189  ///
190  class ScalarEvolution : public FunctionPass {
191    void *Impl;    // ScalarEvolution uses the pimpl pattern
192  public:
193    static char ID; // Pass identification, replacement for typeid
194    ScalarEvolution() : FunctionPass((intptr_t)&ID), Impl(0) {}
195
196    /// getSCEV - Return a SCEV expression handle for the full generality of the
197    /// specified expression.
198    SCEVHandle getSCEV(Value *V) const;
199
200    SCEVHandle getConstant(ConstantInt *V);
201    SCEVHandle getConstant(const APInt& Val);
202    SCEVHandle getTruncateExpr(const SCEVHandle &Op, const Type *Ty);
203    SCEVHandle getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty);
204    SCEVHandle getSignExtendExpr(const SCEVHandle &Op, const Type *Ty);
205    SCEVHandle getAddExpr(std::vector<SCEVHandle> &Ops);
206    SCEVHandle getAddExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
207      std::vector<SCEVHandle> Ops;
208      Ops.push_back(LHS);
209      Ops.push_back(RHS);
210      return getAddExpr(Ops);
211    }
212    SCEVHandle getAddExpr(const SCEVHandle &Op0, const SCEVHandle &Op1,
213                          const SCEVHandle &Op2) {
214      std::vector<SCEVHandle> Ops;
215      Ops.push_back(Op0);
216      Ops.push_back(Op1);
217      Ops.push_back(Op2);
218      return getAddExpr(Ops);
219    }
220    SCEVHandle getMulExpr(std::vector<SCEVHandle> &Ops);
221    SCEVHandle getMulExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
222      std::vector<SCEVHandle> Ops;
223      Ops.push_back(LHS);
224      Ops.push_back(RHS);
225      return getMulExpr(Ops);
226    }
227    SCEVHandle getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS);
228    SCEVHandle getAddRecExpr(const SCEVHandle &Start, const SCEVHandle &Step,
229                             const Loop *L);
230    SCEVHandle getAddRecExpr(std::vector<SCEVHandle> &Operands,
231                             const Loop *L);
232    SCEVHandle getAddRecExpr(const std::vector<SCEVHandle> &Operands,
233                             const Loop *L) {
234      std::vector<SCEVHandle> NewOp(Operands);
235      return getAddRecExpr(NewOp, L);
236    }
237    SCEVHandle getSMaxExpr(const SCEVHandle &LHS, const SCEVHandle &RHS);
238    SCEVHandle getSMaxExpr(std::vector<SCEVHandle> Operands);
239    SCEVHandle getUMaxExpr(const SCEVHandle &LHS, const SCEVHandle &RHS);
240    SCEVHandle getUMaxExpr(std::vector<SCEVHandle> Operands);
241    SCEVHandle getUnknown(Value *V);
242
243    /// getNegativeSCEV - Return the SCEV object corresponding to -V.
244    ///
245    SCEVHandle getNegativeSCEV(const SCEVHandle &V);
246
247    /// getNotSCEV - Return the SCEV object corresponding to ~V.
248    ///
249    SCEVHandle getNotSCEV(const SCEVHandle &V);
250
251    /// getMinusSCEV - Return LHS-RHS.
252    ///
253    SCEVHandle getMinusSCEV(const SCEVHandle &LHS,
254                            const SCEVHandle &RHS);
255
256    /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
257    /// of the input value to the specified type.  If the type must be
258    /// extended, it is zero extended.
259    SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty);
260
261    /// getIntegerSCEV - Given an integer or FP type, create a constant for the
262    /// specified signed integer value and return a SCEV for the constant.
263    SCEVHandle getIntegerSCEV(int Val, const Type *Ty);
264
265    /// hasSCEV - Return true if the SCEV for this value has already been
266    /// computed.
267    bool hasSCEV(Value *V) const;
268
269    /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
270    /// the specified value.
271    void setSCEV(Value *V, const SCEVHandle &H);
272
273    /// getSCEVAtScope - Return a SCEV expression handle for the specified value
274    /// at the specified scope in the program.  The L value specifies a loop
275    /// nest to evaluate the expression at, where null is the top-level or a
276    /// specified loop is immediately inside of the loop.
277    ///
278    /// This method can be used to compute the exit value for a variable defined
279    /// in a loop by querying what the value will hold in the parent loop.
280    ///
281    /// If this value is not computable at this scope, a SCEVCouldNotCompute
282    /// object is returned.
283    SCEVHandle getSCEVAtScope(Value *V, const Loop *L) const;
284
285    /// getIterationCount - If the specified loop has a predictable iteration
286    /// count, return it, otherwise return a SCEVCouldNotCompute object.
287    SCEVHandle getIterationCount(const Loop *L) const;
288
289    /// hasLoopInvariantIterationCount - Return true if the specified loop has
290    /// an analyzable loop-invariant iteration count.
291    bool hasLoopInvariantIterationCount(const Loop *L) const;
292
293    /// deleteValueFromRecords - This method should be called by the
294    /// client before it removes a Value from the program, to make sure
295    /// that no dangling references are left around.
296    void deleteValueFromRecords(Value *V) const;
297
298    virtual bool runOnFunction(Function &F);
299    virtual void releaseMemory();
300    virtual void getAnalysisUsage(AnalysisUsage &AU) const;
301    virtual void print(std::ostream &OS, const Module* = 0) const;
302    void print(std::ostream *OS, const Module* M = 0) const {
303      if (OS) print(*OS, M);
304    }
305  };
306}
307
308#endif
309