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