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