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