Make use of @llvm.assume in ValueTracking (computeKnownBits, etc.)
[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     ///
265     /// If MustExit is true, then the exit must be taken when the BECount
266     /// reaches Exact (and before surpassing Max). If MustExit is false, then
267     /// BECount may exceed Exact or Max if the loop exits via another branch. In
268     /// either case, the loop may exit early via another branch.
269     ///
270     /// MustExit is true for most cases. However, an exit guarded by an
271     /// (in)equality on a nonunit stride may be skipped.
272     struct ExitLimit {
273       const SCEV *Exact;
274       const SCEV *Max;
275       bool MustExit;
276
277       /*implicit*/ ExitLimit(const SCEV *E)
278         : Exact(E), Max(E), MustExit(true) {}
279
280       ExitLimit(const SCEV *E, const SCEV *M, bool MustExit)
281         : Exact(E), Max(M), MustExit(MustExit) {}
282
283       /// hasAnyInfo - Test whether this ExitLimit contains any computed
284       /// information, or whether it's all SCEVCouldNotCompute values.
285       bool hasAnyInfo() const {
286         return !isa<SCEVCouldNotCompute>(Exact) ||
287           !isa<SCEVCouldNotCompute>(Max);
288       }
289     };
290
291     /// ExitNotTakenInfo - Information about the number of times a particular
292     /// loop exit may be reached before exiting the loop.
293     struct ExitNotTakenInfo {
294       AssertingVH<BasicBlock> ExitingBlock;
295       const SCEV *ExactNotTaken;
296       PointerIntPair<ExitNotTakenInfo*, 1> NextExit;
297
298       ExitNotTakenInfo() : ExitingBlock(nullptr), ExactNotTaken(nullptr) {}
299
300       /// isCompleteList - Return true if all loop exits are computable.
301       bool isCompleteList() const {
302         return NextExit.getInt() == 0;
303       }
304
305       void setIncomplete() { NextExit.setInt(1); }
306
307       /// getNextExit - Return a pointer to the next exit's not-taken info.
308       ExitNotTakenInfo *getNextExit() const {
309         return NextExit.getPointer();
310       }
311
312       void setNextExit(ExitNotTakenInfo *ENT) { NextExit.setPointer(ENT); }
313     };
314
315     /// BackedgeTakenInfo - Information about the backedge-taken count
316     /// of a loop. This currently includes an exact count and a maximum count.
317     ///
318     class BackedgeTakenInfo {
319       /// ExitNotTaken - A list of computable exits and their not-taken counts.
320       /// Loops almost never have more than one computable exit.
321       ExitNotTakenInfo ExitNotTaken;
322
323       /// Max - An expression indicating the least maximum backedge-taken
324       /// count of the loop that is known, or a SCEVCouldNotCompute.
325       const SCEV *Max;
326
327     public:
328       BackedgeTakenInfo() : Max(nullptr) {}
329
330       /// Initialize BackedgeTakenInfo from a list of exact exit counts.
331       BackedgeTakenInfo(
332         SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts,
333         bool Complete, const SCEV *MaxCount);
334
335       /// hasAnyInfo - Test whether this BackedgeTakenInfo contains any
336       /// computed information, or whether it's all SCEVCouldNotCompute
337       /// values.
338       bool hasAnyInfo() const {
339         return ExitNotTaken.ExitingBlock || !isa<SCEVCouldNotCompute>(Max);
340       }
341
342       /// getExact - Return an expression indicating the exact backedge-taken
343       /// count of the loop if it is known, or SCEVCouldNotCompute
344       /// otherwise. This is the number of times the loop header can be
345       /// guaranteed to execute, minus one.
346       const SCEV *getExact(ScalarEvolution *SE) const;
347
348       /// getExact - Return the number of times this loop exit may fall through
349       /// to the back edge, or SCEVCouldNotCompute. The loop is guaranteed not
350       /// to exit via this block before this number of iterations, but may exit
351       /// via another block.
352       const SCEV *getExact(BasicBlock *ExitingBlock, ScalarEvolution *SE) const;
353
354       /// getMax - Get the max backedge taken count for the loop.
355       const SCEV *getMax(ScalarEvolution *SE) const;
356
357       /// Return true if any backedge taken count expressions refer to the given
358       /// subexpression.
359       bool hasOperand(const SCEV *S, ScalarEvolution *SE) const;
360
361       /// clear - Invalidate this result and free associated memory.
362       void clear();
363     };
364
365     /// BackedgeTakenCounts - Cache the backedge-taken count of the loops for
366     /// this function as they are computed.
367     DenseMap<const Loop*, BackedgeTakenInfo> BackedgeTakenCounts;
368
369     /// ConstantEvolutionLoopExitValue - This map contains entries for all of
370     /// the PHI instructions that we attempt to compute constant evolutions for.
371     /// This allows us to avoid potentially expensive recomputation of these
372     /// properties.  An instruction maps to null if we are unable to compute its
373     /// exit value.
374     DenseMap<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
375
376     /// ValuesAtScopes - This map contains entries for all the expressions
377     /// that we attempt to compute getSCEVAtScope information for, which can
378     /// be expensive in extreme cases.
379     DenseMap<const SCEV *,
380              SmallVector<std::pair<const Loop *, const SCEV *>, 2> > ValuesAtScopes;
381
382     /// LoopDispositions - Memoized computeLoopDisposition results.
383     DenseMap<const SCEV *,
384              SmallVector<std::pair<const Loop *, LoopDisposition>, 2> > LoopDispositions;
385
386     /// computeLoopDisposition - Compute a LoopDisposition value.
387     LoopDisposition computeLoopDisposition(const SCEV *S, const Loop *L);
388
389     /// BlockDispositions - Memoized computeBlockDisposition results.
390     DenseMap<const SCEV *,
391              SmallVector<std::pair<const BasicBlock *, BlockDisposition>, 2> > BlockDispositions;
392
393     /// computeBlockDisposition - Compute a BlockDisposition value.
394     BlockDisposition computeBlockDisposition(const SCEV *S, const BasicBlock *BB);
395
396     /// UnsignedRanges - Memoized results from getUnsignedRange
397     DenseMap<const SCEV *, ConstantRange> UnsignedRanges;
398
399     /// SignedRanges - Memoized results from getSignedRange
400     DenseMap<const SCEV *, ConstantRange> SignedRanges;
401
402     /// setUnsignedRange - Set the memoized unsigned range for the given SCEV.
403     const ConstantRange &setUnsignedRange(const SCEV *S,
404                                           const ConstantRange &CR) {
405       std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair =
406         UnsignedRanges.insert(std::make_pair(S, CR));
407       if (!Pair.second)
408         Pair.first->second = CR;
409       return Pair.first->second;
410     }
411
412     /// setUnsignedRange - Set the memoized signed range for the given SCEV.
413     const ConstantRange &setSignedRange(const SCEV *S,
414                                         const ConstantRange &CR) {
415       std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair =
416         SignedRanges.insert(std::make_pair(S, CR));
417       if (!Pair.second)
418         Pair.first->second = CR;
419       return Pair.first->second;
420     }
421
422     /// createSCEV - We know that there is no SCEV for the specified value.
423     /// Analyze the expression.
424     const SCEV *createSCEV(Value *V);
425
426     /// createNodeForPHI - Provide the special handling we need to analyze PHI
427     /// SCEVs.
428     const SCEV *createNodeForPHI(PHINode *PN);
429
430     /// createNodeForGEP - Provide the special handling we need to analyze GEP
431     /// SCEVs.
432     const SCEV *createNodeForGEP(GEPOperator *GEP);
433
434     /// computeSCEVAtScope - Implementation code for getSCEVAtScope; called
435     /// at most once for each SCEV+Loop pair.
436     ///
437     const SCEV *computeSCEVAtScope(const SCEV *S, const Loop *L);
438
439     /// ForgetSymbolicValue - This looks up computed SCEV values for all
440     /// instructions that depend on the given instruction and removes them from
441     /// the ValueExprMap map if they reference SymName. This is used during PHI
442     /// resolution.
443     void ForgetSymbolicName(Instruction *I, const SCEV *SymName);
444
445     /// getBackedgeTakenInfo - Return the BackedgeTakenInfo for the given
446     /// loop, lazily computing new values if the loop hasn't been analyzed
447     /// yet.
448     const BackedgeTakenInfo &getBackedgeTakenInfo(const Loop *L);
449
450     /// ComputeBackedgeTakenCount - Compute the number of times the specified
451     /// loop will iterate.
452     BackedgeTakenInfo ComputeBackedgeTakenCount(const Loop *L);
453
454     /// ComputeExitLimit - Compute the number of times the backedge of the
455     /// specified loop will execute if it exits via the specified block.
456     ExitLimit ComputeExitLimit(const Loop *L, BasicBlock *ExitingBlock);
457
458     /// ComputeExitLimitFromCond - Compute the number of times the backedge of
459     /// the specified loop will execute if its exit condition were a conditional
460     /// branch of ExitCond, TBB, and FBB.
461     ExitLimit ComputeExitLimitFromCond(const Loop *L,
462                                        Value *ExitCond,
463                                        BasicBlock *TBB,
464                                        BasicBlock *FBB,
465                                        bool IsSubExpr);
466
467     /// ComputeExitLimitFromICmp - Compute the number of times the backedge of
468     /// the specified loop will execute if its exit condition were a conditional
469     /// branch of the ICmpInst ExitCond, TBB, and FBB.
470     ExitLimit ComputeExitLimitFromICmp(const Loop *L,
471                                        ICmpInst *ExitCond,
472                                        BasicBlock *TBB,
473                                        BasicBlock *FBB,
474                                        bool IsSubExpr);
475
476     /// ComputeExitLimitFromSingleExitSwitch - Compute the number of times the
477     /// backedge of the specified loop will execute if its exit condition were a
478     /// switch with a single exiting case to ExitingBB.
479     ExitLimit
480     ComputeExitLimitFromSingleExitSwitch(const Loop *L, SwitchInst *Switch,
481                                BasicBlock *ExitingBB, bool IsSubExpr);
482
483     /// ComputeLoadConstantCompareExitLimit - Given an exit condition
484     /// of 'icmp op load X, cst', try to see if we can compute the
485     /// backedge-taken count.
486     ExitLimit ComputeLoadConstantCompareExitLimit(LoadInst *LI,
487                                                   Constant *RHS,
488                                                   const Loop *L,
489                                                   ICmpInst::Predicate p);
490
491     /// ComputeExitCountExhaustively - If the loop is known to execute a
492     /// constant number of times (the condition evolves only from constants),
493     /// try to evaluate a few iterations of the loop until we get the exit
494     /// condition gets a value of ExitWhen (true or false).  If we cannot
495     /// evaluate the exit count of the loop, return CouldNotCompute.
496     const SCEV *ComputeExitCountExhaustively(const Loop *L,
497                                              Value *Cond,
498                                              bool ExitWhen);
499
500     /// HowFarToZero - Return the number of times an exit condition comparing
501     /// the specified value to zero will execute.  If not computable, return
502     /// CouldNotCompute.
503     ExitLimit HowFarToZero(const SCEV *V, const Loop *L, bool IsSubExpr);
504
505     /// HowFarToNonZero - Return the number of times an exit condition checking
506     /// the specified value for nonzero will execute.  If not computable, return
507     /// CouldNotCompute.
508     ExitLimit HowFarToNonZero(const SCEV *V, const Loop *L);
509
510     /// HowManyLessThans - Return the number of times an exit condition
511     /// containing the specified less-than comparison will execute.  If not
512     /// computable, return CouldNotCompute. isSigned specifies whether the
513     /// less-than is signed.
514     ExitLimit HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
515                                const Loop *L, bool isSigned, bool IsSubExpr);
516     ExitLimit HowManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
517                                   const Loop *L, bool isSigned, bool IsSubExpr);
518
519     /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
520     /// (which may not be an immediate predecessor) which has exactly one
521     /// successor from which BB is reachable, or null if no such block is
522     /// found.
523     std::pair<BasicBlock *, BasicBlock *>
524     getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
525
526     /// isImpliedCond - Test whether the condition described by Pred, LHS, and
527     /// RHS is true whenever the given FoundCondValue value evaluates to true.
528     bool isImpliedCond(ICmpInst::Predicate Pred,
529                        const SCEV *LHS, const SCEV *RHS,
530                        Value *FoundCondValue,
531                        bool Inverse);
532
533     /// isImpliedCondOperands - Test whether the condition described by Pred,
534     /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
535     /// and FoundRHS is true.
536     bool isImpliedCondOperands(ICmpInst::Predicate Pred,
537                                const SCEV *LHS, const SCEV *RHS,
538                                const SCEV *FoundLHS, const SCEV *FoundRHS);
539
540     /// isImpliedCondOperandsHelper - Test whether the condition described by
541     /// Pred, LHS, and RHS is true whenever the condition described by Pred,
542     /// FoundLHS, and FoundRHS is true.
543     bool isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
544                                      const SCEV *LHS, const SCEV *RHS,
545                                      const SCEV *FoundLHS,
546                                      const SCEV *FoundRHS);
547
548     /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
549     /// in the header of its containing loop, we know the loop executes a
550     /// constant number of times, and the PHI node is just a recurrence
551     /// involving constants, fold it.
552     Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs,
553                                                 const Loop *L);
554
555     /// isKnownPredicateWithRanges - Test if the given expression is known to
556     /// satisfy the condition described by Pred and the known constant ranges
557     /// of LHS and RHS.
558     ///
559     bool isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
560                                     const SCEV *LHS, const SCEV *RHS);
561
562     /// forgetMemoizedResults - Drop memoized information computed for S.
563     void forgetMemoizedResults(const SCEV *S);
564
565     /// Return false iff given SCEV contains a SCEVUnknown with NULL value-
566     /// pointer.
567     bool checkValidity(const SCEV *S) const;
568
569   public:
570     static char ID; // Pass identification, replacement for typeid
571     ScalarEvolution();
572
573     LLVMContext &getContext() const { return F->getContext(); }
574
575     /// isSCEVable - Test if values of the given type are analyzable within
576     /// the SCEV framework. This primarily includes integer types, and it
577     /// can optionally include pointer types if the ScalarEvolution class
578     /// has access to target-specific information.
579     bool isSCEVable(Type *Ty) const;
580
581     /// getTypeSizeInBits - Return the size in bits of the specified type,
582     /// for which isSCEVable must return true.
583     uint64_t getTypeSizeInBits(Type *Ty) const;
584
585     /// getEffectiveSCEVType - Return a type with the same bitwidth as
586     /// the given type and which represents how SCEV will treat the given
587     /// type, for which isSCEVable must return true. For pointer types,
588     /// this is the pointer-sized integer type.
589     Type *getEffectiveSCEVType(Type *Ty) const;
590
591     /// getSCEV - Return a SCEV expression for the full generality of the
592     /// specified expression.
593     const SCEV *getSCEV(Value *V);
594
595     const SCEV *getConstant(ConstantInt *V);
596     const SCEV *getConstant(const APInt& Val);
597     const SCEV *getConstant(Type *Ty, uint64_t V, bool isSigned = false);
598     const SCEV *getTruncateExpr(const SCEV *Op, Type *Ty);
599     const SCEV *getZeroExtendExpr(const SCEV *Op, Type *Ty);
600     const SCEV *getSignExtendExpr(const SCEV *Op, Type *Ty);
601     const SCEV *getAnyExtendExpr(const SCEV *Op, Type *Ty);
602     const SCEV *getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
603                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
604     const SCEV *getAddExpr(const SCEV *LHS, const SCEV *RHS,
605                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
606       SmallVector<const SCEV *, 2> Ops;
607       Ops.push_back(LHS);
608       Ops.push_back(RHS);
609       return getAddExpr(Ops, Flags);
610     }
611     const SCEV *getAddExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
612                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
613       SmallVector<const SCEV *, 3> Ops;
614       Ops.push_back(Op0);
615       Ops.push_back(Op1);
616       Ops.push_back(Op2);
617       return getAddExpr(Ops, Flags);
618     }
619     const SCEV *getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
620                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
621     const SCEV *getMulExpr(const SCEV *LHS, const SCEV *RHS,
622                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap)
623     {
624       SmallVector<const SCEV *, 2> Ops;
625       Ops.push_back(LHS);
626       Ops.push_back(RHS);
627       return getMulExpr(Ops, Flags);
628     }
629     const SCEV *getMulExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
630                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
631       SmallVector<const SCEV *, 3> Ops;
632       Ops.push_back(Op0);
633       Ops.push_back(Op1);
634       Ops.push_back(Op2);
635       return getMulExpr(Ops, Flags);
636     }
637     const SCEV *getUDivExpr(const SCEV *LHS, const SCEV *RHS);
638     const SCEV *getUDivExactExpr(const SCEV *LHS, const SCEV *RHS);
639     const SCEV *getAddRecExpr(const SCEV *Start, const SCEV *Step,
640                               const Loop *L, SCEV::NoWrapFlags Flags);
641     const SCEV *getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
642                               const Loop *L, SCEV::NoWrapFlags Flags);
643     const SCEV *getAddRecExpr(const SmallVectorImpl<const SCEV *> &Operands,
644                               const Loop *L, SCEV::NoWrapFlags Flags) {
645       SmallVector<const SCEV *, 4> NewOp(Operands.begin(), Operands.end());
646       return getAddRecExpr(NewOp, L, Flags);
647     }
648     const SCEV *getSMaxExpr(const SCEV *LHS, const SCEV *RHS);
649     const SCEV *getSMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
650     const SCEV *getUMaxExpr(const SCEV *LHS, const SCEV *RHS);
651     const SCEV *getUMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
652     const SCEV *getSMinExpr(const SCEV *LHS, const SCEV *RHS);
653     const SCEV *getUMinExpr(const SCEV *LHS, const SCEV *RHS);
654     const SCEV *getUnknown(Value *V);
655     const SCEV *getCouldNotCompute();
656
657     /// getSizeOfExpr - Return an expression for sizeof AllocTy that is type
658     /// IntTy
659     ///
660     const SCEV *getSizeOfExpr(Type *IntTy, Type *AllocTy);
661
662     /// getOffsetOfExpr - Return an expression for offsetof on the given field
663     /// with type IntTy
664     ///
665     const SCEV *getOffsetOfExpr(Type *IntTy, StructType *STy, unsigned FieldNo);
666
667     /// getNegativeSCEV - Return the SCEV object corresponding to -V.
668     ///
669     const SCEV *getNegativeSCEV(const SCEV *V);
670
671     /// getNotSCEV - Return the SCEV object corresponding to ~V.
672     ///
673     const SCEV *getNotSCEV(const SCEV *V);
674
675     /// getMinusSCEV - Return LHS-RHS.  Minus is represented in SCEV as A+B*-1.
676     const SCEV *getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
677                              SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
678
679     /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
680     /// of the input value to the specified type.  If the type must be
681     /// extended, it is zero extended.
682     const SCEV *getTruncateOrZeroExtend(const SCEV *V, Type *Ty);
683
684     /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
685     /// of the input value to the specified type.  If the type must be
686     /// extended, it is sign extended.
687     const SCEV *getTruncateOrSignExtend(const SCEV *V, Type *Ty);
688
689     /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of
690     /// the input value to the specified type.  If the type must be extended,
691     /// it is zero extended.  The conversion must not be narrowing.
692     const SCEV *getNoopOrZeroExtend(const SCEV *V, Type *Ty);
693
694     /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of
695     /// the input value to the specified type.  If the type must be extended,
696     /// it is sign extended.  The conversion must not be narrowing.
697     const SCEV *getNoopOrSignExtend(const SCEV *V, Type *Ty);
698
699     /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
700     /// the input value to the specified type. If the type must be extended,
701     /// it is extended with unspecified bits. The conversion must not be
702     /// narrowing.
703     const SCEV *getNoopOrAnyExtend(const SCEV *V, Type *Ty);
704
705     /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
706     /// input value to the specified type.  The conversion must not be
707     /// widening.
708     const SCEV *getTruncateOrNoop(const SCEV *V, Type *Ty);
709
710     /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
711     /// the types using zero-extension, and then perform a umax operation
712     /// with them.
713     const SCEV *getUMaxFromMismatchedTypes(const SCEV *LHS,
714                                            const SCEV *RHS);
715
716     /// getUMinFromMismatchedTypes - Promote the operands to the wider of
717     /// the types using zero-extension, and then perform a umin operation
718     /// with them.
719     const SCEV *getUMinFromMismatchedTypes(const SCEV *LHS,
720                                            const SCEV *RHS);
721
722     /// getPointerBase - Transitively follow the chain of pointer-type operands
723     /// until reaching a SCEV that does not have a single pointer operand. This
724     /// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
725     /// but corner cases do exist.
726     const SCEV *getPointerBase(const SCEV *V);
727
728     /// getSCEVAtScope - Return a SCEV expression for the specified value
729     /// at the specified scope in the program.  The L value specifies a loop
730     /// nest to evaluate the expression at, where null is the top-level or a
731     /// specified loop is immediately inside of the loop.
732     ///
733     /// This method can be used to compute the exit value for a variable defined
734     /// in a loop by querying what the value will hold in the parent loop.
735     ///
736     /// In the case that a relevant loop exit value cannot be computed, the
737     /// original value V is returned.
738     const SCEV *getSCEVAtScope(const SCEV *S, const Loop *L);
739
740     /// getSCEVAtScope - This is a convenience function which does
741     /// getSCEVAtScope(getSCEV(V), L).
742     const SCEV *getSCEVAtScope(Value *V, const Loop *L);
743
744     /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
745     /// by a conditional between LHS and RHS.  This is used to help avoid max
746     /// expressions in loop trip counts, and to eliminate casts.
747     bool isLoopEntryGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
748                                   const SCEV *LHS, const SCEV *RHS);
749
750     /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
751     /// protected by a conditional between LHS and RHS.  This is used to
752     /// to eliminate casts.
753     bool isLoopBackedgeGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
754                                      const SCEV *LHS, const SCEV *RHS);
755
756     /// getSmallConstantTripCount - Returns the maximum trip count of this loop
757     /// as a normal unsigned value. Returns 0 if the trip count is unknown or
758     /// not constant. This "trip count" assumes that control exits via
759     /// ExitingBlock. More precisely, it is the number of times that control may
760     /// reach ExitingBlock before taking the branch. For loops with multiple
761     /// exits, it may not be the number times that the loop header executes if
762     /// the loop exits prematurely via another branch.
763     unsigned getSmallConstantTripCount(Loop *L, BasicBlock *ExitingBlock);
764
765     /// getSmallConstantTripMultiple - Returns the largest constant divisor of
766     /// the trip count of this loop as a normal unsigned value, if
767     /// possible. This means that the actual trip count is always a multiple of
768     /// the returned value (don't forget the trip count could very well be zero
769     /// as well!). As explained in the comments for getSmallConstantTripCount,
770     /// this assumes that control exits the loop via ExitingBlock.
771     unsigned getSmallConstantTripMultiple(Loop *L, BasicBlock *ExitingBlock);
772
773     // getExitCount - Get the expression for the number of loop iterations for
774     // which this loop is guaranteed not to exit via ExitingBlock. Otherwise
775     // return SCEVCouldNotCompute.
776     const SCEV *getExitCount(Loop *L, BasicBlock *ExitingBlock);
777
778     /// getBackedgeTakenCount - If the specified loop has a predictable
779     /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
780     /// object. The backedge-taken count is the number of times the loop header
781     /// will be branched to from within the loop. This is one less than the
782     /// trip count of the loop, since it doesn't count the first iteration,
783     /// when the header is branched to from outside the loop.
784     ///
785     /// Note that it is not valid to call this method on a loop without a
786     /// loop-invariant backedge-taken count (see
787     /// hasLoopInvariantBackedgeTakenCount).
788     ///
789     const SCEV *getBackedgeTakenCount(const Loop *L);
790
791     /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
792     /// return the least SCEV value that is known never to be less than the
793     /// actual backedge taken count.
794     const SCEV *getMaxBackedgeTakenCount(const Loop *L);
795
796     /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop
797     /// has an analyzable loop-invariant backedge-taken count.
798     bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
799
800     /// forgetLoop - This method should be called by the client when it has
801     /// changed a loop in a way that may effect ScalarEvolution's ability to
802     /// compute a trip count, or if the loop is deleted.  This call is
803     /// potentially expensive for large loop bodies.
804     void forgetLoop(const Loop *L);
805
806     /// forgetValue - This method should be called by the client when it has
807     /// changed a value in a way that may effect its value, or which may
808     /// disconnect it from a def-use chain linking it to a loop.
809     void forgetValue(Value *V);
810
811     /// \brief Called when the client has changed the disposition of values in
812     /// this loop.
813     ///
814     /// We don't have a way to invalidate per-loop dispositions. Clear and
815     /// recompute is simpler.
816     void forgetLoopDispositions(const Loop *L) { LoopDispositions.clear(); }
817
818     /// GetMinTrailingZeros - Determine the minimum number of zero bits that S
819     /// is guaranteed to end in (at every loop iteration).  It is, at the same
820     /// time, the minimum number of times S is divisible by 2.  For example,
821     /// given {4,+,8} it returns 2.  If S is guaranteed to be 0, it returns the
822     /// bitwidth of S.
823     uint32_t GetMinTrailingZeros(const SCEV *S);
824
825     /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
826     ///
827     ConstantRange getUnsignedRange(const SCEV *S);
828
829     /// getSignedRange - Determine the signed range for a particular SCEV.
830     ///
831     ConstantRange getSignedRange(const SCEV *S);
832
833     /// isKnownNegative - Test if the given expression is known to be negative.
834     ///
835     bool isKnownNegative(const SCEV *S);
836
837     /// isKnownPositive - Test if the given expression is known to be positive.
838     ///
839     bool isKnownPositive(const SCEV *S);
840
841     /// isKnownNonNegative - Test if the given expression is known to be
842     /// non-negative.
843     ///
844     bool isKnownNonNegative(const SCEV *S);
845
846     /// isKnownNonPositive - Test if the given expression is known to be
847     /// non-positive.
848     ///
849     bool isKnownNonPositive(const SCEV *S);
850
851     /// isKnownNonZero - Test if the given expression is known to be
852     /// non-zero.
853     ///
854     bool isKnownNonZero(const SCEV *S);
855
856     /// isKnownPredicate - Test if the given expression is known to satisfy
857     /// the condition described by Pred, LHS, and RHS.
858     ///
859     bool isKnownPredicate(ICmpInst::Predicate Pred,
860                           const SCEV *LHS, const SCEV *RHS);
861
862     /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
863     /// predicate Pred. Return true iff any changes were made. If the
864     /// operands are provably equal or unequal, LHS and RHS are set to
865     /// the same value and Pred is set to either ICMP_EQ or ICMP_NE.
866     ///
867     bool SimplifyICmpOperands(ICmpInst::Predicate &Pred,
868                               const SCEV *&LHS,
869                               const SCEV *&RHS,
870                               unsigned Depth = 0);
871
872     /// getLoopDisposition - Return the "disposition" of the given SCEV with
873     /// respect to the given loop.
874     LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L);
875
876     /// isLoopInvariant - Return true if the value of the given SCEV is
877     /// unchanging in the specified loop.
878     bool isLoopInvariant(const SCEV *S, const Loop *L);
879
880     /// hasComputableLoopEvolution - Return true if the given SCEV changes value
881     /// in a known way in the specified loop.  This property being true implies
882     /// that the value is variant in the loop AND that we can emit an expression
883     /// to compute the value of the expression at any particular loop iteration.
884     bool hasComputableLoopEvolution(const SCEV *S, const Loop *L);
885
886     /// getLoopDisposition - Return the "disposition" of the given SCEV with
887     /// respect to the given block.
888     BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB);
889
890     /// dominates - Return true if elements that makes up the given SCEV
891     /// dominate the specified basic block.
892     bool dominates(const SCEV *S, const BasicBlock *BB);
893
894     /// properlyDominates - Return true if elements that makes up the given SCEV
895     /// properly dominate the specified basic block.
896     bool properlyDominates(const SCEV *S, const BasicBlock *BB);
897
898     /// hasOperand - Test whether the given SCEV has Op as a direct or
899     /// indirect operand.
900     bool hasOperand(const SCEV *S, const SCEV *Op) const;
901
902     /// Return the size of an element read or written by Inst.
903     const SCEV *getElementSize(Instruction *Inst);
904
905     /// Compute the array dimensions Sizes from the set of Terms extracted from
906     /// the memory access function of this SCEVAddRecExpr.
907     void findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
908                              SmallVectorImpl<const SCEV *> &Sizes,
909                              const SCEV *ElementSize) const;
910
911     bool runOnFunction(Function &F) override;
912     void releaseMemory() override;
913     void getAnalysisUsage(AnalysisUsage &AU) const override;
914     void print(raw_ostream &OS, const Module* = nullptr) const override;
915     void verifyAnalysis() const override;
916
917   private:
918     /// Compute the backedge taken count knowing the interval difference, the
919     /// stride and presence of the equality in the comparison.
920     const SCEV *computeBECount(const SCEV *Delta, const SCEV *Stride,
921                                bool Equality);
922
923     /// Verify if an linear IV with positive stride can overflow when in a
924     /// less-than comparison, knowing the invariant term of the comparison,
925     /// the stride and the knowledge of NSW/NUW flags on the recurrence.
926     bool doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
927                             bool IsSigned, bool NoWrap);
928
929     /// Verify if an linear IV with negative stride can overflow when in a
930     /// greater-than comparison, knowing the invariant term of the comparison,
931     /// the stride and the knowledge of NSW/NUW flags on the recurrence.
932     bool doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
933                             bool IsSigned, bool NoWrap);
934
935   private:
936     FoldingSet<SCEV> UniqueSCEVs;
937     BumpPtrAllocator SCEVAllocator;
938
939     /// FirstUnknown - The head of a linked list of all SCEVUnknown
940     /// values that have been allocated. This is used by releaseMemory
941     /// to locate them all and call their destructors.
942     SCEVUnknown *FirstUnknown;
943   };
944 }
945
946 #endif