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