LLVM 24.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"
26#include "llvm/ADT/DenseMap.h"
28#include "llvm/ADT/FoldingSet.h"
35#include "llvm/IR/PassManager.h"
36#include "llvm/IR/ValueHandle.h"
37#include "llvm/IR/ValueMap.h"
38#include "llvm/Pass.h"
40#include <cassert>
41#include <cstdint>
42#include <memory>
43#include <optional>
44#include <utility>
45
46namespace llvm {
47
49struct AnalysisOptions;
50class AssumptionCache;
51class BasicBlock;
52class Constant;
53class ConstantInt;
54class DataLayout;
55class DominatorTree;
56class GEPOperator;
57class LLVMContext;
58class Loop;
59class LoopInfo;
60class raw_ostream;
61class ScalarEvolution;
62class SCEVAddRecExpr;
63class SCEVConstant;
64class SCEVUnknown;
65class StructType;
67class Type;
68class VPSCEVExpander;
69enum SCEVTypes : unsigned short;
70
71LLVM_ABI extern bool VerifySCEV;
72
73/// SCEVFlags are bitfield indices into SCEV's SubclassData.
74///
75/// Add and Mul expressions may have no-unsigned-wrap <NUW> or
76/// no-signed-wrap <NSW> properties, which are derived from the IR
77/// operator. NSW is a misnomer that we use to mean no signed overflow or
78/// underflow. NUW and NSW must hold for all subsets and orders of
79/// Add/Mul operands. That is, in `(a + b + c)<nsw>`, all of `a + b`,
80/// `b + c`, `a + c` must be nsw as well.
81///
82/// AddRec expressions may have a no-self-wraparound <NW> property if, in
83/// the integer domain, abs(step) * max-iteration(loop) <=
84/// unsigned-max(bitwidth). This means that the recurrence will never reach
85/// its start value if the step is non-zero. Computing the same value on
86/// each iteration is not considered wrapping, and recurrences with step = 0
87/// are trivially <NW>. <NW> is independent of the sign of step and the
88/// value the add recurrence starts with.
89///
90/// Note that NUW and NSW are also valid properties of a recurrence, and
91/// either implies NW. For convenience, NW will be set for a recurrence
92/// whenever either NUW or NSW are set.
93///
94/// We require that the flag on a SCEV apply to the entire scope in which
95/// that SCEV is defined. A SCEV's scope is set of locations dominated by
96/// a defining location, which is in turn described by the following rules:
97/// * A SCEVUnknown is at the point of definition of the Value.
98/// * A SCEVConstant is defined at all points.
99/// * A SCEVAddRec is defined starting with the header of the associated
100/// loop.
101/// * All other SCEVs are defined at the earlest point all operands are
102/// defined.
103///
104/// The above rules describe a maximally hoisted form (without regards to
105/// potential control dependence). A SCEV is defined anywhere a
106/// corresponding instruction could be defined in said maximally hoisted
107/// form. Note that SCEVUDivExpr (currently the only expression type which
108/// can trap) can be defined per these rules in regions where it would trap
109/// at runtime. A SCEV being defined does not require the existence of any
110/// instruction within the defined scope.
111enum class SCEVFlags {
112 FlagNone = 0, // No guarantee.
113 FlagNW = (1 << 0), // No self-wrap.
114 FlagNUW = (1 << 1), // No unsigned wrap.
115 FlagNSW = (1 << 2), // No signed wrap.
116 FlagsNoWrapMask = (1 << 3) - 1,
117 FlagsMask = (1 << 3) - 1,
118 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/FlagsMask)
119};
120
121class SCEV;
122struct SCEVFlagsPair;
123
124template <typename SCEVPtrT = const SCEV *>
125struct SCEVUseT : private PointerIntPair<SCEVPtrT, 2> {
128 using Base::getPointer;
129
130 SCEVUseT() : Base(nullptr, 0) {}
131 SCEVUseT(SCEVPtrT S) : Base(S, 0) {}
132 /// Construct with SCEVFlags; only NUW/NSW are encoded, NW is dropped. \p S
133 /// must be an expression supporting flags. Only flags not already present on
134 /// \p S are added. Note that the expression may gain flags also part of the
135 /// SCEVUse later, via setFlags.
136 SCEVUseT(SCEVPtrT S, SCEVFlags Flags);
137 template <typename OtherPtrT, typename = std::enable_if_t<
138 std::is_convertible_v<OtherPtrT, SCEVPtrT>>>
141
142 operator SCEVPtrT() const { return getPointer(); }
143 SCEVPtrT operator->() const { return getPointer(); }
144
145 /// Returns true if the SCEVUse is canonical, i.e. no SCEVUse flags set in any
146 /// operands.
147 bool isCanonical() const { return getCanonical() == getOpaqueValue(); }
148
149 /// Returns true if this use itself carries use-specific no-wrap flags.
150 bool hasUseFlags() const { return getOpaqueValue() != getPointer(); }
151
152 /// Return the canonical SCEV for this SCEVUse.
153 const SCEV *getCanonical() const;
154
155 /// Return a SCEVUse that can replace both \p A and \p B. Both must be
156 /// operands of the same poison-propagating expression, so the use flags of
157 /// both hold for either.
159
160 /// Return the flags for this SCEVUse, which is the union of the use-specific
161 /// flags and the underlying SCEV's flags, masked by \p Mask.
163
164 /// Return only the use-specific flags without the underlying SCEV's flags.
166 return static_cast<SCEVFlags>(Base::getInt() << 1) &
168 }
169
170 /// Returns a pair of expression and use-specific flags respectively.
172
173 /// Returns the flags safe to propagate in folds established based on the
174 /// flags in \p CheckedFlags.
176
177 bool operator==(const SCEVUseT &RHS) const {
178 return getOpaqueValue() == RHS.getOpaqueValue();
179 }
180
181 bool operator!=(const SCEVUseT &RHS) const { return !(*this == RHS); }
182
183 bool operator>(const SCEVUseT &RHS) const { return Base::operator>(RHS); }
184
185 bool operator==(const SCEV *RHS) const { return getOpaqueValue() == RHS; }
186 bool operator!=(const SCEV *RHS) const { return getOpaqueValue() != RHS; }
187
188 /// Print out the internal representation of this scalar to the specified
189 /// stream. This should really only be used for debugging purposes.
190 void print(raw_ostream &OS) const;
191
192 /// This method is used for debugging.
193 void dump() const;
194
195private:
196 /// Construct a use of \p S with the use flags of \p Other, which must be a
197 /// use of the same expression.
198 template <typename OtherPtrT>
199 SCEVUseT(const SCEVUseT<OtherPtrT> &Other, SCEVPtrT S)
200 : Base(S, Other.getInt()) {
201 assert(S == Other.getPointer() && "Other must be a use of S");
202 }
203
204 using Base::getInt;
206 template <typename> friend struct SCEVUseT;
207 friend struct CastInfo<SCEVUseT, SCEVUseT<const SCEV *>>;
208 friend struct PointerLikeTypeTraits<SCEVUseT>;
209};
210
211/// Deduction guide for various SCEV subclass pointers.
212template <typename SCEVPtrT> SCEVUseT(SCEVPtrT) -> SCEVUseT<SCEVPtrT>;
213
215
216/// The no-wrap flags to apply when creating a SCEV expression, to the
217/// expression and use respectively.
219 /// Flags applied directly to a SCEV expression, must be valid wherever the
220 /// expression is valid.
222
223 /// Flags only applied to a SCEVUse.
225
229
230 /// Returns the combination of the expression and use-specific flags.
232};
233
234/// Provide PointerLikeTypeTraits for SCEVUse, so it can be used with
235/// SmallPtrSet, among others.
236template <> struct PointerLikeTypeTraits<SCEVUse> {
237 static inline void *getAsVoidPointer(SCEVUse U) { return U.getOpaqueValue(); }
238 static inline SCEVUse getFromVoidPointer(void *P) {
239 SCEVUse U;
240 U.setFromOpaqueValue(P);
241 return U;
242 }
243
244 /// The Low bits are used by the PointerIntPair.
245 static constexpr int NumLowBitsAvailable = 0;
246};
247
248template <> struct DenseMapInfo<SCEVUse> {
249 static unsigned getHashValue(SCEVUse U) {
250 return DenseMapInfo<void *>::getHashValue(U.getOpaqueValue());
251 }
252
253 static bool isEqual(const SCEVUse LHS, const SCEVUse RHS) {
254 return LHS.getOpaqueValue() == RHS.getOpaqueValue();
255 }
256};
257
258template <> struct simplify_type<SCEVUse> {
259 using SimpleType = const SCEV *;
260
262 return Val.getPointer();
263 }
264};
265
266/// Provide CastInfo for SCEVUseT so that cast<SCEVUseT<const To *>>(use)
267/// returns SCEVUseT<const To *> with flags preserved.
268template <typename ToSCEVPtrT>
269struct CastInfo<SCEVUseT<ToSCEVPtrT>, SCEVUse,
270 std::enable_if_t<!is_simple_type<SCEVUse>::value>> {
271 using To = std::remove_cv_t<std::remove_pointer_t<ToSCEVPtrT>>;
273
274 static bool isPossible(const SCEVUse &U) { return isa<To>(U.getPointer()); }
275 static CastReturnType doCast(const SCEVUse &U) {
276 return CastReturnType(U, cast<To>(U.getPointer()));
277 }
278 static CastReturnType castFailed() { return CastReturnType(nullptr); }
280 if (!isPossible(U))
281 return castFailed();
282 return doCast(U);
283 }
284};
285
286template <typename ToSCEVPtrT>
287struct CastInfo<SCEVUseT<ToSCEVPtrT>, const SCEVUse,
288 std::enable_if_t<!is_simple_type<const SCEVUse>::value>>
289 : CastInfo<SCEVUseT<ToSCEVPtrT>, SCEVUse> {};
290
291/// This class represents an analyzed expression in the program. These are
292/// opaque objects that the client is not allowed to do much with directly.
293///
294class SCEV : public FoldingSetNode {
295 friend struct FoldingSetTrait<SCEV>;
296
297 /// A reference to an Interned FoldingSetNodeID for this node. The
298 /// ScalarEvolution's BumpPtrAllocator holds the data.
299 FoldingSetNodeIDRef FastID;
300
301 // The SCEV baseclass this node corresponds to
302 const SCEVTypes SCEVType;
303
304protected:
305 // Estimated complexity of this node's expression tree size.
306 const unsigned short ExpressionSize;
307
308 /// This field is initialized to zero and may be used in subclasses to store
309 /// miscellaneous information.
310 unsigned short SubclassData = 0;
311
312 /// Pointer to the canonical version of the SCEV, i.e. one where all operands
313 /// have no SCEVUse flags.
314 const SCEV *CanonicalSCEV = nullptr;
315
316 /// Immutable type of the SCEV.
317 Type *const Ty;
318
319public:
320 static constexpr auto FlagNone = SCEVFlags::FlagNone;
321 static constexpr auto FlagNW = SCEVFlags::FlagNW;
322 static constexpr auto FlagNUW = SCEVFlags::FlagNUW;
323 static constexpr auto FlagNSW = SCEVFlags::FlagNSW;
325 static constexpr auto FlagsMask = SCEVFlags::FlagsMask;
326
327 explicit SCEV(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy,
328 unsigned short ExpressionSize, Type *Ty)
329 : FastID(ID), SCEVType(SCEVTy), ExpressionSize(ExpressionSize), Ty(Ty) {}
330 SCEV(const SCEV &) = delete;
331 SCEV &operator=(const SCEV &) = delete;
332
333 SCEVTypes getSCEVType() const { return SCEVType; }
334
335 /// Return the LLVM type of this SCEV expression.
336 Type *getType() const { return Ty; }
337
338 /// Return operands of this SCEV expression.
340
341 /// Return true if the expression is a constant zero.
342 LLVM_ABI bool isZero() const;
343
344 /// Return true if the expression is a constant one.
345 LLVM_ABI bool isOne() const;
346
347 /// Return true if the expression is a constant all-ones value.
348 LLVM_ABI bool isAllOnesValue() const;
349
350 /// Return true if the specified scev is negated, but not a constant.
351 LLVM_ABI bool isNonConstantNegative() const;
352
353 // Returns estimated size of the mathematical expression represented by this
354 // SCEV. The rules of its calculation are following:
355 // 1) Size of a SCEV without operands (like constants and SCEVUnknown) is 1;
356 // 2) Size SCEV with operands Op1, Op2, ..., OpN is calculated by formula:
357 // (1 + Size(Op1) + ... + Size(OpN)).
358 // This value gives us an estimation of time we need to traverse through this
359 // SCEV and all its operands recursively. We may use it to avoid performing
360 // heavy transformations on SCEVs of excessive size for sake of saving the
361 // compilation time.
362 unsigned short getExpressionSize() const {
363 return ExpressionSize;
364 }
365
366 /// Print out the internal representation of this scalar to the specified
367 /// stream. This should really only be used for debugging purposes.
368 LLVM_ABI void print(raw_ostream &OS) const;
369
370 /// This method is used for debugging.
371 LLVM_ABI void dump() const;
372
373 /// Compute and set the canonical SCEV, by constructing a SCEV with the same
374 /// operands, but all SCEVUse flags dropped.
376
377 /// Return the canonical SCEV.
378 const SCEV *getCanonical() const {
379 assert(CanonicalSCEV && "canonical SCEV not yet computed");
380 return CanonicalSCEV;
381 }
382};
383
384// Specialize FoldingSetTrait for SCEV to avoid needing to compute
385// temporary FoldingSetNodeID values.
386template <> struct FoldingSetTrait<SCEV> : DefaultFoldingSetTrait<SCEV> {
387 static void Profile(const SCEV &X, FoldingSetNodeID &ID) { ID = X.FastID; }
388
389 static bool Equals(const SCEV &X, const FoldingSetNodeID &ID) {
390 return ID == X.FastID;
391 }
392};
393
394inline raw_ostream &operator<<(raw_ostream &OS, const SCEV &S) {
395 S.print(OS);
396 return OS;
397}
398
400 U.print(OS);
401 return OS;
402}
403
404/// An object of this class is returned by queries that could not be answered.
405/// For example, if you ask for the number of iterations of a linked-list
406/// traversal loop, you will get one of these. None of the standard SCEV
407/// operations are valid on this class, it is just a marker.
408struct SCEVCouldNotCompute : public SCEV {
410
411 /// Methods for support type inquiry through isa, cast, and dyn_cast:
412 LLVM_ABI static bool classof(const SCEV *S);
413};
414
415/// This class represents an assumption made using SCEV expressions which can
416/// be checked at run-time.
418 friend struct FoldingSetTrait<SCEVPredicate>;
419
420 /// A reference to an Interned FoldingSetNodeID for this node. The
421 /// ScalarEvolution's BumpPtrAllocator holds the data.
422 FoldingSetNodeIDRef FastID;
423
424public:
426
427protected:
429 ~SCEVPredicate() = default;
430 SCEVPredicate(const SCEVPredicate &) = default;
432
433public:
435
436 SCEVPredicateKind getKind() const { return Kind; }
437
438 /// Returns the estimated complexity of this predicate. This is roughly
439 /// measured in the number of run-time checks required.
440 virtual unsigned getComplexity() const { return 1; }
441
442 /// Returns true if the predicate is always true. This means that no
443 /// assumptions were made and nothing needs to be checked at run-time.
444 virtual bool isAlwaysTrue() const = 0;
445
446 /// Returns true if this predicate implies \p N.
447 virtual bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const = 0;
448
449 /// Prints a textual representation of this predicate with an indentation of
450 /// \p Depth.
451 virtual void print(raw_ostream &OS, unsigned Depth = 0) const = 0;
452};
453
455 P.print(OS);
456 return OS;
457}
458
459// Specialize FoldingSetTrait for SCEVPredicate to avoid needing to compute
460// temporary FoldingSetNodeID values.
461template <>
463 static void Profile(const SCEVPredicate &X, FoldingSetNodeID &ID) {
464 ID = X.FastID;
465 }
466
467 static bool Equals(const SCEVPredicate &X, const FoldingSetNodeID &ID) {
468 return ID == X.FastID;
469 }
470};
471
472/// This class represents an assumption that the expression LHS Pred RHS
473/// evaluates to true, and this can be checked at run-time.
475 /// We assume that LHS Pred RHS is true.
476 const ICmpInst::Predicate Pred;
477 const SCEV *LHS;
478 const SCEV *RHS;
479
480public:
482 const ICmpInst::Predicate Pred,
483 const SCEV *LHS, const SCEV *RHS);
484
485 /// Implementation of the SCEVPredicate interface
486 bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override;
487 void print(raw_ostream &OS, unsigned Depth = 0) const override;
488 bool isAlwaysTrue() const override;
489
490 ICmpInst::Predicate getPredicate() const { return Pred; }
491
492 /// Returns the left hand side of the predicate.
493 const SCEV *getLHS() const { return LHS; }
494
495 /// Returns the right hand side of the predicate.
496 const SCEV *getRHS() const { return RHS; }
497
498 /// Methods for support type inquiry through isa, cast, and dyn_cast:
499 static bool classof(const SCEVPredicate *P) {
500 return P->getKind() == P_Compare;
501 }
502};
503
504/// This class represents an assumption made on an AddRec expression. Given an
505/// affine AddRec expression {a,+,b}, we assume that it has the nssw or nusw
506/// flags (defined below) in the first X iterations of the loop, where X is a
507/// SCEV expression returned by getPredicatedBackedgeTakenCount).
508///
509/// Note that this does not imply that X is equal to the backedge taken
510/// count. This means that if we have a nusw predicate for i32 {0,+,1} with a
511/// predicated backedge taken count of X, we only guarantee that {0,+,1} has
512/// nusw in the first X iterations. {0,+,1} may still wrap in the loop if we
513/// have more than X iterations.
515public:
516 /// Similar to SCEVFlags, but with slightly different semantics
517 /// for FlagNUSW. The increment is considered to be signed, and a + b
518 /// (where b is the increment) is considered to wrap if:
519 /// zext(a + b) != zext(a) + sext(b)
520 ///
521 /// If Signed is a function that takes an n-bit tuple and maps to the
522 /// integer domain as the tuples value interpreted as twos complement,
523 /// and Unsigned a function that takes an n-bit tuple and maps to the
524 /// integer domain as the base two value of input tuple, then a + b
525 /// has IncrementNUSW iff:
526 ///
527 /// 0 <= Unsigned(a) + Signed(b) < 2^n
528 ///
529 /// The IncrementNSSW flag has identical semantics with SCEV::FlagNSW.
530 ///
531 /// Note that the IncrementNUSW flag is not commutative: if base + inc
532 /// has IncrementNUSW, then inc + base doesn't neccessarily have this
533 /// property. The reason for this is that this is used for sign/zero
534 /// extending affine AddRec SCEV expressions when a SCEVWrapPredicate is
535 /// assumed. A {base,+,inc} expression is already non-commutative with
536 /// regards to base and inc, since it is interpreted as:
537 /// (((base + inc) + inc) + inc) ...
539 IncrementAnyWrap = 0, // No guarantee.
540 IncrementNUSW = (1 << 0), // No unsigned with signed increment wrap.
541 IncrementNSSW = (1 << 1), // No signed with signed increment wrap
542 // (equivalent with SCEV::NSW)
543 IncrementNoWrapMask = (1 << 2) - 1
544 };
545
546 /// Convenient IncrementWrapFlags manipulation methods.
547 [[nodiscard]] static SCEVWrapPredicate::IncrementWrapFlags
550 assert((Flags & IncrementNoWrapMask) == Flags && "Invalid flags value!");
551 assert((OffFlags & IncrementNoWrapMask) == OffFlags &&
552 "Invalid flags value!");
553 return (SCEVWrapPredicate::IncrementWrapFlags)(Flags & ~OffFlags);
554 }
555
556 [[nodiscard]] static SCEVWrapPredicate::IncrementWrapFlags
558 assert((Flags & IncrementNoWrapMask) == Flags && "Invalid flags value!");
559 assert((Mask & IncrementNoWrapMask) == Mask && "Invalid mask value!");
560
561 return (SCEVWrapPredicate::IncrementWrapFlags)(Flags & Mask);
562 }
563
564 [[nodiscard]] static SCEVWrapPredicate::IncrementWrapFlags
567 assert((Flags & IncrementNoWrapMask) == Flags && "Invalid flags value!");
568 assert((OnFlags & IncrementNoWrapMask) == OnFlags &&
569 "Invalid flags value!");
570
571 return (SCEVWrapPredicate::IncrementWrapFlags)(Flags | OnFlags);
572 }
573
574private:
575 const SCEVAddRecExpr *AR;
576 IncrementWrapFlags Flags;
577
578public:
579 explicit SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
580 const SCEVAddRecExpr *AR,
581 IncrementWrapFlags Flags);
582
583 /// Returns the set assumed no overflow flags.
584 IncrementWrapFlags getFlags() const { return Flags; }
585
586 /// Implementation of the SCEVPredicate interface
587 const SCEVAddRecExpr *getExpr() const;
588 bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override;
589 void print(raw_ostream &OS, unsigned Depth = 0) const override;
590 bool isAlwaysTrue() const override;
591
592 /// Methods for support type inquiry through isa, cast, and dyn_cast:
593 static bool classof(const SCEVPredicate *P) {
594 return P->getKind() == P_Wrap;
595 }
596};
597
598/// This class represents a composition of other SCEV predicates, and is the
599/// class that most clients will interact with. This is equivalent to a
600/// logical "AND" of all the predicates in the union.
601///
602/// NB! Unlike other SCEVPredicate sub-classes this class does not live in the
603/// ScalarEvolution::Preds folding set. This is why the \c add function is sound.
605private:
606 /// Vector with references to all predicates in this union.
608
609 /// Adds a predicate to this union.
610 void add(const SCEVPredicate *N, ScalarEvolution &SE);
611
612public:
614 ScalarEvolution &SE);
615
617
618 /// Returns a new SCEVUnionPredicate that is the union of this predicate
619 /// and the given predicate \p N.
621 ScalarEvolution &SE) const {
622 SCEVUnionPredicate Result = *this;
623 Result.add(N, SE);
624 return Result;
625 }
626
627 /// Implementation of the SCEVPredicate interface
628 bool isAlwaysTrue() const override;
629 bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override;
630 void print(raw_ostream &OS, unsigned Depth) const override;
631
632 /// We estimate the complexity of a union predicate as the size number of
633 /// predicates in the union.
634 unsigned getComplexity() const override { return Preds.size(); }
635
636 /// Methods for support type inquiry through isa, cast, and dyn_cast:
637 static bool classof(const SCEVPredicate *P) {
638 return P->getKind() == P_Union;
639 }
640};
641
642/// The main scalar evolution driver. Because client code (intentionally)
643/// can't do much with the SCEV objects directly, they must ask this class
644/// for services.
647
648public:
649 /// An enum describing the relationship between a SCEV and a loop.
651 LoopVariant, ///< The SCEV is loop-variant (unknown).
652 LoopInvariant, ///< The SCEV is loop-invariant.
653 LoopUniform, ///< The SCEV is loop-uniform.
654 LoopComputable ///< The SCEV varies predictably with the loop.
655 };
656
657 /// An enum describing the relationship between a SCEV and a basic block.
659 DoesNotDominateBlock, ///< The SCEV does not dominate the block.
660 DominatesBlock, ///< The SCEV dominates the block.
661 ProperlyDominatesBlock ///< The SCEV properly dominates the block.
662 };
663
664 /// Convenient SCEVFlags manipulation. TODO: Replace with & operator of
665 /// enum class.
666 [[nodiscard]] static SCEVFlags maskFlags(SCEVFlags Flags, SCEVFlags Mask) {
667 return Flags & Mask;
668 }
669 [[nodiscard]] static SCEVFlags setFlags(SCEVFlags Flags, SCEVFlags OnFlags) {
670 return Flags | OnFlags;
671 }
672 [[nodiscard]] static SCEVFlags clearFlags(SCEVFlags Flags,
673 SCEVFlags OffFlags) {
674 return Flags & ~OffFlags;
675 }
676 [[nodiscard]] static bool hasFlags(SCEVFlags Flags, SCEVFlags TestFlags) {
677 return TestFlags == maskFlags(Flags, TestFlags);
678 };
679
682 LoopInfo &LI);
685
686 LLVMContext &getContext() const { return F.getContext(); }
687
688 Module &getModule() const { return *F.getParent(); }
689
690 /// Test if values of the given type are analyzable within the SCEV
691 /// framework. This primarily includes integer types, and it can optionally
692 /// include pointer types if the ScalarEvolution class has access to
693 /// target-specific information.
694 LLVM_ABI bool isSCEVable(Type *Ty) const;
695
696 /// Return the size in bits of the specified type, for which isSCEVable must
697 /// return true.
699
700 /// Return a type with the same bitwidth as the given type and which
701 /// represents how SCEV will treat the given type, for which isSCEVable must
702 /// return true. For pointer types, this is the pointer-sized integer type.
704
705 // Returns a wider type among {Ty1, Ty2}.
706 LLVM_ABI Type *getWiderType(Type *Ty1, Type *Ty2) const;
707
708 /// Return true if there exists a point in the program at which both
709 /// A and B could be operands to the same instruction.
710 /// SCEV expressions are generally assumed to correspond to instructions
711 /// which could exists in IR. In general, this requires that there exists
712 /// a use point in the program where all operands dominate the use.
713 ///
714 /// Example:
715 /// loop {
716 /// if
717 /// loop { v1 = load @global1; }
718 /// else
719 /// loop { v2 = load @global2; }
720 /// }
721 /// No SCEV with operand V1, and v2 can exist in this program.
723
724 /// Return true if the SCEV is a scAddRecExpr or it contains
725 /// scAddRecExpr. The result will be cached in HasRecMap.
726 LLVM_ABI bool containsAddRecurrence(const SCEV *S);
727
728 /// Is operation \p BinOp between \p LHS and \p RHS provably does not have
729 /// a signed/unsigned overflow (\p Signed)? If \p CtxI is specified, the
730 /// no-overflow fact should be true in the context of this instruction.
732 const SCEV *LHS, const SCEV *RHS,
733 const Instruction *CtxI = nullptr);
734
735 /// Parse NSW/NUW flags from add/sub/mul IR binary operation \p Op into
736 /// SCEV no-wrap flags, and deduce flag[s] that aren't known yet.
737 /// Does not mutate the original instruction. Returns std::nullopt if it could
738 /// not deduce more precise flags than the instruction already has, otherwise
739 /// returns proven flags.
740 LLVM_ABI std::optional<SCEVFlags>
742
743 /// Notify this ScalarEvolution that \p User directly uses SCEVs in \p Ops.
745
746 /// Return true if the SCEV expression contains an undef value.
747 LLVM_ABI bool containsUndefs(const SCEV *S) const;
748
749 /// Return true if the SCEV expression contains a Value that has been
750 /// optimised out and is now a nullptr.
751 LLVM_ABI bool containsErasedValue(const SCEV *S) const;
752
753 /// Return a SCEV expression for the full generality of the specified
754 /// expression.
755 LLVM_ABI const SCEV *getSCEV(Value *V);
756
757 /// Return an existing SCEV for V if there is one, otherwise return nullptr.
759
761 LLVM_ABI const SCEV *getConstant(const APInt &Val);
762 LLVM_ABI const SCEV *getConstant(Type *Ty, uint64_t V, bool isSigned = false);
763
764 LLVM_ABI const SCEV *getPtrToAddrExpr(const SCEV *Op);
766 unsigned Depth = 0);
767 LLVM_ABI const SCEV *getVScale(Type *Ty);
769 SCEVFlags Flags = SCEV::FlagNone);
772 unsigned Depth = 0);
775 unsigned Depth = 0);
776 LLVM_ABI const SCEV *getCastExpr(SCEVTypes Kind, SCEVUse Op, Type *Ty);
778
780 SCEVFlagsPair Flags = {}, unsigned Depth = 0);
782 unsigned Depth = 0) {
784 return getAddExpr(Ops, Flags, Depth);
785 }
787 SCEVFlagsPair Flags = {}, unsigned Depth = 0) {
788 SmallVector<SCEVUse, 3> Ops = {Op0, Op1, Op2};
789 return getAddExpr(Ops, Flags, Depth);
790 }
791 LLVM_ABI SCEVUse getMulExpr(SmallVectorImpl<SCEVUse> &Ops,
792 SCEVFlagsPair Flags = {}, unsigned Depth = 0);
794 unsigned Depth = 0) {
796 return getMulExpr(Ops, Flags, Depth);
797 }
799 SCEVFlagsPair Flags = {}, unsigned Depth = 0) {
800 SmallVector<SCEVUse, 3> Ops = {Op0, Op1, Op2};
801 return getMulExpr(Ops, Flags, Depth);
802 }
806 LLVM_ABI SCEVUse getAddRecExpr(SCEVUse Start, SCEVUse Step, const Loop *L,
807 SCEVFlagsPair Flags);
808 LLVM_ABI SCEVUse getAddRecExpr(SmallVectorImpl<SCEVUse> &Operands,
809 const Loop *L, SCEVFlagsPair Flags);
811 SCEVFlagsPair Flags) {
812 SmallVector<SCEVUse, 4> NewOp(Operands.begin(), Operands.end());
813 return getAddRecExpr(NewOp, L, Flags);
814 }
815
816 /// Checks if \p SymbolicPHI can be rewritten as an AddRecExpr under some
817 /// Predicates. If successful return these <AddRecExpr, Predicates>;
818 /// The function is intended to be called from PSCEV (the caller will decide
819 /// whether to actually add the predicates and carry out the rewrites).
820 LLVM_ABI std::optional<
821 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
822 createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI);
823
824 /// Returns an expression for a GEP
825 ///
826 /// \p GEP The GEP. The indices contained in the GEP itself are ignored,
827 /// instead we use IndexExprs.
828 /// \p IndexExprs The expressions for the indices.
830 ArrayRef<SCEVUse> IndexExprs);
831 LLVM_ABI const SCEV *
832 getGEPExpr(SCEVUse BaseExpr, ArrayRef<SCEVUse> IndexExprs, Type *SrcElementTy,
835 LLVM_ABI const SCEV *getAbsExpr(const SCEV *Op, bool IsNSW);
838 LLVM_ABI const SCEV *
847 bool Sequential = false);
849 bool Sequential = false);
850 LLVM_ABI const SCEV *getUnknown(Value *V);
852
853 /// Return a SCEV for the constant 0 of a specific type.
854 const SCEV *getZero(Type *Ty) { return getConstant(Ty, 0); }
855
856 /// Return a SCEV for the constant 1 of a specific type.
857 const SCEV *getOne(Type *Ty) { return getConstant(Ty, 1); }
858
859 /// Return a SCEV for the constant \p Power of two.
860 const SCEV *getPowerOfTwo(Type *Ty, unsigned Power) {
861 assert(Power < getTypeSizeInBits(Ty) && "Power out of range");
863 }
864
865 /// Return a SCEV for the constant -1 of a specific type.
866 const SCEV *getMinusOne(Type *Ty) {
867 return getConstant(Ty, -1, /*isSigned=*/true);
868 }
869
870 /// Return an expression for a TypeSize.
872
873 /// Return an expression for the alloc size of AllocTy that is type IntTy
874 LLVM_ABI const SCEV *getSizeOfExpr(Type *IntTy, Type *AllocTy);
875
876 /// Return an expression for the store size of StoreTy that is type IntTy
877 LLVM_ABI const SCEV *getStoreSizeOfExpr(Type *IntTy, Type *StoreTy);
878
879 /// Return an expression for offsetof on the given field with type IntTy
880 LLVM_ABI const SCEV *getOffsetOfExpr(Type *IntTy, StructType *STy,
881 unsigned FieldNo);
882
883 /// Return the SCEV object corresponding to -V.
884 LLVM_ABI const SCEV *getNegativeSCEV(const SCEV *V,
885 SCEVFlags Flags = SCEV::FlagNone);
886
887 /// Return the SCEV object corresponding to ~V.
888 LLVM_ABI const SCEV *getNotSCEV(const SCEV *V);
889
890 /// Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
891 ///
892 /// If the LHS and RHS are pointers which don't share a common base
893 /// (according to getPointerBase()), this returns a SCEVCouldNotCompute.
894 /// To compute the difference between two unrelated pointers, you can
895 /// explicitly convert the arguments using getPtrToAddrExpr(), for pointer
896 /// types that support it.
899 unsigned Depth = 0);
900
901 /// Compute ceil(N / D). N and D are treated as unsigned values.
902 ///
903 /// Since SCEV doesn't have native ceiling division, this generates a
904 /// SCEV expression of the following form:
905 ///
906 /// umin(N, 1) + floor((N - umin(N, 1)) / D)
907 ///
908 /// A denominator of zero or poison is handled the same way as getUDivExpr().
909 LLVM_ABI const SCEV *getUDivCeilSCEV(const SCEV *N, const SCEV *D);
910
911 /// Return a SCEV corresponding to a conversion of the input value to the
912 /// specified type. If the type must be extended, it is zero extended.
913 LLVM_ABI const SCEV *getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
914 unsigned Depth = 0);
915
916 /// Return a SCEV corresponding to a conversion of the input value to the
917 /// specified type. If the type must be extended, it is sign extended.
918 LLVM_ABI const SCEV *getTruncateOrSignExtend(const SCEV *V, Type *Ty,
919 unsigned Depth = 0);
920
921 /// Return a SCEV corresponding to a conversion of the input value to the
922 /// specified type. If the type must be extended, it is zero extended. The
923 /// conversion must not be narrowing.
924 LLVM_ABI const SCEV *getNoopOrZeroExtend(const SCEV *V, Type *Ty);
925
926 /// Return a SCEV corresponding to a conversion of the input value to the
927 /// specified type. If the type must be extended, it is sign extended. The
928 /// conversion must not be narrowing.
929 LLVM_ABI const SCEV *getNoopOrSignExtend(const SCEV *V, Type *Ty);
930
931 /// Return a SCEV corresponding to a conversion of the input value to the
932 /// specified type. If the type must be extended, it is extended with
933 /// unspecified bits. The conversion must not be narrowing.
934 LLVM_ABI const SCEV *getNoopOrAnyExtend(const SCEV *V, Type *Ty);
935
936 /// Return a SCEV corresponding to a conversion of the input value to the
937 /// specified type. The conversion must not be widening.
938 LLVM_ABI const SCEV *getTruncateOrNoop(const SCEV *V, Type *Ty);
939
940 /// Promote the operands to the wider of the types using zero-extension, and
941 /// then perform a umax operation with them.
943 const SCEV *RHS);
944
945 /// Promote the operands to the wider of the types using zero-extension, and
946 /// then perform a umin operation with them.
948 const SCEV *RHS,
949 bool Sequential = false);
950
951 /// Promote the operands to the wider of the types using zero-extension, and
952 /// then perform a umin operation with them. N-ary function.
954 bool Sequential = false);
955
956 /// Transitively follow the chain of pointer-type operands until reaching a
957 /// SCEV that does not have a single pointer operand. This returns a
958 /// SCEVUnknown pointer for well-formed pointer-type expressions, but corner
959 /// cases do exist.
960 LLVM_ABI const SCEV *getPointerBase(const SCEV *V);
961
962 /// Compute an expression equivalent to S - getPointerBase(S).
963 LLVM_ABI const SCEV *removePointerBase(const SCEV *S);
964
965 /// Return a SCEV expression for the specified value at the specified scope
966 /// in the program. The L value specifies a loop nest to evaluate the
967 /// expression at, where null is the top-level or a specified loop is
968 /// immediately inside of the loop.
969 ///
970 /// This method can be used to compute the exit value for a variable defined
971 /// in a loop by querying what the value will hold in the parent loop.
972 ///
973 /// In the case that a relevant loop exit value cannot be computed, the
974 /// original value V is returned.
975 ///
976 /// The result may carry use-specific no-wrap flags. Those hold only in
977 /// contexts reached via \p L's exit.
978 LLVM_ABI SCEVUse getSCEVAtScope(const SCEV *S, const Loop *L);
979
980 /// This is a convenience function which does getSCEVAtScope(getSCEV(V), L).
982
983 /// Return the SCEV expression at the specified loop exit. Returns the
984 /// original value if no more precise value can be computed.
985 LLVM_ABI SCEVUse getSCEVAtExit(const SCEV *S, const Loop *L,
986 const BasicBlock *ExitingBlock);
987
988 /// This is a convenience function which does
989 /// getSCEVAtExit(getSCEV(V), L, ExitingBlock).
991 const BasicBlock *ExitingBlock) {
992 return getSCEVAtExit(getSCEV(V), L, ExitingBlock);
993 }
994
995 /// Test whether entry to the loop is protected by a conditional between LHS
996 /// and RHS. This is used to help avoid max expressions in loop trip
997 /// counts, and to eliminate casts.
999 const SCEV *LHS, const SCEV *RHS);
1000
1001 /// Test whether entry to the basic block is protected by a conditional
1002 /// between LHS and RHS.
1005 const SCEV *LHS,
1006 const SCEV *RHS);
1007
1008 /// Test whether the backedge of the loop is protected by a conditional
1009 /// between LHS and RHS. This is used to eliminate casts.
1011 const SCEV *LHS, const SCEV *RHS);
1012
1013 /// A version of getTripCountFromExitCount below which always picks an
1014 /// evaluation type which can not result in overflow.
1015 LLVM_ABI const SCEV *getTripCountFromExitCount(const SCEV *ExitCount);
1016
1017 /// Convert from an "exit count" (i.e. "backedge taken count") to a "trip
1018 /// count". A "trip count" is the number of times the header of the loop
1019 /// will execute if an exit is taken after the specified number of backedges
1020 /// have been taken. (e.g. TripCount = ExitCount + 1). Note that the
1021 /// expression can overflow if ExitCount = UINT_MAX. If EvalTy is not wide
1022 /// enough to hold the result without overflow, result unsigned wraps with
1023 /// 2s-complement semantics. ex: EC = 255 (i8), TC = 0 (i8)
1024 LLVM_ABI const SCEV *getTripCountFromExitCount(const SCEV *ExitCount,
1025 Type *EvalTy, const Loop *L);
1026
1027 /// Returns the exact trip count of the loop if we can compute it, and
1028 /// the result is a small constant. '0' is used to represent an unknown
1029 /// or non-constant trip count. Note that a trip count is simply one more
1030 /// than the backedge taken count for the loop.
1031 LLVM_ABI unsigned getSmallConstantTripCount(const Loop *L);
1032
1033 /// Return the exact trip count for this loop if we exit through ExitingBlock.
1034 /// '0' is used to represent an unknown or non-constant trip count. Note
1035 /// that a trip count is simply one more than the backedge taken count for
1036 /// the same exit.
1037 /// This "trip count" assumes that control exits via ExitingBlock. More
1038 /// precisely, it is the number of times that control will reach ExitingBlock
1039 /// before taking the branch. For loops with multiple exits, it may not be
1040 /// the number times that the loop header executes if the loop exits
1041 /// prematurely via another branch.
1042 LLVM_ABI unsigned getSmallConstantTripCount(const Loop *L,
1043 const BasicBlock *ExitingBlock);
1044
1045 /// Returns the upper bound of the loop trip count as a normal unsigned
1046 /// value.
1047 /// Returns 0 if the trip count is unknown, not constant or requires
1048 /// SCEV predicates and \p Predicates is nullptr.
1050 const Loop *L,
1051 SmallVectorImpl<const SCEVPredicate *> *Predicates = nullptr);
1052
1053 /// Returns the largest constant divisor of the trip count as a normal
1054 /// unsigned value, if possible. This means that the actual trip count is
1055 /// always a multiple of the returned value. Returns 1 if the trip count is
1056 /// unknown or not guaranteed to be the multiple of a constant., Will also
1057 /// return 1 if the trip count is very large (>= 2^32).
1058 /// Note that the argument is an exit count for loop L, NOT a trip count.
1059 LLVM_ABI unsigned getSmallConstantTripMultiple(const Loop *L,
1060 const SCEV *ExitCount);
1061
1062 /// Returns the largest constant divisor of the trip count of the
1063 /// loop. Will return 1 if no trip count could be computed, or if a
1064 /// divisor could not be found.
1065 LLVM_ABI unsigned getSmallConstantTripMultiple(const Loop *L);
1066
1067 /// Returns the largest constant divisor of the trip count of this loop as a
1068 /// normal unsigned value, if possible. This means that the actual trip
1069 /// count is always a multiple of the returned value (don't forget the trip
1070 /// count could very well be zero as well!). As explained in the comments
1071 /// for getSmallConstantTripCount, this assumes that control exits the loop
1072 /// via ExitingBlock.
1073 LLVM_ABI unsigned
1074 getSmallConstantTripMultiple(const Loop *L, const BasicBlock *ExitingBlock);
1075
1076 /// The terms "backedge taken count" and "exit count" are used
1077 /// interchangeably to refer to the number of times the backedge of a loop
1078 /// has executed before the loop is exited.
1080 /// An expression exactly describing the number of times the backedge has
1081 /// executed when a loop is exited.
1083 /// A constant which provides an upper bound on the exact trip count.
1085 /// An expression which provides an upper bound on the exact trip count.
1087 };
1088
1089 /// Return the number of times the backedge executes before the given exit
1090 /// would be taken; if not exactly computable, return SCEVCouldNotCompute.
1091 /// For a single exit loop, this value is equivelent to the result of
1092 /// getBackedgeTakenCount. The loop is guaranteed to exit (via *some* exit)
1093 /// before the backedge is executed (ExitCount + 1) times. Note that there
1094 /// is no guarantee about *which* exit is taken on the exiting iteration.
1095 LLVM_ABI const SCEV *getExitCount(const Loop *L,
1096 const BasicBlock *ExitingBlock,
1097 ExitCountKind Kind = Exact);
1098
1099 /// Same as above except this uses the predicated backedge taken info and
1100 /// may require predicates.
1101 LLVM_ABI const SCEV *
1102 getPredicatedExitCount(const Loop *L, const BasicBlock *ExitingBlock,
1104 ExitCountKind Kind = Exact);
1105
1106 /// If the specified loop has a predictable backedge-taken count, return it,
1107 /// otherwise return a SCEVCouldNotCompute object. The backedge-taken count is
1108 /// the number of times the loop header will be branched to from within the
1109 /// loop, assuming there are no abnormal exists like exception throws. This is
1110 /// one less than the trip count of the loop, since it doesn't count the first
1111 /// iteration, when the header is branched to from outside the loop.
1112 ///
1113 /// Note that it is not valid to call this method on a loop without a
1114 /// loop-invariant backedge-taken count (see
1115 /// hasLoopInvariantBackedgeTakenCount).
1116 LLVM_ABI const SCEV *getBackedgeTakenCount(const Loop *L,
1117 ExitCountKind Kind = Exact);
1118
1119 /// Similar to getBackedgeTakenCount, except it will add a set of
1120 /// SCEV predicates to Predicates that are required to be true in order for
1121 /// the answer to be correct. Predicates can be checked with run-time
1122 /// checks and can be used to perform loop versioning.
1124 const Loop *L, SmallVectorImpl<const SCEVPredicate *> &Predicates);
1125
1126 /// When successful, this returns a SCEVConstant that is greater than or equal
1127 /// to (i.e. a "conservative over-approximation") of the value returend by
1128 /// getBackedgeTakenCount. If such a value cannot be computed, it returns the
1129 /// SCEVCouldNotCompute object.
1133
1134 /// Similar to getConstantMaxBackedgeTakenCount, except it will add a set of
1135 /// SCEV predicates to Predicates that are required to be true in order for
1136 /// the answer to be correct. Predicates can be checked with run-time
1137 /// checks and can be used to perform loop versioning.
1139 const Loop *L, SmallVectorImpl<const SCEVPredicate *> &Predicates);
1140
1141 /// When successful, this returns a SCEV that is greater than or equal
1142 /// to (i.e. a "conservative over-approximation") of the value returend by
1143 /// getBackedgeTakenCount. If such a value cannot be computed, it returns the
1144 /// SCEVCouldNotCompute object.
1148
1149 /// Similar to getSymbolicMaxBackedgeTakenCount, except it will add a set of
1150 /// SCEV predicates to Predicates that are required to be true in order for
1151 /// the answer to be correct. Predicates can be checked with run-time
1152 /// checks and can be used to perform loop versioning.
1154 const Loop *L, SmallVectorImpl<const SCEVPredicate *> &Predicates);
1155
1156 /// Return true if the backedge taken count is either the value returned by
1157 /// getConstantMaxBackedgeTakenCount or zero.
1159
1160 /// Return true if the specified loop has an analyzable loop-invariant
1161 /// backedge-taken count.
1163
1164 // This method should be called by the client when it made any change that
1165 // would invalidate SCEV's answers, and the client wants to remove all loop
1166 // information held internally by ScalarEvolution. This is intended to be used
1167 // when the alternative to forget a loop is too expensive (i.e. large loop
1168 // bodies).
1169 LLVM_ABI void forgetAllLoops();
1170
1171 /// This method should be called by the client when it has changed a loop in
1172 /// a way that may effect ScalarEvolution's ability to compute a trip count,
1173 /// or if the loop is deleted. This call is potentially expensive for large
1174 /// loop bodies.
1175 LLVM_ABI void forgetLoop(const Loop *L);
1176
1177 // This method invokes forgetLoop for the outermost loop of the given loop
1178 // \p L, making ScalarEvolution forget about all this subtree. This needs to
1179 // be done whenever we make a transform that may affect the parameters of the
1180 // outer loop, such as exit counts for branches.
1181 LLVM_ABI void forgetTopmostLoop(const Loop *L);
1182
1183 /// This method should be called by the client when it has changed a value
1184 /// in a way that may effect its value, or which may disconnect it from a
1185 /// def-use chain linking it to a loop.
1186 LLVM_ABI void forgetValue(Value *V);
1187
1188 /// Batched forgetValue: invalidates all \p Values in one shared def-use walk,
1189 /// avoiding the redundant re-traversal of overlapping users.
1191
1192 /// Forget LCSSA phi node V of loop L to which a new predecessor was added,
1193 /// such that it may no longer be trivial.
1195
1196 /// Called when the client has changed the disposition of values in
1197 /// this loop.
1198 ///
1199 /// We don't have a way to invalidate per-loop dispositions. Clear and
1200 /// recompute is simpler.
1202
1203 /// Called when the client has changed the disposition of values in
1204 /// a loop or block.
1205 ///
1206 /// We don't have a way to invalidate per-loop/per-block dispositions. Clear
1207 /// and recompute is simpler.
1209
1210 /// Determine the minimum number of zero bits that S is guaranteed to end in
1211 /// (at every loop iteration). It is, at the same time, the minimum number
1212 /// of times S is divisible by 2. For example, given {4,+,8} it returns 2.
1213 /// If S is guaranteed to be 0, it returns the bitwidth of S.
1214 /// If \p CtxI is not nullptr, return a constant multiple valid at \p CtxI.
1216 const Instruction *CtxI = nullptr);
1217
1218 /// Returns the max constant multiple of S. If \p CtxI is not nullptr, return
1219 /// a constant multiple valid at \p CtxI.
1221 const Instruction *CtxI = nullptr);
1222
1223 // Returns the max constant multiple of S. If S is exactly 0, return 1.
1225
1226 /// Determine the unsigned range for a particular SCEV.
1227 /// NOTE: This returns a copy of the reference returned by getRangeRef.
1229 if (const APInt *C = getConstantAPIntOrNull(S))
1230 return ConstantRange(*C);
1231 return getRangeRef(S, HINT_RANGE_UNSIGNED);
1232 }
1233
1234 /// Determine the min of the unsigned range for a particular SCEV.
1236 if (const APInt *C = getConstantAPIntOrNull(S))
1237 return *C;
1238 return getRangeRef(S, HINT_RANGE_UNSIGNED).getUnsignedMin();
1239 }
1240
1241 /// Determine the max of the unsigned range for a particular SCEV.
1243 if (const APInt *C = getConstantAPIntOrNull(S))
1244 return *C;
1245 return getRangeRef(S, HINT_RANGE_UNSIGNED).getUnsignedMax();
1246 }
1247
1248 /// Determine the signed range for a particular SCEV.
1249 /// NOTE: This returns a copy of the reference returned by getRangeRef.
1251 if (const APInt *C = getConstantAPIntOrNull(S))
1252 return ConstantRange(*C);
1253 return getRangeRef(S, HINT_RANGE_SIGNED);
1254 }
1255
1256 /// Determine the min of the signed range for a particular SCEV.
1258 if (const APInt *C = getConstantAPIntOrNull(S))
1259 return *C;
1260 return getRangeRef(S, HINT_RANGE_SIGNED).getSignedMin();
1261 }
1262
1263 /// Determine the max of the signed range for a particular SCEV.
1265 if (const APInt *C = getConstantAPIntOrNull(S))
1266 return *C;
1267 return getRangeRef(S, HINT_RANGE_SIGNED).getSignedMax();
1268 }
1269
1270 /// Test if the given expression is known to be negative.
1271 LLVM_ABI bool isKnownNegative(const SCEV *S);
1272
1273 /// Test if the given expression is known to be positive.
1274 LLVM_ABI bool isKnownPositive(const SCEV *S);
1275
1276 /// Test if the given expression is known to be non-negative.
1277 LLVM_ABI bool isKnownNonNegative(const SCEV *S);
1278
1279 /// Test if the given expression is known to be non-positive.
1280 LLVM_ABI bool isKnownNonPositive(const SCEV *S);
1281
1282 /// Test if the given expression is known to be non-zero.
1283 LLVM_ABI bool isKnownNonZero(const SCEV *S);
1284
1285 /// Returns true if \p Op is guaranteed to not be poison.
1286 LLVM_ABI static bool isGuaranteedNotToBePoison(const SCEV *Op);
1287
1288 /// Returns true if \p Op is guaranteed not to cause immediate UB.
1290
1291 /// Test if the given expression is known to be a power of 2. OrNegative
1292 /// allows matching negative power of 2s, and OrZero allows matching 0.
1293 LLVM_ABI bool isKnownToBeAPowerOfTwo(const SCEV *S, bool OrZero = false,
1294 bool OrNegative = false);
1295
1296 /// Check that \p S is a multiple of \p M. When \p S is an AddRecExpr, \p S is
1297 /// a multiple of \p M if \p S starts with a multiple of \p M and at every
1298 /// iteration step \p S only adds multiples of \p M. \p Assumptions records
1299 /// the runtime predicates under which \p S is a multiple of \p M.
1301 const SCEV *S, uint64_t M,
1302 SmallVectorImpl<const SCEVPredicate *> *Predicates = nullptr);
1303
1304 /// Return true if we know that S1 and S2 must have the same sign.
1305 LLVM_ABI bool haveSameSign(const SCEV *S1, const SCEV *S2);
1306
1307 /// Splits SCEV expression \p S into two SCEVs. One of them is obtained from
1308 /// \p S by substitution of all AddRec sub-expression related to loop \p L
1309 /// with initial value of that SCEV. The second is obtained from \p S by
1310 /// substitution of all AddRec sub-expressions related to loop \p L with post
1311 /// increment of this AddRec in the loop \p L. In both cases all other AddRec
1312 /// sub-expressions (not related to \p L) remain the same.
1313 /// If the \p S contains non-invariant unknown SCEV the function returns
1314 /// CouldNotCompute SCEV in both values of std::pair.
1315 /// For example, for SCEV S={0, +, 1}<L1> + {0, +, 1}<L2> and loop L=L1
1316 /// the function returns pair:
1317 /// first = {0, +, 1}<L2>
1318 /// second = {1, +, 1}<L1> + {0, +, 1}<L2>
1319 /// We can see that for the first AddRec sub-expression it was replaced with
1320 /// 0 (initial value) for the first element and to {1, +, 1}<L1> (post
1321 /// increment value) for the second one. In both cases AddRec expression
1322 /// related to L2 remains the same.
1323 LLVM_ABI std::pair<const SCEV *, const SCEV *>
1324 SplitIntoInitAndPostInc(const Loop *L, const SCEV *S);
1325
1326 /// We'd like to check the predicate on every iteration of the most dominated
1327 /// loop between loops used in LHS and RHS.
1328 /// To do this we use the following list of steps:
1329 /// 1. Collect set S all loops on which either LHS or RHS depend.
1330 /// 2. If S is non-empty
1331 /// a. Let PD be the element of S which is dominated by all other elements.
1332 /// b. Let E(LHS) be value of LHS on entry of PD.
1333 /// To get E(LHS), we should just take LHS and replace all AddRecs that are
1334 /// attached to PD on with their entry values.
1335 /// Define E(RHS) in the same way.
1336 /// c. Let B(LHS) be value of L on backedge of PD.
1337 /// To get B(LHS), we should just take LHS and replace all AddRecs that are
1338 /// attached to PD on with their backedge values.
1339 /// Define B(RHS) in the same way.
1340 /// d. Note that E(LHS) and E(RHS) are automatically available on entry of PD,
1341 /// so we can assert on that.
1342 /// e. Return true if isLoopEntryGuardedByCond(Pred, E(LHS), E(RHS)) &&
1343 /// isLoopBackedgeGuardedByCond(Pred, B(LHS), B(RHS))
1345 SCEVUse RHS);
1346
1347 /// Test if the given expression is known to satisfy the condition described
1348 /// by Pred, LHS, and RHS. \p Depth is the current recursion depth.
1350 unsigned Depth = 0);
1351
1352 /// Check whether the condition described by Pred, LHS, and RHS is true or
1353 /// false. If we know it, return the evaluation of this condition. If neither
1354 /// is proved, return std::nullopt.
1355 LLVM_ABI std::optional<bool>
1357
1358 /// Test if the given expression is known to satisfy the condition described
1359 /// by Pred, LHS, and RHS in the given Context.
1361 const SCEV *RHS, const Instruction *CtxI);
1362
1363 /// Check whether the condition described by Pred, LHS, and RHS is true or
1364 /// false in the given \p Context. If we know it, return the evaluation of
1365 /// this condition. If neither is proved, return std::nullopt.
1366 LLVM_ABI std::optional<bool> evaluatePredicateAt(CmpPredicate Pred,
1367 const SCEV *LHS,
1368 const SCEV *RHS,
1369 const Instruction *CtxI);
1370
1371 /// Test if the condition described by Pred, LHS, RHS is known to be true on
1372 /// every iteration of the loop of the recurrency LHS.
1374 const SCEVAddRecExpr *LHS,
1375 const SCEV *RHS);
1376
1377 /// Information about the number of loop iterations for which a loop exit's
1378 /// branch condition evaluates to the not-taken path. This is a temporary
1379 /// pair of exact and max expressions that are eventually summarized in
1380 /// ExitNotTakenInfo and BackedgeTakenInfo.
1381 struct ExitLimit {
1382 const SCEV *ExactNotTaken; // The exit is not taken exactly this many times
1383 const SCEV *ConstantMaxNotTaken; // The exit is not taken at most this many
1384 // times
1386
1387 // Not taken either exactly ConstantMaxNotTaken or zero times
1388 bool MaxOrZero = false;
1389
1390 /// A vector of predicate guards for this ExitLimit. The result is only
1391 /// valid if all of the predicates in \c Predicates evaluate to 'true' at
1392 /// run-time.
1394
1395 /// Construct either an exact exit limit from a constant, or an unknown
1396 /// one from a SCEVCouldNotCompute. No other types of SCEVs are allowed
1397 /// as arguments and asserts enforce that internally.
1398 /*implicit*/ LLVM_ABI ExitLimit(const SCEV *E);
1399 /*implicit*/ ExitLimit(SCEVUse E) : ExitLimit((const SCEV *)E) {}
1400
1401 LLVM_ABI
1402 ExitLimit(const SCEV *E, const SCEV *ConstantMaxNotTaken,
1403 const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
1405
1407 const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
1409
1410 /// Test whether this ExitLimit contains any computed information, or
1411 /// whether it's all SCEVCouldNotCompute values.
1416
1417 /// Test whether this ExitLimit contains all information.
1418 bool hasFullInfo() const {
1420 }
1421 };
1422
1423 /// Compute the number of times the backedge of the specified loop will
1424 /// execute if its exit condition were a conditional branch of ExitCond.
1425 ///
1426 /// \p ControlsOnlyExit is true if ExitCond directly controls the only exit
1427 /// branch. In this case, we can assume that the loop exits only if the
1428 /// condition is true and can infer that failing to meet the condition prior
1429 /// to integer wraparound results in undefined behavior.
1430 ///
1431 /// If \p AllowPredicates is set, this call will try to use a minimal set of
1432 /// SCEV predicates in order to return an exact answer.
1433 LLVM_ABI ExitLimit computeExitLimitFromCond(const Loop *L, Value *ExitCond,
1434 bool ExitIfTrue,
1435 bool ControlsOnlyExit,
1436 bool AllowPredicates = false);
1437
1438 /// A predicate is said to be monotonically increasing if may go from being
1439 /// false to being true as the loop iterates, but never the other way
1440 /// around. A predicate is said to be monotonically decreasing if may go
1441 /// from being true to being false as the loop iterates, but never the other
1442 /// way around.
1447
1448 /// If, for all loop invariant X, the predicate "LHS `Pred` X" is
1449 /// monotonically increasing or decreasing, returns
1450 /// Some(MonotonicallyIncreasing) and Some(MonotonicallyDecreasing)
1451 /// respectively. If we could not prove either of these facts, returns
1452 /// std::nullopt.
1453 LLVM_ABI std::optional<MonotonicPredicateType>
1456
1465 /// If the result of the predicate LHS `Pred` RHS is loop invariant with
1466 /// respect to L, return a LoopInvariantPredicate with LHS and RHS being
1467 /// invariants, available at L's entry. Otherwise, return std::nullopt.
1468 LLVM_ABI std::optional<LoopInvariantPredicate>
1470 const Loop *L, const Instruction *CtxI = nullptr);
1471
1472 /// If the result of the predicate LHS `Pred` RHS is loop invariant with
1473 /// respect to L at given Context during at least first MaxIter iterations,
1474 /// return a LoopInvariantPredicate with LHS and RHS being invariants,
1475 /// available at L's entry. Otherwise, return std::nullopt. The predicate
1476 /// should be the loop's exit condition.
1477 LLVM_ABI std::optional<LoopInvariantPredicate>
1479 const SCEV *LHS,
1480 const SCEV *RHS, const Loop *L,
1481 const Instruction *CtxI,
1482 const SCEV *MaxIter);
1483
1484 LLVM_ABI std::optional<LoopInvariantPredicate>
1486 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
1487 const Instruction *CtxI, const SCEV *MaxIter);
1488
1489 /// Simplify LHS and RHS in a comparison with predicate Pred. Return true
1490 /// iff any changes were made. If the operands are provably equal or
1491 /// unequal, LHS and RHS are set to the same value and Pred is set to either
1492 /// ICMP_EQ or ICMP_NE.
1494 SCEVUse &RHS, unsigned Depth = 0);
1495
1496 /// Return the "disposition" of the given SCEV with respect to the given
1497 /// loop.
1499
1500 /// Returns true if the given SCEV is loop-uniform with respect to the
1501 /// specified loop L.
1502 ///
1503 /// A SCEV is considered loop-uniform if its value is invariant across all
1504 /// iterations of L, meaning it does not depend on any induction variables
1505 /// or values that vary within L.
1506 ///
1507 /// This notion is particularly useful in nested loops, where a value may vary
1508 /// in an inner loop but remain invariant in an outer loop.
1509 ///
1510 /// Example:
1511 /// \code
1512 /// for (i)
1513 /// for (j)
1514 /// dep(j);
1515 /// dep(i, j);
1516 /// \endcode
1517 /// isLoopUniform(SCEV(dep(j)), loop_i) returns true, as `j` is independent of
1518 /// `i`.
1519 /// isLoopUniform(SCEV(dep(i, j)), loop_i) returns false, as the expression
1520 /// depends on `i`, which varies in loop_i.
1521 LLVM_ABI bool isLoopUniform(const SCEV *S, const Loop *L);
1522
1523 /// Return true if the value of the given SCEV is unchanging in the
1524 /// specified loop.
1525 LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L);
1526
1527 /// Determine if the SCEV can be evaluated at loop's entry. It is true if it
1528 /// doesn't depend on a SCEVUnknown of an instruction which is dominated by
1529 /// the header of loop L.
1530 LLVM_ABI bool isAvailableAtLoopEntry(const SCEV *S, const Loop *L);
1531
1532 /// Return true if the given SCEV changes value in a known way in the
1533 /// specified loop. This property being true implies that the value is
1534 /// variant in the loop AND that we can emit an expression to compute the
1535 /// value of the expression at any particular loop iteration.
1536 LLVM_ABI bool hasComputableLoopEvolution(const SCEV *S, const Loop *L);
1537
1538 /// Return the "disposition" of the given SCEV with respect to the given
1539 /// block.
1541 const BasicBlock *BB);
1542
1543 /// Return true if elements that makes up the given SCEV dominate the
1544 /// specified basic block.
1545 LLVM_ABI bool dominates(const SCEV *S, const BasicBlock *BB);
1546
1547 /// Return true if elements that makes up the given SCEV properly dominate
1548 /// the specified basic block.
1549 LLVM_ABI bool properlyDominates(const SCEV *S, const BasicBlock *BB);
1550
1551 /// Return the size of an element read or written by Inst.
1553
1554 LLVM_ABI void print(raw_ostream &OS) const;
1555 LLVM_ABI void verify() const;
1557 FunctionAnalysisManager::Invalidator &Inv);
1558
1559 /// Return the DataLayout associated with the module this SCEV instance is
1560 /// operating on.
1561 const DataLayout &getDataLayout() const { return DL; }
1562
1564 const SCEV *RHS);
1566 const SCEV *LHS,
1567 const SCEV *RHS);
1568
1569 LLVM_ABI const SCEVPredicate *
1572
1573 /// Re-writes the SCEV according to the Predicates in \p A.
1574 LLVM_ABI const SCEV *rewriteUsingPredicate(const SCEV *S, const Loop *L,
1575 const SCEVPredicate &A);
1576 /// Tries to convert the \p S expression to an AddRec expression,
1577 /// adding additional predicates to \p Preds as required.
1579 const SCEV *S, const Loop *L,
1581
1582 /// Compute \p LHS - \p RHS and returns the result as an APInt if it is a
1583 /// constant, and std::nullopt if it isn't.
1584 ///
1585 /// This is intended to be a cheaper version of getMinusSCEV. We can be
1586 /// frugal here since we just bail out of actually constructing and
1587 /// canonicalizing an expression in the cases where the result isn't going
1588 /// to be a constant.
1589 LLVM_ABI std::optional<APInt> computeConstantDifference(const SCEV *LHS,
1590 const SCEV *RHS);
1591
1592 /// Update no-wrap flags of an AddRec. This may drop the cached info about
1593 /// this AddRec (such as range info) in case if new flags may potentially
1594 /// sharpen it.
1595 LLVM_ABI void setNoWrapFlags(SCEVAddRecExpr *AddRec, SCEVFlags Flags);
1596
1597 class LoopGuards {
1600 bool PreserveNUW = false;
1601 bool PreserveNSW = false;
1602 /// The loop to collect guards for on first use by applyLoopGuards, if not
1603 /// collected yet.
1604 const Loop *PendingLoop = nullptr;
1605 ScalarEvolution &SE;
1606
1607 LoopGuards(ScalarEvolution &SE) : SE(SE) {}
1608
1609 friend class ScalarEvolution;
1610
1611 /// Collect the guards for PendingLoop.
1612 void collectPending();
1613
1614 /// Recursively collect loop guards in \p Guards, starting from
1615 /// block \p Block with predecessor \p Pred. The intended starting point
1616 /// is to collect from a loop header and its predecessor.
1617 static void
1618 collectFromBlock(ScalarEvolution &SE, ScalarEvolution::LoopGuards &Guards,
1619 const BasicBlock *Block, const BasicBlock *Pred,
1621 unsigned Depth = 0);
1622
1623 /// Collect loop guards in \p Guards, starting from PHINode \p
1624 /// Phi, by calling \p collectFromBlock on the incoming blocks of
1625 /// \Phi and trying to merge the found constraints into a single
1626 /// combined one for \p Phi.
1627 static void collectFromPHI(
1631 unsigned Depth);
1632
1633 /// Like rewrite(Expr), but look up rewrites with \p Lookup if set.
1634 const SCEV *rewrite(const SCEV *Expr,
1635 function_ref<const SCEV *(const SCEV *)> Lookup) const;
1636
1637 public:
1638 /// Return loop guards for loop \p L, which are collected on first use.
1639 static LoopGuards collectOnDemand(const Loop *L, ScalarEvolution &SE) {
1640 LoopGuards Guards(SE);
1641 Guards.PendingLoop = L;
1642 return Guards;
1643 }
1644
1645 /// Try to apply the collected loop guards to \p Expr.
1646 LLVM_ABI const SCEV *rewrite(const SCEV *Expr) const;
1647 };
1648
1649 /// Try to apply information from loop guards for \p L to \p Expr.
1650 LLVM_ABI const SCEV *applyLoopGuards(const SCEV *Expr, const Loop *L);
1651 LLVM_ABI const SCEV *applyLoopGuards(const SCEV *Expr, LoopGuards &Guards);
1652
1653 /// Return true if the loop has no abnormal exits. That is, if the loop
1654 /// is not infinite, it must exit through an explicit edge in the CFG.
1655 /// (As opposed to either a) throwing out of the function or b) entering a
1656 /// well defined infinite loop in some callee.)
1658 return getLoopProperties(L).HasNoAbnormalExits;
1659 }
1660
1661 /// Return true if this loop is finite by assumption. That is,
1662 /// to be infinite, it must also be undefined.
1663 LLVM_ABI bool loopIsFiniteByAssumption(const Loop *L);
1664
1665 /// Return the set of Values that, if poison, will definitively result in S
1666 /// being poison as well. The returned set may be incomplete, i.e. there can
1667 /// be additional Values that also result in S being poison.
1668 LLVM_ABI void
1670 const SCEV *S);
1671
1672 /// Check whether it is poison-safe to represent the expression S using the
1673 /// instruction I. If such a replacement is performed, the poison flags of
1674 /// instructions in DropPoisonGeneratingInsts must be dropped.
1676 const SCEV *S, Instruction *I,
1677 SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts);
1678
1679 class FoldID {
1680 SCEVUse Op;
1681 const Type *Ty = nullptr;
1682 unsigned short C;
1683
1684 public:
1685 FoldID(SCEVTypes C, SCEVUse Op, const Type *Ty) : Op(Op), Ty(Ty), C(C) {
1686 assert(Op.getPointer());
1687 assert(Ty);
1688 }
1689
1690 FoldID(unsigned short C) : C(C) {}
1691
1692 unsigned computeHash() const {
1695 reinterpret_cast<uintptr_t>(Op.getOpaqueValue()),
1696 reinterpret_cast<uintptr_t>(Ty)));
1697 }
1698
1699 bool operator==(const FoldID &RHS) const {
1700 return std::tie(Op, Ty, C) == std::tie(RHS.Op, RHS.Ty, RHS.C);
1701 }
1702 };
1703
1704private:
1705 /// A CallbackVH to arrange for ScalarEvolution to be notified whenever a
1706 /// Value is deleted.
1707 class LLVM_ABI SCEVCallbackVH final : public CallbackVH {
1708 ScalarEvolution *SE;
1709
1710 void deleted() override;
1711 void allUsesReplacedWith(Value *New) override;
1712
1713 public:
1714 SCEVCallbackVH(Value *V, ScalarEvolution *SE = nullptr);
1715 };
1716
1717 friend class SCEVCallbackVH;
1718 friend class SCEVExpander;
1719 friend class SCEVUnknown;
1720 friend class VPSCEVExpander;
1721 // Needs getWithOperands to rebuild a node from its canonical operands.
1723
1724 const AnalysisOptions &Opts;
1725
1726 /// The function we are analyzing.
1727 Function &F;
1728
1729 /// Data layout of the module.
1730 const DataLayout &DL;
1731
1732 /// Does the module have any calls to the llvm.experimental.guard intrinsic
1733 /// at all? If this is false, we avoid doing work that will only help if
1734 /// thare are guards present in the IR.
1735 bool HasGuards;
1736
1737 /// The target library information for the target we are targeting.
1738 TargetLibraryInfo &TLI;
1739
1740 /// The tracker for \@llvm.assume intrinsics in this function.
1741 AssumptionCache &AC;
1742
1743 /// The dominator tree.
1744 DominatorTree &DT;
1745
1746 /// The loop information for the function we are currently analyzing.
1747 LoopInfo &LI;
1748
1749 /// This SCEV is used to represent unknown trip counts and things.
1750 std::unique_ptr<SCEVCouldNotCompute> CouldNotCompute;
1751
1752 /// The type for HasRecMap.
1753 using HasRecMapType = DenseMap<const SCEV *, bool>;
1754
1755 /// This is a cache to record whether a SCEV contains any scAddRecExpr.
1756 HasRecMapType HasRecMap;
1757
1758 /// The type for ExprValueMap.
1759 using ExprValueMapType = DenseMap<const SCEV *, TinyPtrVector<Value *>>;
1760
1761 /// ExprValueMap -- This map records the original values from which
1762 /// the SCEV expr is generated from.
1763 ExprValueMapType ExprValueMap;
1764
1765 /// The type for ValueExprMap.
1766 using ValueExprMapType =
1768
1769 /// This is a cache of the values we have analyzed so far.
1770 ValueExprMapType ValueExprMap;
1771
1772 /// This is a cache for expressions that got folded to a different existing
1773 /// SCEV.
1776
1777 /// Mark predicate values currently being processed by isImpliedCond.
1778 SmallPtrSet<const Value *, 6> PendingLoopPredicates;
1779
1780 // Mark SCEVUnknown Phis currently being processed by isImpliedViaMerge.
1781 SmallPtrSet<const PHINode *, 6> PendingMerges;
1782
1783 /// Set to true by isLoopBackedgeGuardedByCond when we're walking the set of
1784 /// conditions dominating the backedge of a loop.
1785 bool WalkingBEDominatingConds = false;
1786
1787 /// Set to true by isKnownPredicateViaSplitting when we're trying to prove a
1788 /// predicate by splitting it into a set of independent predicates.
1789 bool ProvingSplitPredicate = false;
1790
1791 /// Memoized values for the getConstantMultiple
1792 DenseMap<const SCEV *, APInt> ConstantMultipleCache;
1793
1794 /// Return the Value set from which the SCEV expr is generated.
1795 ArrayRef<Value *> getSCEVValues(const SCEV *S);
1796
1797 /// Private helper method for the getConstantMultiple method. If \p CtxI is
1798 /// not nullptr, return a constant multiple valid at \p CtxI.
1799 APInt getConstantMultipleImpl(const SCEV *S,
1800 const Instruction *Ctx = nullptr);
1801
1802 /// Information about the number of times a particular loop exit may be
1803 /// reached before exiting the loop.
1804 struct ExitNotTakenInfo {
1805 PoisoningVH<BasicBlock> ExitingBlock;
1806 const SCEV *ExactNotTaken;
1807 const SCEV *ConstantMaxNotTaken;
1808 const SCEV *SymbolicMaxNotTaken;
1810
1811 explicit ExitNotTakenInfo(PoisoningVH<BasicBlock> ExitingBlock,
1812 const SCEV *ExactNotTaken,
1813 const SCEV *ConstantMaxNotTaken,
1814 const SCEV *SymbolicMaxNotTaken,
1816 : ExitingBlock(ExitingBlock), ExactNotTaken(ExactNotTaken),
1817 ConstantMaxNotTaken(ConstantMaxNotTaken),
1818 SymbolicMaxNotTaken(SymbolicMaxNotTaken), Predicates(Predicates) {}
1819
1820 bool hasAlwaysTruePredicate() const {
1821 return Predicates.empty();
1822 }
1823 };
1824
1825 /// Information about the backedge-taken count of a loop. This currently
1826 /// includes an exact count and a maximum count.
1827 ///
1828 class BackedgeTakenInfo {
1829 friend class ScalarEvolution;
1830
1831 /// A list of computable exits and their not-taken counts. Loops almost
1832 /// never have more than one computable exit.
1833 SmallVector<ExitNotTakenInfo, 1> ExitNotTaken;
1834
1835 /// Expression indicating the least constant maximum backedge-taken count of
1836 /// the loop that is known, or a SCEVCouldNotCompute. This expression is
1837 /// only valid if the predicates associated with all loop exits are true.
1838 const SCEV *ConstantMax = nullptr;
1839
1840 /// Indicating if \c ExitNotTaken has an element for every exiting block in
1841 /// the loop.
1842 bool IsComplete = false;
1843
1844 /// Expression indicating the least maximum backedge-taken count of the loop
1845 /// that is known, or a SCEVCouldNotCompute. Lazily computed on first query.
1846 const SCEV *SymbolicMax = nullptr;
1847
1848 /// True iff the backedge is taken either exactly Max or zero times.
1849 bool MaxOrZero = false;
1850
1851 bool isComplete() const { return IsComplete; }
1852 const SCEV *getConstantMax() const { return ConstantMax; }
1853
1854 LLVM_ABI const ExitNotTakenInfo *getExitNotTaken(
1855 const BasicBlock *ExitingBlock,
1856 SmallVectorImpl<const SCEVPredicate *> *Predicates = nullptr) const;
1857
1858 public:
1859 BackedgeTakenInfo() = default;
1860 BackedgeTakenInfo(BackedgeTakenInfo &&) = default;
1861 BackedgeTakenInfo &operator=(BackedgeTakenInfo &&) = default;
1862
1863 using EdgeExitInfo = std::pair<BasicBlock *, ExitLimit>;
1864
1865 /// Initialize BackedgeTakenInfo from a list of exact exit counts.
1866 LLVM_ABI BackedgeTakenInfo(ArrayRef<EdgeExitInfo> ExitCounts,
1867 bool IsComplete, const SCEV *ConstantMax,
1868 bool MaxOrZero);
1869
1870 /// Test whether this BackedgeTakenInfo contains any computed information,
1871 /// or whether it's all SCEVCouldNotCompute values.
1872 bool hasAnyInfo() const {
1873 return !ExitNotTaken.empty() ||
1874 !isa<SCEVCouldNotCompute>(getConstantMax());
1875 }
1876
1877 /// Test whether this BackedgeTakenInfo contains complete information.
1878 bool hasFullInfo() const { return isComplete(); }
1879
1880 /// Return an expression indicating the exact *backedge-taken*
1881 /// count of the loop if it is known or SCEVCouldNotCompute
1882 /// otherwise. If execution makes it to the backedge on every
1883 /// iteration (i.e. there are no abnormal exists like exception
1884 /// throws and thread exits) then this is the number of times the
1885 /// loop header will execute minus one.
1886 ///
1887 /// If the SCEV predicate associated with the answer can be different
1888 /// from AlwaysTrue, we must add a (non null) Predicates argument.
1889 /// The SCEV predicate associated with the answer will be added to
1890 /// Predicates. A run-time check needs to be emitted for the SCEV
1891 /// predicate in order for the answer to be valid.
1892 ///
1893 /// Note that we should always know if we need to pass a predicate
1894 /// argument or not from the way the ExitCounts vector was computed.
1895 /// If we allowed SCEV predicates to be generated when populating this
1896 /// vector, this information can contain them and therefore a
1897 /// SCEVPredicate argument should be added to getExact.
1898 LLVM_ABI const SCEV *getExact(
1899 const Loop *L, ScalarEvolution *SE,
1900 SmallVectorImpl<const SCEVPredicate *> *Predicates = nullptr) const;
1901
1902 /// Return the number of times this loop exit may fall through to the back
1903 /// edge, or SCEVCouldNotCompute. The loop is guaranteed not to exit via
1904 /// this block before this number of iterations, but may exit via another
1905 /// block. If \p Predicates is null the function returns CouldNotCompute if
1906 /// predicates are required, otherwise it fills in the required predicates.
1907 const SCEV *getExact(
1908 const BasicBlock *ExitingBlock, ScalarEvolution *SE,
1909 SmallVectorImpl<const SCEVPredicate *> *Predicates = nullptr) const {
1910 if (auto *ENT = getExitNotTaken(ExitingBlock, Predicates))
1911 return ENT->ExactNotTaken;
1912 else
1913 return SE->getCouldNotCompute();
1914 }
1915
1916 /// Get the constant max backedge taken count for the loop.
1917 LLVM_ABI const SCEV *getConstantMax(
1918 ScalarEvolution *SE,
1919 SmallVectorImpl<const SCEVPredicate *> *Predicates = nullptr) const;
1920
1921 /// Get the constant max backedge taken count for the particular loop exit.
1922 const SCEV *getConstantMax(
1923 const BasicBlock *ExitingBlock, ScalarEvolution *SE,
1924 SmallVectorImpl<const SCEVPredicate *> *Predicates = nullptr) const {
1925 if (auto *ENT = getExitNotTaken(ExitingBlock, Predicates))
1926 return ENT->ConstantMaxNotTaken;
1927 else
1928 return SE->getCouldNotCompute();
1929 }
1930
1931 /// Get the symbolic max backedge taken count for the loop.
1932 LLVM_ABI const SCEV *getSymbolicMax(
1933 const Loop *L, ScalarEvolution *SE,
1934 SmallVectorImpl<const SCEVPredicate *> *Predicates = nullptr);
1935
1936 /// Get the symbolic max backedge taken count for the particular loop exit.
1937 const SCEV *getSymbolicMax(
1938 const BasicBlock *ExitingBlock, ScalarEvolution *SE,
1939 SmallVectorImpl<const SCEVPredicate *> *Predicates = nullptr) const {
1940 if (auto *ENT = getExitNotTaken(ExitingBlock, Predicates))
1941 return ENT->SymbolicMaxNotTaken;
1942 else
1943 return SE->getCouldNotCompute();
1944 }
1945
1946 /// Return true if the number of times this backedge is taken is either the
1947 /// value returned by getConstantMax or zero.
1948 LLVM_ABI bool isConstantMaxOrZero(ScalarEvolution *SE) const;
1949 };
1950
1951 /// Cache the backedge-taken count of the loops for this function as they
1952 /// are computed.
1953 DenseMap<const Loop *, BackedgeTakenInfo> BackedgeTakenCounts;
1954
1955 /// Cache the predicated backedge-taken count of the loops for this
1956 /// function as they are computed.
1957 DenseMap<const Loop *, BackedgeTakenInfo> PredicatedBackedgeTakenCounts;
1958
1959 /// Loops whose backedge taken counts directly use this non-constant SCEV.
1960 DenseMap<const SCEV *, SmallPtrSet<PointerIntPair<const Loop *, 1, bool>, 4>>
1961 BECountUsers;
1962
1963 /// This map contains entries for all of the PHI instructions that we
1964 /// attempt to compute constant evolutions for. This allows us to avoid
1965 /// potentially expensive recomputation of these properties. An instruction
1966 /// maps to null if we are unable to compute its exit value.
1967 DenseMap<PHINode *, Constant *> ConstantEvolutionLoopExitValue;
1968
1969 /// This map contains entries for all the expressions that we attempt to
1970 /// compute getSCEVAtScope information for, which can be expensive in
1971 /// extreme cases.
1972 DenseMap<const SCEV *, SmallVector<std::pair<const Loop *, SCEVUse>, 2>>
1973 ValuesAtScopes;
1974
1975 /// Reverse map for invalidation purposes: Stores of which SCEV and which
1976 /// loop this is the value-at-scope of.
1977 DenseMap<const SCEV *, SmallVector<std::pair<const Loop *, const SCEV *>, 2>>
1978 ValuesAtScopesUsers;
1979
1980 /// Memoized computeLoopDisposition results.
1981 DenseMap<const SCEV *,
1983 LoopDispositions;
1984
1985 struct LoopProperties {
1986 /// Set to true if the loop contains no instruction that can abnormally exit
1987 /// the loop (i.e. via throwing an exception, by terminating the thread
1988 /// cleanly or by infinite looping in a called function). Strictly
1989 /// speaking, the last one is not leaving the loop, but is identical to
1990 /// leaving the loop for reasoning about undefined behavior.
1991 bool HasNoAbnormalExits;
1992
1993 /// Set to true if the loop contains no instruction that can have side
1994 /// effects (i.e. via throwing an exception, volatile or atomic access).
1995 bool HasNoSideEffects;
1996 };
1997
1998 /// Cache for \c getLoopProperties.
1999 DenseMap<const Loop *, LoopProperties> LoopPropertiesCache;
2000
2001 /// Return a \c LoopProperties instance for \p L, creating one if necessary.
2002 LLVM_ABI LoopProperties getLoopProperties(const Loop *L);
2003
2004 bool loopHasNoSideEffects(const Loop *L) {
2005 return getLoopProperties(L).HasNoSideEffects;
2006 }
2007
2008 /// Compute a LoopDisposition value.
2009 LoopDisposition computeLoopDisposition(const SCEV *S, const Loop *L);
2010
2011 /// Memoized computeBlockDisposition results.
2012 DenseMap<
2013 const SCEV *,
2015 BlockDispositions;
2016
2017 /// Compute a BlockDisposition value.
2018 BlockDisposition computeBlockDisposition(const SCEV *S, const BasicBlock *BB);
2019
2020 /// Stores all SCEV that use a given SCEV as its direct operand.
2021 DenseMap<const SCEV *, SmallPtrSet<const SCEV *, 8> > SCEVUsers;
2022
2023 /// Memoized results from getRange
2024 DenseMap<const SCEV *, ConstantRange> UnsignedRanges;
2025
2026 /// Memoized results from getRange
2027 DenseMap<const SCEV *, ConstantRange> SignedRanges;
2028
2029 /// Used to parameterize getRange
2030 enum RangeSignHint { HINT_RANGE_UNSIGNED, HINT_RANGE_SIGNED };
2031
2032 /// Set the memoized range for the given SCEV.
2033 const ConstantRange &setRange(const SCEV *S, RangeSignHint Hint,
2034 ConstantRange CR) {
2035 DenseMap<const SCEV *, ConstantRange> &Cache =
2036 Hint == HINT_RANGE_UNSIGNED ? UnsignedRanges : SignedRanges;
2037
2038 auto Pair = Cache.insert_or_assign(S, std::move(CR));
2039 return Pair.first->second;
2040 }
2041
2042 /// Determine the range for a particular SCEV.
2043 /// NOTE: This returns a reference to an entry in a cache. It must be
2044 /// copied if its needed for longer.
2045 LLVM_ABI const ConstantRange &getRangeRef(const SCEV *S, RangeSignHint Hint,
2046 unsigned Depth = 0);
2047
2048 /// Determine the range for a particular SCEV, but evaluates ranges for
2049 /// operands iteratively first.
2050 const ConstantRange &getRangeRefIter(const SCEV *S, RangeSignHint Hint);
2051
2052 /// Determines the range for the affine SCEVAddRecExpr {\p Start,+,\p Step},
2053 /// and whether it may wrap. Helper for \c getRange.
2054 std::pair<ConstantRange, SCEVFlags>
2055 getRangeForAffineAR(const SCEV *Start, const SCEV *Step,
2056 const APInt &MaxBECount);
2057 /// If \p S is a SCEVConstant, return the wrapped constant or nullptr
2058 /// otherwise.
2059 LLVM_ABI static const APInt *getConstantAPIntOrNull(const SCEV *S);
2060
2061 /// Determines the range for the affine non-self-wrapping SCEVAddRecExpr {\p
2062 /// Start,+,\p Step}<nw>.
2063 ConstantRange getRangeForAffineNoSelfWrappingAR(const SCEVAddRecExpr *AddRec,
2064 const SCEV *MaxBECount,
2065 unsigned BitWidth,
2066 RangeSignHint SignHint);
2067
2068 /// Try to compute a range for the affine SCEVAddRecExpr {\p Start,+,\p
2069 /// Step} by "factoring out" a ternary expression from the add recurrence.
2070 /// Helper called by \c getRange.
2071 ConstantRange getRangeViaFactoring(const SCEV *Start, const SCEV *Step,
2072 const APInt &MaxBECount);
2073
2074 /// If the unknown expression U corresponds to a simple recurrence, return
2075 /// a constant range which represents the entire recurrence. Note that
2076 /// *add* recurrences with loop invariant steps aren't represented by
2077 /// SCEVUnknowns and thus don't use this mechanism.
2078 ConstantRange getRangeForUnknownRecurrence(const SCEVUnknown *U);
2079
2080 /// We know that there is no SCEV for the specified value. Analyze the
2081 /// expression recursively.
2082 const SCEV *createSCEV(Value *V);
2083
2084 /// We know that there is no SCEV for the specified value. Create a new SCEV
2085 /// for \p V iteratively.
2086 const SCEV *createSCEVIter(Value *V);
2087 /// Collect operands of \p V for which SCEV expressions should be constructed
2088 /// first. Returns a SCEV directly if it can be constructed trivially for \p
2089 /// V.
2090 const SCEV *getOperandsToCreate(Value *V, SmallVectorImpl<Value *> &Ops);
2091
2092 /// Returns SCEV for the first operand of a phi if all phi operands have
2093 /// identical opcodes and operands.
2094 const SCEV *createNodeForPHIWithIdenticalOperands(PHINode *PN);
2095
2096 /// Provide the special handling we need to analyze PHI SCEVs.
2097 const SCEV *createNodeForPHI(PHINode *PN);
2098
2099 /// Helper function called from createNodeForPHI.
2100 const SCEV *createAddRecFromPHI(PHINode *PN);
2101
2102 /// A helper function for createAddRecFromPHI to handle simple cases.
2103 const SCEV *createSimpleAffineAddRec(PHINode *PN, Value *BEValueV,
2104 Value *StartValueV);
2105
2106 /// Helper function called from createNodeForPHI.
2107 const SCEV *createNodeFromSelectLikePHI(PHINode *PN);
2108
2109 /// Provide special handling for a select-like instruction (currently this
2110 /// is either a select instruction or a phi node). \p Ty is the type of the
2111 /// instruction being processed, that is assumed equivalent to
2112 /// "Cond ? TrueVal : FalseVal".
2113 std::optional<const SCEV *>
2114 createNodeForSelectOrPHIInstWithICmpInstCond(Type *Ty, ICmpInst *Cond,
2115 Value *TrueVal, Value *FalseVal);
2116
2117 /// See if we can model this select-like instruction via umin_seq expression.
2118 const SCEV *createNodeForSelectOrPHIViaUMinSeq(Value *I, Value *Cond,
2119 Value *TrueVal,
2120 Value *FalseVal);
2121
2122 /// Given a value \p V, which is a select-like instruction (currently this is
2123 /// either a select instruction or a phi node), which is assumed equivalent to
2124 /// Cond ? TrueVal : FalseVal
2125 /// see if we can model it as a SCEV expression.
2126 const SCEV *createNodeForSelectOrPHI(Value *V, Value *Cond, Value *TrueVal,
2127 Value *FalseVal);
2128
2129 /// Provide the special handling we need to analyze GEP SCEVs.
2130 const SCEV *createNodeForGEP(GEPOperator *GEP);
2131
2132 /// Implementation code for getSCEVAtScope; called at most once for each
2133 /// SCEV+Loop pair.
2134 SCEVUse computeSCEVAtScope(const SCEV *S, const Loop *L);
2135
2136 /// Return the BackedgeTakenInfo for the given loop, lazily computing new
2137 /// values if the loop hasn't been analyzed yet. The returned result is
2138 /// guaranteed not to be predicated.
2139 BackedgeTakenInfo &getBackedgeTakenInfo(const Loop *L);
2140
2141 /// Similar to getBackedgeTakenInfo, but will add predicates as required
2142 /// with the purpose of returning complete information.
2143 BackedgeTakenInfo &getPredicatedBackedgeTakenInfo(const Loop *L);
2144
2145 /// Compute the number of times the specified loop will iterate.
2146 /// If AllowPredicates is set, we will create new SCEV predicates as
2147 /// necessary in order to return an exact answer.
2148 BackedgeTakenInfo computeBackedgeTakenCount(const Loop *L,
2149 bool AllowPredicates = false);
2150
2151 /// Variant of getSmallConstantTripMultiple taking pre-collected loop
2152 /// \p Guards. \p ExitCount must be computable.
2153 unsigned getSmallConstantTripMultiple(const SCEV *ExitCount,
2154 LoopGuards &Guards);
2155
2156 /// Compute the number of times the backedge of the specified loop will
2157 /// execute if it exits via the specified block. If AllowPredicates is set,
2158 /// this call will try to use a minimal set of SCEV predicates in order to
2159 /// return an exact answer.
2160 ExitLimit computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
2161 bool IsOnlyExit, bool AllowPredicates = false);
2162
2163 // Helper functions for computeExitLimitFromCond to avoid exponential time
2164 // complexity.
2165
2166 class ExitLimitCache {
2167 // It may look like we need key on the whole (L, ExitIfTrue,
2168 // ControlsOnlyExit, AllowPredicates) tuple, but recursive calls to
2169 // computeExitLimitFromCondCached from computeExitLimitFromCondImpl only
2170 // vary the in \c ExitCond and \c ControlsOnlyExit parameters. We remember
2171 // the initial values of the other values to assert our assumption.
2172 SmallDenseMap<PointerIntPair<Value *, 1>, ExitLimit> TripCountMap;
2173
2174 const Loop *L;
2175 bool ExitIfTrue;
2176 bool AllowPredicates;
2177
2178 public:
2179 ExitLimitCache(const Loop *L, bool ExitIfTrue, bool AllowPredicates)
2180 : L(L), ExitIfTrue(ExitIfTrue), AllowPredicates(AllowPredicates) {}
2181
2182 LLVM_ABI std::optional<ExitLimit> find(const Loop *L, Value *ExitCond,
2183 bool ExitIfTrue,
2184 bool ControlsOnlyExit,
2185 bool AllowPredicates);
2186
2187 LLVM_ABI void insert(const Loop *L, Value *ExitCond, bool ExitIfTrue,
2188 bool ControlsOnlyExit, bool AllowPredicates,
2189 const ExitLimit &EL);
2190 };
2191
2192 using ExitLimitCacheTy = ExitLimitCache;
2193
2194 ExitLimit computeExitLimitFromCondCached(ExitLimitCacheTy &Cache,
2195 const Loop *L, Value *ExitCond,
2196 bool ExitIfTrue,
2197 bool ControlsOnlyExit,
2198 bool AllowPredicates);
2199 ExitLimit computeExitLimitFromCondImpl(ExitLimitCacheTy &Cache, const Loop *L,
2200 Value *ExitCond, bool ExitIfTrue,
2201 bool ControlsOnlyExit,
2202 bool AllowPredicates);
2203 std::optional<ScalarEvolution::ExitLimit>
2204 computeExitLimitFromCondFromBinOp(ExitLimitCacheTy &Cache, const Loop *L,
2205 Value *ExitCond, bool ExitIfTrue,
2206 bool AllowPredicates);
2207
2208 /// Compute the number of times the backedge of the specified loop will
2209 /// execute if its exit condition were a conditional branch of the ICmpInst
2210 /// ExitCond and ExitIfTrue. If AllowPredicates is set, this call will try
2211 /// to use a minimal set of SCEV predicates in order to return an exact
2212 /// answer.
2213 ExitLimit computeExitLimitFromICmp(const Loop *L, ICmpInst *ExitCond,
2214 bool ExitIfTrue,
2215 bool IsSubExpr,
2216 bool AllowPredicates = false);
2217
2218 /// Variant of previous which takes the components representing an ICmp
2219 /// as opposed to the ICmpInst itself. Note that the prior version can
2220 /// return more precise results in some cases and is preferred when caller
2221 /// has a materialized ICmp.
2222 ExitLimit computeExitLimitFromICmp(const Loop *L, CmpPredicate Pred,
2223 SCEVUse LHS, SCEVUse RHS, bool IsSubExpr,
2224 bool AllowPredicates = false);
2225
2226 /// Compute the number of times the backedge of the specified loop will
2227 /// execute if its exit condition were a switch with a single exiting case
2228 /// to ExitingBB.
2229 ExitLimit computeExitLimitFromSingleExitSwitch(const Loop *L,
2230 SwitchInst *Switch,
2231 BasicBlock *ExitingBB,
2232 bool IsSubExpr);
2233
2234 /// Compute the exit limit of a loop that is controlled by a
2235 /// "(IV >> 1) != 0" type comparison. We cannot compute the exact trip
2236 /// count in these cases (since SCEV has no way of expressing them), but we
2237 /// can still sometimes compute an upper bound.
2238 ///
2239 /// Return an ExitLimit for a loop whose backedge is guarded by `LHS Pred
2240 /// RHS`.
2241 ExitLimit computeShiftCompareExitLimit(Value *LHS, Value *RHS, const Loop *L,
2243
2244 /// If the loop is known to execute a constant number of times (the
2245 /// condition evolves only from constants), try to evaluate a few iterations
2246 /// of the loop until we get the exit condition gets a value of ExitWhen
2247 /// (true or false). If we cannot evaluate the exit count of the loop,
2248 /// return CouldNotCompute.
2249 const SCEV *computeExitCountExhaustively(const Loop *L, Value *Cond,
2250 bool ExitWhen);
2251
2252 /// Return the number of times an exit condition comparing the specified
2253 /// value to zero will execute. If not computable, return CouldNotCompute.
2254 /// If AllowPredicates is set, this call will try to use a minimal set of
2255 /// SCEV predicates in order to return an exact answer.
2256 ExitLimit howFarToZero(const SCEV *V, const Loop *L, bool IsSubExpr,
2257 bool AllowPredicates = false);
2258
2259 /// Return the number of times an exit condition checking the specified
2260 /// value for nonzero will execute. If not computable, return
2261 /// CouldNotCompute.
2262 ExitLimit howFarToNonZero(const SCEV *V, const Loop *L);
2263
2264 /// Return the number of times an exit condition containing the specified
2265 /// less-than comparison will execute. If not computable, return
2266 /// CouldNotCompute.
2267 ///
2268 /// \p IsSigned specifies whether the less-than is signed.
2269 ///
2270 /// If \p Invert is set, analyze "LHS > RHS" as "~LHS < ~RHS".
2271 ///
2272 /// \p ControlsOnlyExit is true when the LHS < RHS condition directly controls
2273 /// the branch (loops exits only if condition is true). In this case, we can
2274 /// use no-wrap flags to skip overflow checks.
2275 ///
2276 /// If \p AllowPredicates is set, this call will try to use a minimal set of
2277 /// SCEV predicates in order to return an exact answer.
2278 ExitLimit howManyLessThans(const SCEV *LHS, SCEVUse RHS, const Loop *L,
2279 LoopGuards &Guards, bool IsSigned, bool Invert,
2280 bool ControlsOnlyExit,
2281 bool AllowPredicates = false);
2282
2283 /// Return a predecessor of BB (which may not be an immediate predecessor)
2284 /// which has exactly one successor from which BB is reachable, or null if
2285 /// no such block is found.
2286 std::pair<const BasicBlock *, const BasicBlock *>
2287 getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB) const;
2288
2289 /// Test whether the condition described by Pred, LHS, and RHS is true
2290 /// whenever the given FoundCondValue value evaluates to true in given
2291 /// Context. If Context is nullptr, then the found predicate is true
2292 /// everywhere. LHS and FoundLHS may have different type width.
2293 LLVM_ABI bool isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
2294 const SCEV *RHS, const Value *FoundCondValue,
2295 bool Inverse,
2296 const Instruction *Context = nullptr);
2297
2298 /// Test whether the condition described by Pred, LHS, and RHS is true
2299 /// whenever the given FoundCondValue value evaluates to true in given
2300 /// Context. If Context is nullptr, then the found predicate is true
2301 /// everywhere. LHS and FoundLHS must have same type width.
2302 LLVM_ABI bool isImpliedCondBalancedTypes(CmpPredicate Pred, SCEVUse LHS,
2303 SCEVUse RHS, CmpPredicate FoundPred,
2304 SCEVUse FoundLHS, SCEVUse FoundRHS,
2305 const Instruction *CtxI);
2306
2307 /// Test whether the condition described by Pred, LHS, and RHS is true
2308 /// whenever the condition described by FoundPred, FoundLHS, FoundRHS is
2309 /// true in given Context. If Context is nullptr, then the found predicate is
2310 /// true everywhere.
2311 LLVM_ABI bool isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
2312 const SCEV *RHS, CmpPredicate FoundPred,
2313 const SCEV *FoundLHS, const SCEV *FoundRHS,
2314 const Instruction *Context = nullptr);
2315
2316 /// Test whether the condition described by Pred, LHS, and RHS is true
2317 /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
2318 /// true in given Context. If Context is nullptr, then the found predicate is
2319 /// true everywhere.
2320 bool isImpliedCondOperands(CmpPredicate Pred, const SCEV *LHS,
2321 const SCEV *RHS, const SCEV *FoundLHS,
2322 const SCEV *FoundRHS,
2323 const Instruction *Context = nullptr);
2324
2325 /// Test whether the condition described by Pred, LHS, and RHS is true
2326 /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
2327 /// true. Here LHS is an operation that includes FoundLHS as one of its
2328 /// arguments.
2329 bool isImpliedViaOperations(CmpPredicate Pred, const SCEV *LHS,
2330 const SCEV *RHS, const SCEV *FoundLHS,
2331 const SCEV *FoundRHS, unsigned Depth = 0);
2332
2333 /// Test whether the condition described by Pred, LHS, and RHS is true.
2334 /// Use only simple non-recursive types of checks, such as range analysis etc.
2335 bool isKnownViaNonRecursiveReasoning(CmpPredicate Pred, SCEVUse LHS,
2336 SCEVUse RHS);
2337
2338 /// Test whether the condition described by Pred, LHS, and RHS is true
2339 /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
2340 /// true.
2341 bool isImpliedCondOperandsHelper(CmpPredicate Pred, const SCEV *LHS,
2342 const SCEV *RHS, const SCEV *FoundLHS,
2343 const SCEV *FoundRHS);
2344
2345 /// Test whether the condition described by Pred, LHS, and RHS is true
2346 /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
2347 /// true. Utility function used by isImpliedCondOperands. Tries to get
2348 /// cases like "X `sgt` 0 => X - 1 `sgt` -1".
2349 bool isImpliedCondOperandsViaRanges(CmpPredicate Pred, const SCEV *LHS,
2350 const SCEV *RHS, CmpPredicate FoundPred,
2351 const SCEV *FoundLHS,
2352 const SCEV *FoundRHS);
2353
2354 /// Test whether the condition described by Pred, LHS, and RHS is true
2355 /// whenever the condition described by FoundLHS, FoundRHS, and Pred with the
2356 /// other signedness is true.
2357 bool isImpliedCondViaSignFlippedPred(CmpPredicate Pred, const SCEV *LHS,
2358 const SCEV *RHS, const SCEV *FoundLHS,
2359 const SCEV *FoundRHS,
2360 const Instruction *CtxI);
2361
2362 /// Return true if the condition denoted by \p LHS \p Pred \p RHS is implied
2363 /// by a call to @llvm.experimental.guard in \p BB.
2364 bool isImpliedViaGuard(const BasicBlock *BB, CmpPredicate Pred,
2365 const SCEV *LHS, const SCEV *RHS);
2366
2367 /// Test whether the condition described by Pred, LHS, and RHS is true
2368 /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
2369 /// true.
2370 ///
2371 /// This routine tries to rule out certain kinds of integer overflow, and
2372 /// then tries to reason about arithmetic properties of the predicates.
2373 bool isImpliedCondOperandsViaNoOverflow(CmpPredicate Pred, const SCEV *LHS,
2374 const SCEV *RHS, const SCEV *FoundLHS,
2375 const SCEV *FoundRHS);
2376
2377 /// Test whether the condition described by Pred, LHS, and RHS is true
2378 /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
2379 /// true.
2380 ///
2381 /// This routine tries to weaken the known condition basing on fact that
2382 /// FoundLHS is an AddRec.
2383 bool isImpliedCondOperandsViaAddRecStart(CmpPredicate Pred, const SCEV *LHS,
2384 const SCEV *RHS,
2385 const SCEV *FoundLHS,
2386 const SCEV *FoundRHS,
2387 const Instruction *CtxI);
2388
2389 /// Test whether the condition described by Pred, LHS, and RHS is true
2390 /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
2391 /// true.
2392 ///
2393 /// This routine tries to figure out predicate for Phis which are SCEVUnknown
2394 /// if it is true for every possible incoming value from their respective
2395 /// basic blocks.
2396 bool isImpliedViaMerge(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS,
2397 const SCEV *FoundLHS, const SCEV *FoundRHS,
2398 unsigned Depth);
2399
2400 /// Test whether the condition described by Pred, LHS, and RHS is true
2401 /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
2402 /// true.
2403 ///
2404 /// This routine tries to reason about shifts.
2405 bool isImpliedCondOperandsViaShift(CmpPredicate Pred, const SCEV *LHS,
2406 const SCEV *RHS, const SCEV *FoundLHS,
2407 const SCEV *FoundRHS);
2408
2409 /// Test whether the condition described by Pred, LHS, and RHS is true
2410 /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
2411 /// true.
2412 ///
2413 /// This routine tries to analyze if the SCEV differences match.
2414 bool isImpliedCondOperandsViaMatchingDiff(CmpPredicate Pred, const SCEV *LHS,
2415 const SCEV *RHS,
2416 const SCEV *FoundLHS,
2417 const SCEV *FoundRHS);
2418
2419 /// If we know that the specified Phi is in the header of its containing
2420 /// loop, we know the loop executes a constant number of times, and the PHI
2421 /// node is just a recurrence involving constants, fold it.
2422 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt &BEs,
2423 const Loop *L);
2424
2425 /// Test if the given expression is known to satisfy the condition described
2426 /// by Pred and the known constant ranges of LHS and RHS.
2427 bool isKnownPredicateViaConstantRanges(CmpPredicate Pred, SCEVUse LHS,
2428 SCEVUse RHS);
2429
2430 /// Try to prove the condition described by "LHS Pred RHS" by ruling out
2431 /// integer overflow.
2432 ///
2433 /// For instance, this will return true for "A s< (A + C)<nsw>" if C is
2434 /// positive.
2435 bool isKnownPredicateViaNoOverflow(CmpPredicate Pred, SCEVUse LHS,
2436 SCEVUse RHS);
2437
2438 /// Try to split Pred LHS RHS into logical conjunctions (and's) and try to
2439 /// prove them individually.
2440 bool isKnownPredicateViaSplitting(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS,
2441 unsigned Depth);
2442
2443 /// Try to match the Expr as "(L + R)<Flags>".
2444 bool splitBinaryAdd(SCEVUse Expr, SCEVUse &L, SCEVUse &R, SCEVFlags &Flags);
2445
2446 /// Forget predicated/non-predicated backedge taken counts for the given loop.
2447 void forgetBackedgeTakenCounts(const Loop *L, bool Predicated);
2448
2449 /// Drop memoized information for all \p SCEVs.
2450 void forgetMemoizedResults(ArrayRef<SCEVUse> SCEVs);
2451
2452 /// Helper for forgetMemoizedResults.
2453 void forgetMemoizedResultsImpl(const SCEV *S);
2454
2455 /// Iterate over instructions in \p Worklist and their users. Erase entries
2456 /// from ValueExprMap and collect SCEV expressions in \p ToForget
2457 void visitAndClearUsers(SmallVectorImpl<Instruction *> &Worklist,
2458 SmallPtrSetImpl<Instruction *> &Visited,
2459 SmallVectorImpl<SCEVUse> &ToForget);
2460
2461 /// Erase Value from ValueExprMap and ExprValueMap.
2462 void eraseValueFromMap(Value *V);
2463
2464 /// Insert V to S mapping into ValueExprMap and ExprValueMap.
2465 void insertValueToMap(Value *V, const SCEV *S);
2466
2467 /// Return false iff given SCEV contains a SCEVUnknown with NULL value-
2468 /// pointer.
2469 bool checkValidity(const SCEV *S) const;
2470
2471 /// Return true if `ExtendOpTy`({`Start`,+,`Step`}) can be proved to be
2472 /// equal to {`ExtendOpTy`(`Start`),+,`ExtendOpTy`(`Step`)}. This is
2473 /// equivalent to proving no signed (resp. unsigned) wrap in
2474 /// {`Start`,+,`Step`} if `ExtendOpTy` is `SCEVSignExtendExpr`
2475 /// (resp. `SCEVZeroExtendExpr`).
2476 template <typename ExtendOpTy>
2477 bool proveNoWrapByVaryingStart(const SCEV *Start, const SCEV *Step,
2478 const Loop *L);
2479
2480 /// Try to infer NSW or NUW on \p AR relying on ConstantRange manipulation.
2481 void inferNoWrapViaConstantRanges(const SCEVAddRecExpr *AR);
2482
2483 /// Try to prove NSW on \p AR by proving facts about conditions known on
2484 /// entry and backedge.
2485 SCEVFlags proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR);
2486
2487 /// Try to prove NUW on \p AR by proving facts about conditions known on
2488 /// entry and backedge.
2489 SCEVFlags proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR);
2490
2491 std::optional<MonotonicPredicateType>
2492 getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
2494
2495 /// Return SCEV no-wrap flags that can be proven based on reasoning about
2496 /// how poison produced from no-wrap flags on this value (e.g. a nuw add)
2497 /// would trigger undefined behavior on overflow.
2498 SCEVFlags getNoWrapFlagsFromUB(const Value *V);
2499
2500 /// Return a scope which provides an upper bound on the defining scope of
2501 /// 'S'. Specifically, return the first instruction in said bounding scope.
2502 /// Return nullptr if the scope is trivial (function entry).
2503 /// (See scope definition rules associated with flag discussion above)
2504 const Instruction *getNonTrivialDefiningScopeBound(const SCEV *S);
2505
2506 /// Return a scope which provides an upper bound on the defining scope for
2507 /// a SCEV with the operands in Ops. The outparam Precise is set if the
2508 /// bound found is a precise bound (i.e. must be the defining scope.)
2509 const Instruction *getDefiningScopeBound(ArrayRef<SCEVUse> Ops,
2510 bool &Precise);
2511
2512 /// Wrapper around the above for cases which don't care if the bound
2513 /// is precise.
2514 const Instruction *getDefiningScopeBound(ArrayRef<SCEVUse> Ops);
2515
2516 /// Given two instructions in the same function, return true if we can
2517 /// prove B must execute given A executes.
2518 bool isGuaranteedToTransferExecutionTo(const Instruction *A,
2519 const Instruction *B);
2520
2521 /// Return true if the SCEV corresponding to \p I is never poison. Proving
2522 /// this is more complex than proving that just \p I is never poison, since
2523 /// SCEV commons expressions across control flow, and you can have cases
2524 /// like:
2525 ///
2526 /// idx0 = a + b;
2527 /// ptr[idx0] = 100;
2528 /// if (<condition>) {
2529 /// idx1 = a +nsw b;
2530 /// ptr[idx1] = 200;
2531 /// }
2532 ///
2533 /// where the SCEV expression (+ a b) is guaranteed to not be poison (and
2534 /// hence not sign-overflow) only if "<condition>" is true. Since both
2535 /// `idx0` and `idx1` will be mapped to the same SCEV expression, (+ a b),
2536 /// it is not okay to annotate (+ a b) with <nsw> in the above example.
2537 bool isSCEVExprNeverPoison(const Instruction *I);
2538
2539 /// This is like \c isSCEVExprNeverPoison but it specifically works for
2540 /// instructions that will get mapped to SCEV add recurrences. Return true
2541 /// if \p I will never generate poison under the assumption that \p I is an
2542 /// add recurrence on the loop \p L.
2543 bool isAddRecNeverPoison(const Instruction *I, const Loop *L);
2544
2545 /// Similar to createAddRecFromPHI, but with the additional flexibility of
2546 /// suggesting runtime overflow checks in case casts are encountered.
2547 /// If successful, the analysis records that for this loop, \p SymbolicPHI,
2548 /// which is the UnknownSCEV currently representing the PHI, can be rewritten
2549 /// into an AddRec, assuming some predicates; The function then returns the
2550 /// AddRec and the predicates as a pair, and caches this pair in
2551 /// PredicatedSCEVRewrites.
2552 /// If the analysis is not successful, a mapping from the \p SymbolicPHI to
2553 /// itself (with no predicates) is recorded, and a nullptr with an empty
2554 /// predicates vector is returned as a pair.
2555 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
2556 createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI);
2557
2558 /// Return the smallest signed (\p IsSigned) or unsigned value for \p S. If \p
2559 /// Invert, return it for complement ~S instead.
2560 APInt getRangeMin(const SCEV *S, bool IsSigned, bool Invert = false) {
2561 if (Invert)
2562 return ~getRangeMax(S, IsSigned);
2563 return IsSigned ? getSignedRangeMin(S) : getUnsignedRangeMin(S);
2564 }
2565 /// Return the largest signed (\p IsSigned) or unsigned value for \p S. If \p
2566 /// Invert, return it for complement ~S instead.
2567 APInt getRangeMax(const SCEV *S, bool IsSigned, bool Invert = false) {
2568 if (Invert)
2569 return ~getRangeMin(S, IsSigned);
2570 return IsSigned ? getSignedRangeMax(S) : getUnsignedRangeMax(S);
2571 }
2572
2573 /// Compute the maximum backedge count based on the range of values
2574 /// permitted by Start, End, and Stride. This is for loops of the form
2575 /// {Start, +, Stride} LT End, or, if \p Invert is set, for the equivalent
2576 /// "~Start < ~End" form of {Start, +, -Stride} GT End.
2577 ///
2578 /// Preconditions:
2579 /// * the induction variable is known to be positive.
2580 /// * the induction variable is assumed not to overflow (i.e. either it
2581 /// actually doesn't, or we'd have to immediately execute UB)
2582 /// We *don't* assert these preconditions so please be careful.
2583 const SCEV *computeMaxBECountForLT(const SCEV *Start, const SCEV *Stride,
2584 const SCEV *End, unsigned BitWidth,
2585 bool IsSigned, bool Invert);
2586
2587 /// Verify if a linear IV with positive \p Stride can overflow when compared
2588 /// against the invariant \p RHS with a less-than. If \p Invert is true, both
2589 /// the IV and \p RHS are inverted
2590 bool canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, bool IsSigned,
2591 bool Invert = false);
2592
2593 /// Get add expr already created or create a new one.
2594 const SCEV *getOrCreateAddExpr(ArrayRef<SCEVUse> Ops, SCEVFlags Flags);
2595
2596 /// Get mul expr already created or create a new one.
2597 const SCEV *getOrCreateMulExpr(ArrayRef<SCEVUse> Ops, SCEVFlags Flags);
2598
2599 // Get addrec expr already created or create a new one.
2600 const SCEV *getOrCreateAddRecExpr(ArrayRef<SCEVUse> Ops, const Loop *L,
2601 SCEVFlags Flags);
2602
2603 // Get UDiv expression already created or create a new one.
2604 const SCEV *getOrCreateUDivExpr(SCEVUse LHS, SCEVUse RHS);
2605
2606 /// Return x if \p Val is f(x) where f is a 1-1 function.
2607 const SCEV *stripInjectiveFunctions(const SCEV *Val) const;
2608
2609 /// Find all of the loops transitively used in \p S, and fill \p LoopsUsed.
2610 /// A loop is considered "used" by an expression if it contains
2611 /// an add rec on said loop.
2612 void getUsedLoops(const SCEV *S, SmallPtrSetImpl<const Loop *> &LoopsUsed);
2613
2614 /// Look for a SCEV expression with type \p SCEVType and operands \p Ops in
2615 /// UniqueSCEVs. If \p SCEVType is scAddRecExpr, the loop \p L must be passed.
2616 /// Return if found, else nullptr.
2617 SCEV *findExistingSCEVInCache(SCEVTypes SCEVType, ArrayRef<SCEVUse> Ops,
2618 const Loop *L = nullptr);
2619
2620 /// Get reachable blocks in this function, making limited use of SCEV
2621 /// reasoning about conditions.
2622 void getReachableBlocks(SmallPtrSetImpl<BasicBlock *> &Reachable,
2623 Function &F);
2624
2625 /// Return the given SCEV expression with a new set of operands.
2626 /// This preserves the origial nowrap flags.
2627 const SCEV *getWithOperands(const SCEV *S, SmallVectorImpl<SCEVUse> &NewOps);
2628
2629 FoldingSet<SCEV> UniqueSCEVs;
2630 FoldingSet<SCEVPredicate> UniquePreds;
2631 BumpPtrAllocator SCEVAllocator;
2632
2633 /// Fast lookup cache for SCEVConstant nodes, using the fact that IR constants
2634 /// are already uniqued.
2635 DenseMap<ConstantInt *, SCEVConstant *> ConstantSCEVs;
2636
2637 /// This maps loops to a list of addrecs that directly use said loop.
2638 DenseMap<const Loop *, SmallVector<const SCEVAddRecExpr *, 4>> LoopUsers;
2639
2640 /// Cache tentative mappings from UnknownSCEVs in a Loop, to a SCEV expression
2641 /// they can be rewritten into under certain predicates.
2642 DenseMap<std::pair<const SCEVUnknown *, const Loop *>,
2643 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
2644 PredicatedSCEVRewrites;
2645
2646 /// Set of AddRecs for which proving NUW via an induction has already been
2647 /// tried.
2648 SmallPtrSet<const SCEVAddRecExpr *, 16> UnsignedWrapViaInductionTried;
2649
2650 /// Set of AddRecs for which proving NSW via an induction has already been
2651 /// tried.
2652 SmallPtrSet<const SCEVAddRecExpr *, 16> SignedWrapViaInductionTried;
2653
2654 /// The head of a linked list of all SCEVUnknown values that have been
2655 /// allocated. This is used by releaseMemory to locate them all and call
2656 /// their destructors.
2657 SCEVUnknown *FirstUnknown = nullptr;
2658
2659 /// OrderID to assign to the next SCEVUnknown created.
2660 unsigned NextUnknownOrderID = 0;
2661};
2662
2663/// Analysis pass that exposes the \c ScalarEvolution for a function.
2665 : public AnalysisInfoMixin<ScalarEvolutionAnalysis> {
2667
2668 LLVM_ABI static AnalysisKey Key;
2669
2670public:
2672
2674};
2675
2676/// Verifier pass for the \c ScalarEvolutionAnalysis results.
2678 : public RequiredPassInfoMixin<ScalarEvolutionVerifierPass> {
2679public:
2681};
2682
2683/// Printer pass for the \c ScalarEvolutionAnalysis results.
2685 : public RequiredPassInfoMixin<ScalarEvolutionPrinterPass> {
2686 raw_ostream &OS;
2687
2688public:
2689 explicit ScalarEvolutionPrinterPass(raw_ostream &OS) : OS(OS) {}
2690
2692};
2693
2695 std::unique_ptr<ScalarEvolution> SE;
2696
2697public:
2698 static char ID;
2699
2701
2702 ScalarEvolution &getSE() { return *SE; }
2703 const ScalarEvolution &getSE() const { return *SE; }
2704
2705 bool runOnFunction(Function &F) override;
2706 void releaseMemory() override;
2707 void getAnalysisUsage(AnalysisUsage &AU) const override;
2708 void print(raw_ostream &OS, const Module * = nullptr) const override;
2709 void verifyAnalysis() const override;
2710};
2711
2712/// An interface layer with SCEV used to manage how we see SCEV expressions
2713/// for values in the context of existing predicates. We can add new
2714/// predicates, but we cannot remove them.
2715///
2716/// This layer has multiple purposes:
2717/// - provides a simple interface for SCEV versioning.
2718/// - guarantees that the order of transformations applied on a SCEV
2719/// expression for a single Value is consistent across two different
2720/// getSCEV calls. This means that, for example, once we've obtained
2721/// an AddRec expression for a certain value through expression
2722/// rewriting, we will continue to get an AddRec expression for that
2723/// Value.
2724/// - lowers the number of expression rewrites.
2726public:
2728
2729 LLVM_ABI const SCEVPredicate &getPredicate() const;
2730
2731 /// Returns the SCEV expression of V, in the context of the current SCEV
2732 /// predicate. The order of transformations applied on the expression of V
2733 /// returned by ScalarEvolution is guaranteed to be preserved, even when
2734 /// adding new predicates.
2735 LLVM_ABI const SCEV *getSCEV(Value *V);
2736
2737 /// Returns the rewritten SCEV for \p Expr in the context of the current SCEV
2738 /// predicate. The order of transformations applied on the expression of \p
2739 /// Expr returned by ScalarEvolution is guaranteed to be preserved, even when
2740 /// adding new predicates.
2741 LLVM_ABI const SCEV *getPredicatedSCEV(const SCEV *Expr);
2742
2743 /// Get the (predicated) backedge count for the analyzed loop.
2745
2746 /// Get the (predicated) symbolic max backedge count for the analyzed loop.
2748
2749 /// Returns the upper bound of the loop trip count as a normal unsigned
2750 /// value, or 0 if the trip count is unknown.
2752
2753 /// Adds a new predicate.
2755
2756 /// Adds all predicates in \p Preds.
2758
2759 /// Attempts to produce an AddRecExpr for V by adding additional SCEV
2760 /// predicates. If we can't transform the expression into an AddRecExpr we
2761 /// return nullptr and not add additional SCEV predicates to the current
2762 /// context. If \p WrapPredsAdded is non-null, the required predicates are
2763 /// collected there instead of being added to this context.
2764 LLVM_ABI const SCEVAddRecExpr *
2766 SmallVectorImpl<const SCEVPredicate *> *WrapPredsAdded = nullptr);
2767
2768 /// Returns the ScalarEvolution analysis used.
2769 ScalarEvolution *getSE() const { return &SE; }
2770
2771 /// We need to explicitly define the copy constructor due to the ownership of
2772 /// the SCEVUnionPredicate Preds.
2774
2775 /// Print the SCEV mappings done by the Predicated Scalar Evolution.
2776 /// The printed text is indented by \p Depth.
2777 LLVM_ABI void print(raw_ostream &OS, unsigned Depth) const;
2778
2779 /// Check if \p AR1 and \p AR2 are equal, while taking into account
2780 /// Equal predicates in Preds and \p ExtraPreds.
2782 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2,
2783 ArrayRef<const SCEVPredicate *> ExtraPreds = {}) const;
2784
2785private:
2786 /// Increments the version number of the predicate. This needs to be called
2787 /// every time the SCEV predicate changes.
2788 void updateGeneration();
2789
2790 /// Holds a SCEV and the version number of the SCEV predicate used to
2791 /// perform the rewrite of the expression.
2792 using RewriteEntry = std::pair<unsigned, const SCEV *>;
2793
2794 /// Maps a SCEV to the rewrite result of that SCEV at a certain version
2795 /// number. If this number doesn't match the current Generation, we will
2796 /// need to do a rewrite. To preserve the transformation order of previous
2797 /// rewrites, we will rewrite the previous result instead of the original
2798 /// SCEV.
2799 DenseMap<const SCEV *, RewriteEntry> RewriteMap;
2800
2801 /// The ScalarEvolution analysis.
2802 ScalarEvolution &SE;
2803
2804 /// The analyzed Loop.
2805 const Loop &L;
2806
2807 /// The SCEVPredicate that forms our context. We will rewrite all
2808 /// expressions assuming that this predicate true.
2809 std::unique_ptr<SCEVUnionPredicate> Preds;
2810
2811 /// Marks the version of the SCEV predicate used. When rewriting a SCEV
2812 /// expression we mark it with the version of the predicate. We use this to
2813 /// figure out if the predicate has changed from the last rewrite of the
2814 /// SCEV. If so, we need to perform a new rewrite.
2815 unsigned Generation = 0;
2816
2817 /// The backedge taken count.
2818 const SCEV *BackedgeCount = nullptr;
2819
2820 /// The symbolic backedge taken count.
2821 const SCEV *SymbolicMaxBackedgeCount = nullptr;
2822
2823 /// The constant max trip count for the loop.
2824 std::optional<unsigned> SmallConstantMaxTripCount;
2825};
2826
2827template <> struct DenseMapInfo<ScalarEvolution::FoldID> {
2828 static unsigned getHashValue(const ScalarEvolution::FoldID &Val) {
2829 return Val.computeHash();
2830 }
2831
2834 return LHS == RHS;
2835 }
2836};
2837
2838template <> inline const SCEV *SCEVUseT<const SCEV *>::getCanonical() const {
2839 return getPointer()->getCanonical();
2840}
2841
2842template <>
2844 if (A.getPointer() == B.getPointer()) {
2845 A.setInt(A.getInt() | B.getInt());
2846 return A;
2847 }
2848 if (A.getCanonical() == B.getCanonical())
2849 return A.getCanonical();
2850 return SCEVUse();
2851}
2852
2853template <typename SCEVPtrT>
2855 getPointer()->print(OS);
2856 SCEVFlags Flags = getUseNoWrapFlags();
2857 if (any(Flags & SCEV::FlagNUW))
2858 OS << "<u nuw>";
2859 if (any(Flags & SCEV::FlagNSW))
2860 OS << "<u nsw>";
2861}
2862
2863#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2864template <typename SCEVPtrT>
2866 print(dbgs());
2867 dbgs() << '\n';
2868}
2869#endif
2870
2871} // end namespace llvm
2872
2873#endif // LLVM_ANALYSIS_SCALAREVOLUTION_H
const TargetLowering & TLI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
uint64_t uint64_t
constexpr LLT S1
This file implements a class to represent arbitrary precision integral constant values and operations...
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_ABI
Definition Compiler.h:211
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:702
SmallPtrSet< const BasicBlock *, 8 > VisitedBlocks
This file defines DenseMapInfo traits for DenseMap.
This file defines the DenseMap class.
static bool runOnFunction(Function &F, bool PostInlining)
static bool isSigned(unsigned Opcode)
This file defines a hash set that can be used to remove duplication of nodes in a graph.
Hexagon Common GEP
Value * getPointer(Value *Ptr)
This header defines various interfaces for pass management in LLVM.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
SmallVector< MachineOperand, 4 > Cond
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define P(N)
This file defines the PointerIntPair class.
SI Fold Operands
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static int Lookup(ArrayRef< TableEntry > Table, unsigned Opcode)
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
Represent the analysis usage information of a pass.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:61
Value handle with callbacks on RAUW and destruction.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
This is the shared class of boolean and integer constants.
Definition Constants.h:87
This class represents a range of values.
This is an important base class in LLVM.
Definition Constant.h:44
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
This class describes a reference to an interned FoldingSetNodeID, which can be a useful to store node...
Definition FoldingSet.h:123
This class is used to gather all the unique data bits of a node.
Definition FoldingSet.h:162
FoldingSetNode()=default
FunctionPass(char &pid)
Definition Pass.h:314
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags none()
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition Operator.h:78
bool operator>(const PointerIntPair &RHS) const
Value handle that poisons itself if the Value is deleted.
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
LLVM_ABI void addPredicate(const SCEVPredicate &Pred)
Adds a new predicate.
ScalarEvolution * getSE() const
Returns the ScalarEvolution analysis used.
LLVM_ABI const SCEVPredicate & getPredicate() const
LLVM_ABI const SCEV * getPredicatedSCEV(const SCEV *Expr)
Returns the rewritten SCEV for Expr in the context of the current SCEV predicate.
LLVM_ABI bool areAddRecsEqualWithPreds(const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2, ArrayRef< const SCEVPredicate * > ExtraPreds={}) const
Check if AR1 and AR2 are equal, while taking into account Equal predicates in Preds and ExtraPreds.
LLVM_ABI const SCEVAddRecExpr * getAsAddRec(Value *V, SmallVectorImpl< const SCEVPredicate * > *WrapPredsAdded=nullptr)
Attempts to produce an AddRecExpr for V by adding additional SCEV predicates.
LLVM_ABI void print(raw_ostream &OS, unsigned Depth) const
Print the SCEV mappings done by the Predicated Scalar Evolution.
LLVM_ABI PredicatedScalarEvolution(ScalarEvolution &SE, Loop &L)
LLVM_ABI unsigned getSmallConstantMaxTripCount()
Returns the upper bound of the loop trip count as a normal unsigned value, or 0 if the trip count is ...
LLVM_ABI void addPredicates(ArrayRef< const SCEVPredicate * > Preds)
Adds all predicates in Preds.
LLVM_ABI const SCEV * getBackedgeTakenCount()
Get the (predicated) backedge count for the analyzed loop.
LLVM_ABI const SCEV * getSymbolicMaxBackedgeTakenCount()
Get the (predicated) symbolic max backedge count for the analyzed loop.
LLVM_ABI const SCEV * getSCEV(Value *V)
Returns the SCEV expression of V, in the context of the current SCEV predicate.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
This node represents a polynomial recurrence on the trip count of the specified loop.
SCEVComparePredicate(const FoldingSetNodeIDRef ID, const ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
const SCEV * getRHS() const
Returns the right hand side of the predicate.
ICmpInst::Predicate getPredicate() const
bool isAlwaysTrue() const override
Returns true if the predicate is always true.
const SCEV * getLHS() const
Returns the left hand side of the predicate.
static bool classof(const SCEVPredicate *P)
Methods for support type inquiry through isa, cast, and dyn_cast:
bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override
Implementation of the SCEVPredicate interface.
This class represents a constant integer value.
This class represents an assumption made using SCEV expressions which can be checked at run-time.
SCEVPredicateKind getKind() const
virtual unsigned getComplexity() const
Returns the estimated complexity of this predicate.
SCEVPredicate & operator=(const SCEVPredicate &)=default
SCEVPredicate(const SCEVPredicate &)=default
virtual bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const =0
Returns true if this predicate implies N.
virtual void print(raw_ostream &OS, unsigned Depth=0) const =0
Prints a textual representation of this predicate with an indentation of Depth.
~SCEVPredicate()=default
virtual bool isAlwaysTrue() const =0
Returns true if the predicate is always true.
SCEVPredicateKind Kind
unsigned getComplexity() const override
We estimate the complexity of a union predicate as the size number of predicates in the union.
SCEVUnionPredicate(ArrayRef< const SCEVPredicate * > Preds, ScalarEvolution &SE)
Union predicates don't get cached so create a dummy set ID for it.
SCEVUnionPredicate getUnionWith(const SCEVPredicate *N, ScalarEvolution &SE) const
Returns a new SCEVUnionPredicate that is the union of this predicate and the given predicate N.
ArrayRef< const SCEVPredicate * > getPredicates() const
static bool classof(const SCEVPredicate *P)
Methods for support type inquiry through isa, cast, and dyn_cast:
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
This class represents an assumption made on an AddRec expression.
IncrementWrapFlags
Similar to SCEVFlags, but with slightly different semantics for FlagNUSW.
SCEVWrapPredicate(const FoldingSetNodeIDRef ID, const SCEVAddRecExpr *AR, IncrementWrapFlags Flags)
static SCEVWrapPredicate::IncrementWrapFlags setFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OnFlags)
static SCEVWrapPredicate::IncrementWrapFlags clearFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OffFlags)
Convenient IncrementWrapFlags manipulation methods.
static bool classof(const SCEVPredicate *P)
Methods for support type inquiry through isa, cast, and dyn_cast:
IncrementWrapFlags getFlags() const
Returns the set assumed no overflow flags.
static SCEVWrapPredicate::IncrementWrapFlags maskFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, int Mask)
This class represents an analyzed expression in the program.
unsigned short getExpressionSize() const
SCEV & operator=(const SCEV &)=delete
static constexpr auto FlagsNoWrapMask
LLVM_ABI bool isOne() const
Return true if the expression is a constant one.
SCEV(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, unsigned short ExpressionSize, Type *Ty)
static constexpr auto FlagNUW
LLVM_ABI void computeAndSetCanonical(ScalarEvolution &SE)
Compute and set the canonical SCEV, by constructing a SCEV with the same operands,...
LLVM_ABI bool isZero() const
Return true if the expression is a constant zero.
const SCEV * getCanonical() const
Return the canonical SCEV.
SCEV(const SCEV &)=delete
static constexpr auto FlagsMask
const SCEV * CanonicalSCEV
Pointer to the canonical version of the SCEV, i.e.
LLVM_ABI void dump() const
This method is used for debugging.
Type *const Ty
Immutable type of the SCEV.
LLVM_ABI bool isAllOnesValue() const
Return true if the expression is a constant all-ones value.
LLVM_ABI bool isNonConstantNegative() const
Return true if the specified scev is negated, but not a constant.
static constexpr auto FlagNSW
LLVM_ABI ArrayRef< SCEVUse > operands() const
Return operands of this SCEV expression.
const unsigned short ExpressionSize
Type * getType() const
Return the LLVM type of this SCEV expression.
static constexpr auto FlagNone
LLVM_ABI void print(raw_ostream &OS) const
Print out the internal representation of this scalar to the specified stream.
SCEVTypes getSCEVType() const
unsigned short SubclassData
This field is initialized to zero and may be used in subclasses to store miscellaneous information.
static constexpr auto FlagNW
Analysis pass that exposes the ScalarEvolution for a function.
LLVM_ABI ScalarEvolution run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Verifier pass for the ScalarEvolutionAnalysis results.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
const ScalarEvolution & getSE() const
bool operator==(const FoldID &RHS) const
FoldID(SCEVTypes C, SCEVUse Op, const Type *Ty)
static LoopGuards collectOnDemand(const Loop *L, ScalarEvolution &SE)
Return loop guards for loop L, which are collected on first use.
The main scalar evolution driver.
LLVM_ABI const SCEV * getUDivExpr(SCEVUse LHS, SCEVUse RHS)
Get a canonical unsigned division expression, or something simpler if possible.
const SCEV * getConstantMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEVConstant that is greater than or equal to (i.e.
const DataLayout & getDataLayout() const
Return the DataLayout associated with the module this SCEV instance is operating on.
LLVM_ABI bool isKnownNonNegative(const SCEV *S)
Test if the given expression is known to be non-negative.
LLVM_ABI bool isKnownOnEveryIteration(CmpPredicate 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 ...
static bool hasFlags(SCEVFlags Flags, SCEVFlags TestFlags)
LLVM_ABI std::optional< LoopInvariantPredicate > getLoopInvariantExitCondDuringFirstIterationsImpl(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI, const SCEV *MaxIter)
LLVM_ABI const SCEV * getUDivCeilSCEV(const SCEV *N, const SCEV *D)
Compute ceil(N / D).
LLVM_ABI std::optional< LoopInvariantPredicate > getLoopInvariantExitCondDuringFirstIterations(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI, const SCEV *MaxIter)
If the result of the predicate LHS Pred RHS is loop invariant with respect to L at given Context duri...
LLVM_ABI Type * getWiderType(Type *Ty1, Type *Ty2) const
LLVM_ABI const SCEV * getAbsExpr(const SCEV *Op, bool IsNSW)
LLVM_ABI bool isKnownNonPositive(const SCEV *S)
Test if the given expression is known to be non-positive.
LLVM_ABI const SCEV * getElementCount(Type *Ty, ElementCount EC, SCEVFlags Flags=SCEV::FlagNone)
LLVM_ABI bool isKnownNegative(const SCEV *S)
Test if the given expression is known to be negative.
LLVM_ABI SCEVUse getZeroExtendExprImpl(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI const SCEV * getPredicatedConstantMaxBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getConstantMaxBackedgeTakenCount, except it will add a set of SCEV predicates to Predicate...
LLVM_ABI const SCEV * removePointerBase(const SCEV *S)
Compute an expression equivalent to S - getPointerBase(S).
LLVM_ABI bool isLoopEntryGuardedByCond(const Loop *L, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether entry to the loop is protected by a conditional between LHS and RHS.
LLVM_ABI bool isKnownNonZero(const SCEV *S)
Test if the given expression is known to be non-zero.
LLVM_ABI const SCEV * getURemExpr(SCEVUse LHS, SCEVUse RHS)
Represents an unsigned remainder expression based on unsigned division.
LLVM_ABI 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...
LLVM_ABI const SCEV * getSMinExpr(SCEVUse LHS, SCEVUse RHS)
LLVM_ABI 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...
const SCEV * getZero(Type *Ty)
Return a SCEV for the constant 0 of a specific type.
LLVM_ABI bool willNotOverflow(Instruction::BinaryOps BinOp, bool Signed, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI=nullptr)
Is operation BinOp between LHS and RHS provably does not have a signed/unsigned overflow (Signed)?
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEVFlags Flags=SCEV::FlagNone, unsigned Depth=0)
Return LHS-RHS.
LLVM_ABI ExitLimit computeExitLimitFromCond(const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit, bool AllowPredicates=false)
Compute the number of times the backedge of the specified loop will execute if its exit condition wer...
LLVM_ABI const SCEV * getMinMaxExpr(SCEVTypes Kind, SmallVectorImpl< SCEVUse > &Operands)
LLVM_ABI const SCEVPredicate * getEqualPredicate(const SCEV *LHS, const SCEV *RHS)
LLVM_ABI unsigned getSmallConstantTripMultiple(const Loop *L, const SCEV *ExitCount)
Returns the largest constant divisor of the trip count as a normal unsigned value,...
LLVM_ABI SCEVUse getSCEVAtScope(const SCEV *S, const Loop *L)
Return a SCEV expression for the specified value at the specified scope in the program.
LLVM_ABI uint64_t getTypeSizeInBits(Type *Ty) const
Return the size in bits of the specified type, for which isSCEVable must return true.
LLVM_ABI void registerUser(const SCEV *User, ArrayRef< SCEVUse > Ops)
Notify this ScalarEvolution that User directly uses SCEVs in Ops.
LLVM_ABI const SCEV * getConstant(ConstantInt *V)
LLVM_ABI const SCEV * getPredicatedBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getBackedgeTakenCount, except it will add a set of SCEV predicates to Predicates that are ...
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
SCEVUse getSCEVAtExit(Value *V, const Loop *L, const BasicBlock *ExitingBlock)
This is a convenience function which does getSCEVAtExit(getSCEV(V), L, ExitingBlock).
ConstantRange getSignedRange(const SCEV *S)
Determine the signed range for a particular SCEV.
LLVM_ABI const SCEV * getNoopOrSignExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
SCEVUse getAddExpr(SCEVUse Op0, SCEVUse Op1, SCEVUse Op2, SCEVFlagsPair Flags={}, unsigned Depth=0)
static SCEVFlags setFlags(SCEVFlags Flags, SCEVFlags OnFlags)
static LLVM_ABI bool isGuaranteedNotToBePoison(const SCEV *Op)
Returns true if Op is guaranteed to not be poison.
bool loopHasNoAbnormalExits(const Loop *L)
Return true if the loop has no abnormal exits.
LLVM_ABI const SCEV * getTripCountFromExitCount(const SCEV *ExitCount)
A version of getTripCountFromExitCount below which always picks an evaluation type which can not resu...
LLVM_ABI ScalarEvolution(Function &F, TargetLibraryInfo &TLI, AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI)
SCEVUse getAddExpr(SCEVUse LHS, SCEVUse RHS, SCEVFlagsPair Flags={}, unsigned Depth=0)
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
LLVM_ABI const SCEV * getTruncateOrNoop(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI void forgetValues(ArrayRef< Value * > Values)
Batched forgetValue: invalidates all Values in one shared def-use walk, avoiding the redundant re-tra...
LLVM_ABI const SCEV * getSequentialMinMaxExpr(SCEVTypes Kind, SmallVectorImpl< SCEVUse > &Operands)
LLVM_ABI const SCEV * getCastExpr(SCEVTypes Kind, SCEVUse Op, Type *Ty)
LLVM_ABI std::optional< bool > evaluatePredicateAt(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI)
Check whether the condition described by Pred, LHS, and RHS is true or false in the given Context.
LLVM_ABI SCEVUse getAddRecExpr(SCEVUse Start, SCEVUse Step, const Loop *L, SCEVFlagsPair Flags)
Get an add recurrence expression for the specified loop.
LLVM_ABI unsigned getSmallConstantMaxTripCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Returns the upper bound of the loop trip count as a normal unsigned value.
LLVM_ABI bool isKnownMultipleOf(const SCEV *S, uint64_t M, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Check that S is a multiple of M.
LLVM_ABI bool isBackedgeTakenCountMaxOrZero(const Loop *L)
Return true if the backedge taken count is either the value returned by getConstantMaxBackedgeTakenCo...
LLVM_ABI 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...
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI bool isKnownPositive(const SCEV *S)
Test if the given expression is known to be positive.
LLVM_ABI bool SimplifyICmpOperands(CmpPredicate &Pred, SCEVUse &LHS, SCEVUse &RHS, unsigned Depth=0)
Simplify LHS and RHS in a comparison with predicate Pred.
APInt getUnsignedRangeMin(const SCEV *S)
Determine the min of the unsigned range for a particular SCEV.
static SCEVFlags clearFlags(SCEVFlags Flags, SCEVFlags OffFlags)
LLVM_ABI const SCEV * getOffsetOfExpr(Type *IntTy, StructType *STy, unsigned FieldNo)
Return an expression for offsetof on the given field with type IntTy.
LLVM_ABI LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L)
Return the "disposition" of the given SCEV with respect to the given loop.
static SCEVFlags maskFlags(SCEVFlags Flags, SCEVFlags Mask)
Convenient SCEVFlags manipulation.
LLVM_ABI bool containsAddRecurrence(const SCEV *S)
Return true if the SCEV is a scAddRecExpr or it contains scAddRecExpr.
SCEVUse getMulExpr(SCEVUse LHS, SCEVUse RHS, SCEVFlagsPair Flags={}, unsigned Depth=0)
LLVM_ABI const SCEV * getTruncateExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI SCEVUse getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
LLVM_ABI 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...
LLVM_ABI const SCEVPredicate * getComparePredicate(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
LLVM_ABI bool haveSameSign(const SCEV *S1, const SCEV *S2)
Return true if we know that S1 and S2 must have the same sign.
LLVM_ABI const SCEV * getNotSCEV(const SCEV *V)
Return the SCEV object corresponding to ~V.
LLVM_ABI bool instructionCouldExistWithOperands(const SCEV *A, const SCEV *B)
Return true if there exists a point in the program at which both A and B could be operands to the sam...
LLVM_ABI std::optional< SCEVFlags > getStrengthenedNoWrapFlagsFromBinOp(const OverflowingBinaryOperator *OBO)
Parse NSW/NUW flags from add/sub/mul IR binary operation Op into SCEV no-wrap flags,...
ConstantRange getUnsignedRange(const SCEV *S)
Determine the unsigned range for a particular SCEV.
LLVM_ABI void print(raw_ostream &OS) const
LLVM_ABI const SCEV * getAnyExtendExpr(SCEVUse Op, Type *Ty)
getAnyExtendExpr - Return a SCEV for the given operand extended with unspecified bits out to the give...
LLVM_ABI const SCEV * getPredicatedExitCount(const Loop *L, const BasicBlock *ExitingBlock, SmallVectorImpl< const SCEVPredicate * > *Predicates, ExitCountKind Kind=Exact)
Same as above except this uses the predicated backedge taken info and may require predicates.
LLVM_ABI void forgetTopmostLoop(const Loop *L)
friend class ScalarEvolutionsTest
LLVM_ABI 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...
APInt getSignedRangeMin(const SCEV *S)
Determine the min of the signed range for a particular SCEV.
LLVM_ABI bool isLoopUniform(const SCEV *S, const Loop *L)
Returns true if the given SCEV is loop-uniform with respect to the specified loop L.
LLVM_ABI const SCEV * getNoopOrAnyExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
LLVM_ABI const SCEV * getUMaxExpr(SCEVUse LHS, SCEVUse RHS)
MonotonicPredicateType
A predicate is said to be monotonically increasing if may go from being false to being true as the lo...
LLVM_ABI std::optional< LoopInvariantPredicate > getLoopInvariantPredicate(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI=nullptr)
If the result of the predicate LHS Pred RHS is loop invariant with respect to L, return a LoopInvaria...
LLVM_ABI const SCEV * getStoreSizeOfExpr(Type *IntTy, Type *StoreTy)
Return an expression for the store size of StoreTy that is type IntTy.
LLVM_ABI const SCEVPredicate * getWrapPredicate(const SCEVAddRecExpr *AR, SCEVWrapPredicate::IncrementWrapFlags AddedFlags)
LLVM_ABI bool isLoopBackedgeGuardedByCond(const Loop *L, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether the backedge of the loop is protected by a conditional between LHS and RHS.
LLVM_ABI APInt getNonZeroConstantMultiple(const SCEV *S)
const SCEV * getMinusOne(Type *Ty)
Return a SCEV for the constant -1 of a specific type.
LLVM_ABI SCEVUse getZeroExtendExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI bool hasLoopInvariantBackedgeTakenCount(const Loop *L)
Return true if the specified loop has an analyzable loop-invariant backedge-taken count.
LLVM_ABI BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB)
Return the "disposition" of the given SCEV with respect to the given block.
LLVM_ABI const SCEV * getNoopOrZeroExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
LLVM_ABI const SCEV * getUMinFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS, bool Sequential=false)
Promote the operands to the wider of the types using zero-extension, and then perform a umin operatio...
LLVM_ABI bool loopIsFiniteByAssumption(const Loop *L)
Return true if this loop is finite by assumption.
LLVM_ABI SCEVUse getSCEVAtExit(const SCEV *S, const Loop *L, const BasicBlock *ExitingBlock)
Return the SCEV expression at the specified loop exit.
LLVM_ABI const SCEV * getExistingSCEV(Value *V)
Return an existing SCEV for V if there is one, otherwise return nullptr.
SCEVUse getMulExpr(SCEVUse Op0, SCEVUse Op1, SCEVUse Op2, SCEVFlagsPair Flags={}, unsigned Depth=0)
LLVM_ABI APInt getConstantMultiple(const SCEV *S, const Instruction *CtxI=nullptr)
Returns the max constant multiple of S.
LoopDisposition
An enum describing the relationship between a SCEV and a loop.
@ LoopComputable
The SCEV varies predictably with the loop.
@ LoopVariant
The SCEV is loop-variant (unknown).
@ LoopInvariant
The SCEV is loop-invariant.
@ LoopUniform
The SCEV is loop-uniform.
LLVM_ABI bool isKnownToBeAPowerOfTwo(const SCEV *S, bool OrZero=false, bool OrNegative=false)
Test if the given expression is known to be a power of 2.
LLVM_ABI void forgetLcssaPhiWithNewPredecessor(Loop *L, PHINode *V)
Forget LCSSA phi node V of loop L to which a new predecessor was added, such that it may no longer be...
LLVM_ABI bool containsUndefs(const SCEV *S) const
Return true if the SCEV expression contains an undef value.
LLVM_ABI std::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,...
LLVM_ABI const SCEV * getCouldNotCompute()
LLVM_ABI bool isAvailableAtLoopEntry(const SCEV *S, const Loop *L)
Determine if the SCEV can be evaluated at loop's entry.
LLVM_ABI uint32_t getMinTrailingZeros(const SCEV *S, const Instruction *CtxI=nullptr)
Determine the minimum number of zero bits that S is guaranteed to end in (at every loop iteration).
BlockDisposition
An enum describing the relationship between a SCEV and a basic block.
@ DominatesBlock
The SCEV dominates the block.
@ ProperlyDominatesBlock
The SCEV properly dominates the block.
@ DoesNotDominateBlock
The SCEV does not dominate the block.
LLVM_ABI 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...
LLVM_ABI void getPoisonGeneratingValues(SmallPtrSetImpl< const Value * > &Result, const SCEV *S)
Return the set of Values that, if poison, will definitively result in S being poison as well.
LLVM_ABI void setNoWrapFlags(SCEVAddRecExpr *AddRec, SCEVFlags Flags)
Update no-wrap flags of an AddRec.
LLVM_ABI void forgetLoopDispositions()
Called when the client has changed the disposition of values in this loop.
LLVM_ABI const SCEV * getVScale(Type *Ty)
LLVM_ABI SCEVUse getMulExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
LLVM_ABI unsigned getSmallConstantTripCount(const Loop *L)
Returns the exact trip count of the loop if we can compute it, and the result is a small constant.
LLVM_ABI bool hasComputableLoopEvolution(const SCEV *S, const Loop *L)
Return true if the given SCEV changes value in a known way in the specified loop.
LLVM_ABI const SCEV * getPointerBase(const SCEV *V)
Transitively follow the chain of pointer-type operands until reaching a SCEV that does not have a sin...
const SCEV * getPowerOfTwo(Type *Ty, unsigned Power)
Return a SCEV for the constant Power of two.
LLVM_ABI SCEVUse getSignExtendExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI void forgetAllLoops()
LLVM_ABI bool dominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV dominate the specified basic block.
APInt getUnsignedRangeMax(const SCEV *S)
Determine the max of the unsigned range for a particular SCEV.
ExitCountKind
The terms "backedge taken count" and "exit count" are used interchangeably to refer to the number of ...
@ SymbolicMaximum
An expression which provides an upper bound on the exact trip count.
@ ConstantMaximum
A constant which provides an upper bound on the exact trip count.
@ Exact
An expression exactly describing the number of times the backedge has executed when a loop is exited.
LLVM_ABI const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
LLVM_ABI const SCEV * getPtrToAddrExpr(const SCEV *Op)
LLVM_ABI const SCEVAddRecExpr * convertSCEVToAddRecWithPredicates(const SCEV *S, const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Preds)
Tries to convert the S expression to an AddRec expression, adding additional predicates to Preds as r...
SCEVUse getAddRecExpr(const SmallVectorImpl< SCEVUse > &Operands, const Loop *L, SCEVFlagsPair Flags)
Module & getModule() const
LLVM_ABI const SCEV * getSMaxExpr(SCEVUse LHS, SCEVUse RHS)
LLVM_ABI const SCEV * getElementSize(Instruction *Inst)
Return the size of an element read or written by Inst.
LLVM_ABI bool isGuaranteedNotToCauseUB(const SCEV *Op)
Returns true if Op is guaranteed not to cause immediate UB.
LLVM_ABI const SCEV * getSizeOfExpr(Type *IntTy, TypeSize Size)
Return an expression for a TypeSize.
LLVM_ABI std::optional< bool > evaluatePredicate(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Check whether the condition described by Pred, LHS, and RHS is true or false.
LLVM_ABI const SCEV * getUnknown(Value *V)
LLVM_ABI std::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.
LLVM_ABI 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.
LLVM_ABI bool isKnownViaInduction(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
We'd like to check the predicate on every iteration of the most dominated loop between loops used in ...
LLVM_ABI std::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 std::nullopt if it isn'...
LLVM_ABI bool properlyDominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV properly dominate the specified basic block.
LLVM_ABI const SCEV * getNegativeSCEV(const SCEV *V, SCEVFlags Flags=SCEV::FlagNone)
Return the SCEV object corresponding to -V.
LLVM_ABI bool isKnownPredicate(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS, unsigned Depth=0)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
LLVM_ABI const SCEV * getUDivExactExpr(SCEVUse LHS, SCEVUse RHS)
Get a canonical unsigned division expression, or something simpler if possible.
LLVM_ABI const SCEV * rewriteUsingPredicate(const SCEV *S, const Loop *L, const SCEVPredicate &A)
Re-writes the SCEV according to the Predicates in A.
LLVM_ABI std::pair< const SCEV *, const SCEV * > SplitIntoInitAndPostInc(const Loop *L, const SCEV *S)
Splits SCEV expression S into two SCEVs.
LLVM_ABI bool canReuseInstruction(const SCEV *S, Instruction *I, SmallVectorImpl< Instruction * > &DropPoisonGeneratingInsts)
Check whether it is poison-safe to represent the expression S using the instruction I.
LLVM_ABI bool isKnownPredicateAt(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
LLVM_ABI const SCEV * getPredicatedSymbolicMaxBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getSymbolicMaxBackedgeTakenCount, except it will add a set of SCEV predicates to Predicate...
LLVM_ABI const SCEV * getGEPExpr(GEPOperator *GEP, ArrayRef< SCEVUse > IndexExprs)
Returns an expression for a GEP.
LLVM_ABI const SCEV * getUMinExpr(SCEVUse LHS, SCEVUse RHS, bool Sequential=false)
LLVM_ABI bool isBasicBlockEntryGuardedByCond(const BasicBlock *BB, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether entry to the basic block is protected by a conditional between LHS and RHS.
LLVM_ABI 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.
LLVM_ABI bool containsErasedValue(const SCEV *S) const
Return true if the SCEV expression contains a Value that has been optimised out and is now a nullptr.
const SCEV * getSymbolicMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEV that is greater than or equal to (i.e.
LLVM_ABI SCEVUse getSignExtendExprImpl(SCEVUse Op, Type *Ty, unsigned Depth=0)
APInt getSignedRangeMax(const SCEV *S)
Determine the max of the signed range for a particular SCEV.
LLVM_ABI void verify() const
LLVMContext & getContext() const
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:295
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Class to represent struct types.
Provides information about what library functions are available for the current target.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
Lightweight SCEV-to-VPlan expander.
Definition VPlanUtils.h:286
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI void print(raw_ostream &O, bool IsForDebug=false) const
Implement operator<< on Value.
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
unsigned combineHashValue(unsigned a, unsigned b)
Simplistic combination of 32-bit hash values into 32-bit hash values.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
SCEVUseT< const SCEV * > SCEVUse
LLVM_ABI bool VerifySCEV
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
SCEVUseT(SCEVPtrT) -> SCEVUseT< SCEVPtrT >
Deduction guide for various SCEV subclass pointers.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
@ Other
Any other memory.
Definition ModRef.h:68
DWARFExpression::Operation Op
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
SCEVFlags
SCEVFlags are bitfield indices into SCEV's SubclassData.
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:391
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
FoldingSetImpl< T, Trait > FoldingSet
This template class is used to instantiate a specialized implementation of the folding set to the nod...
Definition FoldingSet.h:556
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
#define N
A CRTP mix-in that provides informational APIs needed for analysis passes.
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
This struct provides a method for customizing the way a cast is performed.
Definition Casting.h:476
static CastReturnType castFailed()
Definition Casting.h:490
static CastReturnType doCast(const From &f)
Definition Casting.h:481
typename cast_retty< To, From >::ret_type CastReturnType
Definition Casting.h:479
static bool isPossible(const From &f)
Definition Casting.h:254
This class provides default implementations for FoldingSetTrait implementations.
Definition FoldingSet.h:232
static bool isEqual(const SCEVUse LHS, const SCEVUse RHS)
static unsigned getHashValue(SCEVUse U)
static unsigned getHashValue(const ScalarEvolution::FoldID &Val)
static bool isEqual(const ScalarEvolution::FoldID &LHS, const ScalarEvolution::FoldID &RHS)
An information struct used to provide DenseMap with the various necessary components for a given valu...
static void Profile(const SCEVPredicate &X, FoldingSetNodeID &ID)
static bool Equals(const SCEVPredicate &X, const FoldingSetNodeID &ID)
static bool Equals(const SCEV &X, const FoldingSetNodeID &ID)
static void Profile(const SCEV &X, FoldingSetNodeID &ID)
This trait class is used to define behavior of how to "profile" (in the FoldingSet parlance) an objec...
Definition FoldingSet.h:255
static constexpr int NumLowBitsAvailable
The Low bits are used by the PointerIntPair.
static void * getAsVoidPointer(SCEVUse U)
static SCEVUse getFromVoidPointer(void *P)
A traits type that is used to handle pointer types and things that are just wrappers for pointers as ...
A CRTP mix-in for passes that should not be skipped.
static LLVM_ABI bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
The no-wrap flags to apply when creating a SCEV expression, to the expression and use respectively.
SCEVFlags ExprFlags
Flags applied directly to a SCEV expression, must be valid wherever the expression is valid.
constexpr SCEVFlagsPair(SCEVFlags ExprFlags=SCEVFlags::FlagNone, SCEVFlags UseFlags=SCEVFlags::FlagNone)
SCEVFlags getCombinedFlags() const
Returns the combination of the expression and use-specific flags.
SCEVFlags UseFlags
Flags only applied to a SCEVUse.
SCEVFlags getUseNoWrapFlags() const
Return only the use-specific flags without the underlying SCEV's flags.
bool operator==(const SCEVUseT &RHS) const
const SCEV * getCanonical() const
Return the canonical SCEV for this SCEVUse.
bool operator!=(const SCEVUseT &RHS) const
SCEVFlagsPair getFlagsToPropagate(SCEVFlags CheckedFlags) const
Returns the flags safe to propagate in folds established based on the flags in CheckedFlags.
SCEVPtrT operator->() const
SCEVFlags getNoWrapFlags(SCEVFlags Mask=SCEVFlags::FlagsNoWrapMask) const
Return the flags for this SCEVUse, which is the union of the use-specific flags and the underlying SC...
SCEVUseT(SCEVPtrT S, SCEVFlags Flags)
Construct with SCEVFlags; only NUW/NSW are encoded, NW is dropped.
static SCEVUseT getCommon(SCEVUseT A, SCEVUseT B)
Return a SCEVUse that can replace both A and B.
SCEVFlagsPair getNoWrapFlagsPair() const
Returns a pair of expression and use-specific flags respectively.
SCEVUseT(const SCEVUseT< OtherPtrT > &Other)
void * getOpaqueValue() const
bool isCanonical() const
Returns true if the SCEVUse is canonical, i.e.
const SCEV * getPointer() const
bool operator==(const SCEV *RHS) const
void dump() const
This method is used for debugging.
bool operator>(const SCEVUseT &RHS) const
PointerIntPair< const SCEV *, 2 > Base
bool operator!=(const SCEV *RHS) const
void print(raw_ostream &OS) const
Print out the internal representation of this scalar to the specified stream.
friend struct SCEVUseT
SCEVUseT(SCEVPtrT S)
bool hasUseFlags() const
Returns true if this use itself carries use-specific no-wrap flags.
Information about the number of loop iterations for which a loop exit's branch condition evaluates to...
LLVM_ABI ExitLimit(const SCEV *E)
Construct either an exact exit limit from a constant, or an unknown one from a SCEVCouldNotCompute.
bool hasAnyInfo() const
Test whether this ExitLimit contains any computed information, or whether it's all SCEVCouldNotComput...
SmallVector< const SCEVPredicate *, 4 > Predicates
A vector of predicate guards for this ExitLimit.
bool hasFullInfo() const
Test whether this ExitLimit contains all information.
LoopInvariantPredicate(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
static SimpleType getSimplifiedValue(SCEVUse &Val)
Define a template that can be specialized by smart pointers to reflect the fact that they are automat...
Definition Casting.h:34