[PM/AA] Run clang-format over this code to establish a clean baseline
[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 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     /// 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 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     static char ID; // Pass identification, replacement for typeid
608     ScalarEvolution();
609
610     LLVMContext &getContext() const { return F->getContext(); }
611
612     /// isSCEVable - Test if values of the given type are analyzable within
613     /// the SCEV framework. This primarily includes integer types, and it
614     /// can optionally include pointer types if the ScalarEvolution class
615     /// has access to target-specific information.
616     bool isSCEVable(Type *Ty) const;
617
618     /// getTypeSizeInBits - Return the size in bits of the specified type,
619     /// for which isSCEVable must return true.
620     uint64_t getTypeSizeInBits(Type *Ty) const;
621
622     /// getEffectiveSCEVType - Return a type with the same bitwidth as
623     /// the given type and which represents how SCEV will treat the given
624     /// type, for which isSCEVable must return true. For pointer types,
625     /// this is the pointer-sized integer type.
626     Type *getEffectiveSCEVType(Type *Ty) const;
627
628     /// getSCEV - Return a SCEV expression for the full generality of the
629     /// specified expression.
630     const SCEV *getSCEV(Value *V);
631
632     const SCEV *getConstant(ConstantInt *V);
633     const SCEV *getConstant(const APInt& Val);
634     const SCEV *getConstant(Type *Ty, uint64_t V, bool isSigned = false);
635     const SCEV *getTruncateExpr(const SCEV *Op, Type *Ty);
636     const SCEV *getZeroExtendExpr(const SCEV *Op, Type *Ty);
637     const SCEV *getSignExtendExpr(const SCEV *Op, Type *Ty);
638     const SCEV *getAnyExtendExpr(const SCEV *Op, Type *Ty);
639     const SCEV *getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
640                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
641     const SCEV *getAddExpr(const SCEV *LHS, const SCEV *RHS,
642                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
643       SmallVector<const SCEV *, 2> Ops;
644       Ops.push_back(LHS);
645       Ops.push_back(RHS);
646       return getAddExpr(Ops, Flags);
647     }
648     const SCEV *getAddExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
649                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
650       SmallVector<const SCEV *, 3> Ops;
651       Ops.push_back(Op0);
652       Ops.push_back(Op1);
653       Ops.push_back(Op2);
654       return getAddExpr(Ops, Flags);
655     }
656     const SCEV *getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
657                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
658     const SCEV *getMulExpr(const SCEV *LHS, const SCEV *RHS,
659                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap)
660     {
661       SmallVector<const SCEV *, 2> Ops;
662       Ops.push_back(LHS);
663       Ops.push_back(RHS);
664       return getMulExpr(Ops, Flags);
665     }
666     const SCEV *getMulExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
667                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
668       SmallVector<const SCEV *, 3> Ops;
669       Ops.push_back(Op0);
670       Ops.push_back(Op1);
671       Ops.push_back(Op2);
672       return getMulExpr(Ops, Flags);
673     }
674     const SCEV *getUDivExpr(const SCEV *LHS, const SCEV *RHS);
675     const SCEV *getUDivExactExpr(const SCEV *LHS, const SCEV *RHS);
676     const SCEV *getAddRecExpr(const SCEV *Start, const SCEV *Step,
677                               const Loop *L, SCEV::NoWrapFlags Flags);
678     const SCEV *getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
679                               const Loop *L, SCEV::NoWrapFlags Flags);
680     const SCEV *getAddRecExpr(const SmallVectorImpl<const SCEV *> &Operands,
681                               const Loop *L, SCEV::NoWrapFlags Flags) {
682       SmallVector<const SCEV *, 4> NewOp(Operands.begin(), Operands.end());
683       return getAddRecExpr(NewOp, L, Flags);
684     }
685     /// \brief Returns an expression for a GEP
686     ///
687     /// \p PointeeType The type used as the basis for the pointer arithmetics
688     /// \p BaseExpr The expression for the pointer operand.
689     /// \p IndexExprs The expressions for the indices.
690     /// \p InBounds Whether the GEP is in bounds.
691     const SCEV *getGEPExpr(Type *PointeeType, const SCEV *BaseExpr,
692                            const SmallVectorImpl<const SCEV *> &IndexExprs,
693                            bool InBounds = false);
694     const SCEV *getSMaxExpr(const SCEV *LHS, const SCEV *RHS);
695     const SCEV *getSMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
696     const SCEV *getUMaxExpr(const SCEV *LHS, const SCEV *RHS);
697     const SCEV *getUMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
698     const SCEV *getSMinExpr(const SCEV *LHS, const SCEV *RHS);
699     const SCEV *getUMinExpr(const SCEV *LHS, const SCEV *RHS);
700     const SCEV *getUnknown(Value *V);
701     const SCEV *getCouldNotCompute();
702
703     /// getSizeOfExpr - Return an expression for sizeof AllocTy that is type
704     /// IntTy
705     ///
706     const SCEV *getSizeOfExpr(Type *IntTy, Type *AllocTy);
707
708     /// getOffsetOfExpr - Return an expression for offsetof on the given field
709     /// with type IntTy
710     ///
711     const SCEV *getOffsetOfExpr(Type *IntTy, StructType *STy, unsigned FieldNo);
712
713     /// getNegativeSCEV - Return the SCEV object corresponding to -V.
714     ///
715     const SCEV *getNegativeSCEV(const SCEV *V);
716
717     /// getNotSCEV - Return the SCEV object corresponding to ~V.
718     ///
719     const SCEV *getNotSCEV(const SCEV *V);
720
721     /// getMinusSCEV - Return LHS-RHS.  Minus is represented in SCEV as A+B*-1.
722     const SCEV *getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
723                              SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
724
725     /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
726     /// of the input value to the specified type.  If the type must be
727     /// extended, it is zero extended.
728     const SCEV *getTruncateOrZeroExtend(const SCEV *V, Type *Ty);
729
730     /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
731     /// of the input value to the specified type.  If the type must be
732     /// extended, it is sign extended.
733     const SCEV *getTruncateOrSignExtend(const SCEV *V, Type *Ty);
734
735     /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of
736     /// the input value to the specified type.  If the type must be extended,
737     /// it is zero extended.  The conversion must not be narrowing.
738     const SCEV *getNoopOrZeroExtend(const SCEV *V, Type *Ty);
739
740     /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of
741     /// the input value to the specified type.  If the type must be extended,
742     /// it is sign extended.  The conversion must not be narrowing.
743     const SCEV *getNoopOrSignExtend(const SCEV *V, Type *Ty);
744
745     /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
746     /// the input value to the specified type. If the type must be extended,
747     /// it is extended with unspecified bits. The conversion must not be
748     /// narrowing.
749     const SCEV *getNoopOrAnyExtend(const SCEV *V, Type *Ty);
750
751     /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
752     /// input value to the specified type.  The conversion must not be
753     /// widening.
754     const SCEV *getTruncateOrNoop(const SCEV *V, Type *Ty);
755
756     /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
757     /// the types using zero-extension, and then perform a umax operation
758     /// with them.
759     const SCEV *getUMaxFromMismatchedTypes(const SCEV *LHS,
760                                            const SCEV *RHS);
761
762     /// getUMinFromMismatchedTypes - Promote the operands to the wider of
763     /// the types using zero-extension, and then perform a umin operation
764     /// with them.
765     const SCEV *getUMinFromMismatchedTypes(const SCEV *LHS,
766                                            const SCEV *RHS);
767
768     /// getPointerBase - Transitively follow the chain of pointer-type operands
769     /// until reaching a SCEV that does not have a single pointer operand. This
770     /// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
771     /// but corner cases do exist.
772     const SCEV *getPointerBase(const SCEV *V);
773
774     /// getSCEVAtScope - Return a SCEV expression for the specified value
775     /// at the specified scope in the program.  The L value specifies a loop
776     /// nest to evaluate the expression at, where null is the top-level or a
777     /// specified loop is immediately inside of the loop.
778     ///
779     /// This method can be used to compute the exit value for a variable defined
780     /// in a loop by querying what the value will hold in the parent loop.
781     ///
782     /// In the case that a relevant loop exit value cannot be computed, the
783     /// original value V is returned.
784     const SCEV *getSCEVAtScope(const SCEV *S, const Loop *L);
785
786     /// getSCEVAtScope - This is a convenience function which does
787     /// getSCEVAtScope(getSCEV(V), L).
788     const SCEV *getSCEVAtScope(Value *V, const Loop *L);
789
790     /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
791     /// by a conditional between LHS and RHS.  This is used to help avoid max
792     /// expressions in loop trip counts, and to eliminate casts.
793     bool isLoopEntryGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
794                                   const SCEV *LHS, const SCEV *RHS);
795
796     /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
797     /// protected by a conditional between LHS and RHS.  This is used to
798     /// to eliminate casts.
799     bool isLoopBackedgeGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
800                                      const SCEV *LHS, const SCEV *RHS);
801
802     /// \brief Returns the maximum trip count of the loop if it is a single-exit
803     /// loop and we can compute a small maximum for that loop.
804     ///
805     /// Implemented in terms of the \c getSmallConstantTripCount overload with
806     /// the single exiting block passed to it. See that routine for details.
807     unsigned getSmallConstantTripCount(Loop *L);
808
809     /// getSmallConstantTripCount - Returns the maximum trip count of this loop
810     /// as a normal unsigned value. Returns 0 if the trip count is unknown or
811     /// not constant. This "trip count" assumes that control exits via
812     /// ExitingBlock. More precisely, it is the number of times that control may
813     /// reach ExitingBlock before taking the branch. For loops with multiple
814     /// exits, it may not be the number times that the loop header executes if
815     /// the loop exits prematurely via another branch.
816     unsigned getSmallConstantTripCount(Loop *L, BasicBlock *ExitingBlock);
817
818     /// \brief Returns the largest constant divisor of the trip count of the
819     /// loop if it is a single-exit loop and we can compute a small maximum for
820     /// that loop.
821     ///
822     /// Implemented in terms of the \c getSmallConstantTripMultiple overload with
823     /// the single exiting block passed to it. See that routine for details.
824     unsigned getSmallConstantTripMultiple(Loop *L);
825
826     /// getSmallConstantTripMultiple - Returns the largest constant divisor of
827     /// the trip count of this loop as a normal unsigned value, if
828     /// possible. This means that the actual trip count is always a multiple of
829     /// the returned value (don't forget the trip count could very well be zero
830     /// as well!). As explained in the comments for getSmallConstantTripCount,
831     /// this assumes that control exits the loop via ExitingBlock.
832     unsigned getSmallConstantTripMultiple(Loop *L, BasicBlock *ExitingBlock);
833
834     // getExitCount - Get the expression for the number of loop iterations for
835     // which this loop is guaranteed not to exit via ExitingBlock. Otherwise
836     // return SCEVCouldNotCompute.
837     const SCEV *getExitCount(Loop *L, BasicBlock *ExitingBlock);
838
839     /// getBackedgeTakenCount - If the specified loop has a predictable
840     /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
841     /// object. The backedge-taken count is the number of times the loop header
842     /// will be branched to from within the loop. This is one less than the
843     /// trip count of the loop, since it doesn't count the first iteration,
844     /// when the header is branched to from outside the loop.
845     ///
846     /// Note that it is not valid to call this method on a loop without a
847     /// loop-invariant backedge-taken count (see
848     /// hasLoopInvariantBackedgeTakenCount).
849     ///
850     const SCEV *getBackedgeTakenCount(const Loop *L);
851
852     /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
853     /// return the least SCEV value that is known never to be less than the
854     /// actual backedge taken count.
855     const SCEV *getMaxBackedgeTakenCount(const Loop *L);
856
857     /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop
858     /// has an analyzable loop-invariant backedge-taken count.
859     bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
860
861     /// forgetLoop - This method should be called by the client when it has
862     /// changed a loop in a way that may effect ScalarEvolution's ability to
863     /// compute a trip count, or if the loop is deleted.  This call is
864     /// potentially expensive for large loop bodies.
865     void forgetLoop(const Loop *L);
866
867     /// forgetValue - This method should be called by the client when it has
868     /// changed a value in a way that may effect its value, or which may
869     /// disconnect it from a def-use chain linking it to a loop.
870     void forgetValue(Value *V);
871
872     /// \brief Called when the client has changed the disposition of values in
873     /// this loop.
874     ///
875     /// We don't have a way to invalidate per-loop dispositions. Clear and
876     /// recompute is simpler.
877     void forgetLoopDispositions(const Loop *L) { LoopDispositions.clear(); }
878
879     /// GetMinTrailingZeros - Determine the minimum number of zero bits that S
880     /// is guaranteed to end in (at every loop iteration).  It is, at the same
881     /// time, the minimum number of times S is divisible by 2.  For example,
882     /// given {4,+,8} it returns 2.  If S is guaranteed to be 0, it returns the
883     /// bitwidth of S.
884     uint32_t GetMinTrailingZeros(const SCEV *S);
885
886     /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
887     ///
888     ConstantRange getUnsignedRange(const SCEV *S) {
889       return getRange(S, HINT_RANGE_UNSIGNED);
890     }
891
892     /// getSignedRange - Determine the signed range for a particular SCEV.
893     ///
894     ConstantRange getSignedRange(const SCEV *S) {
895       return getRange(S, HINT_RANGE_SIGNED);
896     }
897
898     /// isKnownNegative - Test if the given expression is known to be negative.
899     ///
900     bool isKnownNegative(const SCEV *S);
901
902     /// isKnownPositive - Test if the given expression is known to be positive.
903     ///
904     bool isKnownPositive(const SCEV *S);
905
906     /// isKnownNonNegative - Test if the given expression is known to be
907     /// non-negative.
908     ///
909     bool isKnownNonNegative(const SCEV *S);
910
911     /// isKnownNonPositive - Test if the given expression is known to be
912     /// non-positive.
913     ///
914     bool isKnownNonPositive(const SCEV *S);
915
916     /// isKnownNonZero - Test if the given expression is known to be
917     /// non-zero.
918     ///
919     bool isKnownNonZero(const SCEV *S);
920
921     /// isKnownPredicate - Test if the given expression is known to satisfy
922     /// the condition described by Pred, LHS, and RHS.
923     ///
924     bool isKnownPredicate(ICmpInst::Predicate Pred,
925                           const SCEV *LHS, const SCEV *RHS);
926
927     /// Return true if the result of the predicate LHS `Pred` RHS is loop
928     /// invariant with respect to L.  Set InvariantPred, InvariantLHS and
929     /// InvariantLHS so that InvariantLHS `InvariantPred` InvariantRHS is the
930     /// loop invariant form of LHS `Pred` RHS.
931     bool isLoopInvariantPredicate(ICmpInst::Predicate Pred, const SCEV *LHS,
932                                   const SCEV *RHS, const Loop *L,
933                                   ICmpInst::Predicate &InvariantPred,
934                                   const SCEV *&InvariantLHS,
935                                   const SCEV *&InvariantRHS);
936
937     /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
938     /// predicate Pred. Return true iff any changes were made. If the
939     /// operands are provably equal or unequal, LHS and RHS are set to
940     /// the same value and Pred is set to either ICMP_EQ or ICMP_NE.
941     ///
942     bool SimplifyICmpOperands(ICmpInst::Predicate &Pred,
943                               const SCEV *&LHS,
944                               const SCEV *&RHS,
945                               unsigned Depth = 0);
946
947     /// getLoopDisposition - Return the "disposition" of the given SCEV with
948     /// respect to the given loop.
949     LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L);
950
951     /// isLoopInvariant - Return true if the value of the given SCEV is
952     /// unchanging in the specified loop.
953     bool isLoopInvariant(const SCEV *S, const Loop *L);
954
955     /// hasComputableLoopEvolution - Return true if the given SCEV changes value
956     /// in a known way in the specified loop.  This property being true implies
957     /// that the value is variant in the loop AND that we can emit an expression
958     /// to compute the value of the expression at any particular loop iteration.
959     bool hasComputableLoopEvolution(const SCEV *S, const Loop *L);
960
961     /// getLoopDisposition - Return the "disposition" of the given SCEV with
962     /// respect to the given block.
963     BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB);
964
965     /// dominates - Return true if elements that makes up the given SCEV
966     /// dominate the specified basic block.
967     bool dominates(const SCEV *S, const BasicBlock *BB);
968
969     /// properlyDominates - Return true if elements that makes up the given SCEV
970     /// properly dominate the specified basic block.
971     bool properlyDominates(const SCEV *S, const BasicBlock *BB);
972
973     /// hasOperand - Test whether the given SCEV has Op as a direct or
974     /// indirect operand.
975     bool hasOperand(const SCEV *S, const SCEV *Op) const;
976
977     /// Return the size of an element read or written by Inst.
978     const SCEV *getElementSize(Instruction *Inst);
979
980     /// Compute the array dimensions Sizes from the set of Terms extracted from
981     /// the memory access function of this SCEVAddRecExpr.
982     void findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
983                              SmallVectorImpl<const SCEV *> &Sizes,
984                              const SCEV *ElementSize) const;
985
986     bool runOnFunction(Function &F) override;
987     void releaseMemory() override;
988     void getAnalysisUsage(AnalysisUsage &AU) const override;
989     void print(raw_ostream &OS, const Module* = nullptr) const override;
990     void verifyAnalysis() const override;
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
1101 #endif