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