LLVM  9.0.0svn
ScalarEvolution.h
Go to the documentation of this file.
1 //===- llvm/Analysis/ScalarEvolution.h - Scalar Evolution -------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // The ScalarEvolution class is an LLVM pass which can be used to analyze and
10 // categorize scalar expressions in loops. It specializes in recognizing
11 // general induction variables, representing them with the abstract and opaque
12 // SCEV class. Given this analysis, trip counts of loops and other important
13 // properties can be obtained.
14 //
15 // This analysis is primarily useful for induction variable substitution and
16 // strength reduction.
17 //
18 //===----------------------------------------------------------------------===//
19 
20 #ifndef LLVM_ANALYSIS_SCALAREVOLUTION_H
21 #define LLVM_ANALYSIS_SCALAREVOLUTION_H
22 
23 #include "llvm/ADT/APInt.h"
24 #include "llvm/ADT/ArrayRef.h"
25 #include "llvm/ADT/DenseMap.h"
26 #include "llvm/ADT/DenseMapInfo.h"
27 #include "llvm/ADT/FoldingSet.h"
28 #include "llvm/ADT/Hashing.h"
29 #include "llvm/ADT/Optional.h"
31 #include "llvm/ADT/SetVector.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/Analysis/LoopInfo.h"
35 #include "llvm/IR/ConstantRange.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/InstrTypes.h"
38 #include "llvm/IR/Instructions.h"
39 #include "llvm/IR/Operator.h"
40 #include "llvm/IR/PassManager.h"
41 #include "llvm/IR/ValueHandle.h"
42 #include "llvm/IR/ValueMap.h"
43 #include "llvm/Pass.h"
44 #include "llvm/Support/Allocator.h"
45 #include "llvm/Support/Casting.h"
46 #include "llvm/Support/Compiler.h"
47 #include <algorithm>
48 #include <cassert>
49 #include <cstdint>
50 #include <memory>
51 #include <utility>
52 
53 namespace llvm {
54 
55 class AssumptionCache;
56 class BasicBlock;
57 class Constant;
58 class ConstantInt;
59 class DataLayout;
60 class DominatorTree;
61 class GEPOperator;
62 class Instruction;
63 class LLVMContext;
64 class raw_ostream;
65 class ScalarEvolution;
66 class SCEVAddRecExpr;
67 class SCEVUnknown;
68 class StructType;
69 class TargetLibraryInfo;
70 class Type;
71 class Value;
72 
73 /// This class represents an analyzed expression in the program. These are
74 /// opaque objects that the client is not allowed to do much with directly.
75 ///
76 class SCEV : public FoldingSetNode {
77  friend struct FoldingSetTrait<SCEV>;
78 
79  /// A reference to an Interned FoldingSetNodeID for this node. The
80  /// ScalarEvolution's BumpPtrAllocator holds the data.
81  FoldingSetNodeIDRef FastID;
82 
83  // The SCEV baseclass this node corresponds to
84  const unsigned short SCEVType;
85 
86 protected:
87  // Estimated complexity of this node's expression tree size.
88  const unsigned short ExpressionSize;
89 
90  /// This field is initialized to zero and may be used in subclasses to store
91  /// miscellaneous information.
92  unsigned short SubclassData = 0;
93 
94 public:
95  /// NoWrapFlags are bitfield indices into SubclassData.
96  ///
97  /// Add and Mul expressions may have no-unsigned-wrap <NUW> or
98  /// no-signed-wrap <NSW> properties, which are derived from the IR
99  /// operator. NSW is a misnomer that we use to mean no signed overflow or
100  /// underflow.
101  ///
102  /// AddRec expressions may have a no-self-wraparound <NW> property if, in
103  /// the integer domain, abs(step) * max-iteration(loop) <=
104  /// unsigned-max(bitwidth). This means that the recurrence will never reach
105  /// its start value if the step is non-zero. Computing the same value on
106  /// each iteration is not considered wrapping, and recurrences with step = 0
107  /// are trivially <NW>. <NW> is independent of the sign of step and the
108  /// value the add recurrence starts with.
109  ///
110  /// Note that NUW and NSW are also valid properties of a recurrence, and
111  /// either implies NW. For convenience, NW will be set for a recurrence
112  /// whenever either NUW or NSW are set.
113  enum NoWrapFlags {
114  FlagAnyWrap = 0, // No guarantee.
115  FlagNW = (1 << 0), // No self-wrap.
116  FlagNUW = (1 << 1), // No unsigned wrap.
117  FlagNSW = (1 << 2), // No signed wrap.
118  NoWrapMask = (1 << 3) - 1
119  };
120 
121  explicit SCEV(const FoldingSetNodeIDRef ID, unsigned SCEVTy,
122  unsigned short ExpressionSize)
123  : FastID(ID), SCEVType(SCEVTy), ExpressionSize(ExpressionSize) {}
124  SCEV(const SCEV &) = delete;
125  SCEV &operator=(const SCEV &) = delete;
126 
127  unsigned getSCEVType() const { return SCEVType; }
128 
129  /// Return the LLVM type of this SCEV expression.
130  Type *getType() const;
131 
132  /// Return true if the expression is a constant zero.
133  bool isZero() const;
134 
135  /// Return true if the expression is a constant one.
136  bool isOne() const;
137 
138  /// Return true if the expression is a constant all-ones value.
139  bool isAllOnesValue() const;
140 
141  /// Return true if the specified scev is negated, but not a constant.
142  bool isNonConstantNegative() const;
143 
144  // Returns estimated size of the mathematical expression represented by this
145  // SCEV. The rules of its calculation are following:
146  // 1) Size of a SCEV without operands (like constants and SCEVUnknown) is 1;
147  // 2) Size SCEV with operands Op1, Op2, ..., OpN is calculated by formula:
148  // (1 + Size(Op1) + ... + Size(OpN)).
149  // This value gives us an estimation of time we need to traverse through this
150  // SCEV and all its operands recursively. We may use it to avoid performing
151  // heavy transformations on SCEVs of excessive size for sake of saving the
152  // compilation time.
153  unsigned short getExpressionSize() const {
154  return ExpressionSize;
155  }
156 
157  /// Print out the internal representation of this scalar to the specified
158  /// stream. This should really only be used for debugging purposes.
159  void print(raw_ostream &OS) const;
160 
161  /// This method is used for debugging.
162  void dump() const;
163 };
164 
165 // Specialize FoldingSetTrait for SCEV to avoid needing to compute
166 // temporary FoldingSetNodeID values.
167 template <> struct FoldingSetTrait<SCEV> : DefaultFoldingSetTrait<SCEV> {
168  static void Profile(const SCEV &X, FoldingSetNodeID &ID) { ID = X.FastID; }
169 
170  static bool Equals(const SCEV &X, const FoldingSetNodeID &ID, unsigned IDHash,
171  FoldingSetNodeID &TempID) {
172  return ID == X.FastID;
173  }
174 
175  static unsigned ComputeHash(const SCEV &X, FoldingSetNodeID &TempID) {
176  return X.FastID.ComputeHash();
177  }
178 };
179 
180 inline raw_ostream &operator<<(raw_ostream &OS, const SCEV &S) {
181  S.print(OS);
182  return OS;
183 }
184 
185 /// An object of this class is returned by queries that could not be answered.
186 /// For example, if you ask for the number of iterations of a linked-list
187 /// traversal loop, you will get one of these. None of the standard SCEV
188 /// operations are valid on this class, it is just a marker.
189 struct SCEVCouldNotCompute : public SCEV {
191 
192  /// Methods for support type inquiry through isa, cast, and dyn_cast:
193  static bool classof(const SCEV *S);
194 };
195 
196 /// This class represents an assumption made using SCEV expressions which can
197 /// be checked at run-time.
200 
201  /// A reference to an Interned FoldingSetNodeID for this node. The
202  /// ScalarEvolution's BumpPtrAllocator holds the data.
203  FoldingSetNodeIDRef FastID;
204 
205 public:
206  enum SCEVPredicateKind { P_Union, P_Equal, P_Wrap };
207 
208 protected:
210  ~SCEVPredicate() = default;
211  SCEVPredicate(const SCEVPredicate &) = default;
212  SCEVPredicate &operator=(const SCEVPredicate &) = default;
213 
214 public:
216 
217  SCEVPredicateKind getKind() const { return Kind; }
218 
219  /// Returns the estimated complexity of this predicate. This is roughly
220  /// measured in the number of run-time checks required.
221  virtual unsigned getComplexity() const { return 1; }
222 
223  /// Returns true if the predicate is always true. This means that no
224  /// assumptions were made and nothing needs to be checked at run-time.
225  virtual bool isAlwaysTrue() const = 0;
226 
227  /// Returns true if this predicate implies \p N.
228  virtual bool implies(const SCEVPredicate *N) const = 0;
229 
230  /// Prints a textual representation of this predicate with an indentation of
231  /// \p Depth.
232  virtual void print(raw_ostream &OS, unsigned Depth = 0) const = 0;
233 
234  /// Returns the SCEV to which this predicate applies, or nullptr if this is
235  /// a SCEVUnionPredicate.
236  virtual const SCEV *getExpr() const = 0;
237 };
238 
240  P.print(OS);
241  return OS;
242 }
243 
244 // Specialize FoldingSetTrait for SCEVPredicate to avoid needing to compute
245 // temporary FoldingSetNodeID values.
246 template <>
248  static void Profile(const SCEVPredicate &X, FoldingSetNodeID &ID) {
249  ID = X.FastID;
250  }
251 
252  static bool Equals(const SCEVPredicate &X, const FoldingSetNodeID &ID,
253  unsigned IDHash, FoldingSetNodeID &TempID) {
254  return ID == X.FastID;
255  }
256 
257  static unsigned ComputeHash(const SCEVPredicate &X,
258  FoldingSetNodeID &TempID) {
259  return X.FastID.ComputeHash();
260  }
261 };
262 
263 /// This class represents an assumption that two SCEV expressions are equal,
264 /// and this can be checked at run-time.
265 class SCEVEqualPredicate final : public SCEVPredicate {
266  /// We assume that LHS == RHS.
267  const SCEV *LHS;
268  const SCEV *RHS;
269 
270 public:
271  SCEVEqualPredicate(const FoldingSetNodeIDRef ID, const SCEV *LHS,
272  const SCEV *RHS);
273 
274  /// Implementation of the SCEVPredicate interface
275  bool implies(const SCEVPredicate *N) const override;
276  void print(raw_ostream &OS, unsigned Depth = 0) const override;
277  bool isAlwaysTrue() const override;
278  const SCEV *getExpr() const override;
279 
280  /// Returns the left hand side of the equality.
281  const SCEV *getLHS() const { return LHS; }
282 
283  /// Returns the right hand side of the equality.
284  const SCEV *getRHS() const { return RHS; }
285 
286  /// Methods for support type inquiry through isa, cast, and dyn_cast:
287  static bool classof(const SCEVPredicate *P) {
288  return P->getKind() == P_Equal;
289  }
290 };
291 
292 /// This class represents an assumption made on an AddRec expression. Given an
293 /// affine AddRec expression {a,+,b}, we assume that it has the nssw or nusw
294 /// flags (defined below) in the first X iterations of the loop, where X is a
295 /// SCEV expression returned by getPredicatedBackedgeTakenCount).
296 ///
297 /// Note that this does not imply that X is equal to the backedge taken
298 /// count. This means that if we have a nusw predicate for i32 {0,+,1} with a
299 /// predicated backedge taken count of X, we only guarantee that {0,+,1} has
300 /// nusw in the first X iterations. {0,+,1} may still wrap in the loop if we
301 /// have more than X iterations.
302 class SCEVWrapPredicate final : public SCEVPredicate {
303 public:
304  /// Similar to SCEV::NoWrapFlags, but with slightly different semantics
305  /// for FlagNUSW. The increment is considered to be signed, and a + b
306  /// (where b is the increment) is considered to wrap if:
307  /// zext(a + b) != zext(a) + sext(b)
308  ///
309  /// If Signed is a function that takes an n-bit tuple and maps to the
310  /// integer domain as the tuples value interpreted as twos complement,
311  /// and Unsigned a function that takes an n-bit tuple and maps to the
312  /// integer domain as as the base two value of input tuple, then a + b
313  /// has IncrementNUSW iff:
314  ///
315  /// 0 <= Unsigned(a) + Signed(b) < 2^n
316  ///
317  /// The IncrementNSSW flag has identical semantics with SCEV::FlagNSW.
318  ///
319  /// Note that the IncrementNUSW flag is not commutative: if base + inc
320  /// has IncrementNUSW, then inc + base doesn't neccessarily have this
321  /// property. The reason for this is that this is used for sign/zero
322  /// extending affine AddRec SCEV expressions when a SCEVWrapPredicate is
323  /// assumed. A {base,+,inc} expression is already non-commutative with
324  /// regards to base and inc, since it is interpreted as:
325  /// (((base + inc) + inc) + inc) ...
327  IncrementAnyWrap = 0, // No guarantee.
328  IncrementNUSW = (1 << 0), // No unsigned with signed increment wrap.
329  IncrementNSSW = (1 << 1), // No signed with signed increment wrap
330  // (equivalent with SCEV::NSW)
331  IncrementNoWrapMask = (1 << 2) - 1
332  };
333 
334  /// Convenient IncrementWrapFlags manipulation methods.
338  assert((Flags & IncrementNoWrapMask) == Flags && "Invalid flags value!");
339  assert((OffFlags & IncrementNoWrapMask) == OffFlags &&
340  "Invalid flags value!");
341  return (SCEVWrapPredicate::IncrementWrapFlags)(Flags & ~OffFlags);
342  }
343 
346  assert((Flags & IncrementNoWrapMask) == Flags && "Invalid flags value!");
347  assert((Mask & IncrementNoWrapMask) == Mask && "Invalid mask value!");
348 
350  }
351 
355  assert((Flags & IncrementNoWrapMask) == Flags && "Invalid flags value!");
356  assert((OnFlags & IncrementNoWrapMask) == OnFlags &&
357  "Invalid flags value!");
358 
359  return (SCEVWrapPredicate::IncrementWrapFlags)(Flags | OnFlags);
360  }
361 
362  /// Returns the set of SCEVWrapPredicate no wrap flags implied by a
363  /// SCEVAddRecExpr.
365  getImpliedFlags(const SCEVAddRecExpr *AR, ScalarEvolution &SE);
366 
367 private:
368  const SCEVAddRecExpr *AR;
369  IncrementWrapFlags Flags;
370 
371 public:
373  const SCEVAddRecExpr *AR,
374  IncrementWrapFlags Flags);
375 
376  /// Returns the set assumed no overflow flags.
377  IncrementWrapFlags getFlags() const { return Flags; }
378 
379  /// Implementation of the SCEVPredicate interface
380  const SCEV *getExpr() const override;
381  bool implies(const SCEVPredicate *N) const override;
382  void print(raw_ostream &OS, unsigned Depth = 0) const override;
383  bool isAlwaysTrue() const override;
384 
385  /// Methods for support type inquiry through isa, cast, and dyn_cast:
386  static bool classof(const SCEVPredicate *P) {
387  return P->getKind() == P_Wrap;
388  }
389 };
390 
391 /// This class represents a composition of other SCEV predicates, and is the
392 /// class that most clients will interact with. This is equivalent to a
393 /// logical "AND" of all the predicates in the union.
394 ///
395 /// NB! Unlike other SCEVPredicate sub-classes this class does not live in the
396 /// ScalarEvolution::Preds folding set. This is why the \c add function is sound.
397 class SCEVUnionPredicate final : public SCEVPredicate {
398 private:
399  using PredicateMap =
401 
402  /// Vector with references to all predicates in this union.
404 
405  /// Maps SCEVs to predicates for quick look-ups.
406  PredicateMap SCEVToPreds;
407 
408 public:
410 
412  return Preds;
413  }
414 
415  /// Adds a predicate to this union.
416  void add(const SCEVPredicate *N);
417 
418  /// Returns a reference to a vector containing all predicates which apply to
419  /// \p Expr.
420  ArrayRef<const SCEVPredicate *> getPredicatesForExpr(const SCEV *Expr);
421 
422  /// Implementation of the SCEVPredicate interface
423  bool isAlwaysTrue() const override;
424  bool implies(const SCEVPredicate *N) const override;
425  void print(raw_ostream &OS, unsigned Depth) const override;
426  const SCEV *getExpr() const override;
427 
428  /// We estimate the complexity of a union predicate as the size number of
429  /// predicates in the union.
430  unsigned getComplexity() const override { return Preds.size(); }
431 
432  /// Methods for support type inquiry through isa, cast, and dyn_cast:
433  static bool classof(const SCEVPredicate *P) {
434  return P->getKind() == P_Union;
435  }
436 };
437 
439  ExitLimitQuery(const Loop *L, BasicBlock *ExitingBlock, bool AllowPredicates)
440  : L(L), ExitingBlock(ExitingBlock), AllowPredicates(AllowPredicates) {}
441 
442  const Loop *L;
445 };
446 
447 template <> struct DenseMapInfo<ExitLimitQuery> {
448  static inline ExitLimitQuery getEmptyKey() {
449  return ExitLimitQuery(nullptr, nullptr, true);
450  }
451 
452  static inline ExitLimitQuery getTombstoneKey() {
453  return ExitLimitQuery(nullptr, nullptr, false);
454  }
455 
456  static unsigned getHashValue(ExitLimitQuery Val) {
457  return hash_combine(hash_combine(Val.L, Val.ExitingBlock),
458  Val.AllowPredicates);
459  }
460 
461  static bool isEqual(ExitLimitQuery LHS, ExitLimitQuery RHS) {
462  return LHS.L == RHS.L && LHS.ExitingBlock == RHS.ExitingBlock &&
463  LHS.AllowPredicates == RHS.AllowPredicates;
464  }
465 };
466 
467 /// The main scalar evolution driver. Because client code (intentionally)
468 /// can't do much with the SCEV objects directly, they must ask this class
469 /// for services.
471 public:
472  /// An enum describing the relationship between a SCEV and a loop.
474  LoopVariant, ///< The SCEV is loop-variant (unknown).
475  LoopInvariant, ///< The SCEV is loop-invariant.
476  LoopComputable ///< The SCEV varies predictably with the loop.
477  };
478 
479  /// An enum describing the relationship between a SCEV and a basic block.
481  DoesNotDominateBlock, ///< The SCEV does not dominate the block.
482  DominatesBlock, ///< The SCEV dominates the block.
483  ProperlyDominatesBlock ///< The SCEV properly dominates the block.
484  };
485 
486  /// Convenient NoWrapFlags manipulation that hides enum casts and is
487  /// visible in the ScalarEvolution name space.
489  int Mask) {
490  return (SCEV::NoWrapFlags)(Flags & Mask);
491  }
493  SCEV::NoWrapFlags OnFlags) {
494  return (SCEV::NoWrapFlags)(Flags | OnFlags);
495  }
498  return (SCEV::NoWrapFlags)(Flags & ~OffFlags);
499  }
500 
502  DominatorTree &DT, LoopInfo &LI);
504  ~ScalarEvolution();
505 
506  LLVMContext &getContext() const { return F.getContext(); }
507 
508  /// Test if values of the given type are analyzable within the SCEV
509  /// framework. This primarily includes integer types, and it can optionally
510  /// include pointer types if the ScalarEvolution class has access to
511  /// target-specific information.
512  bool isSCEVable(Type *Ty) const;
513 
514  /// Return the size in bits of the specified type, for which isSCEVable must
515  /// return true.
516  uint64_t getTypeSizeInBits(Type *Ty) const;
517 
518  /// Return a type with the same bitwidth as the given type and which
519  /// represents how SCEV will treat the given type, for which isSCEVable must
520  /// return true. For pointer types, this is the pointer-sized integer type.
521  Type *getEffectiveSCEVType(Type *Ty) const;
522 
523  // Returns a wider type among {Ty1, Ty2}.
524  Type *getWiderType(Type *Ty1, Type *Ty2) const;
525 
526  /// Return true if the SCEV is a scAddRecExpr or it contains
527  /// scAddRecExpr. The result will be cached in HasRecMap.
528  bool containsAddRecurrence(const SCEV *S);
529 
530  /// Erase Value from ValueExprMap and ExprValueMap.
531  void eraseValueFromMap(Value *V);
532 
533  /// Return a SCEV expression for the full generality of the specified
534  /// expression.
535  const SCEV *getSCEV(Value *V);
536 
537  const SCEV *getConstant(ConstantInt *V);
538  const SCEV *getConstant(const APInt &Val);
539  const SCEV *getConstant(Type *Ty, uint64_t V, bool isSigned = false);
540  const SCEV *getTruncateExpr(const SCEV *Op, Type *Ty, unsigned Depth = 0);
541  const SCEV *getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth = 0);
542  const SCEV *getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth = 0);
543  const SCEV *getAnyExtendExpr(const SCEV *Op, Type *Ty);
544  const SCEV *getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
546  unsigned Depth = 0);
547  const SCEV *getAddExpr(const SCEV *LHS, const SCEV *RHS,
549  unsigned Depth = 0) {
550  SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
551  return getAddExpr(Ops, Flags, Depth);
552  }
553  const SCEV *getAddExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
555  unsigned Depth = 0) {
556  SmallVector<const SCEV *, 3> Ops = {Op0, Op1, Op2};
557  return getAddExpr(Ops, Flags, Depth);
558  }
559  const SCEV *getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
561  unsigned Depth = 0);
562  const SCEV *getMulExpr(const SCEV *LHS, const SCEV *RHS,
564  unsigned Depth = 0) {
565  SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
566  return getMulExpr(Ops, Flags, Depth);
567  }
568  const SCEV *getMulExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
570  unsigned Depth = 0) {
571  SmallVector<const SCEV *, 3> Ops = {Op0, Op1, Op2};
572  return getMulExpr(Ops, Flags, Depth);
573  }
574  const SCEV *getUDivExpr(const SCEV *LHS, const SCEV *RHS);
575  const SCEV *getUDivExactExpr(const SCEV *LHS, const SCEV *RHS);
576  const SCEV *getURemExpr(const SCEV *LHS, const SCEV *RHS);
577  const SCEV *getAddRecExpr(const SCEV *Start, const SCEV *Step, const Loop *L,
578  SCEV::NoWrapFlags Flags);
579  const SCEV *getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
580  const Loop *L, SCEV::NoWrapFlags Flags);
582  const Loop *L, SCEV::NoWrapFlags Flags) {
583  SmallVector<const SCEV *, 4> NewOp(Operands.begin(), Operands.end());
584  return getAddRecExpr(NewOp, L, Flags);
585  }
586 
587  /// Checks if \p SymbolicPHI can be rewritten as an AddRecExpr under some
588  /// Predicates. If successful return these <AddRecExpr, Predicates>;
589  /// The function is intended to be called from PSCEV (the caller will decide
590  /// whether to actually add the predicates and carry out the rewrites).
592  createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI);
593 
594  /// Returns an expression for a GEP
595  ///
596  /// \p GEP The GEP. The indices contained in the GEP itself are ignored,
597  /// instead we use IndexExprs.
598  /// \p IndexExprs The expressions for the indices.
599  const SCEV *getGEPExpr(GEPOperator *GEP,
600  const SmallVectorImpl<const SCEV *> &IndexExprs);
601  const SCEV *getSMaxExpr(const SCEV *LHS, const SCEV *RHS);
602  const SCEV *getSMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
603  const SCEV *getUMaxExpr(const SCEV *LHS, const SCEV *RHS);
604  const SCEV *getUMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
605  const SCEV *getSMinExpr(const SCEV *LHS, const SCEV *RHS);
606  const SCEV *getSMinExpr(SmallVectorImpl<const SCEV *> &Operands);
607  const SCEV *getUMinExpr(const SCEV *LHS, const SCEV *RHS);
608  const SCEV *getUMinExpr(SmallVectorImpl<const SCEV *> &Operands);
609  const SCEV *getUnknown(Value *V);
610  const SCEV *getCouldNotCompute();
611 
612  /// Return a SCEV for the constant 0 of a specific type.
613  const SCEV *getZero(Type *Ty) { return getConstant(Ty, 0); }
614 
615  /// Return a SCEV for the constant 1 of a specific type.
616  const SCEV *getOne(Type *Ty) { return getConstant(Ty, 1); }
617 
618  /// Return an expression for sizeof AllocTy that is type IntTy
619  const SCEV *getSizeOfExpr(Type *IntTy, Type *AllocTy);
620 
621  /// Return an expression for offsetof on the given field with type IntTy
622  const SCEV *getOffsetOfExpr(Type *IntTy, StructType *STy, unsigned FieldNo);
623 
624  /// Return the SCEV object corresponding to -V.
625  const SCEV *getNegativeSCEV(const SCEV *V,
627 
628  /// Return the SCEV object corresponding to ~V.
629  const SCEV *getNotSCEV(const SCEV *V);
630 
631  /// Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
632  const SCEV *getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
634  unsigned Depth = 0);
635 
636  /// Return a SCEV corresponding to a conversion of the input value to the
637  /// specified type. If the type must be extended, it is zero extended.
638  const SCEV *getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
639  unsigned Depth = 0);
640 
641  /// Return a SCEV corresponding to a conversion of the input value to the
642  /// specified type. If the type must be extended, it is sign extended.
643  const SCEV *getTruncateOrSignExtend(const SCEV *V, Type *Ty,
644  unsigned Depth = 0);
645 
646  /// Return a SCEV corresponding to a conversion of the input value to the
647  /// specified type. If the type must be extended, it is zero extended. The
648  /// conversion must not be narrowing.
649  const SCEV *getNoopOrZeroExtend(const SCEV *V, Type *Ty);
650 
651  /// Return a SCEV corresponding to a conversion of the input value to the
652  /// specified type. If the type must be extended, it is sign extended. The
653  /// conversion must not be narrowing.
654  const SCEV *getNoopOrSignExtend(const SCEV *V, Type *Ty);
655 
656  /// Return a SCEV corresponding to a conversion of the input value to the
657  /// specified type. If the type must be extended, it is extended with
658  /// unspecified bits. The conversion must not be narrowing.
659  const SCEV *getNoopOrAnyExtend(const SCEV *V, Type *Ty);
660 
661  /// Return a SCEV corresponding to a conversion of the input value to the
662  /// specified type. The conversion must not be widening.
663  const SCEV *getTruncateOrNoop(const SCEV *V, Type *Ty);
664 
665  /// Promote the operands to the wider of the types using zero-extension, and
666  /// then perform a umax operation with them.
667  const SCEV *getUMaxFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS);
668 
669  /// Promote the operands to the wider of the types using zero-extension, and
670  /// then perform a umin operation with them.
671  const SCEV *getUMinFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS);
672 
673  /// Promote the operands to the wider of the types using zero-extension, and
674  /// then perform a umin operation with them. N-ary function.
675  const SCEV *getUMinFromMismatchedTypes(SmallVectorImpl<const SCEV *> &Ops);
676 
677  /// Transitively follow the chain of pointer-type operands until reaching a
678  /// SCEV that does not have a single pointer operand. This returns a
679  /// SCEVUnknown pointer for well-formed pointer-type expressions, but corner
680  /// cases do exist.
681  const SCEV *getPointerBase(const SCEV *V);
682 
683  /// Return a SCEV expression for the specified value at the specified scope
684  /// in the program. The L value specifies a loop nest to evaluate the
685  /// expression at, where null is the top-level or a specified loop is
686  /// immediately inside of the loop.
687  ///
688  /// This method can be used to compute the exit value for a variable defined
689  /// in a loop by querying what the value will hold in the parent loop.
690  ///
691  /// In the case that a relevant loop exit value cannot be computed, the
692  /// original value V is returned.
693  const SCEV *getSCEVAtScope(const SCEV *S, const Loop *L);
694 
695  /// This is a convenience function which does getSCEVAtScope(getSCEV(V), L).
696  const SCEV *getSCEVAtScope(Value *V, const Loop *L);
697 
698  /// Test whether entry to the loop is protected by a conditional between LHS
699  /// and RHS. This is used to help avoid max expressions in loop trip
700  /// counts, and to eliminate casts.
701  bool isLoopEntryGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
702  const SCEV *LHS, const SCEV *RHS);
703 
704  /// Test whether the backedge of the loop is protected by a conditional
705  /// between LHS and RHS. This is used to eliminate casts.
706  bool isLoopBackedgeGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
707  const SCEV *LHS, const SCEV *RHS);
708 
709  /// Returns the maximum trip count of the loop if it is a single-exit
710  /// loop and we can compute a small maximum for that loop.
711  ///
712  /// Implemented in terms of the \c getSmallConstantTripCount overload with
713  /// the single exiting block passed to it. See that routine for details.
714  unsigned getSmallConstantTripCount(const Loop *L);
715 
716  /// Returns the maximum trip count of this loop as a normal unsigned
717  /// value. Returns 0 if the trip count is unknown or not constant. This
718  /// "trip count" assumes that control exits via ExitingBlock. More
719  /// precisely, it is the number of times that control may reach ExitingBlock
720  /// before taking the branch. For loops with multiple exits, it may not be
721  /// the number times that the loop header executes if the loop exits
722  /// prematurely via another branch.
723  unsigned getSmallConstantTripCount(const Loop *L, BasicBlock *ExitingBlock);
724 
725  /// Returns the upper bound of the loop trip count as a normal unsigned
726  /// value.
727  /// Returns 0 if the trip count is unknown or not constant.
728  unsigned getSmallConstantMaxTripCount(const Loop *L);
729 
730  /// Returns the largest constant divisor of the trip count of the
731  /// loop if it is a single-exit loop and we can compute a small maximum for
732  /// that loop.
733  ///
734  /// Implemented in terms of the \c getSmallConstantTripMultiple overload with
735  /// the single exiting block passed to it. See that routine for details.
736  unsigned getSmallConstantTripMultiple(const Loop *L);
737 
738  /// Returns the largest constant divisor of the trip count of this loop as a
739  /// normal unsigned value, if possible. This means that the actual trip
740  /// count is always a multiple of the returned value (don't forget the trip
741  /// count could very well be zero as well!). As explained in the comments
742  /// for getSmallConstantTripCount, this assumes that control exits the loop
743  /// via ExitingBlock.
744  unsigned getSmallConstantTripMultiple(const Loop *L,
745  BasicBlock *ExitingBlock);
746 
747  /// Get the expression for the number of loop iterations for which this loop
748  /// is guaranteed not to exit via ExitingBlock. Otherwise return
749  /// SCEVCouldNotCompute.
750  const SCEV *getExitCount(const Loop *L, BasicBlock *ExitingBlock);
751 
752  /// If the specified loop has a predictable backedge-taken count, return it,
753  /// otherwise return a SCEVCouldNotCompute object. The backedge-taken count is
754  /// the number of times the loop header will be branched to from within the
755  /// loop, assuming there are no abnormal exists like exception throws. This is
756  /// one less than the trip count of the loop, since it doesn't count the first
757  /// iteration, when the header is branched to from outside the loop.
758  ///
759  /// Note that it is not valid to call this method on a loop without a
760  /// loop-invariant backedge-taken count (see
761  /// hasLoopInvariantBackedgeTakenCount).
762  const SCEV *getBackedgeTakenCount(const Loop *L);
763 
764  /// Similar to getBackedgeTakenCount, except it will add a set of
765  /// SCEV predicates to Predicates that are required to be true in order for
766  /// the answer to be correct. Predicates can be checked with run-time
767  /// checks and can be used to perform loop versioning.
768  const SCEV *getPredicatedBackedgeTakenCount(const Loop *L,
769  SCEVUnionPredicate &Predicates);
770 
771  /// When successful, this returns a SCEVConstant that is greater than or equal
772  /// to (i.e. a "conservative over-approximation") of the value returend by
773  /// getBackedgeTakenCount. If such a value cannot be computed, it returns the
774  /// SCEVCouldNotCompute object.
775  const SCEV *getMaxBackedgeTakenCount(const Loop *L);
776 
777  /// Return true if the backedge taken count is either the value returned by
778  /// getMaxBackedgeTakenCount or zero.
779  bool isBackedgeTakenCountMaxOrZero(const Loop *L);
780 
781  /// Return true if the specified loop has an analyzable loop-invariant
782  /// backedge-taken count.
783  bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
784 
785  /// This method should be called by the client when it has changed a loop in
786  /// a way that may effect ScalarEvolution's ability to compute a trip count,
787  /// or if the loop is deleted. This call is potentially expensive for large
788  /// loop bodies.
789  void forgetLoop(const Loop *L);
790 
791  // This method invokes forgetLoop for the outermost loop of the given loop
792  // \p L, making ScalarEvolution forget about all this subtree. This needs to
793  // be done whenever we make a transform that may affect the parameters of the
794  // outer loop, such as exit counts for branches.
795  void forgetTopmostLoop(const Loop *L);
796 
797  /// This method should be called by the client when it has changed a value
798  /// in a way that may effect its value, or which may disconnect it from a
799  /// def-use chain linking it to a loop.
800  void forgetValue(Value *V);
801 
802  /// Called when the client has changed the disposition of values in
803  /// this loop.
804  ///
805  /// We don't have a way to invalidate per-loop dispositions. Clear and
806  /// recompute is simpler.
807  void forgetLoopDispositions(const Loop *L) { LoopDispositions.clear(); }
808 
809  /// Determine the minimum number of zero bits that S is guaranteed to end in
810  /// (at every loop iteration). It is, at the same time, the minimum number
811  /// of times S is divisible by 2. For example, given {4,+,8} it returns 2.
812  /// If S is guaranteed to be 0, it returns the bitwidth of S.
813  uint32_t GetMinTrailingZeros(const SCEV *S);
814 
815  /// Determine the unsigned range for a particular SCEV.
816  /// NOTE: This returns a copy of the reference returned by getRangeRef.
818  return getRangeRef(S, HINT_RANGE_UNSIGNED);
819  }
820 
821  /// Determine the min of the unsigned range for a particular SCEV.
823  return getRangeRef(S, HINT_RANGE_UNSIGNED).getUnsignedMin();
824  }
825 
826  /// Determine the max of the unsigned range for a particular SCEV.
828  return getRangeRef(S, HINT_RANGE_UNSIGNED).getUnsignedMax();
829  }
830 
831  /// Determine the signed range for a particular SCEV.
832  /// NOTE: This returns a copy of the reference returned by getRangeRef.
834  return getRangeRef(S, HINT_RANGE_SIGNED);
835  }
836 
837  /// Determine the min of the signed range for a particular SCEV.
839  return getRangeRef(S, HINT_RANGE_SIGNED).getSignedMin();
840  }
841 
842  /// Determine the max of the signed range for a particular SCEV.
844  return getRangeRef(S, HINT_RANGE_SIGNED).getSignedMax();
845  }
846 
847  /// Test if the given expression is known to be negative.
848  bool isKnownNegative(const SCEV *S);
849 
850  /// Test if the given expression is known to be positive.
851  bool isKnownPositive(const SCEV *S);
852 
853  /// Test if the given expression is known to be non-negative.
854  bool isKnownNonNegative(const SCEV *S);
855 
856  /// Test if the given expression is known to be non-positive.
857  bool isKnownNonPositive(const SCEV *S);
858 
859  /// Test if the given expression is known to be non-zero.
860  bool isKnownNonZero(const SCEV *S);
861 
862  /// Splits SCEV expression \p S into two SCEVs. One of them is obtained from
863  /// \p S by substitution of all AddRec sub-expression related to loop \p L
864  /// with initial value of that SCEV. The second is obtained from \p S by
865  /// substitution of all AddRec sub-expressions related to loop \p L with post
866  /// increment of this AddRec in the loop \p L. In both cases all other AddRec
867  /// sub-expressions (not related to \p L) remain the same.
868  /// If the \p S contains non-invariant unknown SCEV the function returns
869  /// CouldNotCompute SCEV in both values of std::pair.
870  /// For example, for SCEV S={0, +, 1}<L1> + {0, +, 1}<L2> and loop L=L1
871  /// the function returns pair:
872  /// first = {0, +, 1}<L2>
873  /// second = {1, +, 1}<L1> + {0, +, 1}<L2>
874  /// We can see that for the first AddRec sub-expression it was replaced with
875  /// 0 (initial value) for the first element and to {1, +, 1}<L1> (post
876  /// increment value) for the second one. In both cases AddRec expression
877  /// related to L2 remains the same.
878  std::pair<const SCEV *, const SCEV *> SplitIntoInitAndPostInc(const Loop *L,
879  const SCEV *S);
880 
881  /// We'd like to check the predicate on every iteration of the most dominated
882  /// loop between loops used in LHS and RHS.
883  /// To do this we use the following list of steps:
884  /// 1. Collect set S all loops on which either LHS or RHS depend.
885  /// 2. If S is non-empty
886  /// a. Let PD be the element of S which is dominated by all other elements.
887  /// b. Let E(LHS) be value of LHS on entry of PD.
888  /// To get E(LHS), we should just take LHS and replace all AddRecs that are
889  /// attached to PD on with their entry values.
890  /// Define E(RHS) in the same way.
891  /// c. Let B(LHS) be value of L on backedge of PD.
892  /// To get B(LHS), we should just take LHS and replace all AddRecs that are
893  /// attached to PD on with their backedge values.
894  /// Define B(RHS) in the same way.
895  /// d. Note that E(LHS) and E(RHS) are automatically available on entry of PD,
896  /// so we can assert on that.
897  /// e. Return true if isLoopEntryGuardedByCond(Pred, E(LHS), E(RHS)) &&
898  /// isLoopBackedgeGuardedByCond(Pred, B(LHS), B(RHS))
899  bool isKnownViaInduction(ICmpInst::Predicate Pred, const SCEV *LHS,
900  const SCEV *RHS);
901 
902  /// Test if the given expression is known to satisfy the condition described
903  /// by Pred, LHS, and RHS.
904  bool isKnownPredicate(ICmpInst::Predicate Pred, const SCEV *LHS,
905  const SCEV *RHS);
906 
907  /// Test if the condition described by Pred, LHS, RHS is known to be true on
908  /// every iteration of the loop of the recurrency LHS.
909  bool isKnownOnEveryIteration(ICmpInst::Predicate Pred,
910  const SCEVAddRecExpr *LHS, const SCEV *RHS);
911 
912  /// Return true if, for all loop invariant X, the predicate "LHS `Pred` X"
913  /// is monotonically increasing or decreasing. In the former case set
914  /// `Increasing` to true and in the latter case set `Increasing` to false.
915  ///
916  /// A predicate is said to be monotonically increasing if may go from being
917  /// false to being true as the loop iterates, but never the other way
918  /// around. A predicate is said to be monotonically decreasing if may go
919  /// from being true to being false as the loop iterates, but never the other
920  /// way around.
921  bool isMonotonicPredicate(const SCEVAddRecExpr *LHS, ICmpInst::Predicate Pred,
922  bool &Increasing);
923 
924  /// Return true if the result of the predicate LHS `Pred` RHS is loop
925  /// invariant with respect to L. Set InvariantPred, InvariantLHS and
926  /// InvariantLHS so that InvariantLHS `InvariantPred` InvariantRHS is the
927  /// loop invariant form of LHS `Pred` RHS.
928  bool isLoopInvariantPredicate(ICmpInst::Predicate Pred, const SCEV *LHS,
929  const SCEV *RHS, const Loop *L,
930  ICmpInst::Predicate &InvariantPred,
931  const SCEV *&InvariantLHS,
932  const SCEV *&InvariantRHS);
933 
934  /// Simplify LHS and RHS in a comparison with predicate Pred. Return true
935  /// iff any changes were made. If the operands are provably equal or
936  /// unequal, LHS and RHS are set to the same value and Pred is set to either
937  /// ICMP_EQ or ICMP_NE.
938  bool SimplifyICmpOperands(ICmpInst::Predicate &Pred, const SCEV *&LHS,
939  const SCEV *&RHS, unsigned Depth = 0);
940 
941  /// Return the "disposition" of the given SCEV with respect to the given
942  /// loop.
943  LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L);
944 
945  /// Return true if the value of the given SCEV is unchanging in the
946  /// specified loop.
947  bool isLoopInvariant(const SCEV *S, const Loop *L);
948 
949  /// Determine if the SCEV can be evaluated at loop's entry. It is true if it
950  /// doesn't depend on a SCEVUnknown of an instruction which is dominated by
951  /// the header of loop L.
952  bool isAvailableAtLoopEntry(const SCEV *S, const Loop *L);
953 
954  /// Return true if the given SCEV changes value in a known way in the
955  /// specified loop. This property being true implies that the value is
956  /// variant in the loop AND that we can emit an expression to compute the
957  /// value of the expression at any particular loop iteration.
958  bool hasComputableLoopEvolution(const SCEV *S, const Loop *L);
959 
960  /// Return the "disposition" of the given SCEV with respect to the given
961  /// block.
962  BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB);
963 
964  /// Return true if elements that makes up the given SCEV dominate the
965  /// specified basic block.
966  bool dominates(const SCEV *S, const BasicBlock *BB);
967 
968  /// Return true if elements that makes up the given SCEV properly dominate
969  /// the specified basic block.
970  bool properlyDominates(const SCEV *S, const BasicBlock *BB);
971 
972  /// Test whether the given SCEV has Op as a direct or indirect operand.
973  bool hasOperand(const SCEV *S, const SCEV *Op) const;
974 
975  /// Return the size of an element read or written by Inst.
976  const SCEV *getElementSize(Instruction *Inst);
977 
978  /// Compute the array dimensions Sizes from the set of Terms extracted from
979  /// the memory access function of this SCEVAddRecExpr (second step of
980  /// delinearization).
981  void findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
983  const SCEV *ElementSize);
984 
985  void print(raw_ostream &OS) const;
986  void verify() const;
987  bool invalidate(Function &F, const PreservedAnalyses &PA,
989 
990  /// Collect parametric terms occurring in step expressions (first step of
991  /// delinearization).
992  void collectParametricTerms(const SCEV *Expr,
994 
995  /// Return in Subscripts the access functions for each dimension in Sizes
996  /// (third step of delinearization).
997  void computeAccessFunctions(const SCEV *Expr,
998  SmallVectorImpl<const SCEV *> &Subscripts,
1000 
1001  /// Split this SCEVAddRecExpr into two vectors of SCEVs representing the
1002  /// subscripts and sizes of an array access.
1003  ///
1004  /// The delinearization is a 3 step process: the first two steps compute the
1005  /// sizes of each subscript and the third step computes the access functions
1006  /// for the delinearized array:
1007  ///
1008  /// 1. Find the terms in the step functions
1009  /// 2. Compute the array size
1010  /// 3. Compute the access function: divide the SCEV by the array size
1011  /// starting with the innermost dimensions found in step 2. The Quotient
1012  /// is the SCEV to be divided in the next step of the recursion. The
1013  /// Remainder is the subscript of the innermost dimension. Loop over all
1014  /// array dimensions computed in step 2.
1015  ///
1016  /// To compute a uniform array size for several memory accesses to the same
1017  /// object, one can collect in step 1 all the step terms for all the memory
1018  /// accesses, and compute in step 2 a unique array shape. This guarantees
1019  /// that the array shape will be the same across all memory accesses.
1020  ///
1021  /// FIXME: We could derive the result of steps 1 and 2 from a description of
1022  /// the array shape given in metadata.
1023  ///
1024  /// Example:
1025  ///
1026  /// A[][n][m]
1027  ///
1028  /// for i
1029  /// for j
1030  /// for k
1031  /// A[j+k][2i][5i] =
1032  ///
1033  /// The initial SCEV:
1034  ///
1035  /// A[{{{0,+,2*m+5}_i, +, n*m}_j, +, n*m}_k]
1036  ///
1037  /// 1. Find the different terms in the step functions:
1038  /// -> [2*m, 5, n*m, n*m]
1039  ///
1040  /// 2. Compute the array size: sort and unique them
1041  /// -> [n*m, 2*m, 5]
1042  /// find the GCD of all the terms = 1
1043  /// divide by the GCD and erase constant terms
1044  /// -> [n*m, 2*m]
1045  /// GCD = m
1046  /// divide by GCD -> [n, 2]
1047  /// remove constant terms
1048  /// -> [n]
1049  /// size of the array is A[unknown][n][m]
1050  ///
1051  /// 3. Compute the access function
1052  /// a. Divide {{{0,+,2*m+5}_i, +, n*m}_j, +, n*m}_k by the innermost size m
1053  /// Quotient: {{{0,+,2}_i, +, n}_j, +, n}_k
1054  /// Remainder: {{{0,+,5}_i, +, 0}_j, +, 0}_k
1055  /// The remainder is the subscript of the innermost array dimension: [5i].
1056  ///
1057  /// b. Divide Quotient: {{{0,+,2}_i, +, n}_j, +, n}_k by next outer size n
1058  /// Quotient: {{{0,+,0}_i, +, 1}_j, +, 1}_k
1059  /// Remainder: {{{0,+,2}_i, +, 0}_j, +, 0}_k
1060  /// The Remainder is the subscript of the next array dimension: [2i].
1061  ///
1062  /// The subscript of the outermost dimension is the Quotient: [j+k].
1063  ///
1064  /// Overall, we have: A[][n][m], and the access function: A[j+k][2i][5i].
1065  void delinearize(const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
1067  const SCEV *ElementSize);
1068 
1069  /// Return the DataLayout associated with the module this SCEV instance is
1070  /// operating on.
1071  const DataLayout &getDataLayout() const {
1072  return F.getParent()->getDataLayout();
1073  }
1074 
1075  const SCEVPredicate *getEqualPredicate(const SCEV *LHS, const SCEV *RHS);
1076 
1077  const SCEVPredicate *
1078  getWrapPredicate(const SCEVAddRecExpr *AR,
1080 
1081  /// Re-writes the SCEV according to the Predicates in \p A.
1082  const SCEV *rewriteUsingPredicate(const SCEV *S, const Loop *L,
1083  SCEVUnionPredicate &A);
1084  /// Tries to convert the \p S expression to an AddRec expression,
1085  /// adding additional predicates to \p Preds as required.
1086  const SCEVAddRecExpr *convertSCEVToAddRecWithPredicates(
1087  const SCEV *S, const Loop *L,
1089 
1090 private:
1091  /// A CallbackVH to arrange for ScalarEvolution to be notified whenever a
1092  /// Value is deleted.
1093  class SCEVCallbackVH final : public CallbackVH {
1094  ScalarEvolution *SE;
1095 
1096  void deleted() override;
1097  void allUsesReplacedWith(Value *New) override;
1098 
1099  public:
1100  SCEVCallbackVH(Value *V, ScalarEvolution *SE = nullptr);
1101  };
1102 
1103  friend class SCEVCallbackVH;
1104  friend class SCEVExpander;
1105  friend class SCEVUnknown;
1106 
1107  /// The function we are analyzing.
1108  Function &F;
1109 
1110  /// Does the module have any calls to the llvm.experimental.guard intrinsic
1111  /// at all? If this is false, we avoid doing work that will only help if
1112  /// thare are guards present in the IR.
1113  bool HasGuards;
1114 
1115  /// The target library information for the target we are targeting.
1116  TargetLibraryInfo &TLI;
1117 
1118  /// The tracker for \@llvm.assume intrinsics in this function.
1119  AssumptionCache &AC;
1120 
1121  /// The dominator tree.
1122  DominatorTree &DT;
1123 
1124  /// The loop information for the function we are currently analyzing.
1125  LoopInfo &LI;
1126 
1127  /// This SCEV is used to represent unknown trip counts and things.
1128  std::unique_ptr<SCEVCouldNotCompute> CouldNotCompute;
1129 
1130  /// The type for HasRecMap.
1132 
1133  /// This is a cache to record whether a SCEV contains any scAddRecExpr.
1134  HasRecMapType HasRecMap;
1135 
1136  /// The type for ExprValueMap.
1137  using ValueOffsetPair = std::pair<Value *, ConstantInt *>;
1139 
1140  /// ExprValueMap -- This map records the original values from which
1141  /// the SCEV expr is generated from.
1142  ///
1143  /// We want to represent the mapping as SCEV -> ValueOffsetPair instead
1144  /// of SCEV -> Value:
1145  /// Suppose we know S1 expands to V1, and
1146  /// S1 = S2 + C_a
1147  /// S3 = S2 + C_b
1148  /// where C_a and C_b are different SCEVConstants. Then we'd like to
1149  /// expand S3 as V1 - C_a + C_b instead of expanding S2 literally.
1150  /// It is helpful when S2 is a complex SCEV expr.
1151  ///
1152  /// In order to do that, we represent ExprValueMap as a mapping from
1153  /// SCEV to ValueOffsetPair. We will save both S1->{V1, 0} and
1154  /// S2->{V1, C_a} into the map when we create SCEV for V1. When S3
1155  /// is expanded, it will first expand S2 to V1 - C_a because of
1156  /// S2->{V1, C_a} in the map, then expand S3 to V1 - C_a + C_b.
1157  ///
1158  /// Note: S->{V, Offset} in the ExprValueMap means S can be expanded
1159  /// to V - Offset.
1160  ExprValueMapType ExprValueMap;
1161 
1162  /// The type for ValueExprMap.
1163  using ValueExprMapType =
1165 
1166  /// This is a cache of the values we have analyzed so far.
1167  ValueExprMapType ValueExprMap;
1168 
1169  /// Mark predicate values currently being processed by isImpliedCond.
1170  SmallPtrSet<Value *, 6> PendingLoopPredicates;
1171 
1172  /// Mark SCEVUnknown Phis currently being processed by getRangeRef.
1173  SmallPtrSet<const PHINode *, 6> PendingPhiRanges;
1174 
1175  // Mark SCEVUnknown Phis currently being processed by isImpliedViaMerge.
1176  SmallPtrSet<const PHINode *, 6> PendingMerges;
1177 
1178  /// Set to true by isLoopBackedgeGuardedByCond when we're walking the set of
1179  /// conditions dominating the backedge of a loop.
1180  bool WalkingBEDominatingConds = false;
1181 
1182  /// Set to true by isKnownPredicateViaSplitting when we're trying to prove a
1183  /// predicate by splitting it into a set of independent predicates.
1184  bool ProvingSplitPredicate = false;
1185 
1186  /// Memoized values for the GetMinTrailingZeros
1187  DenseMap<const SCEV *, uint32_t> MinTrailingZerosCache;
1188 
1189  /// Return the Value set from which the SCEV expr is generated.
1190  SetVector<ValueOffsetPair> *getSCEVValues(const SCEV *S);
1191 
1192  /// Private helper method for the GetMinTrailingZeros method
1193  uint32_t GetMinTrailingZerosImpl(const SCEV *S);
1194 
1195  /// Information about the number of loop iterations for which a loop exit's
1196  /// branch condition evaluates to the not-taken path. This is a temporary
1197  /// pair of exact and max expressions that are eventually summarized in
1198  /// ExitNotTakenInfo and BackedgeTakenInfo.
1199  struct ExitLimit {
1200  const SCEV *ExactNotTaken; // The exit is not taken exactly this many times
1201  const SCEV *MaxNotTaken; // The exit is not taken at most this many times
1202 
1203  // Not taken either exactly MaxNotTaken or zero times
1204  bool MaxOrZero = false;
1205 
1206  /// A set of predicate guards for this ExitLimit. The result is only valid
1207  /// if all of the predicates in \c Predicates evaluate to 'true' at
1208  /// run-time.
1210 
1211  void addPredicate(const SCEVPredicate *P) {
1212  assert(!isa<SCEVUnionPredicate>(P) && "Only add leaf predicates here!");
1213  Predicates.insert(P);
1214  }
1215 
1216  /*implicit*/ ExitLimit(const SCEV *E);
1217 
1218  ExitLimit(
1219  const SCEV *E, const SCEV *M, bool MaxOrZero,
1220  ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList);
1221 
1222  ExitLimit(const SCEV *E, const SCEV *M, bool MaxOrZero,
1224 
1225  ExitLimit(const SCEV *E, const SCEV *M, bool MaxOrZero);
1226 
1227  /// Test whether this ExitLimit contains any computed information, or
1228  /// whether it's all SCEVCouldNotCompute values.
1229  bool hasAnyInfo() const {
1230  return !isa<SCEVCouldNotCompute>(ExactNotTaken) ||
1231  !isa<SCEVCouldNotCompute>(MaxNotTaken);
1232  }
1233 
1234  bool hasOperand(const SCEV *S) const;
1235 
1236  /// Test whether this ExitLimit contains all information.
1237  bool hasFullInfo() const {
1238  return !isa<SCEVCouldNotCompute>(ExactNotTaken);
1239  }
1240  };
1241 
1242  /// Information about the number of times a particular loop exit may be
1243  /// reached before exiting the loop.
1244  struct ExitNotTakenInfo {
1245  PoisoningVH<BasicBlock> ExitingBlock;
1246  const SCEV *ExactNotTaken;
1247  std::unique_ptr<SCEVUnionPredicate> Predicate;
1248 
1249  explicit ExitNotTakenInfo(PoisoningVH<BasicBlock> ExitingBlock,
1250  const SCEV *ExactNotTaken,
1251  std::unique_ptr<SCEVUnionPredicate> Predicate)
1252  : ExitingBlock(ExitingBlock), ExactNotTaken(ExactNotTaken),
1253  Predicate(std::move(Predicate)) {}
1254 
1255  bool hasAlwaysTruePredicate() const {
1256  return !Predicate || Predicate->isAlwaysTrue();
1257  }
1258  };
1259 
1260  /// Information about the backedge-taken count of a loop. This currently
1261  /// includes an exact count and a maximum count.
1262  ///
1263  class BackedgeTakenInfo {
1264  /// A list of computable exits and their not-taken counts. Loops almost
1265  /// never have more than one computable exit.
1266  SmallVector<ExitNotTakenInfo, 1> ExitNotTaken;
1267 
1268  /// The pointer part of \c MaxAndComplete is an expression indicating the
1269  /// least maximum backedge-taken count of the loop that is known, or a
1270  /// SCEVCouldNotCompute. This expression is only valid if the predicates
1271  /// associated with all loop exits are true.
1272  ///
1273  /// The integer part of \c MaxAndComplete is a boolean indicating if \c
1274  /// ExitNotTaken has an element for every exiting block in the loop.
1275  PointerIntPair<const SCEV *, 1> MaxAndComplete;
1276 
1277  /// True iff the backedge is taken either exactly Max or zero times.
1278  bool MaxOrZero = false;
1279 
1280  /// \name Helper projection functions on \c MaxAndComplete.
1281  /// @{
1282  bool isComplete() const { return MaxAndComplete.getInt(); }
1283  const SCEV *getMax() const { return MaxAndComplete.getPointer(); }
1284  /// @}
1285 
1286  public:
1287  BackedgeTakenInfo() : MaxAndComplete(nullptr, 0) {}
1288  BackedgeTakenInfo(BackedgeTakenInfo &&) = default;
1289  BackedgeTakenInfo &operator=(BackedgeTakenInfo &&) = default;
1290 
1291  using EdgeExitInfo = std::pair<BasicBlock *, ExitLimit>;
1292 
1293  /// Initialize BackedgeTakenInfo from a list of exact exit counts.
1294  BackedgeTakenInfo(ArrayRef<EdgeExitInfo> ExitCounts, bool Complete,
1295  const SCEV *MaxCount, bool MaxOrZero);
1296 
1297  /// Test whether this BackedgeTakenInfo contains any computed information,
1298  /// or whether it's all SCEVCouldNotCompute values.
1299  bool hasAnyInfo() const {
1300  return !ExitNotTaken.empty() || !isa<SCEVCouldNotCompute>(getMax());
1301  }
1302 
1303  /// Test whether this BackedgeTakenInfo contains complete information.
1304  bool hasFullInfo() const { return isComplete(); }
1305 
1306  /// Return an expression indicating the exact *backedge-taken*
1307  /// count of the loop if it is known or SCEVCouldNotCompute
1308  /// otherwise. If execution makes it to the backedge on every
1309  /// iteration (i.e. there are no abnormal exists like exception
1310  /// throws and thread exits) then this is the number of times the
1311  /// loop header will execute minus one.
1312  ///
1313  /// If the SCEV predicate associated with the answer can be different
1314  /// from AlwaysTrue, we must add a (non null) Predicates argument.
1315  /// The SCEV predicate associated with the answer will be added to
1316  /// Predicates. A run-time check needs to be emitted for the SCEV
1317  /// predicate in order for the answer to be valid.
1318  ///
1319  /// Note that we should always know if we need to pass a predicate
1320  /// argument or not from the way the ExitCounts vector was computed.
1321  /// If we allowed SCEV predicates to be generated when populating this
1322  /// vector, this information can contain them and therefore a
1323  /// SCEVPredicate argument should be added to getExact.
1324  const SCEV *getExact(const Loop *L, ScalarEvolution *SE,
1325  SCEVUnionPredicate *Predicates = nullptr) const;
1326 
1327  /// Return the number of times this loop exit may fall through to the back
1328  /// edge, or SCEVCouldNotCompute. The loop is guaranteed not to exit via
1329  /// this block before this number of iterations, but may exit via another
1330  /// block.
1331  const SCEV *getExact(BasicBlock *ExitingBlock, ScalarEvolution *SE) const;
1332 
1333  /// Get the max backedge taken count for the loop.
1334  const SCEV *getMax(ScalarEvolution *SE) const;
1335 
1336  /// Return true if the number of times this backedge is taken is either the
1337  /// value returned by getMax or zero.
1338  bool isMaxOrZero(ScalarEvolution *SE) const;
1339 
1340  /// Return true if any backedge taken count expressions refer to the given
1341  /// subexpression.
1342  bool hasOperand(const SCEV *S, ScalarEvolution *SE) const;
1343 
1344  /// Invalidate this result and free associated memory.
1345  void clear();
1346  };
1347 
1348  /// Cache the backedge-taken count of the loops for this function as they
1349  /// are computed.
1350  DenseMap<const Loop *, BackedgeTakenInfo> BackedgeTakenCounts;
1351 
1352  /// Cache the predicated backedge-taken count of the loops for this
1353  /// function as they are computed.
1354  DenseMap<const Loop *, BackedgeTakenInfo> PredicatedBackedgeTakenCounts;
1355 
1356  /// This map contains entries for all of the PHI instructions that we
1357  /// attempt to compute constant evolutions for. This allows us to avoid
1358  /// potentially expensive recomputation of these properties. An instruction
1359  /// maps to null if we are unable to compute its exit value.
1360  DenseMap<PHINode *, Constant *> ConstantEvolutionLoopExitValue;
1361 
1362  /// This map contains entries for all the expressions that we attempt to
1363  /// compute getSCEVAtScope information for, which can be expensive in
1364  /// extreme cases.
1366  ValuesAtScopes;
1367 
1368  /// Memoized computeLoopDisposition results.
1369  DenseMap<const SCEV *,
1371  LoopDispositions;
1372 
1373  struct LoopProperties {
1374  /// Set to true if the loop contains no instruction that can have side
1375  /// effects (i.e. via throwing an exception, volatile or atomic access).
1376  bool HasNoAbnormalExits;
1377 
1378  /// Set to true if the loop contains no instruction that can abnormally exit
1379  /// the loop (i.e. via throwing an exception, by terminating the thread
1380  /// cleanly or by infinite looping in a called function). Strictly
1381  /// speaking, the last one is not leaving the loop, but is identical to
1382  /// leaving the loop for reasoning about undefined behavior.
1383  bool HasNoSideEffects;
1384  };
1385 
1386  /// Cache for \c getLoopProperties.
1387  DenseMap<const Loop *, LoopProperties> LoopPropertiesCache;
1388 
1389  /// Return a \c LoopProperties instance for \p L, creating one if necessary.
1390  LoopProperties getLoopProperties(const Loop *L);
1391 
1392  bool loopHasNoSideEffects(const Loop *L) {
1393  return getLoopProperties(L).HasNoSideEffects;
1394  }
1395 
1396  bool loopHasNoAbnormalExits(const Loop *L) {
1397  return getLoopProperties(L).HasNoAbnormalExits;
1398  }
1399 
1400  /// Compute a LoopDisposition value.
1401  LoopDisposition computeLoopDisposition(const SCEV *S, const Loop *L);
1402 
1403  /// Memoized computeBlockDisposition results.
1404  DenseMap<
1405  const SCEV *,
1407  BlockDispositions;
1408 
1409  /// Compute a BlockDisposition value.
1410  BlockDisposition computeBlockDisposition(const SCEV *S, const BasicBlock *BB);
1411 
1412  /// Memoized results from getRange
1414 
1415  /// Memoized results from getRange
1417 
1418  /// Used to parameterize getRange
1419  enum RangeSignHint { HINT_RANGE_UNSIGNED, HINT_RANGE_SIGNED };
1420 
1421  /// Set the memoized range for the given SCEV.
1422  const ConstantRange &setRange(const SCEV *S, RangeSignHint Hint,
1423  ConstantRange CR) {
1425  Hint == HINT_RANGE_UNSIGNED ? UnsignedRanges : SignedRanges;
1426 
1427  auto Pair = Cache.try_emplace(S, std::move(CR));
1428  if (!Pair.second)
1429  Pair.first->second = std::move(CR);
1430  return Pair.first->second;
1431  }
1432 
1433  /// Determine the range for a particular SCEV.
1434  /// NOTE: This returns a reference to an entry in a cache. It must be
1435  /// copied if its needed for longer.
1436  const ConstantRange &getRangeRef(const SCEV *S, RangeSignHint Hint);
1437 
1438  /// Determines the range for the affine SCEVAddRecExpr {\p Start,+,\p Stop}.
1439  /// Helper for \c getRange.
1440  ConstantRange getRangeForAffineAR(const SCEV *Start, const SCEV *Stop,
1441  const SCEV *MaxBECount, unsigned BitWidth);
1442 
1443  /// Try to compute a range for the affine SCEVAddRecExpr {\p Start,+,\p
1444  /// Stop} by "factoring out" a ternary expression from the add recurrence.
1445  /// Helper called by \c getRange.
1446  ConstantRange getRangeViaFactoring(const SCEV *Start, const SCEV *Stop,
1447  const SCEV *MaxBECount, unsigned BitWidth);
1448 
1449  /// We know that there is no SCEV for the specified value. Analyze the
1450  /// expression.
1451  const SCEV *createSCEV(Value *V);
1452 
1453  /// Provide the special handling we need to analyze PHI SCEVs.
1454  const SCEV *createNodeForPHI(PHINode *PN);
1455 
1456  /// Helper function called from createNodeForPHI.
1457  const SCEV *createAddRecFromPHI(PHINode *PN);
1458 
1459  /// A helper function for createAddRecFromPHI to handle simple cases.
1460  const SCEV *createSimpleAffineAddRec(PHINode *PN, Value *BEValueV,
1461  Value *StartValueV);
1462 
1463  /// Helper function called from createNodeForPHI.
1464  const SCEV *createNodeFromSelectLikePHI(PHINode *PN);
1465 
1466  /// Provide special handling for a select-like instruction (currently this
1467  /// is either a select instruction or a phi node). \p I is the instruction
1468  /// being processed, and it is assumed equivalent to "Cond ? TrueVal :
1469  /// FalseVal".
1470  const SCEV *createNodeForSelectOrPHI(Instruction *I, Value *Cond,
1471  Value *TrueVal, Value *FalseVal);
1472 
1473  /// Provide the special handling we need to analyze GEP SCEVs.
1474  const SCEV *createNodeForGEP(GEPOperator *GEP);
1475 
1476  /// Implementation code for getSCEVAtScope; called at most once for each
1477  /// SCEV+Loop pair.
1478  const SCEV *computeSCEVAtScope(const SCEV *S, const Loop *L);
1479 
1480  /// This looks up computed SCEV values for all instructions that depend on
1481  /// the given instruction and removes them from the ValueExprMap map if they
1482  /// reference SymName. This is used during PHI resolution.
1483  void forgetSymbolicName(Instruction *I, const SCEV *SymName);
1484 
1485  /// Return the BackedgeTakenInfo for the given loop, lazily computing new
1486  /// values if the loop hasn't been analyzed yet. The returned result is
1487  /// guaranteed not to be predicated.
1488  const BackedgeTakenInfo &getBackedgeTakenInfo(const Loop *L);
1489 
1490  /// Similar to getBackedgeTakenInfo, but will add predicates as required
1491  /// with the purpose of returning complete information.
1492  const BackedgeTakenInfo &getPredicatedBackedgeTakenInfo(const Loop *L);
1493 
1494  /// Compute the number of times the specified loop will iterate.
1495  /// If AllowPredicates is set, we will create new SCEV predicates as
1496  /// necessary in order to return an exact answer.
1497  BackedgeTakenInfo computeBackedgeTakenCount(const Loop *L,
1498  bool AllowPredicates = false);
1499 
1500  /// Compute the number of times the backedge of the specified loop will
1501  /// execute if it exits via the specified block. If AllowPredicates is set,
1502  /// this call will try to use a minimal set of SCEV predicates in order to
1503  /// return an exact answer.
1504  ExitLimit computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
1505  bool AllowPredicates = false);
1506 
1507  /// Compute the number of times the backedge of the specified loop will
1508  /// execute if its exit condition were a conditional branch of ExitCond.
1509  ///
1510  /// \p ControlsExit is true if ExitCond directly controls the exit
1511  /// branch. In this case, we can assume that the loop exits only if the
1512  /// condition is true and can infer that failing to meet the condition prior
1513  /// to integer wraparound results in undefined behavior.
1514  ///
1515  /// If \p AllowPredicates is set, this call will try to use a minimal set of
1516  /// SCEV predicates in order to return an exact answer.
1517  ExitLimit computeExitLimitFromCond(const Loop *L, Value *ExitCond,
1518  bool ExitIfTrue, bool ControlsExit,
1519  bool AllowPredicates = false);
1520 
1521  // Helper functions for computeExitLimitFromCond to avoid exponential time
1522  // complexity.
1523 
1524  class ExitLimitCache {
1525  // It may look like we need key on the whole (L, ExitIfTrue, ControlsExit,
1526  // AllowPredicates) tuple, but recursive calls to
1527  // computeExitLimitFromCondCached from computeExitLimitFromCondImpl only
1528  // vary the in \c ExitCond and \c ControlsExit parameters. We remember the
1529  // initial values of the other values to assert our assumption.
1530  SmallDenseMap<PointerIntPair<Value *, 1>, ExitLimit> TripCountMap;
1531 
1532  const Loop *L;
1533  bool ExitIfTrue;
1534  bool AllowPredicates;
1535 
1536  public:
1537  ExitLimitCache(const Loop *L, bool ExitIfTrue, bool AllowPredicates)
1538  : L(L), ExitIfTrue(ExitIfTrue), AllowPredicates(AllowPredicates) {}
1539 
1540  Optional<ExitLimit> find(const Loop *L, Value *ExitCond, bool ExitIfTrue,
1541  bool ControlsExit, bool AllowPredicates);
1542 
1543  void insert(const Loop *L, Value *ExitCond, bool ExitIfTrue,
1544  bool ControlsExit, bool AllowPredicates, const ExitLimit &EL);
1545  };
1546 
1547  using ExitLimitCacheTy = ExitLimitCache;
1548 
1549  ExitLimit computeExitLimitFromCondCached(ExitLimitCacheTy &Cache,
1550  const Loop *L, Value *ExitCond,
1551  bool ExitIfTrue,
1552  bool ControlsExit,
1553  bool AllowPredicates);
1554  ExitLimit computeExitLimitFromCondImpl(ExitLimitCacheTy &Cache, const Loop *L,
1555  Value *ExitCond, bool ExitIfTrue,
1556  bool ControlsExit,
1557  bool AllowPredicates);
1558 
1559  /// Compute the number of times the backedge of the specified loop will
1560  /// execute if its exit condition were a conditional branch of the ICmpInst
1561  /// ExitCond and ExitIfTrue. If AllowPredicates is set, this call will try
1562  /// to use a minimal set of SCEV predicates in order to return an exact
1563  /// answer.
1564  ExitLimit computeExitLimitFromICmp(const Loop *L, ICmpInst *ExitCond,
1565  bool ExitIfTrue,
1566  bool IsSubExpr,
1567  bool AllowPredicates = false);
1568 
1569  /// Compute the number of times the backedge of the specified loop will
1570  /// execute if its exit condition were a switch with a single exiting case
1571  /// to ExitingBB.
1572  ExitLimit computeExitLimitFromSingleExitSwitch(const Loop *L,
1573  SwitchInst *Switch,
1574  BasicBlock *ExitingBB,
1575  bool IsSubExpr);
1576 
1577  /// Given an exit condition of 'icmp op load X, cst', try to see if we can
1578  /// compute the backedge-taken count.
1579  ExitLimit computeLoadConstantCompareExitLimit(LoadInst *LI, Constant *RHS,
1580  const Loop *L,
1582 
1583  /// Compute the exit limit of a loop that is controlled by a
1584  /// "(IV >> 1) != 0" type comparison. We cannot compute the exact trip
1585  /// count in these cases (since SCEV has no way of expressing them), but we
1586  /// can still sometimes compute an upper bound.
1587  ///
1588  /// Return an ExitLimit for a loop whose backedge is guarded by `LHS Pred
1589  /// RHS`.
1590  ExitLimit computeShiftCompareExitLimit(Value *LHS, Value *RHS, const Loop *L,
1591  ICmpInst::Predicate Pred);
1592 
1593  /// If the loop is known to execute a constant number of times (the
1594  /// condition evolves only from constants), try to evaluate a few iterations
1595  /// of the loop until we get the exit condition gets a value of ExitWhen
1596  /// (true or false). If we cannot evaluate the exit count of the loop,
1597  /// return CouldNotCompute.
1598  const SCEV *computeExitCountExhaustively(const Loop *L, Value *Cond,
1599  bool ExitWhen);
1600 
1601  /// Return the number of times an exit condition comparing the specified
1602  /// value to zero will execute. If not computable, return CouldNotCompute.
1603  /// If AllowPredicates is set, this call will try to use a minimal set of
1604  /// SCEV predicates in order to return an exact answer.
1605  ExitLimit howFarToZero(const SCEV *V, const Loop *L, bool IsSubExpr,
1606  bool AllowPredicates = false);
1607 
1608  /// Return the number of times an exit condition checking the specified
1609  /// value for nonzero will execute. If not computable, return
1610  /// CouldNotCompute.
1611  ExitLimit howFarToNonZero(const SCEV *V, const Loop *L);
1612 
1613  /// Return the number of times an exit condition containing the specified
1614  /// less-than comparison will execute. If not computable, return
1615  /// CouldNotCompute.
1616  ///
1617  /// \p isSigned specifies whether the less-than is signed.
1618  ///
1619  /// \p ControlsExit is true when the LHS < RHS condition directly controls
1620  /// the branch (loops exits only if condition is true). In this case, we can
1621  /// use NoWrapFlags to skip overflow checks.
1622  ///
1623  /// If \p AllowPredicates is set, this call will try to use a minimal set of
1624  /// SCEV predicates in order to return an exact answer.
1625  ExitLimit howManyLessThans(const SCEV *LHS, const SCEV *RHS, const Loop *L,
1626  bool isSigned, bool ControlsExit,
1627  bool AllowPredicates = false);
1628 
1629  ExitLimit howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, const Loop *L,
1630  bool isSigned, bool IsSubExpr,
1631  bool AllowPredicates = false);
1632 
1633  /// Return a predecessor of BB (which may not be an immediate predecessor)
1634  /// which has exactly one successor from which BB is reachable, or null if
1635  /// no such block is found.
1636  std::pair<BasicBlock *, BasicBlock *>
1637  getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
1638 
1639  /// Test whether the condition described by Pred, LHS, and RHS is true
1640  /// whenever the given FoundCondValue value evaluates to true.
1641  bool isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
1642  Value *FoundCondValue, bool Inverse);
1643 
1644  /// Test whether the condition described by Pred, LHS, and RHS is true
1645  /// whenever the condition described by FoundPred, FoundLHS, FoundRHS is
1646  /// true.
1647  bool isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
1648  ICmpInst::Predicate FoundPred, const SCEV *FoundLHS,
1649  const SCEV *FoundRHS);
1650 
1651  /// Test whether the condition described by Pred, LHS, and RHS is true
1652  /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
1653  /// true.
1654  bool isImpliedCondOperands(ICmpInst::Predicate Pred, const SCEV *LHS,
1655  const SCEV *RHS, const SCEV *FoundLHS,
1656  const SCEV *FoundRHS);
1657 
1658  /// Test whether the condition described by Pred, LHS, and RHS is true
1659  /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
1660  /// true. Here LHS is an operation that includes FoundLHS as one of its
1661  /// arguments.
1662  bool isImpliedViaOperations(ICmpInst::Predicate Pred,
1663  const SCEV *LHS, const SCEV *RHS,
1664  const SCEV *FoundLHS, const SCEV *FoundRHS,
1665  unsigned Depth = 0);
1666 
1667  /// Test whether the condition described by Pred, LHS, and RHS is true.
1668  /// Use only simple non-recursive types of checks, such as range analysis etc.
1669  bool isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
1670  const SCEV *LHS, const SCEV *RHS);
1671 
1672  /// Test whether the condition described by Pred, LHS, and RHS is true
1673  /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
1674  /// true.
1675  bool isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, const SCEV *LHS,
1676  const SCEV *RHS, const SCEV *FoundLHS,
1677  const SCEV *FoundRHS);
1678 
1679  /// Test whether the condition described by Pred, LHS, and RHS is true
1680  /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
1681  /// true. Utility function used by isImpliedCondOperands. Tries to get
1682  /// cases like "X `sgt` 0 => X - 1 `sgt` -1".
1683  bool isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, const SCEV *LHS,
1684  const SCEV *RHS, const SCEV *FoundLHS,
1685  const SCEV *FoundRHS);
1686 
1687  /// Return true if the condition denoted by \p LHS \p Pred \p RHS is implied
1688  /// by a call to \c @llvm.experimental.guard in \p BB.
1689  bool isImpliedViaGuard(BasicBlock *BB, ICmpInst::Predicate Pred,
1690  const SCEV *LHS, const SCEV *RHS);
1691 
1692  /// Test whether the condition described by Pred, LHS, and RHS is true
1693  /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
1694  /// true.
1695  ///
1696  /// This routine tries to rule out certain kinds of integer overflow, and
1697  /// then tries to reason about arithmetic properties of the predicates.
1698  bool isImpliedCondOperandsViaNoOverflow(ICmpInst::Predicate Pred,
1699  const SCEV *LHS, const SCEV *RHS,
1700  const SCEV *FoundLHS,
1701  const SCEV *FoundRHS);
1702 
1703  /// Test whether the condition described by Pred, LHS, and RHS is true
1704  /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
1705  /// true.
1706  ///
1707  /// This routine tries to figure out predicate for Phis which are SCEVUnknown
1708  /// if it is true for every possible incoming value from their respective
1709  /// basic blocks.
1710  bool isImpliedViaMerge(ICmpInst::Predicate Pred,
1711  const SCEV *LHS, const SCEV *RHS,
1712  const SCEV *FoundLHS, const SCEV *FoundRHS,
1713  unsigned Depth);
1714 
1715  /// If we know that the specified Phi is in the header of its containing
1716  /// loop, we know the loop executes a constant number of times, and the PHI
1717  /// node is just a recurrence involving constants, fold it.
1718  Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt &BEs,
1719  const Loop *L);
1720 
1721  /// Test if the given expression is known to satisfy the condition described
1722  /// by Pred and the known constant ranges of LHS and RHS.
1723  bool isKnownPredicateViaConstantRanges(ICmpInst::Predicate Pred,
1724  const SCEV *LHS, const SCEV *RHS);
1725 
1726  /// Try to prove the condition described by "LHS Pred RHS" by ruling out
1727  /// integer overflow.
1728  ///
1729  /// For instance, this will return true for "A s< (A + C)<nsw>" if C is
1730  /// positive.
1731  bool isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, const SCEV *LHS,
1732  const SCEV *RHS);
1733 
1734  /// Try to split Pred LHS RHS into logical conjunctions (and's) and try to
1735  /// prove them individually.
1736  bool isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, const SCEV *LHS,
1737  const SCEV *RHS);
1738 
1739  /// Try to match the Expr as "(L + R)<Flags>".
1740  bool splitBinaryAdd(const SCEV *Expr, const SCEV *&L, const SCEV *&R,
1741  SCEV::NoWrapFlags &Flags);
1742 
1743  /// Compute \p LHS - \p RHS and returns the result as an APInt if it is a
1744  /// constant, and None if it isn't.
1745  ///
1746  /// This is intended to be a cheaper version of getMinusSCEV. We can be
1747  /// frugal here since we just bail out of actually constructing and
1748  /// canonicalizing an expression in the cases where the result isn't going
1749  /// to be a constant.
1750  Optional<APInt> computeConstantDifference(const SCEV *LHS, const SCEV *RHS);
1751 
1752  /// Drop memoized information computed for S.
1753  void forgetMemoizedResults(const SCEV *S);
1754 
1755  /// Return an existing SCEV for V if there is one, otherwise return nullptr.
1756  const SCEV *getExistingSCEV(Value *V);
1757 
1758  /// Return false iff given SCEV contains a SCEVUnknown with NULL value-
1759  /// pointer.
1760  bool checkValidity(const SCEV *S) const;
1761 
1762  /// Return true if `ExtendOpTy`({`Start`,+,`Step`}) can be proved to be
1763  /// equal to {`ExtendOpTy`(`Start`),+,`ExtendOpTy`(`Step`)}. This is
1764  /// equivalent to proving no signed (resp. unsigned) wrap in
1765  /// {`Start`,+,`Step`} if `ExtendOpTy` is `SCEVSignExtendExpr`
1766  /// (resp. `SCEVZeroExtendExpr`).
1767  template <typename ExtendOpTy>
1768  bool proveNoWrapByVaryingStart(const SCEV *Start, const SCEV *Step,
1769  const Loop *L);
1770 
1771  /// Try to prove NSW or NUW on \p AR relying on ConstantRange manipulation.
1772  SCEV::NoWrapFlags proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR);
1773 
1774  bool isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
1775  ICmpInst::Predicate Pred, bool &Increasing);
1776 
1777  /// Return SCEV no-wrap flags that can be proven based on reasoning about
1778  /// how poison produced from no-wrap flags on this value (e.g. a nuw add)
1779  /// would trigger undefined behavior on overflow.
1780  SCEV::NoWrapFlags getNoWrapFlagsFromUB(const Value *V);
1781 
1782  /// Return true if the SCEV corresponding to \p I is never poison. Proving
1783  /// this is more complex than proving that just \p I is never poison, since
1784  /// SCEV commons expressions across control flow, and you can have cases
1785  /// like:
1786  ///
1787  /// idx0 = a + b;
1788  /// ptr[idx0] = 100;
1789  /// if (<condition>) {
1790  /// idx1 = a +nsw b;
1791  /// ptr[idx1] = 200;
1792  /// }
1793  ///
1794  /// where the SCEV expression (+ a b) is guaranteed to not be poison (and
1795  /// hence not sign-overflow) only if "<condition>" is true. Since both
1796  /// `idx0` and `idx1` will be mapped to the same SCEV expression, (+ a b),
1797  /// it is not okay to annotate (+ a b) with <nsw> in the above example.
1798  bool isSCEVExprNeverPoison(const Instruction *I);
1799 
1800  /// This is like \c isSCEVExprNeverPoison but it specifically works for
1801  /// instructions that will get mapped to SCEV add recurrences. Return true
1802  /// if \p I will never generate poison under the assumption that \p I is an
1803  /// add recurrence on the loop \p L.
1804  bool isAddRecNeverPoison(const Instruction *I, const Loop *L);
1805 
1806  /// Similar to createAddRecFromPHI, but with the additional flexibility of
1807  /// suggesting runtime overflow checks in case casts are encountered.
1808  /// If successful, the analysis records that for this loop, \p SymbolicPHI,
1809  /// which is the UnknownSCEV currently representing the PHI, can be rewritten
1810  /// into an AddRec, assuming some predicates; The function then returns the
1811  /// AddRec and the predicates as a pair, and caches this pair in
1812  /// PredicatedSCEVRewrites.
1813  /// If the analysis is not successful, a mapping from the \p SymbolicPHI to
1814  /// itself (with no predicates) is recorded, and a nullptr with an empty
1815  /// predicates vector is returned as a pair.
1817  createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI);
1818 
1819  /// Compute the backedge taken count knowing the interval difference, the
1820  /// stride and presence of the equality in the comparison.
1821  const SCEV *computeBECount(const SCEV *Delta, const SCEV *Stride,
1822  bool Equality);
1823 
1824  /// Compute the maximum backedge count based on the range of values
1825  /// permitted by Start, End, and Stride. This is for loops of the form
1826  /// {Start, +, Stride} LT End.
1827  ///
1828  /// Precondition: the induction variable is known to be positive. We *don't*
1829  /// assert these preconditions so please be careful.
1830  const SCEV *computeMaxBECountForLT(const SCEV *Start, const SCEV *Stride,
1831  const SCEV *End, unsigned BitWidth,
1832  bool IsSigned);
1833 
1834  /// Verify if an linear IV with positive stride can overflow when in a
1835  /// less-than comparison, knowing the invariant term of the comparison,
1836  /// the stride and the knowledge of NSW/NUW flags on the recurrence.
1837  bool doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, bool IsSigned,
1838  bool NoWrap);
1839 
1840  /// Verify if an linear IV with negative stride can overflow when in a
1841  /// greater-than comparison, knowing the invariant term of the comparison,
1842  /// the stride and the knowledge of NSW/NUW flags on the recurrence.
1843  bool doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, bool IsSigned,
1844  bool NoWrap);
1845 
1846  /// Get add expr already created or create a new one.
1847  const SCEV *getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
1848  SCEV::NoWrapFlags Flags);
1849 
1850  /// Get mul expr already created or create a new one.
1851  const SCEV *getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
1852  SCEV::NoWrapFlags Flags);
1853 
1854  // Get addrec expr already created or create a new one.
1855  const SCEV *getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
1856  const Loop *L, SCEV::NoWrapFlags Flags);
1857 
1858  /// Return x if \p Val is f(x) where f is a 1-1 function.
1859  const SCEV *stripInjectiveFunctions(const SCEV *Val) const;
1860 
1861  /// Find all of the loops transitively used in \p S, and fill \p LoopsUsed.
1862  /// A loop is considered "used" by an expression if it contains
1863  /// an add rec on said loop.
1864  void getUsedLoops(const SCEV *S, SmallPtrSetImpl<const Loop *> &LoopsUsed);
1865 
1866  /// Find all of the loops transitively used in \p S, and update \c LoopUsers
1867  /// accordingly.
1868  void addToLoopUseLists(const SCEV *S);
1869 
1870  /// Try to match the pattern generated by getURemExpr(A, B). If successful,
1871  /// Assign A and B to LHS and RHS, respectively.
1872  bool matchURem(const SCEV *Expr, const SCEV *&LHS, const SCEV *&RHS);
1873 
1874  FoldingSet<SCEV> UniqueSCEVs;
1875  FoldingSet<SCEVPredicate> UniquePreds;
1876  BumpPtrAllocator SCEVAllocator;
1877 
1878  /// This maps loops to a list of SCEV expressions that (transitively) use said
1879  /// loop.
1881 
1882  /// Cache tentative mappings from UnknownSCEVs in a Loop, to a SCEV expression
1883  /// they can be rewritten into under certain predicates.
1885  std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
1886  PredicatedSCEVRewrites;
1887 
1888  /// The head of a linked list of all SCEVUnknown values that have been
1889  /// allocated. This is used by releaseMemory to locate them all and call
1890  /// their destructors.
1891  SCEVUnknown *FirstUnknown = nullptr;
1892 };
1893 
1894 /// Analysis pass that exposes the \c ScalarEvolution for a function.
1896  : public AnalysisInfoMixin<ScalarEvolutionAnalysis> {
1898 
1899  static AnalysisKey Key;
1900 
1901 public:
1903 
1905 };
1906 
1907 /// Printer pass for the \c ScalarEvolutionAnalysis results.
1909  : public PassInfoMixin<ScalarEvolutionPrinterPass> {
1910  raw_ostream &OS;
1911 
1912 public:
1913  explicit ScalarEvolutionPrinterPass(raw_ostream &OS) : OS(OS) {}
1914 
1916 };
1917 
1919  std::unique_ptr<ScalarEvolution> SE;
1920 
1921 public:
1922  static char ID;
1923 
1925 
1926  ScalarEvolution &getSE() { return *SE; }
1927  const ScalarEvolution &getSE() const { return *SE; }
1928 
1929  bool runOnFunction(Function &F) override;
1930  void releaseMemory() override;
1931  void getAnalysisUsage(AnalysisUsage &AU) const override;
1932  void print(raw_ostream &OS, const Module * = nullptr) const override;
1933  void verifyAnalysis() const override;
1934 };
1935 
1936 /// An interface layer with SCEV used to manage how we see SCEV expressions
1937 /// for values in the context of existing predicates. We can add new
1938 /// predicates, but we cannot remove them.
1939 ///
1940 /// This layer has multiple purposes:
1941 /// - provides a simple interface for SCEV versioning.
1942 /// - guarantees that the order of transformations applied on a SCEV
1943 /// expression for a single Value is consistent across two different
1944 /// getSCEV calls. This means that, for example, once we've obtained
1945 /// an AddRec expression for a certain value through expression
1946 /// rewriting, we will continue to get an AddRec expression for that
1947 /// Value.
1948 /// - lowers the number of expression rewrites.
1950 public:
1952 
1953  const SCEVUnionPredicate &getUnionPredicate() const;
1954 
1955  /// Returns the SCEV expression of V, in the context of the current SCEV
1956  /// predicate. The order of transformations applied on the expression of V
1957  /// returned by ScalarEvolution is guaranteed to be preserved, even when
1958  /// adding new predicates.
1959  const SCEV *getSCEV(Value *V);
1960 
1961  /// Get the (predicated) backedge count for the analyzed loop.
1962  const SCEV *getBackedgeTakenCount();
1963 
1964  /// Adds a new predicate.
1965  void addPredicate(const SCEVPredicate &Pred);
1966 
1967  /// Attempts to produce an AddRecExpr for V by adding additional SCEV
1968  /// predicates. If we can't transform the expression into an AddRecExpr we
1969  /// return nullptr and not add additional SCEV predicates to the current
1970  /// context.
1971  const SCEVAddRecExpr *getAsAddRec(Value *V);
1972 
1973  /// Proves that V doesn't overflow by adding SCEV predicate.
1974  void setNoOverflow(Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags);
1975 
1976  /// Returns true if we've proved that V doesn't wrap by means of a SCEV
1977  /// predicate.
1978  bool hasNoOverflow(Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags);
1979 
1980  /// Returns the ScalarEvolution analysis used.
1981  ScalarEvolution *getSE() const { return &SE; }
1982 
1983  /// We need to explicitly define the copy constructor because of FlagsMap.
1985 
1986  /// Print the SCEV mappings done by the Predicated Scalar Evolution.
1987  /// The printed text is indented by \p Depth.
1988  void print(raw_ostream &OS, unsigned Depth) const;
1989 
1990  /// Check if \p AR1 and \p AR2 are equal, while taking into account
1991  /// Equal predicates in Preds.
1992  bool areAddRecsEqualWithPreds(const SCEVAddRecExpr *AR1,
1993  const SCEVAddRecExpr *AR2) const;
1994 
1995 private:
1996  /// Increments the version number of the predicate. This needs to be called
1997  /// every time the SCEV predicate changes.
1998  void updateGeneration();
1999 
2000  /// Holds a SCEV and the version number of the SCEV predicate used to
2001  /// perform the rewrite of the expression.
2002  using RewriteEntry = std::pair<unsigned, const SCEV *>;
2003 
2004  /// Maps a SCEV to the rewrite result of that SCEV at a certain version
2005  /// number. If this number doesn't match the current Generation, we will
2006  /// need to do a rewrite. To preserve the transformation order of previous
2007  /// rewrites, we will rewrite the previous result instead of the original
2008  /// SCEV.
2010 
2011  /// Records what NoWrap flags we've added to a Value *.
2013 
2014  /// The ScalarEvolution analysis.
2015  ScalarEvolution &SE;
2016 
2017  /// The analyzed Loop.
2018  const Loop &L;
2019 
2020  /// The SCEVPredicate that forms our context. We will rewrite all
2021  /// expressions assuming that this predicate true.
2022  SCEVUnionPredicate Preds;
2023 
2024  /// Marks the version of the SCEV predicate used. When rewriting a SCEV
2025  /// expression we mark it with the version of the predicate. We use this to
2026  /// figure out if the predicate has changed from the last rewrite of the
2027  /// SCEV. If so, we need to perform a new rewrite.
2028  unsigned Generation = 0;
2029 
2030  /// The backedge taken count.
2031  const SCEV *BackedgeCount = nullptr;
2032 };
2033 
2034 } // end namespace llvm
2035 
2036 #endif // LLVM_ANALYSIS_SCALAREVOLUTION_H
ExitLimitQuery(const Loop *L, BasicBlock *ExitingBlock, bool AllowPredicates)
bool isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Returns true if the given value is known be positive (i.e.
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:110
Type
MessagePack types as defined in the standard, with the exception of Integer being divided into a sign...
Definition: MsgPackReader.h:48
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
const ScalarEvolution & getSE() const
static Type * getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1)
static bool isLoopInvariant(Value *V, const Loop *L, const DominatorTree *DT)
Perform a quick domtree based check for loop invariance assuming that V is used within the loop...
This class represents lattice values for constants.
Definition: AllocatorList.h:23
SCEV & operator=(const SCEV &)=delete
PointerTy getPointer() const
Various leaf nodes.
Definition: ISDOpcodes.h:59
static unsigned ComputeHash(const SCEVPredicate &X, FoldingSetNodeID &TempID)
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
void dump() const
This method is used for debugging.
const unsigned short ExpressionSize
The main scalar evolution driver.
bool isZero() const
Return true if the expression is a constant zero.
const SCEV * getAddRecExpr(const SmallVectorImpl< const SCEV *> &Operands, const Loop *L, SCEV::NoWrapFlags Flags)
IncrementWrapFlags
Similar to SCEV::NoWrapFlags, but with slightly different semantics for FlagNUSW. ...
static LLVM_NODISCARD SCEV::NoWrapFlags setFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OnFlags)
static bool Equals(const SCEVPredicate &X, const FoldingSetNodeID &ID, unsigned IDHash, FoldingSetNodeID &TempID)
A cache of @llvm.assume calls within a function.
APInt getSignedRangeMin(const SCEV *S)
Determine the min of the signed range for a particular SCEV.
F(f)
An instruction for reading from memory.
Definition: Instructions.h:167
Hexagon Common GEP
An object of this class is returned by queries that could not be answered.
This file defines the MallocAllocator and BumpPtrAllocator interfaces.
APInt getSignedRangeMax(const SCEV *S)
Determine the max of the signed range for a particular SCEV.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:343
const SCEV * getZero(Type *Ty)
Return a SCEV for the constant 0 of a specific type.
The SCEV is loop-invariant.
static LLVM_NODISCARD SCEVWrapPredicate::IncrementWrapFlags setFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OnFlags)
Definition: BitVector.h:937
const SCEV * getAddExpr(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:369
Class to represent struct types.
Definition: DerivedTypes.h:232
APInt getUnsignedRangeMax(const SCEV *S)
Determine the max of the unsigned range for a particular SCEV.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:41
unsigned short SubclassData
This field is initialized to zero and may be used in subclasses to store miscellaneous information...
LLVMContext & getContext() const
BasicBlock * ExitingBlock
This file implements a class to represent arbitrary precision integral constant values and operations...
static int64_t getConstant(const MachineInstr *MI)
Key
PAL metadata keys.
ConstantRange getSignedRange(const SCEV *S)
Determine the signed range for a particular SCEV.
This node represents a polynomial recurrence on the trip count of the specified loop.
IntType getInt() const
A CRTP mix-in to automatically provide informational APIs needed for passes.
Definition: PassManager.h:365
static bool classof(const SCEVPredicate *P)
Methods for support type inquiry through isa, cast, and dyn_cast:
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
bool isKnownNonNegative(const Value *V, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Returns true if the give value is known to be non-negative.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:144
void forgetLoopDispositions(const Loop *L)
Called when the client has changed the disposition of values in this loop.
Value handle that poisons itself if the Value is deleted.
Definition: ValueHandle.h:440
unsigned ComputeHash() const
ComputeHash - Compute a strong hash value for this FoldingSetNodeIDRef, used to lookup the node in th...
Definition: FoldingSet.cpp:29
unsigned short getExpressionSize() const
FoldingSetNodeID - This class is used to gather all the unique data bits of a node.
Definition: FoldingSet.h:305
Printer pass for the ScalarEvolutionAnalysis results.
static bool runOnFunction(Function &F, bool PostInlining)
#define P(N)
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
APInt getUnsignedRangeMin(const SCEV *S)
Determine the min of the unsigned range for a particular SCEV.
FoldingSetTrait - This trait class is used to define behavior of how to "profile" (in the FoldingSet ...
Definition: FoldingSet.h:249
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
static bool Equals(const SCEV &X, const FoldingSetNodeID &ID, unsigned IDHash, FoldingSetNodeID &TempID)
SCEVPredicateKind getKind() const
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
PointerIntPair - This class implements a pair of a pointer and small integer.
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:64
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition: Allocator.h:140
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Definition: Constant.h:41
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:370
A CRTP mix-in that provides informational APIs needed for analysis passes.
Definition: PassManager.h:382
ScalarEvolutionPrinterPass(raw_ostream &OS)
Represent the analysis usage information of a pass.
This instruction compares its operands according to the predicate given to the constructor.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:646
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:284
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
static LLVM_NODISCARD SCEV::NoWrapFlags clearFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OffFlags)
const SCEV * getLHS() const
Returns the left hand side of the equality.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:192
const SCEV * getRHS() const
Returns the right hand side of the equality.
ScalarEvolution * getSE() const
Returns the ScalarEvolution analysis used.
size_t size() const
Definition: SmallVector.h:52
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1206
FoldingSet - This template class is used to instantiate a specialized implementation of the folding s...
Definition: FoldingSet.h:473
bool verify(const TargetRegisterInfo &TRI) const
Check that information hold by this instance make sense for the given TRI.
static unsigned ComputeHash(const SCEV &X, FoldingSetNodeID &TempID)
static ExitLimitQuery getEmptyKey()
The SCEV is loop-variant (unknown).
This class represents an assumption made using SCEV expressions which can be checked at run-time...
void print(raw_ostream &OS) const
Print out the internal representation of this scalar to the specified stream.
unsigned getSCEVType() const
bool isNonConstantNegative() const
Return true if the specified scev is negated, but not a constant.
See the file comment.
Definition: ValueMap.h:85
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:417
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
bool isAllOnesValue() const
Return true if the expression is a constant all-ones value.
Type * getType() const
Return the LLVM type of this SCEV expression.
static LLVM_NODISCARD SCEVWrapPredicate::IncrementWrapFlags clearFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OffFlags)
Convenient IncrementWrapFlags manipulation methods.
static bool isEqual(ExitLimitQuery LHS, ExitLimitQuery RHS)
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:841
Provides information about what library functions are available for the current target.
The SCEV dominates the block.
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
Definition: PPCPredicates.h:26
This class represents a range of values.
Definition: ConstantRange.h:47
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
static LLVM_NODISCARD SCEVWrapPredicate::IncrementWrapFlags maskFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, int Mask)
static void Profile(const SCEV &X, FoldingSetNodeID &ID)
static void Profile(const SCEVPredicate &X, FoldingSetNodeID &ID)
LoopDisposition
An enum describing the relationship between a SCEV and a loop.
Class for arbitrary precision integers.
Definition: APInt.h:69
virtual void print(raw_ostream &OS, unsigned Depth=0) const =0
Prints a textual representation of this predicate with an indentation of Depth.
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition: Hashing.h:600
bool isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return true if the given value is known to be non-zero when defined.
This class uses information about analyze scalars to rewrite expressions in canonical form...
static void clear(coro::Shape &Shape)
Definition: Coroutines.cpp:211
const DataLayout & getDataLayout() const
Return the DataLayout associated with the module this SCEV instance is operating on.
static bool classof(const SCEVPredicate *P)
Methods for support type inquiry through isa, cast, and dyn_cast:
Analysis pass that exposes the ScalarEvolution for a function.
unsigned getComplexity() const override
We estimate the complexity of a union predicate as the size number of predicates in the union...
static ExitLimitQuery getTombstoneKey()
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:277
MCExpr const & getExpr(MCExpr const &Expr)
Node - This class is used to maintain the singly linked bucket list in a folding set.
Definition: FoldingSet.h:135
This class represents an analyzed expression in the program.
bool isKnownNegative(const Value *V, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Returns true if the given value is known be negative (i.e.
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
const SCEV * getMulExpr(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:464
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
BlockDisposition
An enum describing the relationship between a SCEV and a basic block.
static LLVM_NODISCARD SCEV::NoWrapFlags maskFlags(SCEV::NoWrapFlags Flags, int Mask)
Convenient NoWrapFlags manipulation that hides enum casts and is visible in the ScalarEvolution name ...
raw_ostream & operator<<(raw_ostream &OS, const APInt &I)
Definition: APInt.h:2038
virtual unsigned getComplexity() const
Returns the estimated complexity of this predicate.
#define LLVM_NODISCARD
LLVM_NODISCARD - Warn if a type or return value is discarded.
Definition: Compiler.h:128
API to communicate dependencies between analyses during invalidation.
Definition: PassManager.h:641
ConstantRange getUnsignedRange(const SCEV *S)
Determine the unsigned range for a particular SCEV.
const SmallVectorImpl< const SCEVPredicate * > & getPredicates() const
Multiway switch.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This class represents a composition of other SCEV predicates, and is the class that most clients will...
bool isOne() const
Return true if the expression is a constant one.
const SCEV * getMulExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:565
LLVM Value Representation.
Definition: Value.h:72
A vector that has set insertion semantics.
Definition: SetVector.h:40
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E&#39;s largest value.
Definition: BitmaskEnum.h:80
DefaultFoldingSetTrait - This class provides default implementations for FoldingSetTrait implementati...
Definition: FoldingSet.h:220
SCEVPredicateKind Kind
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:45
static unsigned getHashValue(ExitLimitQuery Val)
Value handle with callbacks on RAUW and destruction.
Definition: ValueHandle.h:379
A container for analyses that lazily runs them and caches their results.
static Optional< bool > isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS, const Value *ARHS, const Value *BLHS, const Value *BRHS, const DataLayout &DL, unsigned Depth)
Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred ALHS ARHS" is true.
SCEV(const FoldingSetNodeIDRef ID, unsigned SCEVTy, unsigned short ExpressionSize)
This header defines various interfaces for pass management in LLVM.
const SCEV * getAddExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
This class represents an assumption made on an AddRec expression.
static bool classof(const SCEVPredicate *P)
Methods for support type inquiry through isa, cast, and dyn_cast:
NoWrapFlags
NoWrapFlags are bitfield indices into SubclassData.
This class represents an assumption that two SCEV expressions are equal, and this can be checked at r...
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition: PassManager.h:70
IncrementWrapFlags getFlags() const
Returns the set assumed no overflow flags.