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