Extend ScalarEvolution's getBackedgeTakenCount to be able to
[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(raw_ostream &OS) const = 0;
97     void print(std::ostream &OS) const;
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 raw_ostream &operator<<(raw_ostream &OS, const SCEV &S) {
106     S.print(OS);
107     return OS;
108   }
109
110   inline std::ostream &operator<<(std::ostream &OS, const SCEV &S) {
111     S.print(OS);
112     return OS;
113   }
114
115   /// SCEVCouldNotCompute - An object of this class is returned by queries that
116   /// could not be answered.  For example, if you ask for the number of
117   /// iterations of a linked-list traversal loop, you will get one of these.
118   /// None of the standard SCEV operations are valid on this class, it is just a
119   /// marker.
120   struct SCEVCouldNotCompute : public SCEV {
121     SCEVCouldNotCompute();
122     ~SCEVCouldNotCompute();
123
124     // None of these methods are valid for this object.
125     virtual bool isLoopInvariant(const Loop *L) const;
126     virtual const Type *getType() const;
127     virtual bool hasComputableLoopEvolution(const Loop *L) const;
128     virtual void print(raw_ostream &OS) const;
129     virtual SCEVHandle
130     replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
131                                       const SCEVHandle &Conc,
132                                       ScalarEvolution &SE) const;
133
134     virtual bool dominates(BasicBlock *BB, DominatorTree *DT) const {
135       return true;
136     }
137
138     /// Methods for support type inquiry through isa, cast, and dyn_cast:
139     static inline bool classof(const SCEVCouldNotCompute *S) { return true; }
140     static bool classof(const SCEV *S);
141   };
142
143   /// SCEVHandle - This class is used to maintain the SCEV object's refcounts,
144   /// freeing the objects when the last reference is dropped.
145   class SCEVHandle {
146     SCEV *S;
147     SCEVHandle();  // DO NOT IMPLEMENT
148   public:
149     SCEVHandle(const SCEV *s) : S(const_cast<SCEV*>(s)) {
150       assert(S && "Cannot create a handle to a null SCEV!");
151       S->addRef();
152     }
153     SCEVHandle(const SCEVHandle &RHS) : S(RHS.S) {
154       S->addRef();
155     }
156     ~SCEVHandle() { S->dropRef(); }
157
158     operator SCEV*() const { return S; }
159
160     SCEV &operator*() const { return *S; }
161     SCEV *operator->() const { return S; }
162
163     bool operator==(SCEV *RHS) const { return S == RHS; }
164     bool operator!=(SCEV *RHS) const { return S != RHS; }
165
166     const SCEVHandle &operator=(SCEV *RHS) {
167       if (S != RHS) {
168         S->dropRef();
169         S = RHS;
170         S->addRef();
171       }
172       return *this;
173     }
174
175     const SCEVHandle &operator=(const SCEVHandle &RHS) {
176       if (S != RHS.S) {
177         S->dropRef();
178         S = RHS.S;
179         S->addRef();
180       }
181       return *this;
182     }
183   };
184
185   template<typename From> struct simplify_type;
186   template<> struct simplify_type<const SCEVHandle> {
187     typedef SCEV* SimpleType;
188     static SimpleType getSimplifiedValue(const SCEVHandle &Node) {
189       return Node;
190     }
191   };
192   template<> struct simplify_type<SCEVHandle>
193     : public simplify_type<const SCEVHandle> {};
194
195   /// ScalarEvolution - This class is the main scalar evolution driver.  Because
196   /// client code (intentionally) can't do much with the SCEV objects directly,
197   /// they must ask this class for services.
198   ///
199   class ScalarEvolution : public FunctionPass {
200     /// F - The function we are analyzing.
201     ///
202     Function *F;
203
204     /// LI - The loop information for the function we are currently analyzing.
205     ///
206     LoopInfo *LI;
207
208     /// TD - The target data information for the target we are targetting.
209     ///
210     TargetData *TD;
211
212     /// UnknownValue - This SCEV is used to represent unknown trip counts and
213     /// things.
214     SCEVHandle UnknownValue;
215
216     /// Scalars - This is a cache of the scalars we have analyzed so far.
217     ///
218     std::map<Value*, SCEVHandle> Scalars;
219
220     /// BackedgeTakenInfo - Information about the backedge-taken count
221     /// of a loop. This currently inclues an exact count and a maximum count.
222     ///
223     struct BackedgeTakenInfo {
224       /// Exact - An expression indicating the exact backedge-taken count of
225       /// the loop if it is known, or a SCEVCouldNotCompute otherwise.
226       SCEVHandle Exact;
227
228       /// Exact - An expression indicating the least maximum backedge-taken
229       /// count of the loop that is known, or a SCEVCouldNotCompute.
230       SCEVHandle Max;
231
232       /*implicit*/ BackedgeTakenInfo(SCEVHandle exact) :
233         Exact(exact), Max(exact) {}
234
235       /*implicit*/ BackedgeTakenInfo(SCEV *exact) :
236         Exact(exact), Max(exact) {}
237
238       BackedgeTakenInfo(SCEVHandle exact, SCEVHandle max) :
239         Exact(exact), Max(max) {}
240
241       /// hasAnyInfo - Test whether this BackedgeTakenInfo contains any
242       /// computed information, or whether it's all SCEVCouldNotCompute
243       /// values.
244       bool hasAnyInfo() const {
245         return !isa<SCEVCouldNotCompute>(Exact) ||
246                !isa<SCEVCouldNotCompute>(Max);
247       }
248     };
249
250     /// BackedgeTakenCounts - Cache the backedge-taken count of the loops for
251     /// this function as they are computed.
252     std::map<const Loop*, BackedgeTakenInfo> BackedgeTakenCounts;
253
254     /// ConstantEvolutionLoopExitValue - This map contains entries for all of
255     /// the PHI instructions that we attempt to compute constant evolutions for.
256     /// This allows us to avoid potentially expensive recomputation of these
257     /// properties.  An instruction maps to null if we are unable to compute its
258     /// exit value.
259     std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
260
261     /// createSCEV - We know that there is no SCEV for the specified value.
262     /// Analyze the expression.
263     SCEVHandle createSCEV(Value *V);
264
265     /// createNodeForPHI - Provide the special handling we need to analyze PHI
266     /// SCEVs.
267     SCEVHandle createNodeForPHI(PHINode *PN);
268
269     /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
270     /// for the specified instruction and replaces any references to the
271     /// symbolic value SymName with the specified value.  This is used during
272     /// PHI resolution.
273     void ReplaceSymbolicValueWithConcrete(Instruction *I,
274                                           const SCEVHandle &SymName,
275                                           const SCEVHandle &NewVal);
276
277     /// getBackedgeTakenInfo - Return the BackedgeTakenInfo for the given
278     /// loop, lazily computing new values if the loop hasn't been analyzed
279     /// yet.
280     const BackedgeTakenInfo &getBackedgeTakenInfo(const Loop *L);
281
282     /// ComputeBackedgeTakenCount - Compute the number of times the specified
283     /// loop will iterate.
284     BackedgeTakenInfo ComputeBackedgeTakenCount(const Loop *L);
285
286     /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition
287     /// of 'icmp op load X, cst', try to see if we can compute the trip count.
288     SCEVHandle
289       ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI,
290                                                    Constant *RHS,
291                                                    const Loop *L,
292                                                    ICmpInst::Predicate p);
293
294     /// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute
295     /// a constant number of times (the condition evolves only from constants),
296     /// try to evaluate a few iterations of the loop until we get the exit
297     /// condition gets a value of ExitWhen (true or false).  If we cannot
298     /// evaluate the trip count of the loop, return UnknownValue.
299     SCEVHandle ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond,
300                                                      bool ExitWhen);
301
302     /// HowFarToZero - Return the number of times a backedge comparing the
303     /// specified value to zero will execute.  If not computable, return
304     /// UnknownValue.
305     SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
306
307     /// HowFarToNonZero - Return the number of times a backedge checking the
308     /// specified value for nonzero will execute.  If not computable, return
309     /// UnknownValue.
310     SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
311
312     /// HowManyLessThans - Return the number of times a backedge containing the
313     /// specified less-than comparison will execute.  If not computable, return
314     /// UnknownValue. isSigned specifies whether the less-than is signed.
315     BackedgeTakenInfo HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
316                                        bool isSigned);
317
318     /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
319     /// (which may not be an immediate predecessor) which has exactly one
320     /// successor from which BB is reachable, or null if no such block is
321     /// found.
322     BasicBlock* getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
323
324     /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
325     /// in the header of its containing loop, we know the loop executes a
326     /// constant number of times, and the PHI node is just a recurrence
327     /// involving constants, fold it.
328     Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs,
329                                                 const Loop *L);
330
331     /// getSCEVAtScope - Compute the value of the specified expression within
332     /// the indicated loop (which may be null to indicate in no loop).  If the
333     /// expression cannot be evaluated, return UnknownValue itself.
334     SCEVHandle getSCEVAtScope(SCEV *S, const Loop *L);
335
336   public:
337     static char ID; // Pass identification, replacement for typeid
338     ScalarEvolution();
339
340     /// isSCEVable - Test if values of the given type are analyzable within
341     /// the SCEV framework. This primarily includes integer types, and it
342     /// can optionally include pointer types if the ScalarEvolution class
343     /// has access to target-specific information.
344     bool isSCEVable(const Type *Ty) const;
345
346     /// getTypeSizeInBits - Return the size in bits of the specified type,
347     /// for which isSCEVable must return true.
348     uint64_t getTypeSizeInBits(const Type *Ty) const;
349
350     /// getEffectiveSCEVType - Return a type with the same bitwidth as
351     /// the given type and which represents how SCEV will treat the given
352     /// type, for which isSCEVable must return true. For pointer types,
353     /// this is the pointer-sized integer type.
354     const Type *getEffectiveSCEVType(const Type *Ty) const;
355
356     /// getSCEV - Return a SCEV expression handle for the full generality of the
357     /// specified expression.
358     SCEVHandle getSCEV(Value *V);
359
360     SCEVHandle getConstant(ConstantInt *V);
361     SCEVHandle getConstant(const APInt& Val);
362     SCEVHandle getTruncateExpr(const SCEVHandle &Op, const Type *Ty);
363     SCEVHandle getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty);
364     SCEVHandle getSignExtendExpr(const SCEVHandle &Op, const Type *Ty);
365     SCEVHandle getAddExpr(std::vector<SCEVHandle> &Ops);
366     SCEVHandle getAddExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
367       std::vector<SCEVHandle> Ops;
368       Ops.push_back(LHS);
369       Ops.push_back(RHS);
370       return getAddExpr(Ops);
371     }
372     SCEVHandle getAddExpr(const SCEVHandle &Op0, const SCEVHandle &Op1,
373                           const SCEVHandle &Op2) {
374       std::vector<SCEVHandle> Ops;
375       Ops.push_back(Op0);
376       Ops.push_back(Op1);
377       Ops.push_back(Op2);
378       return getAddExpr(Ops);
379     }
380     SCEVHandle getMulExpr(std::vector<SCEVHandle> &Ops);
381     SCEVHandle getMulExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
382       std::vector<SCEVHandle> Ops;
383       Ops.push_back(LHS);
384       Ops.push_back(RHS);
385       return getMulExpr(Ops);
386     }
387     SCEVHandle getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS);
388     SCEVHandle getAddRecExpr(const SCEVHandle &Start, const SCEVHandle &Step,
389                              const Loop *L);
390     SCEVHandle getAddRecExpr(std::vector<SCEVHandle> &Operands,
391                              const Loop *L);
392     SCEVHandle getAddRecExpr(const std::vector<SCEVHandle> &Operands,
393                              const Loop *L) {
394       std::vector<SCEVHandle> NewOp(Operands);
395       return getAddRecExpr(NewOp, L);
396     }
397     SCEVHandle getSMaxExpr(const SCEVHandle &LHS, const SCEVHandle &RHS);
398     SCEVHandle getSMaxExpr(std::vector<SCEVHandle> Operands);
399     SCEVHandle getUMaxExpr(const SCEVHandle &LHS, const SCEVHandle &RHS);
400     SCEVHandle getUMaxExpr(std::vector<SCEVHandle> Operands);
401     SCEVHandle getUnknown(Value *V);
402     SCEVHandle getCouldNotCompute();
403
404     /// getNegativeSCEV - Return the SCEV object corresponding to -V.
405     ///
406     SCEVHandle getNegativeSCEV(const SCEVHandle &V);
407
408     /// getNotSCEV - Return the SCEV object corresponding to ~V.
409     ///
410     SCEVHandle getNotSCEV(const SCEVHandle &V);
411
412     /// getMinusSCEV - Return LHS-RHS.
413     ///
414     SCEVHandle getMinusSCEV(const SCEVHandle &LHS,
415                             const SCEVHandle &RHS);
416
417     /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
418     /// of the input value to the specified type.  If the type must be
419     /// extended, it is zero extended.
420     SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty);
421
422     /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
423     /// of the input value to the specified type.  If the type must be
424     /// extended, it is sign extended.
425     SCEVHandle getTruncateOrSignExtend(const SCEVHandle &V, const Type *Ty);
426
427     /// getIntegerSCEV - Given an integer or FP type, create a constant for the
428     /// specified signed integer value and return a SCEV for the constant.
429     SCEVHandle getIntegerSCEV(int Val, const Type *Ty);
430
431     /// hasSCEV - Return true if the SCEV for this value has already been
432     /// computed.
433     bool hasSCEV(Value *V) const;
434
435     /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
436     /// the specified value.
437     void setSCEV(Value *V, const SCEVHandle &H);
438
439     /// getSCEVAtScope - Return a SCEV expression handle for the specified value
440     /// at the specified scope in the program.  The L value specifies a loop
441     /// nest to evaluate the expression at, where null is the top-level or a
442     /// specified loop is immediately inside of the loop.
443     ///
444     /// This method can be used to compute the exit value for a variable defined
445     /// in a loop by querying what the value will hold in the parent loop.
446     ///
447     /// If this value is not computable at this scope, a SCEVCouldNotCompute
448     /// object is returned.
449     SCEVHandle getSCEVAtScope(Value *V, const Loop *L);
450
451     /// isLoopGuardedByCond - Test whether entry to the loop is protected by
452     /// a conditional between LHS and RHS.
453     bool isLoopGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
454                              SCEV *LHS, SCEV *RHS);
455
456     /// getBackedgeTakenCount - If the specified loop has a predictable
457     /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
458     /// object. The backedge-taken count is the number of times the loop header
459     /// will be branched to from within the loop. This is one less than the
460     /// trip count of the loop, since it doesn't count the first iteration,
461     /// when the header is branched to from outside the loop.
462     ///
463     /// Note that it is not valid to call this method on a loop without a
464     /// loop-invariant backedge-taken count (see
465     /// hasLoopInvariantBackedgeTakenCount).
466     ///
467     SCEVHandle getBackedgeTakenCount(const Loop *L);
468
469     /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
470     /// return the least SCEV value that is known never to be less than the
471     /// actual backedge taken count.
472     SCEVHandle getMaxBackedgeTakenCount(const Loop *L);
473
474     /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop
475     /// has an analyzable loop-invariant backedge-taken count.
476     bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
477
478     /// forgetLoopBackedgeTakenCount - This method should be called by the
479     /// client when it has changed a loop in a way that may effect
480     /// ScalarEvolution's ability to compute a trip count, or if the loop
481     /// is deleted.
482     void forgetLoopBackedgeTakenCount(const Loop *L);
483
484     /// deleteValueFromRecords - This method should be called by the
485     /// client before it removes a Value from the program, to make sure
486     /// that no dangling references are left around.
487     void deleteValueFromRecords(Value *V);
488
489     virtual bool runOnFunction(Function &F);
490     virtual void releaseMemory();
491     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
492     void print(raw_ostream &OS, const Module* = 0) const;
493     virtual void print(std::ostream &OS, const Module* = 0) const;
494     void print(std::ostream *OS, const Module* M = 0) const {
495       if (OS) print(*OS, M);
496     }
497   };
498 }
499
500 #endif