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