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