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