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