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