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