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