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