[IndVars] Make loop varying predicates loop invariant.
[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/ValueHandle.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Support/Allocator.h"
33 #include "llvm/Support/DataTypes.h"
34 #include <map>
35
36 namespace llvm {
37   class APInt;
38   class AssumptionCache;
39   class Constant;
40   class ConstantInt;
41   class DominatorTree;
42   class Type;
43   class ScalarEvolution;
44   class DataLayout;
45   class TargetLibraryInfo;
46   class LLVMContext;
47   class Loop;
48   class LoopInfo;
49   class Operator;
50   class SCEVUnknown;
51   class SCEVAddRecExpr;
52   class SCEV;
53   template<> struct FoldingSetTrait<SCEV>;
54
55   /// SCEV - This class represents an analyzed expression in the program.  These
56   /// are opaque objects that the client is not allowed to do much with
57   /// directly.
58   ///
59   class SCEV : public FoldingSetNode {
60     friend struct FoldingSetTrait<SCEV>;
61
62     /// FastID - A reference to an Interned FoldingSetNodeID for this node.
63     /// The 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     /// SubclassData - This field is initialized to zero and may be used in
71     /// subclasses to store 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     /// getType - Return the LLVM type of this SCEV expression.
109     ///
110     Type *getType() const;
111
112     /// isZero - Return true if the expression is a constant zero.
113     ///
114     bool isZero() const;
115
116     /// isOne - Return true if the expression is a constant one.
117     ///
118     bool isOne() const;
119
120     /// isAllOnesValue - Return true if the expression is a constant
121     /// all-ones value.
122     ///
123     bool isAllOnesValue() const;
124
125     /// isNonConstantNegative - Return true if the specified scev is negated,
126     /// but not a constant.
127     bool isNonConstantNegative() const;
128
129     /// print - Print out the internal representation of this scalar to the
130     /// specified stream.  This should really only be used for debugging
131     /// purposes.
132     void print(raw_ostream &OS) const;
133
134 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
135     /// dump - This method is used for debugging.
136     ///
137     void dump() const;
138 #endif
139   };
140
141   // Specialize FoldingSetTrait for SCEV to avoid needing to compute
142   // temporary FoldingSetNodeID values.
143   template<> struct FoldingSetTrait<SCEV> : DefaultFoldingSetTrait<SCEV> {
144     static void Profile(const SCEV &X, FoldingSetNodeID& ID) {
145       ID = X.FastID;
146     }
147     static bool Equals(const SCEV &X, const FoldingSetNodeID &ID,
148                        unsigned IDHash, FoldingSetNodeID &TempID) {
149       return ID == X.FastID;
150     }
151     static unsigned ComputeHash(const SCEV &X, FoldingSetNodeID &TempID) {
152       return X.FastID.ComputeHash();
153     }
154   };
155
156   inline raw_ostream &operator<<(raw_ostream &OS, const SCEV &S) {
157     S.print(OS);
158     return OS;
159   }
160
161   /// SCEVCouldNotCompute - An object of this class is returned by queries that
162   /// could not be answered.  For example, if you ask for the number of
163   /// iterations of a linked-list traversal loop, you will get one of these.
164   /// None of the standard SCEV operations are valid on this class, it is just a
165   /// marker.
166   struct SCEVCouldNotCompute : public SCEV {
167     SCEVCouldNotCompute();
168
169     /// Methods for support type inquiry through isa, cast, and dyn_cast:
170     static bool classof(const SCEV *S);
171   };
172
173   /// ScalarEvolution - This class is the main scalar evolution driver.  Because
174   /// client code (intentionally) can't do much with the SCEV objects directly,
175   /// they must ask this class for services.
176   ///
177   class ScalarEvolution : public FunctionPass {
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 : 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     /// The tracker for @llvm.assume intrinsics in this function.
230     AssumptionCache *AC;
231
232     /// LI - The loop information for the function we are currently analyzing.
233     ///
234     LoopInfo *LI;
235
236     /// TLI - The target library information for the target we are targeting.
237     ///
238     TargetLibraryInfo *TLI;
239
240     /// DT - The dominator tree.
241     ///
242     DominatorTree *DT;
243
244     /// CouldNotCompute - This SCEV is used to represent unknown trip
245     /// counts and things.
246     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 false iff given SCEV contains a SCEVUnknown with NULL value-
570     /// pointer.
571     bool checkValidity(const SCEV *S) const;
572
573     /// Return true if `ExtendOpTy`({`Start`,+,`Step`}) can be proved to be
574     /// equal to {`ExtendOpTy`(`Start`),+,`ExtendOpTy`(`Step`)}.  This is
575     /// equivalent to proving no signed (resp. unsigned) wrap in
576     /// {`Start`,+,`Step`} if `ExtendOpTy` is `SCEVSignExtendExpr`
577     /// (resp. `SCEVZeroExtendExpr`).
578     ///
579     template<typename ExtendOpTy>
580     bool proveNoWrapByVaryingStart(const SCEV *Start, const SCEV *Step,
581                                    const Loop *L);
582
583     bool isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
584                                   ICmpInst::Predicate Pred, bool &Increasing);
585
586     /// Return true if, for all loop invariant X, the predicate "LHS `Pred` X"
587     /// is monotonically increasing or decreasing.  In the former case set
588     /// `Increasing` to true and in the latter case set `Increasing` to false.
589     ///
590     /// A predicate is said to be monotonically increasing if may go from being
591     /// false to being true as the loop iterates, but never the other way
592     /// around.  A predicate is said to be monotonically decreasing if may go
593     /// from being true to being false as the loop iterates, but never the other
594     /// way around.
595     bool isMonotonicPredicate(const SCEVAddRecExpr *LHS,
596                               ICmpInst::Predicate Pred, bool &Increasing);
597
598   public:
599     static char ID; // Pass identification, replacement for typeid
600     ScalarEvolution();
601
602     LLVMContext &getContext() const { return F->getContext(); }
603
604     /// isSCEVable - Test if values of the given type are analyzable within
605     /// the SCEV framework. This primarily includes integer types, and it
606     /// can optionally include pointer types if the ScalarEvolution class
607     /// has access to target-specific information.
608     bool isSCEVable(Type *Ty) const;
609
610     /// getTypeSizeInBits - Return the size in bits of the specified type,
611     /// for which isSCEVable must return true.
612     uint64_t getTypeSizeInBits(Type *Ty) const;
613
614     /// getEffectiveSCEVType - Return a type with the same bitwidth as
615     /// the given type and which represents how SCEV will treat the given
616     /// type, for which isSCEVable must return true. For pointer types,
617     /// this is the pointer-sized integer type.
618     Type *getEffectiveSCEVType(Type *Ty) const;
619
620     /// getSCEV - Return a SCEV expression for the full generality of the
621     /// specified expression.
622     const SCEV *getSCEV(Value *V);
623
624     const SCEV *getConstant(ConstantInt *V);
625     const SCEV *getConstant(const APInt& Val);
626     const SCEV *getConstant(Type *Ty, uint64_t V, bool isSigned = false);
627     const SCEV *getTruncateExpr(const SCEV *Op, Type *Ty);
628     const SCEV *getZeroExtendExpr(const SCEV *Op, Type *Ty);
629     const SCEV *getSignExtendExpr(const SCEV *Op, Type *Ty);
630     const SCEV *getAnyExtendExpr(const SCEV *Op, Type *Ty);
631     const SCEV *getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
632                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
633     const SCEV *getAddExpr(const SCEV *LHS, const SCEV *RHS,
634                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
635       SmallVector<const SCEV *, 2> Ops;
636       Ops.push_back(LHS);
637       Ops.push_back(RHS);
638       return getAddExpr(Ops, Flags);
639     }
640     const SCEV *getAddExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
641                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
642       SmallVector<const SCEV *, 3> Ops;
643       Ops.push_back(Op0);
644       Ops.push_back(Op1);
645       Ops.push_back(Op2);
646       return getAddExpr(Ops, Flags);
647     }
648     const SCEV *getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
649                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
650     const SCEV *getMulExpr(const SCEV *LHS, const SCEV *RHS,
651                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap)
652     {
653       SmallVector<const SCEV *, 2> Ops;
654       Ops.push_back(LHS);
655       Ops.push_back(RHS);
656       return getMulExpr(Ops, Flags);
657     }
658     const SCEV *getMulExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
659                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
660       SmallVector<const SCEV *, 3> Ops;
661       Ops.push_back(Op0);
662       Ops.push_back(Op1);
663       Ops.push_back(Op2);
664       return getMulExpr(Ops, Flags);
665     }
666     const SCEV *getUDivExpr(const SCEV *LHS, const SCEV *RHS);
667     const SCEV *getUDivExactExpr(const SCEV *LHS, const SCEV *RHS);
668     const SCEV *getAddRecExpr(const SCEV *Start, const SCEV *Step,
669                               const Loop *L, SCEV::NoWrapFlags Flags);
670     const SCEV *getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
671                               const Loop *L, SCEV::NoWrapFlags Flags);
672     const SCEV *getAddRecExpr(const SmallVectorImpl<const SCEV *> &Operands,
673                               const Loop *L, SCEV::NoWrapFlags Flags) {
674       SmallVector<const SCEV *, 4> NewOp(Operands.begin(), Operands.end());
675       return getAddRecExpr(NewOp, L, Flags);
676     }
677     /// \brief Returns an expression for a GEP
678     ///
679     /// \p PointeeType The type used as the basis for the pointer arithmetics
680     /// \p BaseExpr The expression for the pointer operand.
681     /// \p IndexExprs The expressions for the indices.
682     /// \p InBounds Whether the GEP is in bounds.
683     const SCEV *getGEPExpr(Type *PointeeType, const SCEV *BaseExpr,
684                            const SmallVectorImpl<const SCEV *> &IndexExprs,
685                            bool InBounds = false);
686     const SCEV *getSMaxExpr(const SCEV *LHS, const SCEV *RHS);
687     const SCEV *getSMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
688     const SCEV *getUMaxExpr(const SCEV *LHS, const SCEV *RHS);
689     const SCEV *getUMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
690     const SCEV *getSMinExpr(const SCEV *LHS, const SCEV *RHS);
691     const SCEV *getUMinExpr(const SCEV *LHS, const SCEV *RHS);
692     const SCEV *getUnknown(Value *V);
693     const SCEV *getCouldNotCompute();
694
695     /// getSizeOfExpr - Return an expression for sizeof AllocTy that is type
696     /// IntTy
697     ///
698     const SCEV *getSizeOfExpr(Type *IntTy, Type *AllocTy);
699
700     /// getOffsetOfExpr - Return an expression for offsetof on the given field
701     /// with type IntTy
702     ///
703     const SCEV *getOffsetOfExpr(Type *IntTy, StructType *STy, unsigned FieldNo);
704
705     /// getNegativeSCEV - Return the SCEV object corresponding to -V.
706     ///
707     const SCEV *getNegativeSCEV(const SCEV *V);
708
709     /// getNotSCEV - Return the SCEV object corresponding to ~V.
710     ///
711     const SCEV *getNotSCEV(const SCEV *V);
712
713     /// getMinusSCEV - Return LHS-RHS.  Minus is represented in SCEV as A+B*-1.
714     const SCEV *getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
715                              SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
716
717     /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
718     /// of the input value to the specified type.  If the type must be
719     /// extended, it is zero extended.
720     const SCEV *getTruncateOrZeroExtend(const SCEV *V, Type *Ty);
721
722     /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
723     /// of the input value to the specified type.  If the type must be
724     /// extended, it is sign extended.
725     const SCEV *getTruncateOrSignExtend(const SCEV *V, Type *Ty);
726
727     /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of
728     /// the input value to the specified type.  If the type must be extended,
729     /// it is zero extended.  The conversion must not be narrowing.
730     const SCEV *getNoopOrZeroExtend(const SCEV *V, Type *Ty);
731
732     /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of
733     /// the input value to the specified type.  If the type must be extended,
734     /// it is sign extended.  The conversion must not be narrowing.
735     const SCEV *getNoopOrSignExtend(const SCEV *V, Type *Ty);
736
737     /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
738     /// the input value to the specified type. If the type must be extended,
739     /// it is extended with unspecified bits. The conversion must not be
740     /// narrowing.
741     const SCEV *getNoopOrAnyExtend(const SCEV *V, Type *Ty);
742
743     /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
744     /// input value to the specified type.  The conversion must not be
745     /// widening.
746     const SCEV *getTruncateOrNoop(const SCEV *V, Type *Ty);
747
748     /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
749     /// the types using zero-extension, and then perform a umax operation
750     /// with them.
751     const SCEV *getUMaxFromMismatchedTypes(const SCEV *LHS,
752                                            const SCEV *RHS);
753
754     /// getUMinFromMismatchedTypes - Promote the operands to the wider of
755     /// the types using zero-extension, and then perform a umin operation
756     /// with them.
757     const SCEV *getUMinFromMismatchedTypes(const SCEV *LHS,
758                                            const SCEV *RHS);
759
760     /// getPointerBase - Transitively follow the chain of pointer-type operands
761     /// until reaching a SCEV that does not have a single pointer operand. This
762     /// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
763     /// but corner cases do exist.
764     const SCEV *getPointerBase(const SCEV *V);
765
766     /// getSCEVAtScope - Return a SCEV expression for the specified value
767     /// at the specified scope in the program.  The L value specifies a loop
768     /// nest to evaluate the expression at, where null is the top-level or a
769     /// specified loop is immediately inside of the loop.
770     ///
771     /// This method can be used to compute the exit value for a variable defined
772     /// in a loop by querying what the value will hold in the parent loop.
773     ///
774     /// In the case that a relevant loop exit value cannot be computed, the
775     /// original value V is returned.
776     const SCEV *getSCEVAtScope(const SCEV *S, const Loop *L);
777
778     /// getSCEVAtScope - This is a convenience function which does
779     /// getSCEVAtScope(getSCEV(V), L).
780     const SCEV *getSCEVAtScope(Value *V, const Loop *L);
781
782     /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
783     /// by a conditional between LHS and RHS.  This is used to help avoid max
784     /// expressions in loop trip counts, and to eliminate casts.
785     bool isLoopEntryGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
786                                   const SCEV *LHS, const SCEV *RHS);
787
788     /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
789     /// protected by a conditional between LHS and RHS.  This is used to
790     /// to eliminate casts.
791     bool isLoopBackedgeGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
792                                      const SCEV *LHS, const SCEV *RHS);
793
794     /// \brief Returns the maximum trip count of the loop if it is a single-exit
795     /// loop and we can compute a small maximum for that loop.
796     ///
797     /// Implemented in terms of the \c getSmallConstantTripCount overload with
798     /// the single exiting block passed to it. See that routine for details.
799     unsigned getSmallConstantTripCount(Loop *L);
800
801     /// getSmallConstantTripCount - Returns the maximum trip count of this loop
802     /// as a normal unsigned value. Returns 0 if the trip count is unknown or
803     /// not constant. This "trip count" assumes that control exits via
804     /// ExitingBlock. More precisely, it is the number of times that control may
805     /// reach ExitingBlock before taking the branch. For loops with multiple
806     /// exits, it may not be the number times that the loop header executes if
807     /// the loop exits prematurely via another branch.
808     unsigned getSmallConstantTripCount(Loop *L, BasicBlock *ExitingBlock);
809
810     /// \brief Returns the largest constant divisor of the trip count of the
811     /// loop if it is a single-exit loop and we can compute a small maximum for
812     /// that loop.
813     ///
814     /// Implemented in terms of the \c getSmallConstantTripMultiple overload with
815     /// the single exiting block passed to it. See that routine for details.
816     unsigned getSmallConstantTripMultiple(Loop *L);
817
818     /// getSmallConstantTripMultiple - Returns the largest constant divisor of
819     /// the trip count of this loop as a normal unsigned value, if
820     /// possible. This means that the actual trip count is always a multiple of
821     /// the returned value (don't forget the trip count could very well be zero
822     /// as well!). As explained in the comments for getSmallConstantTripCount,
823     /// this assumes that control exits the loop via ExitingBlock.
824     unsigned getSmallConstantTripMultiple(Loop *L, BasicBlock *ExitingBlock);
825
826     // getExitCount - Get the expression for the number of loop iterations for
827     // which this loop is guaranteed not to exit via ExitingBlock. Otherwise
828     // return SCEVCouldNotCompute.
829     const SCEV *getExitCount(Loop *L, BasicBlock *ExitingBlock);
830
831     /// getBackedgeTakenCount - If the specified loop has a predictable
832     /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
833     /// object. The backedge-taken count is the number of times the loop header
834     /// will be branched to from within the loop. This is one less than the
835     /// trip count of the loop, since it doesn't count the first iteration,
836     /// when the header is branched to from outside the loop.
837     ///
838     /// Note that it is not valid to call this method on a loop without a
839     /// loop-invariant backedge-taken count (see
840     /// hasLoopInvariantBackedgeTakenCount).
841     ///
842     const SCEV *getBackedgeTakenCount(const Loop *L);
843
844     /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
845     /// return the least SCEV value that is known never to be less than the
846     /// actual backedge taken count.
847     const SCEV *getMaxBackedgeTakenCount(const Loop *L);
848
849     /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop
850     /// has an analyzable loop-invariant backedge-taken count.
851     bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
852
853     /// forgetLoop - This method should be called by the client when it has
854     /// changed a loop in a way that may effect ScalarEvolution's ability to
855     /// compute a trip count, or if the loop is deleted.  This call is
856     /// potentially expensive for large loop bodies.
857     void forgetLoop(const Loop *L);
858
859     /// forgetValue - This method should be called by the client when it has
860     /// changed a value in a way that may effect its value, or which may
861     /// disconnect it from a def-use chain linking it to a loop.
862     void forgetValue(Value *V);
863
864     /// \brief Called when the client has changed the disposition of values in
865     /// this loop.
866     ///
867     /// We don't have a way to invalidate per-loop dispositions. Clear and
868     /// recompute is simpler.
869     void forgetLoopDispositions(const Loop *L) { LoopDispositions.clear(); }
870
871     /// GetMinTrailingZeros - Determine the minimum number of zero bits that S
872     /// is guaranteed to end in (at every loop iteration).  It is, at the same
873     /// time, the minimum number of times S is divisible by 2.  For example,
874     /// given {4,+,8} it returns 2.  If S is guaranteed to be 0, it returns the
875     /// bitwidth of S.
876     uint32_t GetMinTrailingZeros(const SCEV *S);
877
878     /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
879     ///
880     ConstantRange getUnsignedRange(const SCEV *S) {
881       return getRange(S, HINT_RANGE_UNSIGNED);
882     }
883
884     /// getSignedRange - Determine the signed range for a particular SCEV.
885     ///
886     ConstantRange getSignedRange(const SCEV *S) {
887       return getRange(S, HINT_RANGE_SIGNED);
888     }
889
890     /// isKnownNegative - Test if the given expression is known to be negative.
891     ///
892     bool isKnownNegative(const SCEV *S);
893
894     /// isKnownPositive - Test if the given expression is known to be positive.
895     ///
896     bool isKnownPositive(const SCEV *S);
897
898     /// isKnownNonNegative - Test if the given expression is known to be
899     /// non-negative.
900     ///
901     bool isKnownNonNegative(const SCEV *S);
902
903     /// isKnownNonPositive - Test if the given expression is known to be
904     /// non-positive.
905     ///
906     bool isKnownNonPositive(const SCEV *S);
907
908     /// isKnownNonZero - Test if the given expression is known to be
909     /// non-zero.
910     ///
911     bool isKnownNonZero(const SCEV *S);
912
913     /// isKnownPredicate - Test if the given expression is known to satisfy
914     /// the condition described by Pred, LHS, and RHS.
915     ///
916     bool isKnownPredicate(ICmpInst::Predicate Pred,
917                           const SCEV *LHS, const SCEV *RHS);
918
919     /// Return true if the result of the predicate LHS `Pred` RHS is loop
920     /// invariant with respect to L.  Set InvariantPred, InvariantLHS and
921     /// InvariantLHS so that InvariantLHS `InvariantPred` InvariantRHS is the
922     /// loop invariant form of LHS `Pred` RHS.
923     bool isLoopInvariantPredicate(ICmpInst::Predicate Pred, const SCEV *LHS,
924                                   const SCEV *RHS, const Loop *L,
925                                   ICmpInst::Predicate &InvariantPred,
926                                   const SCEV *&InvariantLHS,
927                                   const SCEV *&InvariantRHS);
928
929     /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
930     /// predicate Pred. Return true iff any changes were made. If the
931     /// operands are provably equal or unequal, LHS and RHS are set to
932     /// the same value and Pred is set to either ICMP_EQ or ICMP_NE.
933     ///
934     bool SimplifyICmpOperands(ICmpInst::Predicate &Pred,
935                               const SCEV *&LHS,
936                               const SCEV *&RHS,
937                               unsigned Depth = 0);
938
939     /// getLoopDisposition - Return the "disposition" of the given SCEV with
940     /// respect to the given loop.
941     LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L);
942
943     /// isLoopInvariant - Return true if the value of the given SCEV is
944     /// unchanging in the specified loop.
945     bool isLoopInvariant(const SCEV *S, const Loop *L);
946
947     /// hasComputableLoopEvolution - Return true if the given SCEV changes value
948     /// in a known way in the specified loop.  This property being true implies
949     /// that the value is variant in the loop AND that we can emit an expression
950     /// to compute the value of the expression at any particular loop iteration.
951     bool hasComputableLoopEvolution(const SCEV *S, const Loop *L);
952
953     /// getLoopDisposition - Return the "disposition" of the given SCEV with
954     /// respect to the given block.
955     BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB);
956
957     /// dominates - Return true if elements that makes up the given SCEV
958     /// dominate the specified basic block.
959     bool dominates(const SCEV *S, const BasicBlock *BB);
960
961     /// properlyDominates - Return true if elements that makes up the given SCEV
962     /// properly dominate the specified basic block.
963     bool properlyDominates(const SCEV *S, const BasicBlock *BB);
964
965     /// hasOperand - Test whether the given SCEV has Op as a direct or
966     /// indirect operand.
967     bool hasOperand(const SCEV *S, const SCEV *Op) const;
968
969     /// Return the size of an element read or written by Inst.
970     const SCEV *getElementSize(Instruction *Inst);
971
972     /// Compute the array dimensions Sizes from the set of Terms extracted from
973     /// the memory access function of this SCEVAddRecExpr.
974     void findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
975                              SmallVectorImpl<const SCEV *> &Sizes,
976                              const SCEV *ElementSize) const;
977
978     bool runOnFunction(Function &F) override;
979     void releaseMemory() override;
980     void getAnalysisUsage(AnalysisUsage &AU) const override;
981     void print(raw_ostream &OS, const Module* = nullptr) const override;
982     void verifyAnalysis() const override;
983
984     /// Collect parametric terms occurring in step expressions.
985     void collectParametricTerms(const SCEV *Expr,
986                                 SmallVectorImpl<const SCEV *> &Terms);
987
988
989
990     /// Return in Subscripts the access functions for each dimension in Sizes.
991     void computeAccessFunctions(const SCEV *Expr,
992                                 SmallVectorImpl<const SCEV *> &Subscripts,
993                                 SmallVectorImpl<const SCEV *> &Sizes);
994
995     /// Split this SCEVAddRecExpr into two vectors of SCEVs representing the
996     /// subscripts and sizes of an array access.
997     ///
998     /// The delinearization is a 3 step process: the first two steps compute the
999     /// sizes of each subscript and the third step computes the access functions
1000     /// for the delinearized array:
1001     ///
1002     /// 1. Find the terms in the step functions
1003     /// 2. Compute the array size
1004     /// 3. Compute the access function: divide the SCEV by the array size
1005     ///    starting with the innermost dimensions found in step 2. The Quotient
1006     ///    is the SCEV to be divided in the next step of the recursion. The
1007     ///    Remainder is the subscript of the innermost dimension. Loop over all
1008     ///    array dimensions computed in step 2.
1009     ///
1010     /// To compute a uniform array size for several memory accesses to the same
1011     /// object, one can collect in step 1 all the step terms for all the memory
1012     /// accesses, and compute in step 2 a unique array shape. This guarantees
1013     /// that the array shape will be the same across all memory accesses.
1014     ///
1015     /// FIXME: We could derive the result of steps 1 and 2 from a description of
1016     /// the array shape given in metadata.
1017     ///
1018     /// Example:
1019     ///
1020     /// A[][n][m]
1021     ///
1022     /// for i
1023     ///   for j
1024     ///     for k
1025     ///       A[j+k][2i][5i] =
1026     ///
1027     /// The initial SCEV:
1028     ///
1029     /// A[{{{0,+,2*m+5}_i, +, n*m}_j, +, n*m}_k]
1030     ///
1031     /// 1. Find the different terms in the step functions:
1032     /// -> [2*m, 5, n*m, n*m]
1033     ///
1034     /// 2. Compute the array size: sort and unique them
1035     /// -> [n*m, 2*m, 5]
1036     /// find the GCD of all the terms = 1
1037     /// divide by the GCD and erase constant terms
1038     /// -> [n*m, 2*m]
1039     /// GCD = m
1040     /// divide by GCD -> [n, 2]
1041     /// remove constant terms
1042     /// -> [n]
1043     /// size of the array is A[unknown][n][m]
1044     ///
1045     /// 3. Compute the access function
1046     /// a. Divide {{{0,+,2*m+5}_i, +, n*m}_j, +, n*m}_k by the innermost size m
1047     /// Quotient: {{{0,+,2}_i, +, n}_j, +, n}_k
1048     /// Remainder: {{{0,+,5}_i, +, 0}_j, +, 0}_k
1049     /// The remainder is the subscript of the innermost array dimension: [5i].
1050     ///
1051     /// b. Divide Quotient: {{{0,+,2}_i, +, n}_j, +, n}_k by next outer size n
1052     /// Quotient: {{{0,+,0}_i, +, 1}_j, +, 1}_k
1053     /// Remainder: {{{0,+,2}_i, +, 0}_j, +, 0}_k
1054     /// The Remainder is the subscript of the next array dimension: [2i].
1055     ///
1056     /// The subscript of the outermost dimension is the Quotient: [j+k].
1057     ///
1058     /// Overall, we have: A[][n][m], and the access function: A[j+k][2i][5i].
1059     void delinearize(const SCEV *Expr,
1060                      SmallVectorImpl<const SCEV *> &Subscripts,
1061                      SmallVectorImpl<const SCEV *> &Sizes,
1062                      const SCEV *ElementSize);
1063
1064   private:
1065     /// Compute the backedge taken count knowing the interval difference, the
1066     /// stride and presence of the equality in the comparison.
1067     const SCEV *computeBECount(const SCEV *Delta, const SCEV *Stride,
1068                                bool Equality);
1069
1070     /// Verify if an linear IV with positive stride can overflow when in a
1071     /// less-than comparison, knowing the invariant term of the comparison,
1072     /// the stride and the knowledge of NSW/NUW flags on the recurrence.
1073     bool doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
1074                             bool IsSigned, bool NoWrap);
1075
1076     /// Verify if an linear IV with negative stride can overflow when in a
1077     /// greater-than comparison, knowing the invariant term of the comparison,
1078     /// the stride and the knowledge of NSW/NUW flags on the recurrence.
1079     bool doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
1080                             bool IsSigned, bool NoWrap);
1081
1082   private:
1083     FoldingSet<SCEV> UniqueSCEVs;
1084     BumpPtrAllocator SCEVAllocator;
1085
1086     /// FirstUnknown - The head of a linked list of all SCEVUnknown
1087     /// values that have been allocated. This is used by releaseMemory
1088     /// to locate them all and call their destructors.
1089     SCEVUnknown *FirstUnknown;
1090   };
1091 }
1092
1093 #endif