Propagate TargetLibraryInfo throughout ConstantFolding.cpp and
[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 // categorize 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/Instructions.h"
26 #include "llvm/Function.h"
27 #include "llvm/Operator.h"
28 #include "llvm/Support/DataTypes.h"
29 #include "llvm/Support/ValueHandle.h"
30 #include "llvm/Support/Allocator.h"
31 #include "llvm/Support/ConstantRange.h"
32 #include "llvm/ADT/FoldingSet.h"
33 #include "llvm/ADT/DenseMap.h"
34 #include <map>
35
36 namespace llvm {
37   class APInt;
38   class Constant;
39   class ConstantInt;
40   class DominatorTree;
41   class Type;
42   class ScalarEvolution;
43   class TargetData;
44   class TargetLibraryInfo;
45   class LLVMContext;
46   class Loop;
47   class LoopInfo;
48   class Operator;
49   class SCEVUnknown;
50   class SCEV;
51   template<> struct FoldingSetTrait<SCEV>;
52
53   /// SCEV - This class represents an analyzed expression in the program.  These
54   /// are opaque objects that the client is not allowed to do much with
55   /// directly.
56   ///
57   class SCEV : public FoldingSetNode {
58     friend struct FoldingSetTrait<SCEV>;
59
60     /// FastID - A reference to an Interned FoldingSetNodeID for this node.
61     /// The ScalarEvolution's BumpPtrAllocator holds the data.
62     FoldingSetNodeIDRef FastID;
63
64     // The SCEV baseclass this node corresponds to
65     const unsigned short SCEVType;
66
67   protected:
68     /// SubclassData - This field is initialized to zero and may be used in
69     /// subclasses to store miscellaneous information.
70     unsigned short SubclassData;
71
72   private:
73     SCEV(const SCEV &);            // DO NOT IMPLEMENT
74     void operator=(const SCEV &);  // DO NOT IMPLEMENT
75
76   public:
77     /// NoWrapFlags are bitfield indices into SubclassData.
78     ///
79     /// Add and Mul expressions may have no-unsigned-wrap <NUW> or
80     /// no-signed-wrap <NSW> properties, which are derived from the IR
81     /// operator. NSW is a misnomer that we use to mean no signed overflow or
82     /// underflow.
83     ///
84     /// AddRec expression may have a no-self-wraparound <NW> property if the
85     /// result can never reach the start value. This property is independent of
86     /// the actual start value and step direction. Self-wraparound is defined
87     /// purely in terms of the recurrence's loop, step size, and
88     /// bitwidth. Formally, a recurrence with no self-wraparound satisfies:
89     /// abs(step) * max-iteration(loop) <= unsigned-max(bitwidth).
90     ///
91     /// Note that NUW and NSW are also valid properties of a recurrence, and
92     /// either implies NW. For convenience, NW will be set for a recurrence
93     /// whenever either NUW or NSW are set.
94     enum NoWrapFlags { FlagAnyWrap = 0,          // No guarantee.
95                        FlagNW      = (1 << 0),   // No self-wrap.
96                        FlagNUW     = (1 << 1),   // No unsigned wrap.
97                        FlagNSW     = (1 << 2),   // No signed wrap.
98                        NoWrapMask  = (1 << 3) -1 };
99
100     explicit SCEV(const FoldingSetNodeIDRef ID, unsigned SCEVTy) :
101       FastID(ID), SCEVType(SCEVTy), SubclassData(0) {}
102
103     unsigned getSCEVType() const { return SCEVType; }
104
105     /// getType - Return the LLVM type of this SCEV expression.
106     ///
107     Type *getType() const;
108
109     /// isZero - Return true if the expression is a constant zero.
110     ///
111     bool isZero() const;
112
113     /// isOne - Return true if the expression is a constant one.
114     ///
115     bool isOne() const;
116
117     /// isAllOnesValue - Return true if the expression is a constant
118     /// all-ones value.
119     ///
120     bool isAllOnesValue() const;
121
122     /// print - Print out the internal representation of this scalar to the
123     /// specified stream.  This should really only be used for debugging
124     /// purposes.
125     void print(raw_ostream &OS) const;
126
127     /// dump - This method is used for debugging.
128     ///
129     void dump() const;
130   };
131
132   // Specialize FoldingSetTrait for SCEV to avoid needing to compute
133   // temporary FoldingSetNodeID values.
134   template<> struct FoldingSetTrait<SCEV> : DefaultFoldingSetTrait<SCEV> {
135     static void Profile(const SCEV &X, FoldingSetNodeID& ID) {
136       ID = X.FastID;
137     }
138     static bool Equals(const SCEV &X, const FoldingSetNodeID &ID,
139                        FoldingSetNodeID &TempID) {
140       return ID == X.FastID;
141     }
142     static unsigned ComputeHash(const SCEV &X, FoldingSetNodeID &TempID) {
143       return X.FastID.ComputeHash();
144     }
145   };
146
147   inline raw_ostream &operator<<(raw_ostream &OS, const SCEV &S) {
148     S.print(OS);
149     return OS;
150   }
151
152   /// SCEVCouldNotCompute - An object of this class is returned by queries that
153   /// could not be answered.  For example, if you ask for the number of
154   /// iterations of a linked-list traversal loop, you will get one of these.
155   /// None of the standard SCEV operations are valid on this class, it is just a
156   /// marker.
157   struct SCEVCouldNotCompute : public SCEV {
158     SCEVCouldNotCompute();
159
160     /// Methods for support type inquiry through isa, cast, and dyn_cast:
161     static inline bool classof(const SCEVCouldNotCompute *S) { return true; }
162     static bool classof(const SCEV *S);
163   };
164
165   /// ScalarEvolution - This class is the main scalar evolution driver.  Because
166   /// client code (intentionally) can't do much with the SCEV objects directly,
167   /// they must ask this class for services.
168   ///
169   class ScalarEvolution : public FunctionPass {
170   public:
171     /// LoopDisposition - An enum describing the relationship between a
172     /// SCEV and a loop.
173     enum LoopDisposition {
174       LoopVariant,    ///< The SCEV is loop-variant (unknown).
175       LoopInvariant,  ///< The SCEV is loop-invariant.
176       LoopComputable  ///< The SCEV varies predictably with the loop.
177     };
178
179     /// BlockDisposition - An enum describing the relationship between a
180     /// SCEV and a basic block.
181     enum BlockDisposition {
182       DoesNotDominateBlock,  ///< The SCEV does not dominate the block.
183       DominatesBlock,        ///< The SCEV dominates the block.
184       ProperlyDominatesBlock ///< The SCEV properly dominates the block.
185     };
186
187     /// Convenient NoWrapFlags manipulation that hides enum casts and is
188     /// visible in the ScalarEvolution name space.
189     static SCEV::NoWrapFlags maskFlags(SCEV::NoWrapFlags Flags, int Mask) {
190       return (SCEV::NoWrapFlags)(Flags & Mask);
191     }
192     static SCEV::NoWrapFlags setFlags(SCEV::NoWrapFlags Flags,
193                                       SCEV::NoWrapFlags OnFlags) {
194       return (SCEV::NoWrapFlags)(Flags | OnFlags);
195     }
196     static SCEV::NoWrapFlags clearFlags(SCEV::NoWrapFlags Flags,
197                                         SCEV::NoWrapFlags OffFlags) {
198       return (SCEV::NoWrapFlags)(Flags & ~OffFlags);
199     }
200
201   private:
202     /// SCEVCallbackVH - A CallbackVH to arrange for ScalarEvolution to be
203     /// notified whenever a Value is deleted.
204     class SCEVCallbackVH : public CallbackVH {
205       ScalarEvolution *SE;
206       virtual void deleted();
207       virtual void allUsesReplacedWith(Value *New);
208     public:
209       SCEVCallbackVH(Value *V, ScalarEvolution *SE = 0);
210     };
211
212     friend class SCEVCallbackVH;
213     friend class SCEVExpander;
214     friend class SCEVUnknown;
215
216     /// F - The function we are analyzing.
217     ///
218     Function *F;
219
220     /// LI - The loop information for the function we are currently analyzing.
221     ///
222     LoopInfo *LI;
223
224     /// TD - The target data information for the target we are targeting.
225     ///
226     TargetData *TD;
227
228     /// TLI - The target library information for the target we are targeting.
229     ///
230     TargetLibraryInfo *TLI;
231
232     /// DT - The dominator tree.
233     ///
234     DominatorTree *DT;
235
236     /// CouldNotCompute - This SCEV is used to represent unknown trip
237     /// counts and things.
238     SCEVCouldNotCompute CouldNotCompute;
239
240     /// ValueExprMapType - The typedef for ValueExprMap.
241     ///
242     typedef DenseMap<SCEVCallbackVH, const SCEV *, DenseMapInfo<Value *> >
243       ValueExprMapType;
244
245     /// ValueExprMap - This is a cache of the values we have analyzed so far.
246     ///
247     ValueExprMapType ValueExprMap;
248
249     /// ExitLimit - Information about the number of loop iterations for
250     /// which a loop exit's branch condition evaluates to the not-taken path.
251     /// This is a temporary pair of exact and max expressions that are
252     /// eventually summarized in ExitNotTakenInfo and BackedgeTakenInfo.
253     struct ExitLimit {
254       const SCEV *Exact;
255       const SCEV *Max;
256
257       /*implicit*/ ExitLimit(const SCEV *E) : Exact(E), Max(E) {}
258
259       ExitLimit(const SCEV *E, const SCEV *M) : Exact(E), Max(M) {}
260
261       /// hasAnyInfo - Test whether this ExitLimit contains any computed
262       /// information, or whether it's all SCEVCouldNotCompute values.
263       bool hasAnyInfo() const {
264         return !isa<SCEVCouldNotCompute>(Exact) ||
265           !isa<SCEVCouldNotCompute>(Max);
266       }
267     };
268
269     /// ExitNotTakenInfo - Information about the number of times a particular
270     /// loop exit may be reached before exiting the loop.
271     struct ExitNotTakenInfo {
272       AssertingVH<BasicBlock> ExitingBlock;
273       const SCEV *ExactNotTaken;
274       PointerIntPair<ExitNotTakenInfo*, 1> NextExit;
275
276       ExitNotTakenInfo() : ExitingBlock(0), ExactNotTaken(0) {}
277
278       /// isCompleteList - Return true if all loop exits are computable.
279       bool isCompleteList() const {
280         return NextExit.getInt() == 0;
281       }
282
283       void setIncomplete() { NextExit.setInt(1); }
284
285       /// getNextExit - Return a pointer to the next exit's not-taken info.
286       ExitNotTakenInfo *getNextExit() const {
287         return NextExit.getPointer();
288       }
289
290       void setNextExit(ExitNotTakenInfo *ENT) { NextExit.setPointer(ENT); }
291     };
292
293     /// BackedgeTakenInfo - Information about the backedge-taken count
294     /// of a loop. This currently includes an exact count and a maximum count.
295     ///
296     class BackedgeTakenInfo {
297       /// ExitNotTaken - A list of computable exits and their not-taken counts.
298       /// Loops almost never have more than one computable exit.
299       ExitNotTakenInfo ExitNotTaken;
300
301       /// Max - An expression indicating the least maximum backedge-taken
302       /// count of the loop that is known, or a SCEVCouldNotCompute.
303       const SCEV *Max;
304
305     public:
306       BackedgeTakenInfo() : Max(0) {}
307
308       /// Initialize BackedgeTakenInfo from a list of exact exit counts.
309       BackedgeTakenInfo(
310         SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts,
311         bool Complete, const SCEV *MaxCount);
312
313       /// hasAnyInfo - Test whether this BackedgeTakenInfo contains any
314       /// computed information, or whether it's all SCEVCouldNotCompute
315       /// values.
316       bool hasAnyInfo() const {
317         return ExitNotTaken.ExitingBlock || !isa<SCEVCouldNotCompute>(Max);
318       }
319
320       /// getExact - Return an expression indicating the exact backedge-taken
321       /// count of the loop if it is known, or SCEVCouldNotCompute
322       /// otherwise. This is the number of times the loop header can be
323       /// guaranteed to execute, minus one.
324       const SCEV *getExact(ScalarEvolution *SE) const;
325
326       /// getExact - Return the number of times this loop exit may fall through
327       /// to the back edge, or SCEVCouldNotCompute. The loop is guaranteed not
328       /// to exit via this block before this number of iterations, but may exit
329       /// via another block.
330       const SCEV *getExact(BasicBlock *ExitingBlock, ScalarEvolution *SE) const;
331
332       /// getMax - Get the max backedge taken count for the loop.
333       const SCEV *getMax(ScalarEvolution *SE) const;
334
335       /// clear - Invalidate this result and free associated memory.
336       void clear();
337     };
338
339     /// BackedgeTakenCounts - Cache the backedge-taken count of the loops for
340     /// this function as they are computed.
341     DenseMap<const Loop*, BackedgeTakenInfo> BackedgeTakenCounts;
342
343     /// ConstantEvolutionLoopExitValue - This map contains entries for all of
344     /// the PHI instructions that we attempt to compute constant evolutions for.
345     /// This allows us to avoid potentially expensive recomputation of these
346     /// properties.  An instruction maps to null if we are unable to compute its
347     /// exit value.
348     DenseMap<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
349
350     /// ValuesAtScopes - This map contains entries for all the expressions
351     /// that we attempt to compute getSCEVAtScope information for, which can
352     /// be expensive in extreme cases.
353     DenseMap<const SCEV *,
354              std::map<const Loop *, const SCEV *> > ValuesAtScopes;
355
356     /// LoopDispositions - Memoized computeLoopDisposition results.
357     DenseMap<const SCEV *,
358              std::map<const Loop *, LoopDisposition> > LoopDispositions;
359
360     /// computeLoopDisposition - Compute a LoopDisposition value.
361     LoopDisposition computeLoopDisposition(const SCEV *S, const Loop *L);
362
363     /// BlockDispositions - Memoized computeBlockDisposition results.
364     DenseMap<const SCEV *,
365              std::map<const BasicBlock *, BlockDisposition> > BlockDispositions;
366
367     /// computeBlockDisposition - Compute a BlockDisposition value.
368     BlockDisposition computeBlockDisposition(const SCEV *S, const BasicBlock *BB);
369
370     /// UnsignedRanges - Memoized results from getUnsignedRange
371     DenseMap<const SCEV *, ConstantRange> UnsignedRanges;
372
373     /// SignedRanges - Memoized results from getSignedRange
374     DenseMap<const SCEV *, ConstantRange> SignedRanges;
375
376     /// setUnsignedRange - Set the memoized unsigned range for the given SCEV.
377     const ConstantRange &setUnsignedRange(const SCEV *S,
378                                           const ConstantRange &CR) {
379       std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair =
380         UnsignedRanges.insert(std::make_pair(S, CR));
381       if (!Pair.second)
382         Pair.first->second = CR;
383       return Pair.first->second;
384     }
385
386     /// setUnsignedRange - Set the memoized signed range for the given SCEV.
387     const ConstantRange &setSignedRange(const SCEV *S,
388                                         const ConstantRange &CR) {
389       std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair =
390         SignedRanges.insert(std::make_pair(S, CR));
391       if (!Pair.second)
392         Pair.first->second = CR;
393       return Pair.first->second;
394     }
395
396     /// createSCEV - We know that there is no SCEV for the specified value.
397     /// Analyze the expression.
398     const SCEV *createSCEV(Value *V);
399
400     /// createNodeForPHI - Provide the special handling we need to analyze PHI
401     /// SCEVs.
402     const SCEV *createNodeForPHI(PHINode *PN);
403
404     /// createNodeForGEP - Provide the special handling we need to analyze GEP
405     /// SCEVs.
406     const SCEV *createNodeForGEP(GEPOperator *GEP);
407
408     /// computeSCEVAtScope - Implementation code for getSCEVAtScope; called
409     /// at most once for each SCEV+Loop pair.
410     ///
411     const SCEV *computeSCEVAtScope(const SCEV *S, const Loop *L);
412
413     /// ForgetSymbolicValue - This looks up computed SCEV values for all
414     /// instructions that depend on the given instruction and removes them from
415     /// the ValueExprMap map if they reference SymName. This is used during PHI
416     /// resolution.
417     void ForgetSymbolicName(Instruction *I, const SCEV *SymName);
418
419     /// getBECount - Subtract the end and start values and divide by the step,
420     /// rounding up, to get the number of times the backedge is executed. Return
421     /// CouldNotCompute if an intermediate computation overflows.
422     const SCEV *getBECount(const SCEV *Start,
423                            const SCEV *End,
424                            const SCEV *Step,
425                            bool NoWrap);
426
427     /// getBackedgeTakenInfo - Return the BackedgeTakenInfo for the given
428     /// loop, lazily computing new values if the loop hasn't been analyzed
429     /// yet.
430     const BackedgeTakenInfo &getBackedgeTakenInfo(const Loop *L);
431
432     /// ComputeBackedgeTakenCount - Compute the number of times the specified
433     /// loop will iterate.
434     BackedgeTakenInfo ComputeBackedgeTakenCount(const Loop *L);
435
436     /// ComputeExitLimit - Compute the number of times the backedge of the
437     /// specified loop will execute if it exits via the specified block.
438     ExitLimit ComputeExitLimit(const Loop *L, BasicBlock *ExitingBlock);
439
440     /// ComputeExitLimitFromCond - Compute the number of times the backedge of
441     /// the specified loop will execute if its exit condition were a conditional
442     /// branch of ExitCond, TBB, and FBB.
443     ExitLimit ComputeExitLimitFromCond(const Loop *L,
444                                        Value *ExitCond,
445                                        BasicBlock *TBB,
446                                        BasicBlock *FBB);
447
448     /// ComputeExitLimitFromICmp - Compute the number of times the backedge of
449     /// the specified loop will execute if its exit condition were a conditional
450     /// branch of the ICmpInst ExitCond, TBB, and FBB.
451     ExitLimit ComputeExitLimitFromICmp(const Loop *L,
452                                        ICmpInst *ExitCond,
453                                        BasicBlock *TBB,
454                                        BasicBlock *FBB);
455
456     /// ComputeLoadConstantCompareExitLimit - Given an exit condition
457     /// of 'icmp op load X, cst', try to see if we can compute the
458     /// backedge-taken count.
459     ExitLimit ComputeLoadConstantCompareExitLimit(LoadInst *LI,
460                                                   Constant *RHS,
461                                                   const Loop *L,
462                                                   ICmpInst::Predicate p);
463
464     /// ComputeExitCountExhaustively - If the loop is known to execute a
465     /// constant number of times (the condition evolves only from constants),
466     /// try to evaluate a few iterations of the loop until we get the exit
467     /// condition gets a value of ExitWhen (true or false).  If we cannot
468     /// evaluate the exit count of the loop, return CouldNotCompute.
469     const SCEV *ComputeExitCountExhaustively(const Loop *L,
470                                              Value *Cond,
471                                              bool ExitWhen);
472
473     /// HowFarToZero - Return the number of times an exit condition comparing
474     /// the specified value to zero will execute.  If not computable, return
475     /// CouldNotCompute.
476     ExitLimit HowFarToZero(const SCEV *V, const Loop *L);
477
478     /// HowFarToNonZero - Return the number of times an exit condition checking
479     /// the specified value for nonzero will execute.  If not computable, return
480     /// CouldNotCompute.
481     ExitLimit HowFarToNonZero(const SCEV *V, const Loop *L);
482
483     /// HowManyLessThans - Return the number of times an exit condition
484     /// containing the specified less-than comparison will execute.  If not
485     /// computable, return CouldNotCompute. isSigned specifies whether the
486     /// less-than is signed.
487     ExitLimit HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
488                                const Loop *L, bool isSigned);
489
490     /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
491     /// (which may not be an immediate predecessor) which has exactly one
492     /// successor from which BB is reachable, or null if no such block is
493     /// found.
494     std::pair<BasicBlock *, BasicBlock *>
495     getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
496
497     /// isImpliedCond - Test whether the condition described by Pred, LHS, and
498     /// RHS is true whenever the given FoundCondValue value evaluates to true.
499     bool isImpliedCond(ICmpInst::Predicate Pred,
500                        const SCEV *LHS, const SCEV *RHS,
501                        Value *FoundCondValue,
502                        bool Inverse);
503
504     /// isImpliedCondOperands - Test whether the condition described by Pred,
505     /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
506     /// and FoundRHS is true.
507     bool isImpliedCondOperands(ICmpInst::Predicate Pred,
508                                const SCEV *LHS, const SCEV *RHS,
509                                const SCEV *FoundLHS, const SCEV *FoundRHS);
510
511     /// isImpliedCondOperandsHelper - Test whether the condition described by
512     /// Pred, LHS, and RHS is true whenever the condition described by Pred,
513     /// FoundLHS, and FoundRHS is true.
514     bool isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
515                                      const SCEV *LHS, const SCEV *RHS,
516                                      const SCEV *FoundLHS,
517                                      const SCEV *FoundRHS);
518
519     /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
520     /// in the header of its containing loop, we know the loop executes a
521     /// constant number of times, and the PHI node is just a recurrence
522     /// involving constants, fold it.
523     Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs,
524                                                 const Loop *L);
525
526     /// isKnownPredicateWithRanges - Test if the given expression is known to
527     /// satisfy the condition described by Pred and the known constant ranges
528     /// of LHS and RHS.
529     ///
530     bool isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
531                                     const SCEV *LHS, const SCEV *RHS);
532
533     /// forgetMemoizedResults - Drop memoized information computed for S.
534     void forgetMemoizedResults(const SCEV *S);
535
536   public:
537     static char ID; // Pass identification, replacement for typeid
538     ScalarEvolution();
539
540     LLVMContext &getContext() const { return F->getContext(); }
541
542     /// isSCEVable - Test if values of the given type are analyzable within
543     /// the SCEV framework. This primarily includes integer types, and it
544     /// can optionally include pointer types if the ScalarEvolution class
545     /// has access to target-specific information.
546     bool isSCEVable(Type *Ty) const;
547
548     /// getTypeSizeInBits - Return the size in bits of the specified type,
549     /// for which isSCEVable must return true.
550     uint64_t getTypeSizeInBits(Type *Ty) const;
551
552     /// getEffectiveSCEVType - Return a type with the same bitwidth as
553     /// the given type and which represents how SCEV will treat the given
554     /// type, for which isSCEVable must return true. For pointer types,
555     /// this is the pointer-sized integer type.
556     Type *getEffectiveSCEVType(Type *Ty) const;
557
558     /// getSCEV - Return a SCEV expression for the full generality of the
559     /// specified expression.
560     const SCEV *getSCEV(Value *V);
561
562     const SCEV *getConstant(ConstantInt *V);
563     const SCEV *getConstant(const APInt& Val);
564     const SCEV *getConstant(Type *Ty, uint64_t V, bool isSigned = false);
565     const SCEV *getTruncateExpr(const SCEV *Op, Type *Ty);
566     const SCEV *getZeroExtendExpr(const SCEV *Op, Type *Ty);
567     const SCEV *getSignExtendExpr(const SCEV *Op, Type *Ty);
568     const SCEV *getAnyExtendExpr(const SCEV *Op, Type *Ty);
569     const SCEV *getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
570                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
571     const SCEV *getAddExpr(const SCEV *LHS, const SCEV *RHS,
572                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
573       SmallVector<const SCEV *, 2> Ops;
574       Ops.push_back(LHS);
575       Ops.push_back(RHS);
576       return getAddExpr(Ops, Flags);
577     }
578     const SCEV *getAddExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
579                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
580       SmallVector<const SCEV *, 3> Ops;
581       Ops.push_back(Op0);
582       Ops.push_back(Op1);
583       Ops.push_back(Op2);
584       return getAddExpr(Ops, Flags);
585     }
586     const SCEV *getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
587                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
588     const SCEV *getMulExpr(const SCEV *LHS, const SCEV *RHS,
589                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap)
590     {
591       SmallVector<const SCEV *, 2> Ops;
592       Ops.push_back(LHS);
593       Ops.push_back(RHS);
594       return getMulExpr(Ops, Flags);
595     }
596     const SCEV *getMulExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
597                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
598       SmallVector<const SCEV *, 3> Ops;
599       Ops.push_back(Op0);
600       Ops.push_back(Op1);
601       Ops.push_back(Op2);
602       return getMulExpr(Ops, Flags);
603     }
604     const SCEV *getUDivExpr(const SCEV *LHS, const SCEV *RHS);
605     const SCEV *getAddRecExpr(const SCEV *Start, const SCEV *Step,
606                               const Loop *L, SCEV::NoWrapFlags Flags);
607     const SCEV *getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
608                               const Loop *L, SCEV::NoWrapFlags Flags);
609     const SCEV *getAddRecExpr(const SmallVectorImpl<const SCEV *> &Operands,
610                               const Loop *L, SCEV::NoWrapFlags Flags) {
611       SmallVector<const SCEV *, 4> NewOp(Operands.begin(), Operands.end());
612       return getAddRecExpr(NewOp, L, Flags);
613     }
614     const SCEV *getSMaxExpr(const SCEV *LHS, const SCEV *RHS);
615     const SCEV *getSMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
616     const SCEV *getUMaxExpr(const SCEV *LHS, const SCEV *RHS);
617     const SCEV *getUMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
618     const SCEV *getSMinExpr(const SCEV *LHS, const SCEV *RHS);
619     const SCEV *getUMinExpr(const SCEV *LHS, const SCEV *RHS);
620     const SCEV *getUnknown(Value *V);
621     const SCEV *getCouldNotCompute();
622
623     /// getSizeOfExpr - Return an expression for sizeof on the given type.
624     ///
625     const SCEV *getSizeOfExpr(Type *AllocTy);
626
627     /// getAlignOfExpr - Return an expression for alignof on the given type.
628     ///
629     const SCEV *getAlignOfExpr(Type *AllocTy);
630
631     /// getOffsetOfExpr - Return an expression for offsetof on the given field.
632     ///
633     const SCEV *getOffsetOfExpr(StructType *STy, unsigned FieldNo);
634
635     /// getOffsetOfExpr - Return an expression for offsetof on the given field.
636     ///
637     const SCEV *getOffsetOfExpr(Type *CTy, Constant *FieldNo);
638
639     /// getNegativeSCEV - Return the SCEV object corresponding to -V.
640     ///
641     const SCEV *getNegativeSCEV(const SCEV *V);
642
643     /// getNotSCEV - Return the SCEV object corresponding to ~V.
644     ///
645     const SCEV *getNotSCEV(const SCEV *V);
646
647     /// getMinusSCEV - Return LHS-RHS.  Minus is represented in SCEV as A+B*-1.
648     const SCEV *getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
649                              SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
650
651     /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
652     /// of the input value to the specified type.  If the type must be
653     /// extended, it is zero extended.
654     const SCEV *getTruncateOrZeroExtend(const SCEV *V, Type *Ty);
655
656     /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
657     /// of the input value to the specified type.  If the type must be
658     /// extended, it is sign extended.
659     const SCEV *getTruncateOrSignExtend(const SCEV *V, Type *Ty);
660
661     /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of
662     /// the input value to the specified type.  If the type must be extended,
663     /// it is zero extended.  The conversion must not be narrowing.
664     const SCEV *getNoopOrZeroExtend(const SCEV *V, Type *Ty);
665
666     /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of
667     /// the input value to the specified type.  If the type must be extended,
668     /// it is sign extended.  The conversion must not be narrowing.
669     const SCEV *getNoopOrSignExtend(const SCEV *V, Type *Ty);
670
671     /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
672     /// the input value to the specified type. If the type must be extended,
673     /// it is extended with unspecified bits. The conversion must not be
674     /// narrowing.
675     const SCEV *getNoopOrAnyExtend(const SCEV *V, Type *Ty);
676
677     /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
678     /// input value to the specified type.  The conversion must not be
679     /// widening.
680     const SCEV *getTruncateOrNoop(const SCEV *V, Type *Ty);
681
682     /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
683     /// the types using zero-extension, and then perform a umax operation
684     /// with them.
685     const SCEV *getUMaxFromMismatchedTypes(const SCEV *LHS,
686                                            const SCEV *RHS);
687
688     /// getUMinFromMismatchedTypes - Promote the operands to the wider of
689     /// the types using zero-extension, and then perform a umin operation
690     /// with them.
691     const SCEV *getUMinFromMismatchedTypes(const SCEV *LHS,
692                                            const SCEV *RHS);
693
694     /// getPointerBase - Transitively follow the chain of pointer-type operands
695     /// until reaching a SCEV that does not have a single pointer operand. This
696     /// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
697     /// but corner cases do exist.
698     const SCEV *getPointerBase(const SCEV *V);
699
700     /// getSCEVAtScope - Return a SCEV expression for the specified value
701     /// at the specified scope in the program.  The L value specifies a loop
702     /// nest to evaluate the expression at, where null is the top-level or a
703     /// specified loop is immediately inside of the loop.
704     ///
705     /// This method can be used to compute the exit value for a variable defined
706     /// in a loop by querying what the value will hold in the parent loop.
707     ///
708     /// In the case that a relevant loop exit value cannot be computed, the
709     /// original value V is returned.
710     const SCEV *getSCEVAtScope(const SCEV *S, const Loop *L);
711
712     /// getSCEVAtScope - This is a convenience function which does
713     /// getSCEVAtScope(getSCEV(V), L).
714     const SCEV *getSCEVAtScope(Value *V, const Loop *L);
715
716     /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
717     /// by a conditional between LHS and RHS.  This is used to help avoid max
718     /// expressions in loop trip counts, and to eliminate casts.
719     bool isLoopEntryGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
720                                   const SCEV *LHS, const SCEV *RHS);
721
722     /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
723     /// protected by a conditional between LHS and RHS.  This is used to
724     /// to eliminate casts.
725     bool isLoopBackedgeGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
726                                      const SCEV *LHS, const SCEV *RHS);
727
728     /// getSmallConstantTripCount - Returns the maximum trip count of this loop
729     /// as a normal unsigned value, if possible. Returns 0 if the trip count is
730     /// unknown or not constant.
731     unsigned getSmallConstantTripCount(Loop *L, BasicBlock *ExitBlock);
732
733     /// getSmallConstantTripMultiple - Returns the largest constant divisor of
734     /// the trip count of this loop as a normal unsigned value, if
735     /// possible. This means that the actual trip count is always a multiple of
736     /// the returned value (don't forget the trip count could very well be zero
737     /// as well!).
738     unsigned getSmallConstantTripMultiple(Loop *L, BasicBlock *ExitBlock);
739
740     // getExitCount - Get the expression for the number of loop iterations for
741     // which this loop is guaranteed not to exit via ExitingBlock. Otherwise
742     // return SCEVCouldNotCompute.
743     const SCEV *getExitCount(Loop *L, BasicBlock *ExitingBlock);
744
745     /// getBackedgeTakenCount - If the specified loop has a predictable
746     /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
747     /// object. The backedge-taken count is the number of times the loop header
748     /// will be branched to from within the loop. This is one less than the
749     /// trip count of the loop, since it doesn't count the first iteration,
750     /// when the header is branched to from outside the loop.
751     ///
752     /// Note that it is not valid to call this method on a loop without a
753     /// loop-invariant backedge-taken count (see
754     /// hasLoopInvariantBackedgeTakenCount).
755     ///
756     const SCEV *getBackedgeTakenCount(const Loop *L);
757
758     /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
759     /// return the least SCEV value that is known never to be less than the
760     /// actual backedge taken count.
761     const SCEV *getMaxBackedgeTakenCount(const Loop *L);
762
763     /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop
764     /// has an analyzable loop-invariant backedge-taken count.
765     bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
766
767     /// forgetLoop - This method should be called by the client when it has
768     /// changed a loop in a way that may effect ScalarEvolution's ability to
769     /// compute a trip count, or if the loop is deleted.
770     void forgetLoop(const Loop *L);
771
772     /// forgetValue - This method should be called by the client when it has
773     /// changed a value in a way that may effect its value, or which may
774     /// disconnect it from a def-use chain linking it to a loop.
775     void forgetValue(Value *V);
776
777     /// GetMinTrailingZeros - Determine the minimum number of zero bits that S
778     /// is guaranteed to end in (at every loop iteration).  It is, at the same
779     /// time, the minimum number of times S is divisible by 2.  For example,
780     /// given {4,+,8} it returns 2.  If S is guaranteed to be 0, it returns the
781     /// bitwidth of S.
782     uint32_t GetMinTrailingZeros(const SCEV *S);
783
784     /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
785     ///
786     ConstantRange getUnsignedRange(const SCEV *S);
787
788     /// getSignedRange - Determine the signed range for a particular SCEV.
789     ///
790     ConstantRange getSignedRange(const SCEV *S);
791
792     /// isKnownNegative - Test if the given expression is known to be negative.
793     ///
794     bool isKnownNegative(const SCEV *S);
795
796     /// isKnownPositive - Test if the given expression is known to be positive.
797     ///
798     bool isKnownPositive(const SCEV *S);
799
800     /// isKnownNonNegative - Test if the given expression is known to be
801     /// non-negative.
802     ///
803     bool isKnownNonNegative(const SCEV *S);
804
805     /// isKnownNonPositive - Test if the given expression is known to be
806     /// non-positive.
807     ///
808     bool isKnownNonPositive(const SCEV *S);
809
810     /// isKnownNonZero - Test if the given expression is known to be
811     /// non-zero.
812     ///
813     bool isKnownNonZero(const SCEV *S);
814
815     /// isKnownPredicate - Test if the given expression is known to satisfy
816     /// the condition described by Pred, LHS, and RHS.
817     ///
818     bool isKnownPredicate(ICmpInst::Predicate Pred,
819                           const SCEV *LHS, const SCEV *RHS);
820
821     /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
822     /// predicate Pred. Return true iff any changes were made. If the
823     /// operands are provably equal or inequal, LHS and RHS are set to
824     /// the same value and Pred is set to either ICMP_EQ or ICMP_NE.
825     ///
826     bool SimplifyICmpOperands(ICmpInst::Predicate &Pred,
827                               const SCEV *&LHS,
828                               const SCEV *&RHS);
829
830     /// getLoopDisposition - Return the "disposition" of the given SCEV with
831     /// respect to the given loop.
832     LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L);
833
834     /// isLoopInvariant - Return true if the value of the given SCEV is
835     /// unchanging in the specified loop.
836     bool isLoopInvariant(const SCEV *S, const Loop *L);
837
838     /// hasComputableLoopEvolution - Return true if the given SCEV changes value
839     /// in a known way in the specified loop.  This property being true implies
840     /// that the value is variant in the loop AND that we can emit an expression
841     /// to compute the value of the expression at any particular loop iteration.
842     bool hasComputableLoopEvolution(const SCEV *S, const Loop *L);
843
844     /// getLoopDisposition - Return the "disposition" of the given SCEV with
845     /// respect to the given block.
846     BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB);
847
848     /// dominates - Return true if elements that makes up the given SCEV
849     /// dominate the specified basic block.
850     bool dominates(const SCEV *S, const BasicBlock *BB);
851
852     /// properlyDominates - Return true if elements that makes up the given SCEV
853     /// properly dominate the specified basic block.
854     bool properlyDominates(const SCEV *S, const BasicBlock *BB);
855
856     /// hasOperand - Test whether the given SCEV has Op as a direct or
857     /// indirect operand.
858     bool hasOperand(const SCEV *S, const SCEV *Op) const;
859
860     virtual bool runOnFunction(Function &F);
861     virtual void releaseMemory();
862     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
863     virtual void print(raw_ostream &OS, const Module* = 0) const;
864
865   private:
866     FoldingSet<SCEV> UniqueSCEVs;
867     BumpPtrAllocator SCEVAllocator;
868
869     /// FirstUnknown - The head of a linked list of all SCEVUnknown
870     /// values that have been allocated. This is used by releaseMemory
871     /// to locate them all and call their destructors.
872     SCEVUnknown *FirstUnknown;
873   };
874 }
875
876 #endif