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