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