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