LLVM 24.0.0git
Attributor.h
Go to the documentation of this file.
1//===- Attributor.h --- Module-wide attribute deduction ---------*- 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// Attributor: An inter procedural (abstract) "attribute" deduction framework.
10//
11// The Attributor framework is an inter procedural abstract analysis (fixpoint
12// iteration analysis). The goal is to allow easy deduction of new attributes as
13// well as information exchange between abstract attributes in-flight.
14//
15// The Attributor class is the driver and the link between the various abstract
16// attributes. The Attributor will iterate until a fixpoint state is reached by
17// all abstract attributes in-flight, or until it will enforce a pessimistic fix
18// point because an iteration limit is reached.
19//
20// Abstract attributes, derived from the AbstractAttribute class, actually
21// describe properties of the code. They can correspond to actual LLVM-IR
22// attributes, or they can be more general, ultimately unrelated to LLVM-IR
23// attributes. The latter is useful when an abstract attributes provides
24// information to other abstract attributes in-flight but we might not want to
25// manifest the information. The Attributor allows to query in-flight abstract
26// attributes through the `Attributor::getAAFor` method (see the method
27// description for an example). If the method is used by an abstract attribute
28// P, and it results in an abstract attribute Q, the Attributor will
29// automatically capture a potential dependence from Q to P. This dependence
30// will cause P to be reevaluated whenever Q changes in the future.
31//
32// The Attributor will only reevaluate abstract attributes that might have
33// changed since the last iteration. That means that the Attribute will not
34// revisit all instructions/blocks/functions in the module but only query
35// an update from a subset of the abstract attributes.
36//
37// The update method `AbstractAttribute::updateImpl` is implemented by the
38// specific "abstract attribute" subclasses. The method is invoked whenever the
39// currently assumed state (see the AbstractState class) might not be valid
40// anymore. This can, for example, happen if the state was dependent on another
41// abstract attribute that changed. In every invocation, the update method has
42// to adjust the internal state of an abstract attribute to a point that is
43// justifiable by the underlying IR and the current state of abstract attributes
44// in-flight. Since the IR is given and assumed to be valid, the information
45// derived from it can be assumed to hold. However, information derived from
46// other abstract attributes is conditional on various things. If the justifying
47// state changed, the `updateImpl` has to revisit the situation and potentially
48// find another justification or limit the optimistic assumes made.
49//
50// Change is the key in this framework. Until a state of no-change, thus a
51// fixpoint, is reached, the Attributor will query the abstract attributes
52// in-flight to re-evaluate their state. If the (current) state is too
53// optimistic, hence it cannot be justified anymore through other abstract
54// attributes or the state of the IR, the state of the abstract attribute will
55// have to change. Generally, we assume abstract attribute state to be a finite
56// height lattice and the update function to be monotone. However, these
57// conditions are not enforced because the iteration limit will guarantee
58// termination. If an optimistic fixpoint is reached, or a pessimistic fix
59// point is enforced after a timeout, the abstract attributes are tasked to
60// manifest their result in the IR for passes to come.
61//
62// Attribute manifestation is not mandatory. If desired, there is support to
63// generate a single or multiple LLVM-IR attributes already in the helper struct
64// IRAttribute. In the simplest case, a subclass inherits from IRAttribute with
65// a proper Attribute::AttrKind as template parameter. The Attributor
66// manifestation framework will then create and place a new attribute if it is
67// allowed to do so (based on the abstract state). Other use cases can be
68// achieved by overloading AbstractAttribute or IRAttribute methods.
69//
70//
71// The "mechanics" of adding a new "abstract attribute":
72// - Define a class (transitively) inheriting from AbstractAttribute and one
73// (which could be the same) that (transitively) inherits from AbstractState.
74// For the latter, consider the already available BooleanState and
75// {Inc,Dec,Bit}IntegerState if they fit your needs, e.g., you require only a
76// number tracking or bit-encoding.
77// - Implement all pure methods. Also use overloading if the attribute is not
78// conforming with the "default" behavior: A (set of) LLVM-IR attribute(s) for
79// an argument, call site argument, function return value, or function. See
80// the class and method descriptions for more information on the two
81// "Abstract" classes and their respective methods.
82// - Register opportunities for the new abstract attribute in the
83// `Attributor::identifyDefaultAbstractAttributes` method if it should be
84// counted as a 'default' attribute.
85// - Add sufficient tests.
86// - Add a Statistics object for bookkeeping. If it is a simple (set of)
87// attribute(s) manifested through the Attributor manifestation framework, see
88// the bookkeeping function in Attributor.cpp.
89// - If instructions with a certain opcode are interesting to the attribute, add
90// that opcode to the switch in `Attributor::identifyAbstractAttributes`. This
91// will make it possible to query all those instructions through the
92// `InformationCache::getOpcodeInstMapForFunction` interface and eliminate the
93// need to traverse the IR repeatedly.
94//
95//===----------------------------------------------------------------------===//
96
97#ifndef LLVM_TRANSFORMS_IPO_ATTRIBUTOR_H
98#define LLVM_TRANSFORMS_IPO_ATTRIBUTOR_H
99
100#include "llvm/ADT/DenseSet.h"
101#include "llvm/ADT/GraphTraits.h"
102#include "llvm/ADT/IntervalMap.h"
103#include "llvm/ADT/MapVector.h"
104#include "llvm/ADT/STLExtras.h"
106#include "llvm/ADT/SetVector.h"
107#include "llvm/ADT/SmallSet.h"
108#include "llvm/ADT/iterator.h"
110#include "llvm/Analysis/CFG.h"
120#include "llvm/IR/Attributes.h"
122#include "llvm/IR/Constants.h"
123#include "llvm/IR/GlobalValue.h"
124#include "llvm/IR/InstIterator.h"
125#include "llvm/IR/Instruction.h"
126#include "llvm/IR/Instructions.h"
127#include "llvm/IR/Module.h"
128#include "llvm/IR/PassManager.h"
129#include "llvm/IR/Value.h"
132#include "llvm/Support/Casting.h"
137#include "llvm/Support/ModRef.h"
142
143#include <limits>
144#include <map>
145#include <optional>
146
147namespace llvm {
148
149class DataLayout;
150class LLVMContext;
151class Pass;
152template <typename Fn> class function_ref;
153struct AADepGraphNode;
154struct AADepGraph;
155struct Attributor;
156struct AbstractAttribute;
157struct InformationCache;
158struct AAIsDead;
160struct IRPosition;
161
162class Function;
163
164/// Abstract Attribute helper functions.
165namespace AA {
167
168/// Return true iff \p M target a GPU (and we can use GPU AS reasoning).
169LLVM_ABI bool isGPU(const Module &M);
170
171/// Check if the given address space \p AS corresponds to a GPU shared
172/// address space for the target triple in module \p M.
173LLVM_ABI bool isGPUSharedAddressSpace(const Module &M, unsigned AS);
174
175/// Check if the given address space \p AS corresponds to a GPU constant
176/// address space for the target triple in module \p M.
177LLVM_ABI bool isGPUConstantAddressSpace(const Module &M, unsigned AS);
178
179/// Check if the given address space \p AS corresponds to a GPU local/private
180/// address space for the target triple in module \p M.
181LLVM_ABI bool isGPULocalAddressSpace(const Module &M, unsigned AS);
182
183/// Flags to distinguish intra-procedural queries from *potentially*
184/// inter-procedural queries. Not that information can be valid for both and
185/// therefore both bits might be set.
191
192struct ValueAndContext : public std::pair<Value *, const Instruction *> {
193 using Base = std::pair<Value *, const Instruction *>;
195 ValueAndContext(Value &V, const Instruction *CtxI) : Base(&V, CtxI) {}
196 ValueAndContext(Value &V, const Instruction &CtxI) : Base(&V, &CtxI) {}
197
198 Value *getValue() const { return this->first; }
199 const Instruction *getCtxI() const { return this->second; }
200};
201
202/// Return true if \p I is a `nosync` instruction. Use generic reasoning and
203/// potentially the corresponding AANoSync.
205 const AbstractAttribute &QueryingAA);
206
207/// Return true if \p V is dynamically unique, that is, there are no two
208/// "instances" of \p V at runtime with different values.
209/// Note: If \p ForAnalysisOnly is set we only check that the Attributor will
210/// never use \p V to represent two "instances" not that \p V could not
211/// technically represent them.
213 const AbstractAttribute &QueryingAA,
214 const Value &V, bool ForAnalysisOnly = true);
215
216/// Return true if \p V is a valid value in \p Scope, that is a constant or an
217/// instruction/argument of \p Scope.
218LLVM_ABI bool isValidInScope(const Value &V, const Function *Scope);
219
220/// Return true if the value of \p VAC is a valid at the position of \p VAC,
221/// that is a constant, an argument of the same function, or an instruction in
222/// that function that dominates the position.
223LLVM_ABI bool isValidAtPosition(const ValueAndContext &VAC,
224 InformationCache &InfoCache);
225
226/// Try to convert \p V to type \p Ty without introducing new instructions. If
227/// this is not possible return `nullptr`. Note: this function basically knows
228/// how to cast various constants.
230
231/// Return the combination of \p A and \p B such that the result is a possible
232/// value of both. \p B is potentially casted to match the type \p Ty or the
233/// type of \p A if \p Ty is null.
234///
235/// Examples:
236/// X + none => X
237/// not_none + undef => not_none
238/// V1 + V2 => nullptr
239LLVM_ABI std::optional<Value *>
240combineOptionalValuesInAAValueLatice(const std::optional<Value *> &A,
241 const std::optional<Value *> &B, Type *Ty);
242
243/// Helper to represent an access offset and size, with logic to deal with
244/// uncertainty and check for overlapping accesses.
245struct RangeTy {
247 int64_t Size = Unassigned;
248
249 RangeTy(int64_t Offset, int64_t Size) : Offset(Offset), Size(Size) {}
250 RangeTy() = default;
251 static RangeTy getUnknown() { return RangeTy{Unknown, Unknown}; }
252
253 /// Return true if offset or size are unknown.
256 }
257
258 /// Return true if offset and size are unknown, thus this is the default
259 /// unknown object.
262 }
263
264 /// Return true if the offset and size are unassigned.
265 bool isUnassigned() const {
267 "Inconsistent state!");
268 return Offset == RangeTy::Unassigned;
269 }
270
271 /// Return true if this offset and size pair might describe an address that
272 /// overlaps with \p Range.
273 bool mayOverlap(const RangeTy &Range) const {
274 // Any unknown value and we are giving up -> overlap.
275 if (offsetOrSizeAreUnknown() || Range.offsetOrSizeAreUnknown())
276 return true;
277
278 // Check if one offset point is in the other interval [offset,
279 // offset+size].
280 return Range.Offset + Range.Size > Offset && Range.Offset < Offset + Size;
281 }
282
284 if (R.isUnassigned())
285 return *this;
286 if (isUnassigned())
287 return *this = R;
288 if (Offset == Unknown || R.Offset == Unknown)
289 Offset = Unknown;
290 if (Size == Unknown || R.Size == Unknown)
291 Size = Unknown;
293 return *this;
294 if (Offset == Unknown) {
295 Size = std::max(Size, R.Size);
296 } else if (Size == Unknown) {
297 Offset = std::min(Offset, R.Offset);
298 } else {
299 Offset = std::min(Offset, R.Offset);
300 Size = std::max(Offset + Size, R.Offset + R.Size) - Offset;
301 }
302 return *this;
303 }
304
305 /// Comparison for sorting ranges.
306 ///
307 /// Returns true if the offset of \p L is less than that of \p R. If the two
308 /// offsets are same, compare the sizes instead.
309 inline static bool LessThan(const RangeTy &L, const RangeTy &R) {
310 if (L.Offset < R.Offset)
311 return true;
312 if (L.Offset == R.Offset)
313 return L.Size < R.Size;
314 return false;
315 }
316
317 /// Constants used to represent special offsets or sizes.
318 /// - We cannot assume that Offsets and Size are non-negative.
319 /// - The constants should not clash with DenseMapInfo, such as EmptyKey
320 /// (INT64_MAX).
321 /// We use values "in the middle" of the 64 bit range to represent these
322 /// special cases.
323 static constexpr int64_t Unassigned = std::numeric_limits<int32_t>::min();
324 static constexpr int64_t Unknown = std::numeric_limits<int32_t>::max();
325};
326
328 OS << "[" << R.Offset << ", " << R.Size << "]";
329 return OS;
330}
331
332inline bool operator==(const RangeTy &A, const RangeTy &B) {
333 return A.Offset == B.Offset && A.Size == B.Size;
334}
335
336inline bool operator!=(const RangeTy &A, const RangeTy &B) { return !(A == B); }
337
338/// Return the initial value of \p Obj with type \p Ty if that is a constant.
341 Value &Obj, Type &Ty, const TargetLibraryInfo *TLI,
342 const DataLayout &DL, RangeTy *RangePtr = nullptr);
343
344/// Collect all potential values \p LI could read into \p PotentialValues. That
345/// is, the only values read by \p LI are assumed to be known and all are in
346/// \p PotentialValues. \p PotentialValueOrigins will contain all the
347/// instructions that might have put a potential value into \p PotentialValues.
348/// Dependences onto \p QueryingAA are properly tracked, \p
349/// UsedAssumedInformation will inform the caller if assumed information was
350/// used.
351///
352/// \returns True if the assumed potential copies are all in \p PotentialValues,
353/// false if something went wrong and the copies could not be
354/// determined.
356 Attributor &A, LoadInst &LI, SmallSetVector<Value *, 4> &PotentialValues,
357 SmallSetVector<Instruction *, 4> &PotentialValueOrigins,
358 const AbstractAttribute &QueryingAA, bool &UsedAssumedInformation,
359 bool OnlyExact = false);
360
361/// Collect all potential values of the one stored by \p SI into
362/// \p PotentialCopies. That is, the only copies that were made via the
363/// store are assumed to be known and all are in \p PotentialCopies. Dependences
364/// onto \p QueryingAA are properly tracked, \p UsedAssumedInformation will
365/// inform the caller if assumed information was used.
366///
367/// \returns True if the assumed potential copies are all in \p PotentialCopies,
368/// false if something went wrong and the copies could not be
369/// determined.
372 const AbstractAttribute &QueryingAA, bool &UsedAssumedInformation,
373 bool OnlyExact = false);
374
375/// Return true if \p IRP is readonly. This will query respective AAs that
376/// deduce the information and introduce dependences for \p QueryingAA.
378 const AbstractAttribute &QueryingAA,
379 bool &IsKnown);
380
381/// Return true if \p IRP is readnone. This will query respective AAs that
382/// deduce the information and introduce dependences for \p QueryingAA.
384 const AbstractAttribute &QueryingAA,
385 bool &IsKnown);
386
387/// Return true if \p ToI is potentially reachable from \p FromI without running
388/// into any instruction in \p ExclusionSet The two instructions do not need to
389/// be in the same function. \p GoBackwardsCB can be provided to convey domain
390/// knowledge about the "lifespan" the user is interested in. By default, the
391/// callers of \p FromI are checked as well to determine if \p ToI can be
392/// reached. If the query is not interested in callers beyond a certain point,
393/// e.g., a GPU kernel entry or the function containing an alloca, the
394/// \p GoBackwardsCB should return false.
396 Attributor &A, const Instruction &FromI, const Instruction &ToI,
397 const AbstractAttribute &QueryingAA,
398 const AA::InstExclusionSetTy *ExclusionSet = nullptr,
399 std::function<bool(const Function &F)> GoBackwardsCB = nullptr);
400
401/// Same as above but it is sufficient to reach any instruction in \p ToFn.
403 Attributor &A, const Instruction &FromI, const Function &ToFn,
404 const AbstractAttribute &QueryingAA,
405 const AA::InstExclusionSetTy *ExclusionSet = nullptr,
406 std::function<bool(const Function &F)> GoBackwardsCB = nullptr);
407
408/// Return true if \p Obj is assumed to be a thread local object.
410 const AbstractAttribute &QueryingAA);
411
412/// Return true if \p I is potentially affected by a barrier.
413LLVM_ABI bool
415 const AbstractAttribute &QueryingAA);
416LLVM_ABI bool
418 const AbstractAttribute &QueryingAA,
419 const Instruction *CtxI);
420} // namespace AA
421
422template <>
423struct DenseMapInfo<AA::ValueAndContext>
424 : public DenseMapInfo<AA::ValueAndContext::Base> {
426 static unsigned getHashValue(const AA::ValueAndContext &VAC) {
427 return Base::getHashValue(VAC);
428 }
429
430 static bool isEqual(const AA::ValueAndContext &LHS,
431 const AA::ValueAndContext &RHS) {
432 return Base::isEqual(LHS, RHS);
433 }
434};
435
436template <>
437struct DenseMapInfo<AA::ValueScope> : public DenseMapInfo<unsigned char> {
439 static unsigned getHashValue(const AA::ValueScope &S) {
440 return Base::getHashValue(S);
441 }
442
443 static bool isEqual(const AA::ValueScope &LHS, const AA::ValueScope &RHS) {
444 return Base::isEqual(LHS, RHS);
445 }
446};
447
448template <>
449struct DenseMapInfo<const AA::InstExclusionSetTy *>
450 : public DenseMapInfo<void *> {
451 static unsigned getHashValue(const AA::InstExclusionSetTy *BES) {
452 unsigned H = 0;
453 if (BES)
454 for (const auto *II : *BES)
455 H += DenseMapInfo<const Instruction *>::getHashValue(II);
456 return H;
457 }
458 static bool isEqual(const AA::InstExclusionSetTy *LHS,
460 if (LHS == RHS)
461 return true;
462 auto SizeLHS = LHS ? LHS->size() : 0;
463 auto SizeRHS = RHS ? RHS->size() : 0;
464 if (SizeLHS != SizeRHS)
465 return false;
466 if (SizeRHS == 0)
467 return true;
468 return llvm::set_is_subset(*LHS, *RHS);
469 }
470};
471
472/// The value passed to the line option that defines the maximal initialization
473/// chain length.
475
476///{
481
486
487enum class DepClassTy {
488 REQUIRED, ///< The target cannot be valid if the source is not.
489 OPTIONAL, ///< The target may be valid if the source is not.
490 NONE, ///< Do not track a dependence between source and target.
491};
492///}
493
494/// The data structure for the nodes of a dependency graph
496public:
497 virtual ~AADepGraphNode() = default;
500
501protected:
502 /// Set of dependency graph nodes which should be updated if this one
503 /// is updated. The bit encodes if it is optional.
505
506 static AADepGraphNode *DepGetVal(const DepTy &DT) { return DT.getPointer(); }
509 }
510
511 operator AbstractAttribute *() { return cast<AbstractAttribute>(this); }
512
513public:
517
518 aaiterator begin() { return aaiterator(Deps.begin(), &DepGetValAA); }
519 aaiterator end() { return aaiterator(Deps.end(), &DepGetValAA); }
520 iterator child_begin() { return iterator(Deps.begin(), &DepGetVal); }
521 iterator child_end() { return iterator(Deps.end(), &DepGetVal); }
522
523 void print(raw_ostream &OS) const { print(nullptr, OS); }
524 virtual void print(Attributor *, raw_ostream &OS) const {
525 OS << "AADepNode Impl\n";
526 }
527
528 friend struct Attributor;
529 friend struct AADepGraph;
530};
531
532/// The data structure for the dependency graph
533///
534/// Note that in this graph if there is an edge from A to B (A -> B),
535/// then it means that B depends on A, and when the state of A is
536/// updated, node B should also be updated
538 AADepGraph() = default;
539 ~AADepGraph() = default;
540
542 static AADepGraphNode *DepGetVal(const DepTy &DT) { return DT.getPointer(); }
543 using iterator =
545
546 /// There is no root node for the dependency graph. But the SCCIterator
547 /// requires a single entry point, so we maintain a fake("synthetic") root
548 /// node that depends on every node.
551
552 iterator begin() { return SyntheticRoot.child_begin(); }
553 iterator end() { return SyntheticRoot.child_end(); }
554
555 LLVM_ABI void viewGraph();
556
557 /// Dump graph to file
558 LLVM_ABI void dumpGraph();
559
560 /// Print dependency graph
561 LLVM_ABI void print();
562};
563
564/// Helper to describe and deal with positions in the LLVM-IR.
565///
566/// A position in the IR is described by an anchor value and an "offset" that
567/// could be the argument number, for call sites and arguments, or an indicator
568/// of the "position kind". The kinds, specified in the Kind enum below, include
569/// the locations in the attribute list, i.a., function scope and return value,
570/// as well as a distinction between call sites and functions. Finally, there
571/// are floating values that do not have a corresponding attribute list
572/// position.
574 // NOTE: In the future this definition can be changed to support recursive
575 // functions.
577
578 /// The positions we distinguish in the IR.
579 enum Kind : char {
580 IRP_INVALID, ///< An invalid position.
581 IRP_FLOAT, ///< A position that is not associated with a spot suitable
582 ///< for attributes. This could be any value or instruction.
583 IRP_RETURNED, ///< An attribute for the function return value.
584 IRP_CALL_SITE_RETURNED, ///< An attribute for a call site return value.
585 IRP_FUNCTION, ///< An attribute for a function (scope).
586 IRP_CALL_SITE, ///< An attribute for a call site (function scope).
587 IRP_ARGUMENT, ///< An attribute for a function argument.
588 IRP_CALL_SITE_ARGUMENT, ///< An attribute for a call site argument.
589 };
590
591 /// Default constructor available to create invalid positions implicitly. All
592 /// other positions need to be created explicitly through the appropriate
593 /// static member function.
594 IRPosition() : Enc(nullptr, ENC_VALUE) { verify(); }
595
596 /// Create a position describing the value of \p V.
597 static const IRPosition value(const Value &V,
598 const CallBaseContext *CBContext = nullptr) {
599 if (auto *Arg = dyn_cast<Argument>(&V))
600 return IRPosition::argument(*Arg, CBContext);
601 if (auto *CB = dyn_cast<CallBase>(&V))
603 return IRPosition(const_cast<Value &>(V), IRP_FLOAT, CBContext);
604 }
605
606 /// Create a position describing the instruction \p I. This is different from
607 /// the value version because call sites are treated as intrusctions rather
608 /// than their return value in this function.
609 static const IRPosition inst(const Instruction &I,
610 const CallBaseContext *CBContext = nullptr) {
611 return IRPosition(const_cast<Instruction &>(I), IRP_FLOAT, CBContext);
612 }
613
614 /// Create a position describing the function scope of \p F.
615 /// \p CBContext is used for call base specific analysis.
616 static const IRPosition function(const Function &F,
617 const CallBaseContext *CBContext = nullptr) {
618 return IRPosition(const_cast<Function &>(F), IRP_FUNCTION, CBContext);
619 }
620
621 /// Create a position describing the returned value of \p F.
622 /// \p CBContext is used for call base specific analysis.
623 static const IRPosition returned(const Function &F,
624 const CallBaseContext *CBContext = nullptr) {
625 return IRPosition(const_cast<Function &>(F), IRP_RETURNED, CBContext);
626 }
627
628 /// Create a position describing the argument \p Arg.
629 /// \p CBContext is used for call base specific analysis.
630 static const IRPosition argument(const Argument &Arg,
631 const CallBaseContext *CBContext = nullptr) {
632 return IRPosition(const_cast<Argument &>(Arg), IRP_ARGUMENT, CBContext);
633 }
634
635 /// Create a position describing the function scope of \p CB.
636 static const IRPosition callsite_function(const CallBase &CB) {
637 return IRPosition(const_cast<CallBase &>(CB), IRP_CALL_SITE);
638 }
639
640 /// Create a position describing the returned value of \p CB.
641 static const IRPosition callsite_returned(const CallBase &CB) {
642 return IRPosition(const_cast<CallBase &>(CB), IRP_CALL_SITE_RETURNED);
643 }
644
645 /// Create a position describing the argument of \p CB at position \p ArgNo.
646 static const IRPosition callsite_argument(const CallBase &CB,
647 unsigned ArgNo) {
648 return IRPosition(const_cast<Use &>(CB.getArgOperandUse(ArgNo)),
650 }
651
652 /// Create a position describing the argument of \p ACS at position \p ArgNo.
654 unsigned ArgNo) {
655 if (ACS.getNumArgOperands() <= ArgNo)
656 return IRPosition();
657 int CSArgNo = ACS.getCallArgOperandNo(ArgNo);
658 if (CSArgNo >= 0)
660 cast<CallBase>(*ACS.getInstruction()), CSArgNo);
661 return IRPosition();
662 }
663
664 /// Create a position with function scope matching the "context" of \p IRP.
665 /// If \p IRP is a call site (see isAnyCallSitePosition()) then the result
666 /// will be a call site position, otherwise the function position of the
667 /// associated function.
668 static const IRPosition
670 const CallBaseContext *CBContext = nullptr) {
671 if (IRP.isAnyCallSitePosition()) {
674 }
676 return IRPosition::function(*IRP.getAssociatedFunction(), CBContext);
677 }
678
679 bool operator==(const IRPosition &RHS) const {
680 return Enc == RHS.Enc && RHS.CBContext == CBContext;
681 }
682 bool operator!=(const IRPosition &RHS) const { return !(*this == RHS); }
683
684 /// Return the value this abstract attribute is anchored with.
685 ///
686 /// The anchor value might not be the associated value if the latter is not
687 /// sufficient to determine where arguments will be manifested. This is, so
688 /// far, only the case for call site arguments as the value is not sufficient
689 /// to pinpoint them. Instead, we can use the call site as an anchor.
691 switch (getEncodingBits()) {
692 case ENC_VALUE:
693 case ENC_RETURNED_VALUE:
694 case ENC_FLOATING_FUNCTION:
695 return *getAsValuePtr();
696 case ENC_CALL_SITE_ARGUMENT_USE:
697 return *(getAsUsePtr()->getUser());
698 default:
699 llvm_unreachable("Unkown encoding!");
700 };
701 }
702
703 /// Return the associated function, if any.
705 if (auto *CB = dyn_cast<CallBase>(&getAnchorValue())) {
706 // We reuse the logic that associates callback calles to arguments of a
707 // call site here to identify the callback callee as the associated
708 // function.
709 if (Argument *Arg = getAssociatedArgument())
710 return Arg->getParent();
712 CB->getCalledOperand()->stripPointerCasts());
713 }
714 return getAnchorScope();
715 }
716
717 /// Return the associated argument, if any.
719
720 /// Return true if the position refers to a function interface, that is the
721 /// function scope, the function return, or an argument.
722 bool isFnInterfaceKind() const {
723 switch (getPositionKind()) {
727 return true;
728 default:
729 return false;
730 }
731 }
732
733 /// Return true if this is a function or call site position.
734 bool isFunctionScope() const {
735 switch (getPositionKind()) {
738 return true;
739 default:
740 return false;
741 };
742 }
743
744 /// Return the Function surrounding the anchor value.
746 Value &V = getAnchorValue();
747 if (isa<Function>(V))
748 return &cast<Function>(V);
749 if (isa<Argument>(V))
750 return cast<Argument>(V).getParent();
751 if (isa<Instruction>(V))
752 return cast<Instruction>(V).getFunction();
753 return nullptr;
754 }
755
756 /// Return the context instruction, if any.
758 Value &V = getAnchorValue();
759 if (auto *I = dyn_cast<Instruction>(&V))
760 return I;
761 if (auto *Arg = dyn_cast<Argument>(&V))
762 if (!Arg->getParent()->isDeclaration())
763 return &Arg->getParent()->getEntryBlock().front();
764 if (auto *F = dyn_cast<Function>(&V))
765 if (!F->isDeclaration())
766 return &(F->getEntryBlock().front());
767 return nullptr;
768 }
769
770 /// Return the value this abstract attribute is associated with.
773 return getAnchorValue();
774 assert(isa<CallBase>(&getAnchorValue()) && "Expected a call base!");
776 ->getArgOperand(getCallSiteArgNo());
777 }
778
779 /// Return the type this abstract attribute is associated with.
785
786 /// Return the callee argument number of the associated value if it is an
787 /// argument or call site argument, otherwise a negative value. In contrast to
788 /// `getCallSiteArgNo` this method will always return the "argument number"
789 /// from the perspective of the callee. This may not the same as the call site
790 /// if this is a callback call.
791 int getCalleeArgNo() const {
792 return getArgNo(/* CallbackCalleeArgIfApplicable */ true);
793 }
794
795 /// Return the call site argument number of the associated value if it is an
796 /// argument or call site argument, otherwise a negative value. In contrast to
797 /// `getCalleArgNo` this method will always return the "operand number" from
798 /// the perspective of the call site. This may not the same as the callee
799 /// perspective if this is a callback call.
800 int getCallSiteArgNo() const {
801 return getArgNo(/* CallbackCalleeArgIfApplicable */ false);
802 }
803
804 /// Return the index in the attribute list for this position.
805 unsigned getAttrIdx() const {
806 switch (getPositionKind()) {
809 break;
812 return AttributeList::FunctionIndex;
815 return AttributeList::ReturnIndex;
817 return getCalleeArgNo() + AttributeList::FirstArgIndex;
819 return getCallSiteArgNo() + AttributeList::FirstArgIndex;
820 }
822 "There is no attribute index for a floating or invalid position!");
823 }
824
825 /// Return the value attributes are attached to.
827 if (auto *CB = dyn_cast<CallBase>(&getAnchorValue()))
828 return CB;
829 return getAssociatedFunction();
830 }
831
832 /// Return the attributes associated with this function or call site scope.
834 if (auto *CB = dyn_cast<CallBase>(&getAnchorValue()))
835 return CB->getAttributes();
837 }
838
839 /// Update the attributes associated with this function or call site scope.
840 void setAttrList(const AttributeList &AttrList) const {
841 if (auto *CB = dyn_cast<CallBase>(&getAnchorValue()))
842 return CB->setAttributes(AttrList);
843 return getAssociatedFunction()->setAttributes(AttrList);
844 }
845
846 /// Return the associated position kind.
848 char EncodingBits = getEncodingBits();
849 if (EncodingBits == ENC_CALL_SITE_ARGUMENT_USE)
851 if (EncodingBits == ENC_FLOATING_FUNCTION)
852 return IRP_FLOAT;
853
854 Value *V = getAsValuePtr();
855 if (!V)
856 return IRP_INVALID;
857 if (isa<Argument>(V))
858 return IRP_ARGUMENT;
859 if (isa<Function>(V))
860 return isReturnPosition(EncodingBits) ? IRP_RETURNED : IRP_FUNCTION;
861 if (isa<CallBase>(V))
862 return isReturnPosition(EncodingBits) ? IRP_CALL_SITE_RETURNED
864 return IRP_FLOAT;
865 }
866
868 switch (getPositionKind()) {
872 return true;
873 default:
874 return false;
875 }
876 }
877
878 /// Return true if the position is an argument or call site argument.
879 bool isArgumentPosition() const {
880 switch (getPositionKind()) {
883 return true;
884 default:
885 return false;
886 }
887 }
888
889 /// Return the same position without the call base context.
891 IRPosition Result = *this;
892 Result.CBContext = nullptr;
893 return Result;
894 }
895
896 /// Get the call base context from the position.
897 const CallBaseContext *getCallBaseContext() const { return CBContext; }
898
899 /// Check if the position has any call base context.
900 bool hasCallBaseContext() const { return CBContext != nullptr; }
901
902 /// Conversion into a void * to allow reuse of pointer hashing.
903 operator void *() const { return Enc.getOpaqueValue(); }
904
905private:
906 /// Private constructor for special values only!
907 explicit IRPosition(void *Ptr, const CallBaseContext *CBContext = nullptr)
908 : CBContext(CBContext) {
909 Enc.setFromOpaqueValue(Ptr);
910 }
911
912 /// IRPosition anchored at \p AnchorVal with kind/argument numbet \p PK.
913 explicit IRPosition(Value &AnchorVal, Kind PK,
914 const CallBaseContext *CBContext = nullptr)
915 : CBContext(CBContext) {
916 switch (PK) {
918 llvm_unreachable("Cannot create invalid IRP with an anchor value!");
919 break;
921 // Special case for floating functions.
922 if (isa<Function>(AnchorVal) || isa<CallBase>(AnchorVal))
923 Enc = {&AnchorVal, ENC_FLOATING_FUNCTION};
924 else
925 Enc = {&AnchorVal, ENC_VALUE};
926 break;
929 Enc = {&AnchorVal, ENC_VALUE};
930 break;
933 Enc = {&AnchorVal, ENC_RETURNED_VALUE};
934 break;
936 Enc = {&AnchorVal, ENC_VALUE};
937 break;
940 "Cannot create call site argument IRP with an anchor value!");
941 break;
942 }
943 verify();
944 }
945
946 /// Return the callee argument number of the associated value if it is an
947 /// argument or call site argument. See also `getCalleeArgNo` and
948 /// `getCallSiteArgNo`.
949 int getArgNo(bool CallbackCalleeArgIfApplicable) const {
950 if (CallbackCalleeArgIfApplicable)
951 if (Argument *Arg = getAssociatedArgument())
952 return Arg->getArgNo();
953 switch (getPositionKind()) {
955 return cast<Argument>(getAsValuePtr())->getArgNo();
957 Use &U = *getAsUsePtr();
958 return cast<CallBase>(U.getUser())->getArgOperandNo(&U);
959 }
960 default:
961 return -1;
962 }
963 }
964
965 /// IRPosition for the use \p U. The position kind \p PK needs to be
966 /// IRP_CALL_SITE_ARGUMENT, the anchor value is the user, the associated value
967 /// the used value.
968 explicit IRPosition(Use &U, Kind PK) {
970 "Use constructor is for call site arguments only!");
971 Enc = {&U, ENC_CALL_SITE_ARGUMENT_USE};
972 verify();
973 }
974
975 /// Verify internal invariants.
976 LLVM_ABI void verify();
977
978 /// Return the underlying pointer as Value *, valid for all positions but
979 /// IRP_CALL_SITE_ARGUMENT.
980 Value *getAsValuePtr() const {
981 assert(getEncodingBits() != ENC_CALL_SITE_ARGUMENT_USE &&
982 "Not a value pointer!");
983 return reinterpret_cast<Value *>(Enc.getPointer());
984 }
985
986 /// Return the underlying pointer as Use *, valid only for
987 /// IRP_CALL_SITE_ARGUMENT positions.
988 Use *getAsUsePtr() const {
989 assert(getEncodingBits() == ENC_CALL_SITE_ARGUMENT_USE &&
990 "Not a value pointer!");
991 return reinterpret_cast<Use *>(Enc.getPointer());
992 }
993
994 /// Return true if \p EncodingBits describe a returned or call site returned
995 /// position.
996 static bool isReturnPosition(char EncodingBits) {
997 return EncodingBits == ENC_RETURNED_VALUE;
998 }
999
1000 /// The encoding of the IRPosition is a combination of a pointer and two
1001 /// encoding bits. The values of the encoding bits are defined in the enum
1002 /// below. The pointer is either a Value* (for the first three encoding bit
1003 /// combinations) or Use* (for ENC_CALL_SITE_ARGUMENT_USE).
1004 ///
1005 ///{
1006 enum {
1007 ENC_VALUE = 0b00,
1008 ENC_RETURNED_VALUE = 0b01,
1009 ENC_FLOATING_FUNCTION = 0b10,
1010 ENC_CALL_SITE_ARGUMENT_USE = 0b11,
1011 };
1012
1013 // Reserve the maximal amount of bits so there is no need to mask out the
1014 // remaining ones. We will not encode anything else in the pointer anyway.
1015 static constexpr int NumEncodingBits =
1017 static_assert(NumEncodingBits >= 2, "At least two bits are required!");
1018
1019 /// The pointer with the encoding bits.
1020 PointerIntPair<void *, NumEncodingBits, char> Enc;
1021 ///}
1022
1023 /// Call base context. Used for callsite specific analysis.
1024 const CallBaseContext *CBContext = nullptr;
1025
1026 /// Return the encoding bits.
1027 char getEncodingBits() const { return Enc.getInt(); }
1028};
1029
1030/// Helper that allows IRPosition as a key in a DenseMap.
1031template <> struct DenseMapInfo<IRPosition> {
1032 static unsigned getHashValue(const IRPosition &IRP) {
1033 return (DenseMapInfo<void *>::getHashValue(IRP) << 4) ^
1035 }
1036
1037 static bool isEqual(const IRPosition &a, const IRPosition &b) {
1038 return a == b;
1039 }
1040};
1041
1042/// A visitor class for IR positions.
1043///
1044/// Given a position P, the SubsumingPositionIterator allows to visit "subsuming
1045/// positions" wrt. attributes/information. Thus, if a piece of information
1046/// holds for a subsuming position, it also holds for the position P.
1047///
1048/// The subsuming positions always include the initial position and then,
1049/// depending on the position kind, additionally the following ones:
1050/// - for IRP_RETURNED:
1051/// - the function (IRP_FUNCTION)
1052/// - for IRP_ARGUMENT:
1053/// - the function (IRP_FUNCTION)
1054/// - for IRP_CALL_SITE:
1055/// - the callee (IRP_FUNCTION), if known
1056/// - for IRP_CALL_SITE_RETURNED:
1057/// - the callee (IRP_RETURNED), if known
1058/// - the call site (IRP_FUNCTION)
1059/// - the callee (IRP_FUNCTION), if known
1060/// - for IRP_CALL_SITE_ARGUMENT:
1061/// - the argument of the callee (IRP_ARGUMENT), if known
1062/// - the callee (IRP_FUNCTION), if known
1063/// - the position the call site argument is associated with if it is not
1064/// anchored to the call site, e.g., if it is an argument then the argument
1065/// (IRP_ARGUMENT)
1067 SmallVector<IRPosition, 4> IRPositions;
1068 using iterator = decltype(IRPositions)::iterator;
1069
1070public:
1072 iterator begin() { return IRPositions.begin(); }
1073 iterator end() { return IRPositions.end(); }
1074};
1075
1076/// Wrapper for FunctionAnalysisManager.
1078 // The client may be running the old pass manager, in which case, we need to
1079 // map the requested Analysis to its equivalent wrapper in the old pass
1080 // manager. The scheme implemented here does not require every Analysis to be
1081 // updated. Only those new analyses that the client cares about in the old
1082 // pass manager need to expose a LegacyWrapper type, and that wrapper should
1083 // support a getResult() method that matches the new Analysis.
1084 //
1085 // We need SFINAE to check for the LegacyWrapper, but function templates don't
1086 // allow partial specialization, which is needed in this case. So instead, we
1087 // use a constexpr bool to perform the SFINAE, and then use this information
1088 // inside the function template.
1089 template <typename, typename = void>
1090 static constexpr bool HasLegacyWrapper = false;
1091
1092 template <typename Analysis>
1093 typename Analysis::Result *getAnalysis(const Function &F,
1094 bool RequestCachedOnly = false) {
1095 if (!LegacyPass && !FAM)
1096 return nullptr;
1097 if (FAM) {
1098 if (CachedOnly || RequestCachedOnly)
1099 return FAM->getCachedResult<Analysis>(const_cast<Function &>(F));
1100 return &FAM->getResult<Analysis>(const_cast<Function &>(F));
1101 }
1102 if constexpr (HasLegacyWrapper<Analysis>) {
1103 if (!CachedOnly && !RequestCachedOnly)
1104 return &LegacyPass
1105 ->getAnalysis<typename Analysis::LegacyWrapper>(
1106 const_cast<Function &>(F))
1107 .getResult();
1108 if (auto *P =
1109 LegacyPass
1110 ->getAnalysisIfAvailable<typename Analysis::LegacyWrapper>())
1111 return &P->getResult();
1112 }
1113 return nullptr;
1114 }
1115
1116 /// Invalidates the analyses. Valid only when using the new pass manager.
1118 assert(FAM && "Can only be used from the new PM!");
1119 FAM->clear();
1120 }
1121
1122 AnalysisGetter(FunctionAnalysisManager &FAM, bool CachedOnly = false)
1123 : FAM(&FAM), CachedOnly(CachedOnly) {}
1124 AnalysisGetter(Pass *P, bool CachedOnly = false)
1125 : LegacyPass(P), CachedOnly(CachedOnly) {}
1126 AnalysisGetter() = default;
1127
1128private:
1129 FunctionAnalysisManager *FAM = nullptr;
1130 Pass *LegacyPass = nullptr;
1131
1132 /// If \p CachedOnly is true, no pass is created, just existing results are
1133 /// used. Also available per request.
1134 bool CachedOnly = false;
1135};
1136
1137template <typename Analysis>
1139 Analysis, std::void_t<typename Analysis::LegacyWrapper>> = true;
1140
1141/// Data structure to hold cached (LLVM-IR) information.
1142///
1143/// All attributes are given an InformationCache object at creation time to
1144/// avoid inspection of the IR by all of them individually. This default
1145/// InformationCache will hold information required by 'default' attributes,
1146/// thus the ones deduced when Attributor::identifyDefaultAbstractAttributes(..)
1147/// is called.
1148///
1149/// If custom abstract attributes, registered manually through
1150/// Attributor::registerAA(...), need more information, especially if it is not
1151/// reusable, it is advised to inherit from the InformationCache and cast the
1152/// instance down in the abstract attributes.
1156 bool UseExplorer = true)
1157 : CGSCC(CGSCC), M(M), Allocator(Allocator), AG(AG) {
1158 if (UseExplorer)
1159 Explorer = new (Allocator) MustBeExecutedContextExplorer(
1160 /* ExploreInterBlock */
1161 true, /* ExploreCFGForward */ true,
1162 /* ExploreCFGBackward */ true,
1163 /* LIGetter */
1164 [&](const Function &F) { return AG.getAnalysis<LoopAnalysis>(F); },
1165 /* DTGetter */
1166 [&](const Function &F) {
1167 return AG.getAnalysis<DominatorTreeAnalysis>(F);
1168 },
1169 /* PDTGetter */
1170 [&](const Function &F) {
1171 return AG.getAnalysis<PostDominatorTreeAnalysis>(F);
1172 });
1173 }
1174
1176 // The FunctionInfo objects are allocated via a BumpPtrAllocator, we call
1177 // the destructor manually.
1178 for (auto &It : FuncInfoMap)
1179 It.getSecond()->~FunctionInfo();
1180 // Same is true for the instruction exclusions sets.
1182 for (auto *BES : BESets)
1183 BES->~InstExclusionSetTy();
1184 if (Explorer)
1185 Explorer->~MustBeExecutedContextExplorer();
1186 }
1187
1188 /// Apply \p CB to all uses of \p F. If \p LookThroughConstantExprUses is
1189 /// true, constant expression users are not given to \p CB but their uses are
1190 /// traversed transitively.
1191 template <typename CBTy>
1192 static void foreachUse(Function &F, CBTy CB,
1193 bool LookThroughConstantExprUses = true) {
1194 SmallVector<Use *, 8> Worklist(make_pointer_range(F.uses()));
1195
1196 for (unsigned Idx = 0; Idx < Worklist.size(); ++Idx) {
1197 Use &U = *Worklist[Idx];
1198
1199 // Allow use in constant bitcasts and simply look through them.
1200 if (LookThroughConstantExprUses && isa<ConstantExpr>(U.getUser())) {
1201 for (Use &CEU : cast<ConstantExpr>(U.getUser())->uses())
1202 Worklist.push_back(&CEU);
1203 continue;
1204 }
1205
1206 CB(U);
1207 }
1208 }
1209
1210 /// The CG-SCC the pass is run on, or nullptr if it is a module pass.
1211 const SetVector<Function *> *const CGSCC = nullptr;
1212
1213 /// A vector type to hold instructions.
1215
1216 /// A map type from opcodes to instructions with this opcode.
1218
1219 /// Return the map that relates "interesting" opcodes with all instructions
1220 /// with that opcode in \p F.
1222 return getFunctionInfo(F).OpcodeInstMap;
1223 }
1224
1225 /// Return the instructions in \p F that may read or write memory.
1227 return getFunctionInfo(F).RWInsts;
1228 }
1229
1230 /// Return MustBeExecutedContextExplorer
1234
1235 /// Return TargetLibraryInfo for function \p F.
1239
1240 /// Return true if \p F has the "kernel" function attribute
1241 bool isKernel(const Function &F) {
1242 FunctionInfo &FI = getFunctionInfo(F);
1243 return FI.IsKernel;
1244 }
1245
1246 /// Return true if \p Arg is involved in a must-tail call, thus the argument
1247 /// of the caller or callee.
1249 FunctionInfo &FI = getFunctionInfo(*Arg.getParent());
1250 return FI.CalledViaMustTail || FI.ContainsMustTailCall;
1251 }
1252
1253 bool isOnlyUsedByAssume(const Instruction &I) const {
1254 return AssumeOnlyValues.contains(&I);
1255 }
1256
1257 /// Invalidates the cached analyses. Valid only when using the new pass
1258 /// manager.
1259 void invalidateAnalyses() { AG.invalidateAnalyses(); }
1260
1261 /// Return the analysis result from a pass \p AP for function \p F.
1262 template <typename AP>
1263 typename AP::Result *getAnalysisResultForFunction(const Function &F,
1264 bool CachedOnly = false) {
1265 return AG.getAnalysis<AP>(F, CachedOnly);
1266 }
1267
1268 const Module &getModule() const { return M; }
1269
1270 /// Return datalayout used in the module.
1271 const DataLayout &getDL() const { return M.getDataLayout(); }
1272
1273 /// Return the map conaining all the knowledge we have from `llvm.assume`s.
1274 const RetainedKnowledgeMap &getKnowledgeMap() const { return KnowledgeMap; }
1275
1276 /// Given \p BES, return a uniqued version.
1279 auto It = BESets.find(BES);
1280 if (It != BESets.end())
1281 return *It;
1282 auto *UniqueBES = new (Allocator) AA::InstExclusionSetTy(*BES);
1283 bool Success = BESets.insert(UniqueBES).second;
1284 (void)Success;
1285 assert(Success && "Expected only new entries to be added");
1286 return UniqueBES;
1287 }
1288
1289 /// Return true if the stack (llvm::Alloca) can be accessed by other threads.
1291
1292 /// Return true if the target is a GPU.
1293 bool IsTargetGPU() const { return M.getTargetTriple().isGPU(); }
1294
1295 /// Return all functions that might be called indirectly, only valid for
1296 /// closed world modules (see isClosedWorldModule).
1299
1300 /// Return the flat address space if the associated target has.
1301 LLVM_ABI std::optional<unsigned> getFlatAddressSpace() const;
1302
1303 virtual unsigned getMaxAddrSpace() const { return ~0U; }
1304
1305private:
1306 struct FunctionInfo {
1307 LLVM_ABI ~FunctionInfo();
1308
1309 /// A nested map that remembers all instructions in a function with a
1310 /// certain instruction opcode (Instruction::getOpcode()).
1311 OpcodeInstMapTy OpcodeInstMap;
1312
1313 /// A map from functions to their instructions that may read or write
1314 /// memory.
1315 InstructionVectorTy RWInsts;
1316
1317 /// Function is called by a `musttail` call.
1318 bool CalledViaMustTail;
1319
1320 /// Function contains a `musttail` call.
1321 bool ContainsMustTailCall;
1322
1323 /// Function has the `"kernel"` attribute
1324 bool IsKernel;
1325 };
1326
1327 /// A map type from functions to informatio about it.
1328 DenseMap<const Function *, FunctionInfo *> FuncInfoMap;
1329
1330 /// Return information about the function \p F, potentially by creating it.
1331 FunctionInfo &getFunctionInfo(const Function &F) {
1332 FunctionInfo *&FI = FuncInfoMap[&F];
1333 if (!FI) {
1334 FI = new (Allocator) FunctionInfo();
1335 initializeInformationCache(F, *FI);
1336 }
1337 return *FI;
1338 }
1339
1340 /// Vector of functions that might be callable indirectly, i.a., via a
1341 /// function pointer.
1342 SmallVector<Function *> IndirectlyCallableFunctions;
1343
1344 /// Initialize the function information cache \p FI for the function \p F.
1345 ///
1346 /// This method needs to be called for all function that might be looked at
1347 /// through the information cache interface *prior* to looking at them.
1348 LLVM_ABI void initializeInformationCache(const Function &F, FunctionInfo &FI);
1349
1350 /// The module.
1351 const Module &M;
1352
1353 /// The allocator used to allocate memory, e.g. for `FunctionInfo`s.
1354 BumpPtrAllocator &Allocator;
1355
1356 /// MustBeExecutedContextExplorer
1357 MustBeExecutedContextExplorer *Explorer = nullptr;
1358
1359 /// A map with knowledge retained in `llvm.assume` instructions.
1360 RetainedKnowledgeMap KnowledgeMap;
1361
1362 /// A container for all instructions that are only used by `llvm.assume`.
1363 SetVector<const Instruction *> AssumeOnlyValues;
1364
1365 /// Cache for block sets to allow reuse.
1366 DenseSet<const AA::InstExclusionSetTy *> BESets;
1367
1368 /// Getters for analysis.
1369 AnalysisGetter &AG;
1370
1371 /// Set of inlineable functions
1372 SmallPtrSet<const Function *, 8> InlineableFunctions;
1373
1374 /// Give the Attributor access to the members so
1375 /// Attributor::identifyDefaultAbstractAttributes(...) can initialize them.
1376 friend struct Attributor;
1377};
1378
1379/// Configuration for the Attributor.
1381
1383
1384 /// Is the user of the Attributor a module pass or not. This determines what
1385 /// IR we can look at and modify. If it is a module pass we might deduce facts
1386 /// outside the initial function set and modify functions outside that set,
1387 /// but only as part of the optimization of the functions in the initial
1388 /// function set. For CGSCC passes we can look at the IR of the module slice
1389 /// but never run any deduction, or perform any modification, outside the
1390 /// initial function set (which we assume is the SCC).
1391 bool IsModulePass = true;
1392
1393 /// Flag to determine if we can delete functions or keep dead ones around.
1394 bool DeleteFns = true;
1395
1396 /// Flag to determine if we rewrite function signatures.
1398
1399 /// Flag to determine if we want to initialize all default AAs for an internal
1400 /// function marked live. See also: InitializationCallback>
1402
1403 /// Flag to determine if we should skip all liveness checks early on.
1404 bool UseLiveness = true;
1405
1406 /// Flag to indicate if the entire world is contained in this module, that
1407 /// is, no outside functions exist.
1409
1410 /// Callback function to be invoked on internal functions marked live.
1411 std::function<void(Attributor &A, const Function &F)> InitializationCallback =
1412 nullptr;
1413
1414 /// Callback function to determine if an indirect call targets should be made
1415 /// direct call targets (with an if-cascade).
1416 std::function<bool(Attributor &A, const AbstractAttribute &AA, CallBase &CB,
1417 Function &AssumedCallee, unsigned NumAssumedCallees)>
1419
1420 /// Helper to update an underlying call graph and to delete functions.
1422
1423 /// If not null, a set limiting the attribute opportunities.
1425
1426 /// Maximum number of iterations to run until fixpoint.
1427 std::optional<unsigned> MaxFixpointIterations;
1428
1429 /// A callback function that returns an ORE object from a Function pointer.
1430 ///{
1434 ///}
1435
1436 /// The name of the pass running the attributor, used to emit remarks.
1437 const char *PassName = nullptr;
1438
1439 using IPOAmendableCBTy = std::function<bool(const Function &F)>;
1441};
1442
1443/// A debug counter to limit the number of AAs created.
1444DEBUG_COUNTER(NumAbstractAttributes, "num-abstract-attributes",
1445 "How many AAs should be initialized");
1446
1447/// The fixpoint analysis framework that orchestrates the attribute deduction.
1448///
1449/// The Attributor provides a general abstract analysis framework (guided
1450/// fixpoint iteration) as well as helper functions for the deduction of
1451/// (LLVM-IR) attributes. However, also other code properties can be deduced,
1452/// propagated, and ultimately manifested through the Attributor framework. This
1453/// is particularly useful if these properties interact with attributes and a
1454/// co-scheduled deduction allows to improve the solution. Even if not, thus if
1455/// attributes/properties are completely isolated, they should use the
1456/// Attributor framework to reduce the number of fixpoint iteration frameworks
1457/// in the code base. Note that the Attributor design makes sure that isolated
1458/// attributes are not impacted, in any way, by others derived at the same time
1459/// if there is no cross-reasoning performed.
1460///
1461/// The public facing interface of the Attributor is kept simple and basically
1462/// allows abstract attributes to one thing, query abstract attributes
1463/// in-flight. There are two reasons to do this:
1464/// a) The optimistic state of one abstract attribute can justify an
1465/// optimistic state of another, allowing to framework to end up with an
1466/// optimistic (=best possible) fixpoint instead of one based solely on
1467/// information in the IR.
1468/// b) This avoids reimplementing various kinds of lookups, e.g., to check
1469/// for existing IR attributes, in favor of a single lookups interface
1470/// provided by an abstract attribute subclass.
1471///
1472/// NOTE: The mechanics of adding a new "concrete" abstract attribute are
1473/// described in the file comment.
1475
1476 /// Constructor
1477 ///
1478 /// \param Functions The set of functions we are deriving attributes for.
1479 /// \param InfoCache Cache to hold various information accessible for
1480 /// the abstract attributes.
1481 /// \param Configuration The Attributor configuration which determines what
1482 /// generic features to use.
1484 InformationCache &InfoCache,
1485 AttributorConfig Configuration);
1486
1488
1489 /// Run the analyses until a fixpoint is reached or enforced (timeout).
1490 ///
1491 /// The attributes registered with this Attributor can be used after as long
1492 /// as the Attributor is not destroyed (it owns the attributes now).
1493 ///
1494 /// \Returns CHANGED if the IR was changed, otherwise UNCHANGED.
1496
1497 /// Lookup an abstract attribute of type \p AAType at position \p IRP. While
1498 /// no abstract attribute is found equivalent positions are checked, see
1499 /// SubsumingPositionIterator. Thus, the returned abstract attribute
1500 /// might be anchored at a different position, e.g., the callee if \p IRP is a
1501 /// call base.
1502 ///
1503 /// This method is the only (supported) way an abstract attribute can retrieve
1504 /// information from another abstract attribute. As an example, take an
1505 /// abstract attribute that determines the memory access behavior for a
1506 /// argument (readnone, readonly, ...). It should use `getAAFor` to get the
1507 /// most optimistic information for other abstract attributes in-flight, e.g.
1508 /// the one reasoning about the "captured" state for the argument or the one
1509 /// reasoning on the memory access behavior of the function as a whole.
1510 ///
1511 /// If the DepClass enum is set to `DepClassTy::None` the dependence from
1512 /// \p QueryingAA to the return abstract attribute is not automatically
1513 /// recorded. This should only be used if the caller will record the
1514 /// dependence explicitly if necessary, thus if it the returned abstract
1515 /// attribute is used for reasoning. To record the dependences explicitly use
1516 /// the `Attributor::recordDependence` method.
1517 template <typename AAType>
1518 const AAType *getAAFor(const AbstractAttribute &QueryingAA,
1519 const IRPosition &IRP, DepClassTy DepClass) {
1520 return getOrCreateAAFor<AAType>(IRP, &QueryingAA, DepClass,
1521 /* ForceUpdate */ false);
1522 }
1523
1524 /// The version of getAAFor that allows to omit a querying abstract
1525 /// attribute. Using this after Attributor started running is restricted to
1526 /// only the Attributor itself. Initial seeding of AAs can be done via this
1527 /// function.
1528 /// NOTE: ForceUpdate is ignored in any stage other than the update stage.
1529 template <typename AAType>
1530 const AAType *getOrCreateAAFor(IRPosition IRP,
1531 const AbstractAttribute *QueryingAA,
1532 DepClassTy DepClass, bool ForceUpdate = false,
1533 bool UpdateAfterInit = true) {
1534 if (!shouldPropagateCallBaseContext(IRP))
1535 IRP = IRP.stripCallBaseContext();
1536
1537 if (AAType *AAPtr = lookupAAFor<AAType>(IRP, QueryingAA, DepClass,
1538 /* AllowInvalidState */ true)) {
1539 if (ForceUpdate && Phase == AttributorPhase::UPDATE)
1540 updateAA(*AAPtr);
1541 return AAPtr;
1542 }
1543
1544 bool ShouldUpdateAA;
1545 if (!shouldInitialize<AAType>(IRP, ShouldUpdateAA))
1546 return nullptr;
1547
1548 if (!DebugCounter::shouldExecute(NumAbstractAttributes))
1549 return nullptr;
1550
1551 // No matching attribute found, create one.
1552 // Use the static create method.
1553 auto &AA = AAType::createForPosition(IRP, *this);
1554
1555 // Always register a new attribute to make sure we clean up the allocated
1556 // memory properly.
1557 registerAA(AA);
1558
1559 // If we are currenty seeding attributes, enforce seeding rules.
1560 if (Phase == AttributorPhase::SEEDING && !shouldSeedAttribute(AA)) {
1561 AA.getState().indicatePessimisticFixpoint();
1562 return &AA;
1563 }
1564
1565 // Bootstrap the new attribute with an initial update to propagate
1566 // information, e.g., function -> call site.
1567 {
1568 TimeTraceScope TimeScope("initialize", [&]() {
1569 return AA.getName().str() +
1570 std::to_string(AA.getIRPosition().getPositionKind());
1571 });
1572 ++InitializationChainLength;
1573 AA.initialize(*this);
1574 --InitializationChainLength;
1575 }
1576
1577 if (!ShouldUpdateAA) {
1578 AA.getState().indicatePessimisticFixpoint();
1579 return &AA;
1580 }
1581
1582 // Allow seeded attributes to declare dependencies.
1583 // Remember the seeding state.
1584 if (UpdateAfterInit) {
1585 AttributorPhase OldPhase = Phase;
1586 Phase = AttributorPhase::UPDATE;
1587
1588 updateAA(AA);
1589
1590 Phase = OldPhase;
1591 }
1592
1593 if (QueryingAA && AA.getState().isValidState())
1594 recordDependence(AA, const_cast<AbstractAttribute &>(*QueryingAA),
1595 DepClass);
1596 return &AA;
1597 }
1598
1599 template <typename AAType>
1600 const AAType *getOrCreateAAFor(const IRPosition &IRP) {
1601 return getOrCreateAAFor<AAType>(IRP, /* QueryingAA */ nullptr,
1603 }
1604
1605 /// Return the attribute of \p AAType for \p IRP if existing and valid. This
1606 /// also allows non-AA users lookup.
1607 template <typename AAType>
1608 AAType *lookupAAFor(const IRPosition &IRP,
1609 const AbstractAttribute *QueryingAA = nullptr,
1611 bool AllowInvalidState = false) {
1612 static_assert(std::is_base_of<AbstractAttribute, AAType>::value,
1613 "Cannot query an attribute with a type not derived from "
1614 "'AbstractAttribute'!");
1615 // Lookup the abstract attribute of type AAType. If found, return it after
1616 // registering a dependence of QueryingAA on the one returned attribute.
1617 AbstractAttribute *AAPtr = AAMap.lookup({&AAType::ID, IRP});
1618 if (!AAPtr)
1619 return nullptr;
1620
1621 AAType *AA = static_cast<AAType *>(AAPtr);
1622
1623 // Do not register a dependence on an attribute with an invalid state.
1624 if (DepClass != DepClassTy::NONE && QueryingAA &&
1625 AA->getState().isValidState())
1626 recordDependence(*AA, const_cast<AbstractAttribute &>(*QueryingAA),
1627 DepClass);
1628
1629 // Return nullptr if this attribute has an invalid state.
1630 if (!AllowInvalidState && !AA->getState().isValidState())
1631 return nullptr;
1632 return AA;
1633 }
1634
1635 /// Allows a query AA to request an update if a new query was received.
1637
1638 /// Explicitly record a dependence from \p FromAA to \p ToAA, that is if
1639 /// \p FromAA changes \p ToAA should be updated as well.
1640 ///
1641 /// This method should be used in conjunction with the `getAAFor` method and
1642 /// with the DepClass enum passed to the method set to None. This can
1643 /// be beneficial to avoid false dependences but it requires the users of
1644 /// `getAAFor` to explicitly record true dependences through this method.
1645 /// The \p DepClass flag indicates if the dependence is striclty necessary.
1646 /// That means for required dependences, if \p FromAA changes to an invalid
1647 /// state, \p ToAA can be moved to a pessimistic fixpoint because it required
1648 /// information from \p FromAA but none are available anymore.
1649 LLVM_ABI void recordDependence(const AbstractAttribute &FromAA,
1650 const AbstractAttribute &ToAA,
1651 DepClassTy DepClass);
1652
1653 /// Introduce a new abstract attribute into the fixpoint analysis.
1654 ///
1655 /// Note that ownership of the attribute is given to the Attributor. It will
1656 /// invoke delete for the Attributor on destruction of the Attributor.
1657 ///
1658 /// Attributes are identified by their IR position (AAType::getIRPosition())
1659 /// and the address of their static member (see AAType::ID).
1660 template <typename AAType> AAType &registerAA(AAType &AA) {
1661 static_assert(std::is_base_of<AbstractAttribute, AAType>::value,
1662 "Cannot register an attribute with a type not derived from "
1663 "'AbstractAttribute'!");
1664 // Put the attribute in the lookup map structure and the container we use to
1665 // keep track of all attributes.
1666 const IRPosition &IRP = AA.getIRPosition();
1667 AbstractAttribute *&AAPtr = AAMap[{&AAType::ID, IRP}];
1668
1669 assert(!AAPtr && "Attribute already in map!");
1670 AAPtr = &AA;
1671
1672 // Register AA with the synthetic root only before the manifest stage.
1673 if (isDuringDeduction())
1674 DG.SyntheticRoot.Deps.insert(
1676
1677 return AA;
1678 }
1679
1680 /// Return the internal information cache.
1681 InformationCache &getInfoCache() { return InfoCache; }
1682
1683 /// Return the module.
1684 const Module &getModule() { return InfoCache.getModule(); }
1685
1686 /// Return true if this is a module pass, false otherwise.
1687 bool isModulePass() const { return Configuration.IsModulePass; }
1688
1689 /// Return true if we should specialize the call site \b CB for the potential
1690 /// callee \p Fn.
1692 CallBase &CB, Function &Callee,
1693 unsigned NumAssumedCallees) {
1694 return Configuration.IndirectCalleeSpecializationCallback
1695 ? Configuration.IndirectCalleeSpecializationCallback(
1696 *this, AA, CB, Callee, NumAssumedCallees)
1697 : true;
1698 }
1699
1700 /// Return true if the module contains the whole world, thus, no outside
1701 /// functions exist.
1702 LLVM_ABI bool isClosedWorldModule() const;
1703
1704 /// Return true if we derive attributes for \p Fn
1705 bool isRunOn(Function &Fn) const { return isRunOn(&Fn); }
1706 bool isRunOn(Function *Fn) const {
1707 return Functions.empty() || Functions.count(Fn);
1708 }
1709
1710 template <typename AAType> bool shouldUpdateAA(const IRPosition &IRP) {
1711 // If this is queried in the manifest stage, we force the AA to indicate
1712 // pessimistic fixpoint immediately.
1713 if (!isDuringDeduction())
1714 return false;
1715
1716 Function *AssociatedFn = IRP.getAssociatedFunction();
1717
1718 if (IRP.isAnyCallSitePosition()) {
1719 // Check if we require a callee but there is none.
1720 if (!AssociatedFn && AAType::requiresCalleeForCallBase())
1721 return false;
1722
1723 // Check if we require non-asm but it is inline asm.
1724 if (AAType::requiresNonAsmForCallBase() &&
1725 cast<CallBase>(IRP.getAnchorValue()).isInlineAsm())
1726 return false;
1727 }
1728
1729 // Check if we require a calles but we can't see all.
1730 if (AAType::requiresCallersForArgOrFunction())
1733 if (!AssociatedFn->hasLocalLinkage())
1734 return false;
1735
1736 if (!AAType::isValidIRPositionForUpdate(*this, IRP))
1737 return false;
1738
1739 // We update only AAs associated with functions in the Functions set or
1740 // call sites of them.
1741 return (!AssociatedFn || isModulePass() || isRunOn(AssociatedFn) ||
1742 isRunOn(IRP.getAnchorScope()));
1743 }
1744
1745 template <typename AAType>
1746 bool shouldInitialize(const IRPosition &IRP, bool &ShouldUpdateAA) {
1747 if (!AAType::isValidIRPositionForInit(*this, IRP))
1748 return false;
1749
1750 if (Configuration.Allowed && !Configuration.Allowed->count(&AAType::ID))
1751 return false;
1752
1753 // For now we skip anything in naked and optnone functions.
1754 const Function *AnchorFn = IRP.getAnchorScope();
1755 if (AnchorFn && (AnchorFn->hasFnAttribute(Attribute::Naked) ||
1756 AnchorFn->hasFnAttribute(Attribute::OptimizeNone)))
1757 return false;
1758
1759 // Avoid too many nested initializations to prevent a stack overflow.
1760 if (InitializationChainLength > MaxInitializationChainLength)
1761 return false;
1762
1763 ShouldUpdateAA = shouldUpdateAA<AAType>(IRP);
1764
1765 return !AAType::hasTrivialInitializer() || ShouldUpdateAA;
1766 }
1767
1768 /// Determine opportunities to derive 'default' attributes in \p F and create
1769 /// abstract attribute objects for them.
1770 ///
1771 /// \param F The function that is checked for attribute opportunities.
1772 ///
1773 /// Note that abstract attribute instances are generally created even if the
1774 /// IR already contains the information they would deduce. The most important
1775 /// reason for this is the single interface, the one of the abstract attribute
1776 /// instance, which can be queried without the need to look at the IR in
1777 /// various places.
1779
1780 /// Determine whether the function \p F is IPO amendable
1781 ///
1782 /// If a function is exactly defined or it has alwaysinline attribute
1783 /// and is viable to be inlined, we say it is IPO amendable
1785 return F.hasExactDefinition() || InfoCache.InlineableFunctions.count(&F) ||
1786 (Configuration.IPOAmendableCB && Configuration.IPOAmendableCB(F));
1787 }
1788
1789 /// Return whether attributes can participate in fixed-point deduction.
1790 bool isDuringDeduction() const {
1791 return Phase == AttributorPhase::SEEDING ||
1792 Phase == AttributorPhase::UPDATE;
1793 }
1794
1795 /// Mark the internal function \p F as live.
1796 ///
1797 /// This will trigger the identification and initialization of attributes for
1798 /// \p F.
1800 assert(F.hasLocalLinkage() &&
1801 "Only local linkage is assumed dead initially.");
1802
1803 if (Configuration.DefaultInitializeLiveInternals)
1805 if (Configuration.InitializationCallback)
1806 Configuration.InitializationCallback(*this, F);
1807 }
1808
1809 /// Record that \p U is to be replaces with \p NV after information was
1810 /// manifested. This also triggers deletion of trivially dead istructions.
1812 Value *&V = ToBeChangedUses[&U];
1813 if (V && (V->stripPointerCasts() == NV.stripPointerCasts() ||
1815 return false;
1816 assert((!V || V == &NV || isa<UndefValue>(NV)) &&
1817 "Use was registered twice for replacement with different values!");
1818 V = &NV;
1819 return true;
1820 }
1821
1822 /// Helper function to replace all uses associated with \p IRP with \p NV.
1823 /// Return true if there is any change. The flag \p ChangeDroppable indicates
1824 /// if dropppable uses should be changed too.
1826 bool ChangeDroppable = true) {
1828 auto *CB = cast<CallBase>(IRP.getCtxI());
1830 CB->getArgOperandUse(IRP.getCallSiteArgNo()), NV);
1831 }
1832 Value &V = IRP.getAssociatedValue();
1833 auto &Entry = ToBeChangedValues[&V];
1834 Value *CurNV = get<0>(Entry);
1835 if (CurNV && (CurNV->stripPointerCasts() == NV.stripPointerCasts() ||
1836 isa<UndefValue>(CurNV)))
1837 return false;
1838 assert((!CurNV || CurNV == &NV || isa<UndefValue>(NV)) &&
1839 "Value replacement was registered twice with different values!");
1840 Entry = {&NV, ChangeDroppable};
1841 return true;
1842 }
1843
1844 /// Record that \p I is to be replaced with `unreachable` after information
1845 /// was manifested.
1847 ToBeChangedToUnreachableInsts.insert(I);
1848 }
1849
1850 /// Record that \p II has at least one dead successor block. This information
1851 /// is used, e.g., to replace \p II with a call, after information was
1852 /// manifested.
1854 InvokeWithDeadSuccessor.insert(&II);
1855 }
1856
1857 /// Record that \p I is deleted after information was manifested. This also
1858 /// triggers deletion of trivially dead istructions.
1859 void deleteAfterManifest(Instruction &I) { ToBeDeletedInsts.insert(&I); }
1860
1861 /// Record that \p BB is deleted after information was manifested. This also
1862 /// triggers deletion of trivially dead istructions.
1863 void deleteAfterManifest(BasicBlock &BB) { ToBeDeletedBlocks.insert(&BB); }
1864
1865 // Record that \p BB is added during the manifest of an AA. Added basic blocks
1866 // are preserved in the IR.
1868 ManifestAddedBlocks.insert(&BB);
1869 }
1870
1871 /// Record that \p F is deleted after information was manifested.
1873 if (Configuration.DeleteFns)
1874 ToBeDeletedFunctions.insert(&F);
1875 }
1876
1877 /// Return the attributes of kind \p AK existing in the IR as operand bundles
1878 /// of an llvm.assume.
1879 LLVM_ABI bool getAttrsFromAssumes(const IRPosition &IRP,
1882
1883 /// Return true if any kind in \p AKs existing in the IR at a position that
1884 /// will affect this one. See also getAttrs(...).
1885 /// \param IgnoreSubsumingPositions Flag to determine if subsuming positions,
1886 /// e.g., the function position if this is an
1887 /// argument position, should be ignored.
1888 LLVM_ABI bool
1890 bool IgnoreSubsumingPositions = false,
1891 Attribute::AttrKind ImpliedAttributeKind = Attribute::None);
1892
1893 /// Return the attributes of any kind in \p AKs existing in the IR at a
1894 /// position that will affect this one. While each position can only have a
1895 /// single attribute of any kind in \p AKs, there are "subsuming" positions
1896 /// that could have an attribute as well. This method returns all attributes
1897 /// found in \p Attrs.
1898 /// \param IgnoreSubsumingPositions Flag to determine if subsuming positions,
1899 /// e.g., the function position if this is an
1900 /// argument position, should be ignored.
1901 LLVM_ABI void getAttrs(const IRPosition &IRP,
1904 bool IgnoreSubsumingPositions = false);
1905
1906 /// Remove all \p AttrKinds attached to \p IRP.
1910 ArrayRef<StringRef> Attrs);
1911
1912 /// Attach \p DeducedAttrs to \p IRP, if \p ForceReplace is set we do this
1913 /// even if the same attribute kind was already present.
1915 ArrayRef<Attribute> DeducedAttrs,
1916 bool ForceReplace = false);
1917
1918private:
1919 /// Helper to check \p Attrs for \p AK, if not found, check if \p
1920 /// AAType::isImpliedByIR is true, and if not, create AAType for \p IRP.
1921 /// If \p SkipHasAttrCheck is true, don't check whether the attribute is set
1922 /// first. This should be used if only some values of a complex IR attribute
1923 /// imply the AAType.
1924 template <Attribute::AttrKind AK, typename AAType>
1925 void checkAndQueryIRAttr(const IRPosition &IRP, AttributeSet Attrs,
1926 bool SkipHasAttrCheck = false);
1927
1928 /// Helper to apply \p CB on all attributes of type \p AttrDescs of \p IRP.
1929 template <typename DescTy>
1930 ChangeStatus updateAttrMap(const IRPosition &IRP, ArrayRef<DescTy> AttrDescs,
1931 function_ref<bool(const DescTy &, AttributeSet,
1932 AttributeMask &, AttrBuilder &)>
1933 CB);
1934
1935 /// Mapping from functions/call sites to their attributes.
1937
1938public:
1939 /// If \p IRP is assumed to be a constant, return it, if it is unclear yet,
1940 /// return std::nullopt, otherwise return `nullptr`.
1941 LLVM_ABI std::optional<Constant *>
1943 bool &UsedAssumedInformation);
1944 std::optional<Constant *> getAssumedConstant(const Value &V,
1945 const AbstractAttribute &AA,
1946 bool &UsedAssumedInformation) {
1947 return getAssumedConstant(IRPosition::value(V), AA, UsedAssumedInformation);
1948 }
1949
1950 /// If \p V is assumed simplified, return it, if it is unclear yet,
1951 /// return std::nullopt, otherwise return `nullptr`.
1952 std::optional<Value *> getAssumedSimplified(const IRPosition &IRP,
1953 const AbstractAttribute &AA,
1954 bool &UsedAssumedInformation,
1955 AA::ValueScope S) {
1956 return getAssumedSimplified(IRP, &AA, UsedAssumedInformation, S);
1957 }
1958 std::optional<Value *> getAssumedSimplified(const Value &V,
1959 const AbstractAttribute &AA,
1960 bool &UsedAssumedInformation,
1961 AA::ValueScope S) {
1963 UsedAssumedInformation, S);
1964 }
1965
1966 /// If \p V is assumed simplified, return it, if it is unclear yet,
1967 /// return std::nullopt, otherwise return `nullptr`. Same as the public
1968 /// version except that it can be used without recording dependences on any \p
1969 /// AA.
1970 LLVM_ABI std::optional<Value *>
1972 bool &UsedAssumedInformation, AA::ValueScope S);
1973
1974 /// Try to simplify \p IRP and in the scope \p S. If successful, true is
1975 /// returned and all potential values \p IRP can take are put into \p Values.
1976 /// If the result in \p Values contains select or PHI instructions it means
1977 /// those could not be simplified to a single value. Recursive calls with
1978 /// these instructions will yield their respective potential values. If false
1979 /// is returned no other information is valid.
1980 LLVM_ABI bool
1983 AA::ValueScope S, bool &UsedAssumedInformation,
1984 bool RecurseForSelectAndPHI = true);
1985
1986 /// Register \p CB as a simplification callback.
1987 /// `Attributor::getAssumedSimplified` will use these callbacks before
1988 /// we it will ask `AAValueSimplify`. It is important to ensure this
1989 /// is called before `identifyDefaultAbstractAttributes`, assuming the
1990 /// latter is called at all.
1991 using SimplifictionCallbackTy = std::function<std::optional<Value *>(
1992 const IRPosition &, const AbstractAttribute *, bool &)>;
1994 const SimplifictionCallbackTy &CB) {
1995 SimplificationCallbacks[IRP].emplace_back(CB);
1996 }
1997
1998 /// Return true if there is a simplification callback for \p IRP.
2000 return SimplificationCallbacks.count(IRP);
2001 }
2002
2003 /// Register \p CB as a simplification callback.
2004 /// Similar to \p registerSimplificationCallback, the call back will be called
2005 /// first when we simplify a global variable \p GV.
2007 std::function<std::optional<Constant *>(
2008 const GlobalVariable &, const AbstractAttribute *, bool &)>;
2010 const GlobalVariable &GV,
2012 GlobalVariableSimplificationCallbacks[&GV].emplace_back(CB);
2013 }
2014
2015 /// Return true if there is a simplification callback for \p GV.
2017 return GlobalVariableSimplificationCallbacks.count(&GV);
2018 }
2019
2020 /// Return \p std::nullopt if there is no call back registered for \p GV or
2021 /// the call back is still not sure if \p GV can be simplified. Return \p
2022 /// nullptr if \p GV can't be simplified.
2023 std::optional<Constant *>
2025 const AbstractAttribute *AA,
2026 bool &UsedAssumedInformation) {
2027 assert(GlobalVariableSimplificationCallbacks.contains(&GV));
2028 for (auto &CB : GlobalVariableSimplificationCallbacks.lookup(&GV)) {
2029 auto SimplifiedGV = CB(GV, AA, UsedAssumedInformation);
2030 // For now we assume the call back will not return a std::nullopt.
2031 assert(SimplifiedGV.has_value() && "SimplifiedGV has not value");
2032 return *SimplifiedGV;
2033 }
2034 llvm_unreachable("there must be a callback registered");
2035 }
2036
2038 std::function<bool(Attributor &, const AbstractAttribute *)>;
2040 const VirtualUseCallbackTy &CB) {
2041 VirtualUseCallbacks[&V].emplace_back(CB);
2042 }
2043
2044private:
2045 /// The vector with all simplification callbacks registered by outside AAs.
2047 SimplificationCallbacks;
2048
2049 /// The vector with all simplification callbacks for global variables
2050 /// registered by outside AAs.
2051 DenseMap<const GlobalVariable *,
2053 GlobalVariableSimplificationCallbacks;
2054
2056 VirtualUseCallbacks;
2057
2058public:
2059 /// Translate \p V from the callee context into the call site context.
2060 LLVM_ABI std::optional<Value *>
2061 translateArgumentToCallSiteContent(std::optional<Value *> V, CallBase &CB,
2062 const AbstractAttribute &AA,
2063 bool &UsedAssumedInformation);
2064
2065 /// Return true if \p AA (or its context instruction) is assumed dead.
2066 ///
2067 /// If \p LivenessAA is not provided it is queried.
2069 const AAIsDead *LivenessAA,
2070 bool &UsedAssumedInformation,
2071 bool CheckBBLivenessOnly = false,
2072 DepClassTy DepClass = DepClassTy::OPTIONAL);
2073
2074 /// Return true if \p I is assumed dead.
2075 ///
2076 /// If \p LivenessAA is not provided it is queried.
2077 LLVM_ABI bool isAssumedDead(const Instruction &I,
2078 const AbstractAttribute *QueryingAA,
2079 const AAIsDead *LivenessAA,
2080 bool &UsedAssumedInformation,
2081 bool CheckBBLivenessOnly = false,
2083 bool CheckForDeadStore = false);
2084
2085 /// Return true if \p U is assumed dead.
2086 ///
2087 /// If \p FnLivenessAA is not provided it is queried.
2088 LLVM_ABI bool isAssumedDead(const Use &U, const AbstractAttribute *QueryingAA,
2089 const AAIsDead *FnLivenessAA,
2090 bool &UsedAssumedInformation,
2091 bool CheckBBLivenessOnly = false,
2092 DepClassTy DepClass = DepClassTy::OPTIONAL);
2093
2094 /// Return true if \p IRP is assumed dead.
2095 ///
2096 /// If \p FnLivenessAA is not provided it is queried.
2097 LLVM_ABI bool isAssumedDead(const IRPosition &IRP,
2098 const AbstractAttribute *QueryingAA,
2099 const AAIsDead *FnLivenessAA,
2100 bool &UsedAssumedInformation,
2101 bool CheckBBLivenessOnly = false,
2102 DepClassTy DepClass = DepClassTy::OPTIONAL);
2103
2104 /// Return true if \p BB is assumed dead.
2105 ///
2106 /// If \p LivenessAA is not provided it is queried.
2107 LLVM_ABI bool isAssumedDead(const BasicBlock &BB,
2108 const AbstractAttribute *QueryingAA,
2109 const AAIsDead *FnLivenessAA,
2110 DepClassTy DepClass = DepClassTy::OPTIONAL);
2111
2112 /// Check \p Pred on all potential Callees of \p CB.
2113 ///
2114 /// This method will evaluate \p Pred with all potential callees of \p CB as
2115 /// input and return true if \p Pred does. If some callees might be unknown
2116 /// this function will return false.
2118 function_ref<bool(ArrayRef<const Function *> Callees)> Pred,
2119 const AbstractAttribute &QueryingAA, const CallBase &CB);
2120
2121 /// Check \p Pred on all (transitive) uses of \p V.
2122 ///
2123 /// This method will evaluate \p Pred on all (transitive) uses of the
2124 /// associated value and return true if \p Pred holds every time.
2125 /// If uses are skipped in favor of equivalent ones, e.g., if we look through
2126 /// memory, the \p EquivalentUseCB will be used to give the caller an idea
2127 /// what original used was replaced by a new one (or new ones). The visit is
2128 /// cut short if \p EquivalentUseCB returns false and the function will return
2129 /// false as well.
2131 function_ref<bool(const Use &, bool &)> Pred,
2132 const AbstractAttribute &QueryingAA, const Value &V,
2133 bool CheckBBLivenessOnly = false,
2134 DepClassTy LivenessDepClass = DepClassTy::OPTIONAL,
2135 bool IgnoreDroppableUses = true,
2136 function_ref<bool(const Use &OldU, const Use &NewU)> EquivalentUseCB =
2137 nullptr);
2138
2139 /// Emit a remark generically.
2140 ///
2141 /// This template function can be used to generically emit a remark. The
2142 /// RemarkKind should be one of the following:
2143 /// - OptimizationRemark to indicate a successful optimization attempt
2144 /// - OptimizationRemarkMissed to report a failed optimization attempt
2145 /// - OptimizationRemarkAnalysis to provide additional information about an
2146 /// optimization attempt
2147 ///
2148 /// The remark is built using a callback function \p RemarkCB that takes a
2149 /// RemarkKind as input and returns a RemarkKind.
2150 template <typename RemarkKind, typename RemarkCallBack>
2152 RemarkCallBack &&RemarkCB) const {
2153 if (!Configuration.OREGetter)
2154 return;
2155
2156 Function *F = I->getFunction();
2157 auto &ORE = Configuration.OREGetter(F);
2158
2159 if (RemarkName.starts_with("OMP"))
2160 ORE.emit([&]() {
2161 return RemarkCB(RemarkKind(Configuration.PassName, RemarkName, I))
2162 << " [" << RemarkName << "]";
2163 });
2164 else
2165 ORE.emit([&]() {
2166 return RemarkCB(RemarkKind(Configuration.PassName, RemarkName, I));
2167 });
2168 }
2169
2170 /// Emit a remark on a function.
2171 template <typename RemarkKind, typename RemarkCallBack>
2172 void emitRemark(Function *F, StringRef RemarkName,
2173 RemarkCallBack &&RemarkCB) const {
2174 if (!Configuration.OREGetter)
2175 return;
2176
2177 auto &ORE = Configuration.OREGetter(F);
2178
2179 if (RemarkName.starts_with("OMP"))
2180 ORE.emit([&]() {
2181 return RemarkCB(RemarkKind(Configuration.PassName, RemarkName, F))
2182 << " [" << RemarkName << "]";
2183 });
2184 else
2185 ORE.emit([&]() {
2186 return RemarkCB(RemarkKind(Configuration.PassName, RemarkName, F));
2187 });
2188 }
2189
2190 /// Helper struct used in the communication between an abstract attribute (AA)
2191 /// that wants to change the signature of a function and the Attributor which
2192 /// applies the changes. The struct is partially initialized with the
2193 /// information from the AA (see the constructor). All other members are
2194 /// provided by the Attributor prior to invoking any callbacks.
2195 struct ArgumentReplacementInfo {
2196 /// Callee repair callback type
2197 ///
2198 /// The function repair callback is invoked once to rewire the replacement
2199 /// arguments in the body of the new function. The argument replacement info
2200 /// is passed, as build from the registerFunctionSignatureRewrite call, as
2201 /// well as the replacement function and an iteratore to the first
2202 /// replacement argument.
2203 using CalleeRepairCBTy = std::function<void(
2204 const ArgumentReplacementInfo &, Function &, Function::arg_iterator)>;
2205
2206 /// Abstract call site (ACS) repair callback type
2207 ///
2208 /// The abstract call site repair callback is invoked once on every abstract
2209 /// call site of the replaced function (\see ReplacedFn). The callback needs
2210 /// to provide the operands for the call to the new replacement function.
2211 /// The number and type of the operands appended to the provided vector
2212 /// (second argument) is defined by the number and types determined through
2213 /// the replacement type vector (\see ReplacementTypes). The first argument
2214 /// is the ArgumentReplacementInfo object registered with the Attributor
2215 /// through the registerFunctionSignatureRewrite call.
2217 std::function<void(const ArgumentReplacementInfo &, AbstractCallSite,
2219
2220 /// Simple getters, see the corresponding members for details.
2221 ///{
2222
2223 Attributor &getAttributor() const { return A; }
2224 const Function &getReplacedFn() const { return ReplacedFn; }
2225 const Argument &getReplacedArg() const { return ReplacedArg; }
2226 unsigned getNumReplacementArgs() const { return ReplacementTypes.size(); }
2227
2228 ///}
2229
2230 private:
2231 /// Constructor that takes the argument to be replaced, the types of
2232 /// the replacement arguments, as well as callbacks to repair the call sites
2233 /// and new function after the replacement happened.
2235 ArrayRef<Type *> ReplacementTypes,
2236 CalleeRepairCBTy &&CalleeRepairCB,
2237 ACSRepairCBTy &&ACSRepairCB)
2238 : A(A), ReplacedFn(*Arg.getParent()), ReplacedArg(Arg),
2239 ReplacementTypes(ReplacementTypes),
2240 CalleeRepairCB(std::move(CalleeRepairCB)),
2241 ACSRepairCB(std::move(ACSRepairCB)) {}
2242
2243 /// Reference to the attributor to allow access from the callbacks.
2244 Attributor &A;
2245
2246 /// The "old" function replaced by ReplacementFn.
2247 const Function &ReplacedFn;
2248
2249 /// The "old" argument replaced by new ones defined via ReplacementTypes.
2250 const Argument &ReplacedArg;
2251
2252 /// The types of the arguments replacing ReplacedArg.
2253 const SmallVector<Type *, 8> ReplacementTypes;
2254
2255 /// Callee repair callback, see CalleeRepairCBTy.
2256 const CalleeRepairCBTy CalleeRepairCB;
2257
2258 /// Abstract call site (ACS) repair callback, see ACSRepairCBTy.
2259 const ACSRepairCBTy ACSRepairCB;
2260
2261 /// Allow access to the private members from the Attributor.
2262 friend struct Attributor;
2263 };
2264
2265 /// Check if we can rewrite a function signature.
2266 ///
2267 /// The argument \p Arg is replaced with new ones defined by the number,
2268 /// order, and types in \p ReplacementTypes.
2269 ///
2270 /// \returns True, if the replacement can be registered, via
2271 /// registerFunctionSignatureRewrite, false otherwise.
2272 LLVM_ABI bool
2274 ArrayRef<Type *> ReplacementTypes);
2275
2276 /// Register a rewrite for a function signature.
2277 ///
2278 /// The argument \p Arg is replaced with new ones defined by the number,
2279 /// order, and types in \p ReplacementTypes. The rewiring at the call sites is
2280 /// done through \p ACSRepairCB and at the callee site through
2281 /// \p CalleeRepairCB.
2282 ///
2283 /// \returns True, if the replacement was registered, false otherwise.
2285 Argument &Arg, ArrayRef<Type *> ReplacementTypes,
2288
2289 /// Check \p Pred on all function call sites.
2290 ///
2291 /// This method will evaluate \p Pred on call sites and return
2292 /// true if \p Pred holds in every call sites. However, this is only possible
2293 /// all call sites are known, hence the function has internal linkage.
2294 /// If true is returned, \p UsedAssumedInformation is set if assumed
2295 /// information was used to skip or simplify potential call sites.
2297 const AbstractAttribute &QueryingAA,
2298 bool RequireAllCallSites,
2299 bool &UsedAssumedInformation);
2300
2301 /// Check \p Pred on all call sites of \p Fn.
2302 ///
2303 /// This method will evaluate \p Pred on call sites and return
2304 /// true if \p Pred holds in every call sites. However, this is only possible
2305 /// all call sites are known, hence the function has internal linkage.
2306 /// If true is returned, \p UsedAssumedInformation is set if assumed
2307 /// information was used to skip or simplify potential call sites.
2309 const Function &Fn,
2310 bool RequireAllCallSites,
2311 const AbstractAttribute *QueryingAA,
2312 bool &UsedAssumedInformation,
2313 bool CheckPotentiallyDead = false);
2314
2315 /// Check \p Pred on all values potentially returned by the function
2316 /// associated with \p QueryingAA.
2317 ///
2318 /// This is the context insensitive version of the method above.
2319 LLVM_ABI bool
2321 const AbstractAttribute &QueryingAA,
2323 bool RecurseForSelectAndPHI = true);
2324
2325 /// Check \p Pred on all instructions in \p Fn with an opcode present in
2326 /// \p Opcodes.
2327 ///
2328 /// This method will evaluate \p Pred on all instructions with an opcode
2329 /// present in \p Opcode and return true if \p Pred holds on all of them.
2331 const Function *Fn,
2332 const AbstractAttribute *QueryingAA,
2333 ArrayRef<unsigned> Opcodes,
2334 bool &UsedAssumedInformation,
2335 bool CheckBBLivenessOnly = false,
2336 bool CheckPotentiallyDead = false);
2337
2338 /// Check \p Pred on all instructions with an opcode present in \p Opcodes.
2339 ///
2340 /// This method will evaluate \p Pred on all instructions with an opcode
2341 /// present in \p Opcode and return true if \p Pred holds on all of them.
2343 const AbstractAttribute &QueryingAA,
2344 ArrayRef<unsigned> Opcodes,
2345 bool &UsedAssumedInformation,
2346 bool CheckBBLivenessOnly = false,
2347 bool CheckPotentiallyDead = false);
2348
2349 /// Check \p Pred on all call-like instructions (=CallBased derived).
2350 ///
2351 /// See checkForAllCallLikeInstructions(...) for more information.
2353 const AbstractAttribute &QueryingAA,
2354 bool &UsedAssumedInformation,
2355 bool CheckBBLivenessOnly = false,
2356 bool CheckPotentiallyDead = false) {
2358 Pred, QueryingAA,
2359 {(unsigned)Instruction::Invoke, (unsigned)Instruction::CallBr,
2360 (unsigned)Instruction::Call},
2361 UsedAssumedInformation, CheckBBLivenessOnly, CheckPotentiallyDead);
2362 }
2363
2364 /// Check \p Pred on all Read/Write instructions.
2365 ///
2366 /// This method will evaluate \p Pred on all instructions that read or write
2367 /// to memory present in the information cache and return true if \p Pred
2368 /// holds on all of them.
2369 LLVM_ABI bool
2371 AbstractAttribute &QueryingAA,
2372 bool &UsedAssumedInformation);
2373
2374 /// Create a shallow wrapper for \p F such that \p F has internal linkage
2375 /// afterwards. It also sets the original \p F 's name to anonymous
2376 ///
2377 /// A wrapper is a function with the same type (and attributes) as \p F
2378 /// that will only call \p F and return the result, if any.
2379 ///
2380 /// Assuming the declaration of looks like:
2381 /// rty F(aty0 arg0, ..., atyN argN);
2382 ///
2383 /// The wrapper will then look as follows:
2384 /// rty wrapper(aty0 arg0, ..., atyN argN) {
2385 /// return F(arg0, ..., argN);
2386 /// }
2387 ///
2389
2390 /// Returns true if the function \p F can be internalized. i.e. it has a
2391 /// compatible linkage.
2392 LLVM_ABI static bool isInternalizable(Function &F);
2393
2394 /// Make another copy of the function \p F such that the copied version has
2395 /// internal linkage afterwards and can be analysed. Then we replace all uses
2396 /// of the original function to the copied one
2397 ///
2398 /// Only non-locally linked functions that have `linkonce_odr` or `weak_odr`
2399 /// linkage can be internalized because these linkages guarantee that other
2400 /// definitions with the same name have the same semantics as this one.
2401 ///
2402 /// This will only be run if the `attributor-allow-deep-wrappers` option is
2403 /// set, or if the function is called with \p Force set to true.
2404 ///
2405 /// If the function \p F failed to be internalized the return value will be a
2406 /// null pointer.
2408 bool Force = false);
2409
2410 /// Make copies of each function in the set \p FnSet such that the copied
2411 /// version has internal linkage afterwards and can be analysed. Then we
2412 /// replace all uses of the original function to the copied one. The map
2413 /// \p FnMap contains a mapping of functions to their internalized versions.
2414 ///
2415 /// Only non-locally linked functions that have `linkonce_odr` or `weak_odr`
2416 /// linkage can be internalized because these linkages guarantee that other
2417 /// definitions with the same name have the same semantics as this one.
2418 ///
2419 /// This version will internalize all the functions in the set \p FnSet at
2420 /// once and then replace the uses. This prevents internalized functions being
2421 /// called by external functions when there is an internalized version in the
2422 /// module.
2423 LLVM_ABI static bool
2426
2427 /// Return the data layout associated with the anchor scope.
2428 const DataLayout &getDataLayout() const { return InfoCache.getDL(); }
2429
2430 /// The allocator used to allocate memory, e.g. for `AbstractAttribute`s.
2432
2434 return CGModifiedFunctions;
2435 }
2436
2437private:
2438 /// This method will do fixpoint iteration until fixpoint or the
2439 /// maximum iteration count is reached.
2440 ///
2441 /// If the maximum iteration count is reached, This method will
2442 /// indicate pessimistic fixpoint on attributes that transitively depend
2443 /// on attributes that were scheduled for an update.
2444 void runTillFixpoint();
2445
2446 /// Gets called after scheduling, manifests attributes to the LLVM IR.
2447 ChangeStatus manifestAttributes();
2448
2449 /// Gets called after attributes have been manifested, cleans up the IR.
2450 /// Deletes dead functions, blocks and instructions.
2451 /// Rewrites function signitures and updates the call graph.
2452 ChangeStatus cleanupIR();
2453
2454 /// Identify internal functions that are effectively dead, thus not reachable
2455 /// from a live entry point. The functions are added to ToBeDeletedFunctions.
2456 void identifyDeadInternalFunctions();
2457
2458 /// Run `::update` on \p AA and track the dependences queried while doing so.
2459 /// Also adjust the state if we know further updates are not necessary.
2461
2462 /// Remember the dependences on the top of the dependence stack such that they
2463 /// may trigger further updates. (\see DependenceStack)
2464 void rememberDependences();
2465
2466 /// Determine if CallBase context in \p IRP should be propagated.
2467 LLVM_ABI bool shouldPropagateCallBaseContext(const IRPosition &IRP);
2468
2469 /// Apply all requested function signature rewrites
2470 /// (\see registerFunctionSignatureRewrite) and return Changed if the module
2471 /// was altered.
2473 rewriteFunctionSignatures(SmallSetVector<Function *, 8> &ModifiedFns);
2474
2475 /// Check if the Attribute \p AA should be seeded.
2476 /// See getOrCreateAAFor.
2477 LLVM_ABI bool shouldSeedAttribute(AbstractAttribute &AA);
2478
2479 /// A nested map to lookup abstract attributes based on the argument position
2480 /// on the outer level, and the addresses of the static member (AAType::ID) on
2481 /// the inner level.
2482 ///{
2483 using AAMapKeyTy = std::pair<const char *, IRPosition>;
2485 ///}
2486
2487 /// Map to remember all requested signature changes (= argument replacements).
2489 ArgumentReplacementMap;
2490
2491 /// The set of functions we are deriving attributes for.
2492 SetVector<Function *> &Functions;
2493
2494 /// The information cache that holds pre-processed (LLVM-IR) information.
2495 InformationCache &InfoCache;
2496
2497 /// Abstract Attribute dependency graph
2498 AADepGraph DG;
2499
2500 /// Set of functions for which we modified the content such that it might
2501 /// impact the call graph.
2502 SmallSetVector<Function *, 8> CGModifiedFunctions;
2503
2504 /// Information about a dependence. If FromAA is changed ToAA needs to be
2505 /// updated as well.
2506 struct DepInfo {
2507 const AbstractAttribute *FromAA;
2508 const AbstractAttribute *ToAA;
2509 DepClassTy DepClass;
2510 };
2511
2512 /// The dependence stack is used to track dependences during an
2513 /// `AbstractAttribute::update` call. As `AbstractAttribute::update` can be
2514 /// recursive we might have multiple vectors of dependences in here. The stack
2515 /// size, should be adjusted according to the expected recursion depth and the
2516 /// inner dependence vector size to the expected number of dependences per
2517 /// abstract attribute. Since the inner vectors are actually allocated on the
2518 /// stack we can be generous with their size.
2519 using DependenceVector = SmallVector<DepInfo, 8>;
2521
2522 /// A set to remember the functions we already assume to be live and visited.
2523 DenseSet<const Function *> VisitedFunctions;
2524
2525 /// Uses we replace with a new value after manifest is done. We will remove
2526 /// then trivially dead instructions as well.
2527 SmallMapVector<Use *, Value *, 32> ToBeChangedUses;
2528
2529 /// Values we replace with a new value after manifest is done. We will remove
2530 /// then trivially dead instructions as well.
2531 SmallMapVector<Value *, PointerIntPair<Value *, 1, bool>, 32>
2532 ToBeChangedValues;
2533
2534 /// Instructions we replace with `unreachable` insts after manifest is done.
2535 SmallSetVector<WeakVH, 16> ToBeChangedToUnreachableInsts;
2536
2537 /// Invoke instructions with at least a single dead successor block.
2538 SmallSetVector<WeakVH, 16> InvokeWithDeadSuccessor;
2539
2540 /// A flag that indicates which stage of the process we are in. Initially, the
2541 /// phase is SEEDING. Phase is changed in `Attributor::run()`
2542 enum class AttributorPhase {
2543 SEEDING,
2544 UPDATE,
2545 MANIFEST,
2546 CLEANUP,
2547 } Phase = AttributorPhase::SEEDING;
2548
2549 /// The current initialization chain length. Tracked to avoid stack overflows.
2550 unsigned InitializationChainLength = 0;
2551
2552 /// Functions, blocks, and instructions we delete after manifest is done.
2553 ///
2554 ///{
2555 SmallPtrSet<BasicBlock *, 8> ManifestAddedBlocks;
2556 SmallSetVector<Function *, 8> ToBeDeletedFunctions;
2557 SmallSetVector<BasicBlock *, 8> ToBeDeletedBlocks;
2558 SmallSetVector<WeakVH, 8> ToBeDeletedInsts;
2559 ///}
2560
2561 /// Container with all the query AAs that requested an update via
2562 /// registerForUpdate.
2563 SmallSetVector<AbstractAttribute *, 16> QueryAAsAwaitingUpdate;
2564
2565 /// User provided configuration for this Attributor instance.
2566 const AttributorConfig Configuration;
2567
2568 friend AADepGraph;
2569 friend AttributorCallGraph;
2570};
2571
2572/// An interface to query the internal state of an abstract attribute.
2573///
2574/// The abstract state is a minimal interface that allows the Attributor to
2575/// communicate with the abstract attributes about their internal state without
2576/// enforcing or exposing implementation details, e.g., the (existence of an)
2577/// underlying lattice.
2578///
2579/// It is sufficient to be able to query if a state is (1) valid or invalid, (2)
2580/// at a fixpoint, and to indicate to the state that (3) an optimistic fixpoint
2581/// was reached or (4) a pessimistic fixpoint was enforced.
2582///
2583/// All methods need to be implemented by the subclass. For the common use case,
2584/// a single boolean state or a bit-encoded state, the BooleanState and
2585/// {Inc,Dec,Bit}IntegerState classes are already provided. An abstract
2586/// attribute can inherit from them to get the abstract state interface and
2587/// additional methods to directly modify the state based if needed. See the
2588/// class comments for help.
2590 virtual ~AbstractState() = default;
2591
2592 /// Return if this abstract state is in a valid state. If false, no
2593 /// information provided should be used.
2594 virtual bool isValidState() const = 0;
2595
2596 /// Return if this abstract state is fixed, thus does not need to be updated
2597 /// if information changes as it cannot change itself.
2598 virtual bool isAtFixpoint() const = 0;
2599
2600 /// Indicate that the abstract state should converge to the optimistic state.
2601 ///
2602 /// This will usually make the optimistically assumed state the known to be
2603 /// true state.
2604 ///
2605 /// \returns ChangeStatus::UNCHANGED as the assumed value should not change.
2607
2608 /// Indicate that the abstract state should converge to the pessimistic state.
2609 ///
2610 /// This will usually revert the optimistically assumed state to the known to
2611 /// be true state.
2612 ///
2613 /// \returns ChangeStatus::CHANGED as the assumed value may change.
2615};
2616
2617/// Simple state with integers encoding.
2618///
2619/// The interface ensures that the assumed bits are always a subset of the known
2620/// bits. Users can only add known bits and, except through adding known bits,
2621/// they can only remove assumed bits. This should guarantee monotonicity and
2622/// thereby the existence of a fixpoint (if used correctly). The fixpoint is
2623/// reached when the assumed and known state/bits are equal. Users can
2624/// force/inidicate a fixpoint. If an optimistic one is indicated, the known
2625/// state will catch up with the assumed one, for a pessimistic fixpoint it is
2626/// the other way around.
2627template <typename base_ty, base_ty BestState, base_ty WorstState>
2629 using base_t = base_ty;
2630
2631 IntegerStateBase() = default;
2633
2634 /// Return the best possible representable state.
2635 static constexpr base_t getBestState() { return BestState; }
2636 static constexpr base_t getBestState(const IntegerStateBase &) {
2637 return getBestState();
2638 }
2639
2640 /// Return the worst possible representable state.
2641 static constexpr base_t getWorstState() { return WorstState; }
2642 static constexpr base_t getWorstState(const IntegerStateBase &) {
2643 return getWorstState();
2644 }
2645
2646 /// See AbstractState::isValidState()
2647 /// NOTE: For now we simply pretend that the worst possible state is invalid.
2648 bool isValidState() const override { return Assumed != getWorstState(); }
2649
2650 /// See AbstractState::isAtFixpoint()
2651 bool isAtFixpoint() const override { return Assumed == Known; }
2652
2653 /// See AbstractState::indicateOptimisticFixpoint(...)
2658
2659 /// See AbstractState::indicatePessimisticFixpoint(...)
2664
2665 /// Return the known state encoding
2666 base_t getKnown() const { return Known; }
2667
2668 /// Return the assumed state encoding.
2669 base_t getAssumed() const { return Assumed; }
2670
2671 /// Equality for IntegerStateBase.
2672 bool
2674 return this->getAssumed() == R.getAssumed() &&
2675 this->getKnown() == R.getKnown();
2676 }
2677
2678 /// Inequality for IntegerStateBase.
2679 bool
2681 return !(*this == R);
2682 }
2683
2684 /// "Clamp" this state with \p R. The result is subtype dependent but it is
2685 /// intended that only information assumed in both states will be assumed in
2686 /// this one afterwards.
2690
2691 /// "Clamp" this state with \p R. The result is subtype dependent but it is
2692 /// intended that information known in either state will be known in
2693 /// this one afterwards.
2697
2699 joinOR(R.getAssumed(), R.getKnown());
2700 }
2701
2703 joinAND(R.getAssumed(), R.getKnown());
2704 }
2705
2706protected:
2707 /// Handle a new assumed value \p Value. Subtype dependent.
2709
2710 /// Handle a new known value \p Value. Subtype dependent.
2712
2713 /// Handle a value \p Value. Subtype dependent.
2714 virtual void joinOR(base_t AssumedValue, base_t KnownValue) = 0;
2715
2716 /// Handle a new assumed value \p Value. Subtype dependent.
2717 virtual void joinAND(base_t AssumedValue, base_t KnownValue) = 0;
2718
2719 /// The known state encoding in an integer of type base_t.
2721
2722 /// The assumed state encoding in an integer of type base_t.
2724};
2725
2726/// Specialization of the integer state for a bit-wise encoding.
2727template <typename base_ty = uint32_t, base_ty BestState = ~base_ty(0),
2728 base_ty WorstState = 0>
2730 : public IntegerStateBase<base_ty, BestState, WorstState> {
2732 using base_t = base_ty;
2733 BitIntegerState() = default;
2735
2736 /// Return true if the bits set in \p BitsEncoding are "known bits".
2737 bool isKnown(base_t BitsEncoding = BestState) const {
2738 return (this->Known & BitsEncoding) == BitsEncoding;
2739 }
2740
2741 /// Return true if the bits set in \p BitsEncoding are "assumed bits".
2742 bool isAssumed(base_t BitsEncoding = BestState) const {
2743 return (this->Assumed & BitsEncoding) == BitsEncoding;
2744 }
2745
2746 /// Add the bits in \p BitsEncoding to the "known bits".
2748 // Make sure we never miss any "known bits".
2749 this->Assumed |= Bits;
2750 this->Known |= Bits;
2751 return *this;
2752 }
2753
2754 /// Remove the bits in \p BitsEncoding from the "assumed bits" if not known.
2756 return intersectAssumedBits(~BitsEncoding);
2757 }
2758
2759 /// Remove the bits in \p BitsEncoding from the "known bits".
2761 this->Known = (this->Known & ~BitsEncoding);
2762 return *this;
2763 }
2764
2765 /// Keep only "assumed bits" also set in \p BitsEncoding but all known ones.
2767 // Make sure we never lose any "known bits".
2768 this->Assumed = (this->Assumed & BitsEncoding) | this->Known;
2769 return *this;
2770 }
2771
2772private:
2773 void handleNewAssumedValue(base_t Value) override {
2775 }
2776 void handleNewKnownValue(base_t Value) override { addKnownBits(Value); }
2777 void joinOR(base_t AssumedValue, base_t KnownValue) override {
2778 this->Known |= KnownValue;
2779 this->Assumed |= AssumedValue;
2780 }
2781 void joinAND(base_t AssumedValue, base_t KnownValue) override {
2782 this->Known &= KnownValue;
2783 this->Assumed &= AssumedValue;
2784 }
2785};
2786
2787/// Specialization of the integer state for an increasing value, hence ~0u is
2788/// the best state and 0 the worst.
2789template <typename base_ty = uint32_t, base_ty BestState = ~base_ty(0),
2790 base_ty WorstState = 0>
2792 : public IntegerStateBase<base_ty, BestState, WorstState> {
2794 using base_t = base_ty;
2795
2798
2799 /// Return the best possible representable state.
2800 static constexpr base_t getBestState() { return BestState; }
2801 static constexpr base_t
2805
2806 /// Take minimum of assumed and \p Value.
2808 // Make sure we never lose "known value".
2809 this->Assumed = std::max(std::min(this->Assumed, Value), this->Known);
2810 return *this;
2811 }
2812
2813 /// Take maximum of known and \p Value.
2815 // Make sure we never lose "known value".
2816 this->Assumed = std::max(Value, this->Assumed);
2817 this->Known = std::max(Value, this->Known);
2818 return *this;
2819 }
2820
2821private:
2822 void handleNewAssumedValue(base_t Value) override {
2824 }
2825 void handleNewKnownValue(base_t Value) override { takeKnownMaximum(Value); }
2826 void joinOR(base_t AssumedValue, base_t KnownValue) override {
2827 this->Known = std::max(this->Known, KnownValue);
2828 this->Assumed = std::max(this->Assumed, AssumedValue);
2829 }
2830 void joinAND(base_t AssumedValue, base_t KnownValue) override {
2831 this->Known = std::min(this->Known, KnownValue);
2832 this->Assumed = std::min(this->Assumed, AssumedValue);
2833 }
2834};
2835
2836/// Specialization of the integer state for a decreasing value, hence 0 is the
2837/// best state and ~0u the worst.
2838template <typename base_ty = uint32_t>
2839struct DecIntegerState : public IntegerStateBase<base_ty, 0, ~base_ty(0)> {
2840 using base_t = base_ty;
2841
2842 /// Take maximum of assumed and \p Value.
2844 // Make sure we never lose "known value".
2845 this->Assumed = std::min(std::max(this->Assumed, Value), this->Known);
2846 return *this;
2847 }
2848
2849 /// Take minimum of known and \p Value.
2851 // Make sure we never lose "known value".
2852 this->Assumed = std::min(Value, this->Assumed);
2853 this->Known = std::min(Value, this->Known);
2854 return *this;
2855 }
2856
2857private:
2858 void handleNewAssumedValue(base_t Value) override {
2860 }
2861 void handleNewKnownValue(base_t Value) override { takeKnownMinimum(Value); }
2862 void joinOR(base_t AssumedValue, base_t KnownValue) override {
2863 this->Assumed = std::min(this->Assumed, KnownValue);
2864 this->Assumed = std::min(this->Assumed, AssumedValue);
2865 }
2866 void joinAND(base_t AssumedValue, base_t KnownValue) override {
2867 this->Assumed = std::max(this->Assumed, KnownValue);
2868 this->Assumed = std::max(this->Assumed, AssumedValue);
2869 }
2870};
2871
2872/// Simple wrapper for a single bit (boolean) state.
2873struct BooleanState : public IntegerStateBase<bool, true, false> {
2876
2877 BooleanState() = default;
2879
2880 /// Set the known and asssumed value to \p Value.
2881 void setKnown(bool Value) {
2882 Known |= Value;
2883 Assumed |= Value;
2884 }
2885
2886 /// Return true if the state is assumed to hold.
2887 bool isAssumed() const { return getAssumed(); }
2888
2889 /// Return true if the state is known to hold.
2890 bool isKnown() const { return getKnown(); }
2891
2892private:
2893 void handleNewAssumedValue(base_t Value) override {
2894 if (!Value)
2895 Assumed = Known;
2896 }
2897 void handleNewKnownValue(base_t Value) override {
2898 if (Value)
2899 Known = (Assumed = Value);
2900 }
2901 void joinOR(base_t AssumedValue, base_t KnownValue) override {
2902 Known |= KnownValue;
2903 Assumed |= AssumedValue;
2904 }
2905 void joinAND(base_t AssumedValue, base_t KnownValue) override {
2906 Known &= KnownValue;
2907 Assumed &= AssumedValue;
2908 }
2909};
2910
2911/// State for an integer range.
2913
2914 /// Bitwidth of the associated value.
2916
2917 /// State representing assumed range, initially set to empty.
2919
2920 /// State representing known range, initially set to [-inf, inf].
2922
2926
2930
2931 /// Return the worst possible representable state.
2933 return ConstantRange::getFull(BitWidth);
2934 }
2935
2936 /// Return the best possible representable state.
2938 return ConstantRange::getEmpty(BitWidth);
2939 }
2941 return getBestState(IRS.getBitWidth());
2942 }
2943
2944 /// Return associated values' bit width.
2945 uint32_t getBitWidth() const { return BitWidth; }
2946
2947 /// See AbstractState::isValidState()
2948 bool isValidState() const override {
2949 return BitWidth > 0 && !Assumed.isFullSet();
2950 }
2951
2952 /// See AbstractState::isAtFixpoint()
2953 bool isAtFixpoint() const override { return Assumed == Known; }
2954
2955 /// See AbstractState::indicateOptimisticFixpoint(...)
2960
2961 /// See AbstractState::indicatePessimisticFixpoint(...)
2966
2967 /// Return the known state encoding
2968 ConstantRange getKnown() const { return Known; }
2969
2970 /// Return the assumed state encoding.
2972
2973 /// Unite assumed range with the passed state.
2975 // Don't lose a known range.
2976 Assumed = Assumed.unionWith(R).intersectWith(Known);
2977 }
2978
2979 /// See IntegerRangeState::unionAssumed(..).
2981 unionAssumed(R.getAssumed());
2982 }
2983
2984 /// Intersect known range with the passed state.
2986 Assumed = Assumed.intersectWith(R);
2987 Known = Known.intersectWith(R);
2988 }
2989
2990 /// See IntegerRangeState::intersectKnown(..).
2992 intersectKnown(R.getKnown());
2993 }
2994
2995 /// Equality for IntegerRangeState.
2996 bool operator==(const IntegerRangeState &R) const {
2997 return getAssumed() == R.getAssumed() && getKnown() == R.getKnown();
2998 }
2999
3000 /// "Clamp" this state with \p R. The result is subtype dependent but it is
3001 /// intended that only information assumed in both states will be assumed in
3002 /// this one afterwards.
3004 // NOTE: `^=` operator seems like `intersect` but in this case, we need to
3005 // take `union`.
3006 unionAssumed(R);
3007 return *this;
3008 }
3009
3011 // NOTE: `&=` operator seems like `intersect` but in this case, we need to
3012 // take `union`.
3013 Known = Known.unionWith(R.getKnown());
3014 Assumed = Assumed.unionWith(R.getAssumed());
3015 return *this;
3016 }
3017};
3018
3019/// Simple state for a set.
3020///
3021/// This represents a state containing a set of values. The interface supports
3022/// modelling sets that contain all possible elements. The state's internal
3023/// value is modified using union or intersection operations.
3024template <typename BaseTy> struct SetState : public AbstractState {
3025 /// A wrapper around a set that has semantics for handling unions and
3026 /// intersections with a "universal" set that contains all elements.
3028 /// Creates a universal set with no concrete elements or an empty set.
3029 SetContents(bool Universal) : Universal(Universal) {}
3030
3031 /// Creates a non-universal set with concrete values.
3032 SetContents(const DenseSet<BaseTy> &Assumptions)
3033 : Universal(false), Set(Assumptions) {}
3034
3035 SetContents(bool Universal, const DenseSet<BaseTy> &Assumptions)
3036 : Universal(Universal), Set(Assumptions) {}
3037
3038 const DenseSet<BaseTy> &getSet() const { return Set; }
3039
3040 bool isUniversal() const { return Universal; }
3041
3042 bool empty() const { return Set.empty() && !Universal; }
3043
3044 /// Finds A := A ^ B where A or B could be the "Universal" set which
3045 /// contains every possible attribute. Returns true if changes were made.
3047 bool IsUniversal = Universal;
3048 unsigned Size = Set.size();
3049
3050 // A := A ^ U = A
3051 if (RHS.isUniversal())
3052 return false;
3053
3054 // A := U ^ B = B
3055 if (Universal)
3056 Set = RHS.getSet();
3057 else
3058 set_intersect(Set, RHS.getSet());
3059
3060 Universal &= RHS.isUniversal();
3061 return IsUniversal != Universal || Size != Set.size();
3062 }
3063
3064 /// Finds A := A u B where A or B could be the "Universal" set which
3065 /// contains every possible attribute. returns true if changes were made.
3066 bool getUnion(const SetContents &RHS) {
3067 bool IsUniversal = Universal;
3068 unsigned Size = Set.size();
3069
3070 // A := A u U = U = U u B
3071 if (!RHS.isUniversal() && !Universal)
3072 set_union(Set, RHS.getSet());
3073
3074 Universal |= RHS.isUniversal();
3075 return IsUniversal != Universal || Size != Set.size();
3076 }
3077
3078 private:
3079 /// Indicates if this set is "universal", containing every possible element.
3080 bool Universal;
3081
3082 /// The set of currently active assumptions.
3083 DenseSet<BaseTy> Set;
3084 };
3085
3086 SetState() : Known(false), Assumed(true), IsAtFixedpoint(false) {}
3087
3088 /// Initializes the known state with an initial set and initializes the
3089 /// assumed state as universal.
3091 : Known(Known), Assumed(true), IsAtFixedpoint(false) {}
3092
3093 /// See AbstractState::isValidState()
3094 bool isValidState() const override { return !Assumed.empty(); }
3095
3096 /// See AbstractState::isAtFixpoint()
3097 bool isAtFixpoint() const override { return IsAtFixedpoint; }
3098
3099 /// See AbstractState::indicateOptimisticFixpoint(...)
3101 IsAtFixedpoint = true;
3102 Known = Assumed;
3104 }
3105
3106 /// See AbstractState::indicatePessimisticFixpoint(...)
3108 IsAtFixedpoint = true;
3109 Assumed = Known;
3110 return ChangeStatus::CHANGED;
3111 }
3112
3113 /// Return the known state encoding.
3114 const SetContents &getKnown() const { return Known; }
3115
3116 /// Return the assumed state encoding.
3117 const SetContents &getAssumed() const { return Assumed; }
3118
3119 /// Returns if the set state contains the element.
3120 bool setContains(const BaseTy &Elem) const {
3121 return Assumed.getSet().contains(Elem) || Known.getSet().contains(Elem);
3122 }
3123
3124 /// Performs the set intersection between this set and \p RHS. Returns true if
3125 /// changes were made.
3127 bool IsUniversal = Assumed.isUniversal();
3128 unsigned SizeBefore = Assumed.getSet().size();
3129
3130 // Get intersection and make sure that the known set is still a proper
3131 // subset of the assumed set. A := K u (A ^ R).
3132 Assumed.getIntersection(RHS);
3133 Assumed.getUnion(Known);
3134
3135 return SizeBefore != Assumed.getSet().size() ||
3136 IsUniversal != Assumed.isUniversal();
3137 }
3138
3139 /// Performs the set union between this set and \p RHS. Returns true if
3140 /// changes were made.
3141 bool getUnion(const SetContents &RHS) { return Assumed.getUnion(RHS); }
3142
3143private:
3144 /// The set of values known for this state.
3145 SetContents Known;
3146
3147 /// The set of assumed values for this state.
3148 SetContents Assumed;
3149
3150 bool IsAtFixedpoint;
3151};
3152
3153/// Helper to tie a abstract state implementation to an abstract attribute.
3154template <typename StateTy, typename BaseType, class... Ts>
3155struct StateWrapper : public BaseType, public StateTy {
3156 /// Provide static access to the type of the state.
3158
3159 StateWrapper(const IRPosition &IRP, Ts... Args)
3160 : BaseType(IRP), StateTy(Args...) {}
3161
3162 /// See AbstractAttribute::getState(...).
3163 StateType &getState() override { return *this; }
3164
3165 /// See AbstractAttribute::getState(...).
3166 const StateType &getState() const override { return *this; }
3167};
3168
3169/// Helper class that provides common functionality to manifest IR attributes.
3170template <Attribute::AttrKind AK, typename BaseType, typename AAType>
3171struct IRAttribute : public BaseType {
3172 IRAttribute(const IRPosition &IRP) : BaseType(IRP) {}
3173
3174 /// Most boolean IRAttribute AAs don't do anything non-trivial
3175 /// in their initializers while non-boolean ones often do. Subclasses can
3176 /// change this.
3178
3179 /// Compile time access to the IR attribute kind.
3181
3182 /// Return true if the IR attribute(s) associated with this AA are implied for
3183 /// an undef value.
3184 static bool isImpliedByUndef() { return true; }
3185
3186 /// Return true if the IR attribute(s) associated with this AA are implied for
3187 /// an poison value.
3188 static bool isImpliedByPoison() { return true; }
3189
3190 static bool isImpliedByIR(Attributor &A, const IRPosition &IRP,
3191 Attribute::AttrKind ImpliedAttributeKind = AK,
3192 bool IgnoreSubsumingPositions = false) {
3193 if (AAType::isImpliedByUndef() && isa<UndefValue>(IRP.getAssociatedValue()))
3194 return true;
3195 if (AAType::isImpliedByPoison() &&
3197 return true;
3198 return A.hasAttr(IRP, {ImpliedAttributeKind}, IgnoreSubsumingPositions,
3199 ImpliedAttributeKind);
3200 }
3201
3202 /// See AbstractAttribute::manifest(...).
3204 if (isa<UndefValue>(this->getIRPosition().getAssociatedValue()))
3206 SmallVector<Attribute, 4> DeducedAttrs;
3207 getDeducedAttributes(A, this->getAnchorValue().getContext(), DeducedAttrs);
3208 if (DeducedAttrs.empty())
3210 return A.manifestAttrs(this->getIRPosition(), DeducedAttrs);
3211 }
3212
3213 /// Return the kind that identifies the abstract attribute implementation.
3214 Attribute::AttrKind getAttrKind() const { return AK; }
3215
3216 /// Return the deduced attributes in \p Attrs.
3218 SmallVectorImpl<Attribute> &Attrs) const {
3219 Attrs.emplace_back(Attribute::get(Ctx, getAttrKind()));
3220 }
3221};
3222
3223/// Base struct for all "concrete attribute" deductions.
3224///
3225/// The abstract attribute is a minimal interface that allows the Attributor to
3226/// orchestrate the abstract/fixpoint analysis. The design allows to hide away
3227/// implementation choices made for the subclasses but also to structure their
3228/// implementation and simplify the use of other abstract attributes in-flight.
3229///
3230/// To allow easy creation of new attributes, most methods have default
3231/// implementations. The ones that do not are generally straight forward, except
3232/// `AbstractAttribute::updateImpl` which is the location of most reasoning
3233/// associated with the abstract attribute. The update is invoked by the
3234/// Attributor in case the situation used to justify the current optimistic
3235/// state might have changed. The Attributor determines this automatically
3236/// by monitoring the `Attributor::getAAFor` calls made by abstract attributes.
3237///
3238/// The `updateImpl` method should inspect the IR and other abstract attributes
3239/// in-flight to justify the best possible (=optimistic) state. The actual
3240/// implementation is, similar to the underlying abstract state encoding, not
3241/// exposed. In the most common case, the `updateImpl` will go through a list of
3242/// reasons why its optimistic state is valid given the current information. If
3243/// any combination of them holds and is sufficient to justify the current
3244/// optimistic state, the method shall return UNCHAGED. If not, the optimistic
3245/// state is adjusted to the situation and the method shall return CHANGED.
3246///
3247/// If the manifestation of the "concrete attribute" deduced by the subclass
3248/// differs from the "default" behavior, which is a (set of) LLVM-IR
3249/// attribute(s) for an argument, call site argument, function return value, or
3250/// function, the `AbstractAttribute::manifest` method should be overloaded.
3251///
3252/// NOTE: If the state obtained via getState() is INVALID, thus if
3253/// AbstractAttribute::getState().isValidState() returns false, no
3254/// information provided by the methods of this class should be used.
3255/// NOTE: The Attributor currently has certain limitations to what we can do.
3256/// As a general rule of thumb, "concrete" abstract attributes should *for
3257/// now* only perform "backward" information propagation. That means
3258/// optimistic information obtained through abstract attributes should
3259/// only be used at positions that precede the origin of the information
3260/// with regards to the program flow. More practically, information can
3261/// *now* be propagated from instructions to their enclosing function, but
3262/// *not* from call sites to the called function. The mechanisms to allow
3263/// both directions will be added in the future.
3264/// NOTE: The mechanics of adding a new "concrete" abstract attribute are
3265/// described in the file comment.
3268
3270
3271 /// Virtual destructor.
3272 ~AbstractAttribute() override = default;
3273
3274 /// Compile time access to the IR attribute kind.
3276
3277 /// This function is used to identify if an \p DGN is of type
3278 /// AbstractAttribute so that the dyn_cast and cast can use such information
3279 /// to cast an AADepGraphNode to an AbstractAttribute.
3280 ///
3281 /// We eagerly return true here because all AADepGraphNodes except for the
3282 /// Synthethis Node are of type AbstractAttribute
3283 static bool classof(const AADepGraphNode *DGN) { return true; }
3284
3285 /// Return false if this AA does anything non-trivial (hence not done by
3286 /// default) in its initializer.
3287 static bool hasTrivialInitializer() { return false; }
3288
3289 /// Return true if this AA requires a "callee" (or an associted function) for
3290 /// a call site positon. Default is optimistic to minimize AAs.
3291 static bool requiresCalleeForCallBase() { return false; }
3292
3293 /// Return true if this AA requires non-asm "callee" for a call site positon.
3294 static bool requiresNonAsmForCallBase() { return true; }
3295
3296 /// Return true if this AA requires all callees for an argument or function
3297 /// positon.
3298 static bool requiresCallersForArgOrFunction() { return false; }
3299
3300 /// Return false if an AA should not be created for \p IRP.
3302 return true;
3303 }
3304
3305 /// Return false if an AA should not be updated for \p IRP.
3307 Function *AssociatedFn = IRP.getAssociatedFunction();
3308 bool IsFnInterface = IRP.isFnInterfaceKind();
3309 assert((!IsFnInterface || AssociatedFn) &&
3310 "Function interface without a function?");
3311
3312 // TODO: Not all attributes require an exact definition. Find a way to
3313 // enable deduction for some but not all attributes in case the
3314 // definition might be changed at runtime, see also
3315 // http://lists.llvm.org/pipermail/llvm-dev/2018-February/121275.html.
3316 // TODO: We could always determine abstract attributes and if sufficient
3317 // information was found we could duplicate the functions that do not
3318 // have an exact definition.
3319 return !IsFnInterface || A.isFunctionIPOAmendable(*AssociatedFn);
3320 }
3321
3322 /// Initialize the state with the information in the Attributor \p A.
3323 ///
3324 /// This function is called by the Attributor once all abstract attributes
3325 /// have been identified. It can and shall be used for task like:
3326 /// - identify existing knowledge in the IR and use it for the "known state"
3327 /// - perform any work that is not going to change over time, e.g., determine
3328 /// a subset of the IR, or attributes in-flight, that have to be looked at
3329 /// in the `updateImpl` method.
3330 virtual void initialize(Attributor &A) {}
3331
3332 /// A query AA is always scheduled as long as we do updates because it does
3333 /// lazy computation that cannot be determined to be done from the outside.
3334 /// However, while query AAs will not be fixed if they do not have outstanding
3335 /// dependences, we will only schedule them like other AAs. If a query AA that
3336 /// received a new query it needs to request an update via
3337 /// `Attributor::requestUpdateForAA`.
3338 virtual bool isQueryAA() const { return false; }
3339
3340 /// Return the internal abstract state for inspection.
3341 virtual StateType &getState() = 0;
3342 virtual const StateType &getState() const = 0;
3343
3344 /// Return an IR position, see struct IRPosition.
3345 const IRPosition &getIRPosition() const { return *this; };
3346 IRPosition &getIRPosition() { return *this; };
3347
3348 /// Helper functions, for debug purposes only.
3349 ///{
3350 void print(raw_ostream &OS) const { print(nullptr, OS); }
3351 void print(Attributor *, raw_ostream &OS) const override;
3352 virtual void printWithDeps(raw_ostream &OS) const;
3353 void dump() const { this->print(dbgs()); }
3354
3355 /// This function should return the "summarized" assumed state as string.
3356 virtual const std::string getAsStr(Attributor *A) const = 0;
3357
3358 /// This function should return the name of the AbstractAttribute
3359 virtual StringRef getName() const = 0;
3360
3361 /// This function should return the address of the ID of the AbstractAttribute
3362 virtual const char *getIdAddr() const = 0;
3363 ///}
3364
3365 /// Allow the Attributor access to the protected methods.
3366 friend struct Attributor;
3367
3368protected:
3369 /// Hook for the Attributor to trigger an update of the internal state.
3370 ///
3371 /// If this attribute is already fixed, this method will return UNCHANGED,
3372 /// otherwise it delegates to `AbstractAttribute::updateImpl`.
3373 ///
3374 /// \Return CHANGED if the internal state changed, otherwise UNCHANGED.
3376
3377 /// Hook for the Attributor to trigger the manifestation of the information
3378 /// represented by the abstract attribute in the LLVM-IR.
3379 ///
3380 /// \Return CHANGED if the IR was altered, otherwise UNCHANGED.
3384
3385 /// Hook to enable custom statistic tracking, called after manifest that
3386 /// resulted in a change if statistics are enabled.
3387 ///
3388 /// We require subclasses to provide an implementation so we remember to
3389 /// add statistics for them.
3390 virtual void trackStatistics() const = 0;
3391
3392 /// The actual update/transfer function which has to be implemented by the
3393 /// derived classes.
3394 ///
3395 /// If it is called, the environment has changed and we have to determine if
3396 /// the current information is still valid or adjust it otherwise.
3397 ///
3398 /// \Return CHANGED if the internal state changed, otherwise UNCHANGED.
3400};
3401
3402/// Forward declarations of output streams for debug purposes.
3403///
3404///{
3410template <typename base_ty, base_ty BestState, base_ty WorstState>
3414 return OS << "(" << S.getKnown() << "-" << S.getAssumed() << ")"
3415 << static_cast<const AbstractState &>(S);
3416}
3417LLVM_ABI raw_ostream &operator<<(raw_ostream &OS,
3418 const IntegerRangeState &State);
3419///}
3420
3429
3430/// A more lightweight version of the Attributor which only runs attribute
3431/// inference but no simplifications.
3432struct AttributorLightPass : public OptionalPassInfoMixin<AttributorLightPass> {
3434};
3435
3436/// A more lightweight version of the Attributor which only runs attribute
3437/// inference but no simplifications.
3439 : public OptionalPassInfoMixin<AttributorLightCGSCCPass> {
3442 CGSCCUpdateResult &UR);
3443};
3444
3445/// Helper function to clamp a state \p S of type \p StateType with the
3446/// information in \p R and indicate/return if \p S did change (as-in update is
3447/// required to be run again).
3448template <typename StateType>
3449ChangeStatus clampStateAndIndicateChange(StateType &S, const StateType &R) {
3450 auto Assumed = S.getAssumed();
3451 S ^= R;
3452 return Assumed == S.getAssumed() ? ChangeStatus::UNCHANGED
3454}
3455
3456/// ----------------------------------------------------------------------------
3457/// Abstract Attribute Classes
3458/// ----------------------------------------------------------------------------
3459
3461 : public IRAttribute<Attribute::NoUnwind,
3462 StateWrapper<BooleanState, AbstractAttribute>,
3463 AANoUnwind> {
3465
3466 /// Returns true if nounwind is assumed.
3467 bool isAssumedNoUnwind() const { return getAssumed(); }
3468
3469 /// Returns true if nounwind is known.
3470 bool isKnownNoUnwind() const { return getKnown(); }
3471
3472 /// Create an abstract attribute view for the position \p IRP.
3474 Attributor &A);
3475
3476 /// See AbstractAttribute::getName()
3477 StringRef getName() const override { return "AANoUnwind"; }
3478
3479 /// See AbstractAttribute::getIdAddr()
3480 const char *getIdAddr() const override { return &ID; }
3481
3482 /// This function should return true if the type of the \p AA is AANoUnwind
3483 static bool classof(const AbstractAttribute *AA) {
3484 return (AA->getIdAddr() == &ID);
3485 }
3486
3487 /// Unique ID (due to the unique address)
3488 LLVM_ABI static const char ID;
3489};
3490
3492 : public IRAttribute<Attribute::NoSync,
3493 StateWrapper<BooleanState, AbstractAttribute>,
3494 AANoSync> {
3496
3497 static bool isImpliedByIR(Attributor &A, const IRPosition &IRP,
3498 Attribute::AttrKind ImpliedAttributeKind,
3499 bool IgnoreSubsumingPositions = false) {
3500 // Note: This is also run for non-IPO amendable functions.
3501 assert(ImpliedAttributeKind == Attribute::NoSync);
3502 if (A.hasAttr(IRP, {Attribute::NoSync}, IgnoreSubsumingPositions,
3503 Attribute::NoSync))
3504 return true;
3505
3506 // Check for readonly + non-convergent.
3507 // TODO: We should be able to use hasAttr for Attributes, not only
3508 // AttrKinds.
3510 if (!F || F->isConvergent())
3511 return false;
3512
3514 A.getAttrs(IRP, {Attribute::Memory}, Attrs, IgnoreSubsumingPositions);
3515
3517 for (const Attribute &Attr : Attrs)
3518 ME &= Attr.getMemoryEffects();
3519
3520 if (!ME.onlyReadsMemory())
3521 return false;
3522
3523 A.manifestAttrs(IRP, Attribute::get(F->getContext(), Attribute::NoSync));
3524 return true;
3525 }
3526
3527 /// See AbstractAttribute::isValidIRPositionForInit
3529 if (!IRP.isFunctionScope() &&
3531 return false;
3532 return IRAttribute::isValidIRPositionForInit(A, IRP);
3533 }
3534
3535 /// Returns true if "nosync" is assumed.
3536 bool isAssumedNoSync() const { return getAssumed(); }
3537
3538 /// Returns true if "nosync" is known.
3539 bool isKnownNoSync() const { return getKnown(); }
3540
3541 /// Helper function used to determine whether an instruction is non-relaxed
3542 /// atomic. In other words, if an atomic instruction does not have unordered
3543 /// or monotonic ordering
3544 LLVM_ABI static bool isNonRelaxedAtomic(const Instruction *I);
3545
3546 /// Helper function to determine if \p CB is an aligned (GPU) barrier. Aligned
3547 /// barriers have to be executed by all threads. The flag \p ExecutedAligned
3548 /// indicates if the call is executed by all threads in a (thread) block in an
3549 /// aligned way. If that is the case, non-aligned barriers are effectively
3550 /// aligned barriers.
3551 LLVM_ABI static bool isAlignedBarrier(const CallBase &CB,
3552 bool ExecutedAligned);
3553
3554 /// Create an abstract attribute view for the position \p IRP.
3556 Attributor &A);
3557
3558 /// See AbstractAttribute::getName()
3559 StringRef getName() const override { return "AANoSync"; }
3560
3561 /// See AbstractAttribute::getIdAddr()
3562 const char *getIdAddr() const override { return &ID; }
3563
3564 /// This function should return true if the type of the \p AA is AANoSync
3565 static bool classof(const AbstractAttribute *AA) {
3566 return (AA->getIdAddr() == &ID);
3567 }
3568
3569 /// Unique ID (due to the unique address)
3570 LLVM_ABI static const char ID;
3571};
3572
3573/// An abstract interface for all nonnull attributes.
3575 : public IRAttribute<Attribute::MustProgress,
3576 StateWrapper<BooleanState, AbstractAttribute>,
3577 AAMustProgress> {
3579
3580 static bool isImpliedByIR(Attributor &A, const IRPosition &IRP,
3581 Attribute::AttrKind ImpliedAttributeKind,
3582 bool IgnoreSubsumingPositions = false) {
3583 // Note: This is also run for non-IPO amendable functions.
3584 assert(ImpliedAttributeKind == Attribute::MustProgress);
3585 return A.hasAttr(IRP, {Attribute::MustProgress, Attribute::WillReturn},
3586 IgnoreSubsumingPositions, Attribute::MustProgress);
3587 }
3588
3589 /// Return true if we assume that the underlying value is nonnull.
3590 bool isAssumedMustProgress() const { return getAssumed(); }
3591
3592 /// Return true if we know that underlying value is nonnull.
3593 bool isKnownMustProgress() const { return getKnown(); }
3594
3595 /// Create an abstract attribute view for the position \p IRP.
3597 Attributor &A);
3598
3599 /// See AbstractAttribute::getName()
3600 StringRef getName() const override { return "AAMustProgress"; }
3601
3602 /// See AbstractAttribute::getIdAddr()
3603 const char *getIdAddr() const override { return &ID; }
3604
3605 /// This function should return true if the type of the \p AA is
3606 /// AAMustProgress
3607 static bool classof(const AbstractAttribute *AA) {
3608 return (AA->getIdAddr() == &ID);
3609 }
3610
3611 /// Unique ID (due to the unique address)
3612 LLVM_ABI static const char ID;
3613};
3614
3615/// An abstract interface for all nonnull attributes.
3617 : public IRAttribute<Attribute::NonNull,
3618 StateWrapper<BooleanState, AbstractAttribute>,
3619 AANonNull> {
3621
3622 /// See AbstractAttribute::hasTrivialInitializer.
3623 static bool hasTrivialInitializer() { return false; }
3624
3625 /// See IRAttribute::isImpliedByUndef.
3626 /// Undef is not necessarily nonnull as nonnull + noundef would cause poison.
3627 /// Poison implies nonnull though.
3628 static bool isImpliedByUndef() { return false; }
3629
3630 /// See AbstractAttribute::isValidIRPositionForInit
3633 return false;
3634 return IRAttribute::isValidIRPositionForInit(A, IRP);
3635 }
3636
3637 /// See AbstractAttribute::isImpliedByIR(...).
3638 LLVM_ABI static bool isImpliedByIR(Attributor &A, const IRPosition &IRP,
3639 Attribute::AttrKind ImpliedAttributeKind,
3640 bool IgnoreSubsumingPositions = false);
3641
3642 /// Return true if we assume that the underlying value is nonnull.
3643 bool isAssumedNonNull() const { return getAssumed(); }
3644
3645 /// Return true if we know that underlying value is nonnull.
3646 bool isKnownNonNull() const { return getKnown(); }
3647
3648 /// Create an abstract attribute view for the position \p IRP.
3650 Attributor &A);
3651
3652 /// See AbstractAttribute::getName()
3653 StringRef getName() const override { return "AANonNull"; }
3654
3655 /// See AbstractAttribute::getIdAddr()
3656 const char *getIdAddr() const override { return &ID; }
3657
3658 /// This function should return true if the type of the \p AA is AANonNull
3659 static bool classof(const AbstractAttribute *AA) {
3660 return (AA->getIdAddr() == &ID);
3661 }
3662
3663 /// Unique ID (due to the unique address)
3664 LLVM_ABI static const char ID;
3665};
3666
3667/// An abstract attribute for norecurse.
3669 : public IRAttribute<Attribute::NoRecurse,
3670 StateWrapper<BooleanState, AbstractAttribute>,
3671 AANoRecurse> {
3673
3674 /// Return true if "norecurse" is assumed.
3675 bool isAssumedNoRecurse() const { return getAssumed(); }
3676
3677 /// Return true if "norecurse" is known.
3678 bool isKnownNoRecurse() const { return getKnown(); }
3679
3680 /// Create an abstract attribute view for the position \p IRP.
3682 Attributor &A);
3683
3684 /// See AbstractAttribute::getName()
3685 StringRef getName() const override { return "AANoRecurse"; }
3686
3687 /// See AbstractAttribute::getIdAddr()
3688 const char *getIdAddr() const override { return &ID; }
3689
3690 /// This function should return true if the type of the \p AA is AANoRecurse
3691 static bool classof(const AbstractAttribute *AA) {
3692 return (AA->getIdAddr() == &ID);
3693 }
3694
3695 /// Unique ID (due to the unique address)
3696 LLVM_ABI static const char ID;
3697};
3698
3699/// An abstract attribute for willreturn.
3701 : public IRAttribute<Attribute::WillReturn,
3702 StateWrapper<BooleanState, AbstractAttribute>,
3703 AAWillReturn> {
3705
3706 static bool isImpliedByIR(Attributor &A, const IRPosition &IRP,
3707 Attribute::AttrKind ImpliedAttributeKind,
3708 bool IgnoreSubsumingPositions = false) {
3709 // Note: This is also run for non-IPO amendable functions.
3710 assert(ImpliedAttributeKind == Attribute::WillReturn);
3711 if (IRAttribute::isImpliedByIR(A, IRP, ImpliedAttributeKind,
3712 IgnoreSubsumingPositions))
3713 return true;
3715 return false;
3716 A.manifestAttrs(IRP, Attribute::get(IRP.getAnchorValue().getContext(),
3717 Attribute::WillReturn));
3718 return true;
3719 }
3720
3721 /// Check for `mustprogress` and `readonly` as they imply `willreturn`.
3723 const IRPosition &IRP) {
3724 // Check for `mustprogress` in the scope and the associated function which
3725 // might be different if this is a call site.
3726 if (!A.hasAttr(IRP, {Attribute::MustProgress}))
3727 return false;
3728
3730 A.getAttrs(IRP, {Attribute::Memory}, Attrs,
3731 /* IgnoreSubsumingPositions */ false);
3732
3734 for (const Attribute &Attr : Attrs)
3735 ME &= Attr.getMemoryEffects();
3736 return ME.onlyReadsMemory();
3737 }
3738
3739 /// Return true if "willreturn" is assumed.
3740 bool isAssumedWillReturn() const { return getAssumed(); }
3741
3742 /// Return true if "willreturn" is known.
3743 bool isKnownWillReturn() const { return getKnown(); }
3744
3745 /// Create an abstract attribute view for the position \p IRP.
3747 Attributor &A);
3748
3749 /// See AbstractAttribute::getName()
3750 StringRef getName() const override { return "AAWillReturn"; }
3751
3752 /// See AbstractAttribute::getIdAddr()
3753 const char *getIdAddr() const override { return &ID; }
3754
3755 /// This function should return true if the type of the \p AA is AAWillReturn
3756 static bool classof(const AbstractAttribute *AA) {
3757 return (AA->getIdAddr() == &ID);
3758 }
3759
3760 /// Unique ID (due to the unique address)
3761 LLVM_ABI static const char ID;
3762};
3763
3764/// An abstract attribute for undefined behavior.
3766 : public StateWrapper<BooleanState, AbstractAttribute> {
3769
3770 /// Return true if "undefined behavior" is assumed for a specific instruction.
3771 virtual bool isAssumedToCauseUB(Instruction *I) const = 0;
3772
3773 /// Return true if "undefined behavior" is known for a specific instruction.
3774 virtual bool isKnownToCauseUB(Instruction *I) const = 0;
3775
3776 /// Create an abstract attribute view for the position \p IRP.
3778 Attributor &A);
3779
3780 /// See AbstractAttribute::getName()
3781 StringRef getName() const override { return "AAUndefinedBehavior"; }
3782
3783 /// See AbstractAttribute::getIdAddr()
3784 const char *getIdAddr() const override { return &ID; }
3785
3786 /// This function should return true if the type of the \p AA is
3787 /// AAUndefineBehavior
3788 static bool classof(const AbstractAttribute *AA) {
3789 return (AA->getIdAddr() == &ID);
3790 }
3791
3792 /// Unique ID (due to the unique address)
3793 LLVM_ABI static const char ID;
3794};
3795
3796/// An abstract interface to determine reachability of point A to B.
3798 : public StateWrapper<BooleanState, AbstractAttribute> {
3801
3802 /// Returns true if 'From' instruction is assumed to reach, 'To' instruction.
3803 /// Users should provide two positions they are interested in, and the class
3804 /// determines (and caches) reachability.
3806 Attributor &A, const Instruction &From, const Instruction &To,
3807 const AA::InstExclusionSetTy *ExclusionSet = nullptr) const = 0;
3808
3809 /// Create an abstract attribute view for the position \p IRP.
3812
3813 /// See AbstractAttribute::getName()
3814 StringRef getName() const override { return "AAIntraFnReachability"; }
3815
3816 /// See AbstractAttribute::getIdAddr()
3817 const char *getIdAddr() const override { return &ID; }
3818
3819 /// This function should return true if the type of the \p AA is
3820 /// AAIntraFnReachability
3821 static bool classof(const AbstractAttribute *AA) {
3822 return (AA->getIdAddr() == &ID);
3823 }
3824
3825 /// Unique ID (due to the unique address)
3826 LLVM_ABI static const char ID;
3827};
3828
3829/// An abstract interface for all noalias attributes.
3831 : public IRAttribute<Attribute::NoAlias,
3832 StateWrapper<BooleanState, AbstractAttribute>,
3833 AANoAlias> {
3835
3836 /// See AbstractAttribute::isValidIRPositionForInit
3838 if (!IRP.getAssociatedType()->isPointerTy())
3839 return false;
3840 return IRAttribute::isValidIRPositionForInit(A, IRP);
3841 }
3842
3843 /// See IRAttribute::isImpliedByIR
3844 LLVM_ABI static bool isImpliedByIR(Attributor &A, const IRPosition &IRP,
3845 Attribute::AttrKind ImpliedAttributeKind,
3846 bool IgnoreSubsumingPositions = false);
3847
3848 /// See AbstractAttribute::requiresCallersForArgOrFunction
3849 static bool requiresCallersForArgOrFunction() { return true; }
3850
3851 /// Return true if we assume that the underlying value is alias.
3852 bool isAssumedNoAlias() const { return getAssumed(); }
3853
3854 /// Return true if we know that underlying value is noalias.
3855 bool isKnownNoAlias() const { return getKnown(); }
3856
3857 /// Create an abstract attribute view for the position \p IRP.
3859 Attributor &A);
3860
3861 /// See AbstractAttribute::getName()
3862 StringRef getName() const override { return "AANoAlias"; }
3863
3864 /// See AbstractAttribute::getIdAddr()
3865 const char *getIdAddr() const override { return &ID; }
3866
3867 /// This function should return true if the type of the \p AA is AANoAlias
3868 static bool classof(const AbstractAttribute *AA) {
3869 return (AA->getIdAddr() == &ID);
3870 }
3871
3872 /// Unique ID (due to the unique address)
3873 LLVM_ABI static const char ID;
3874};
3875
3876/// An AbstractAttribute for nofree.
3878 : public IRAttribute<Attribute::NoFree,
3879 StateWrapper<BooleanState, AbstractAttribute>,
3880 AANoFree> {
3882
3883 /// See IRAttribute::isImpliedByIR
3884 static bool isImpliedByIR(Attributor &A, const IRPosition &IRP,
3885 Attribute::AttrKind ImpliedAttributeKind,
3886 bool IgnoreSubsumingPositions = false) {
3887 // Note: This is also run for non-IPO amendable functions.
3888 assert(ImpliedAttributeKind == Attribute::NoFree);
3889 return A.hasAttr(
3890 IRP, {Attribute::ReadNone, Attribute::ReadOnly, Attribute::NoFree},
3891 IgnoreSubsumingPositions, Attribute::NoFree);
3892 }
3893
3894 /// See AbstractAttribute::isValidIRPositionForInit
3896 if (!IRP.isFunctionScope() &&
3898 return false;
3899 return IRAttribute::isValidIRPositionForInit(A, IRP);
3900 }
3901
3902 /// Return true if "nofree" is assumed.
3903 bool isAssumedNoFree() const { return getAssumed(); }
3904
3905 /// Return true if "nofree" is known.
3906 bool isKnownNoFree() const { return getKnown(); }
3907
3908 /// Create an abstract attribute view for the position \p IRP.
3910 Attributor &A);
3911
3912 /// See AbstractAttribute::getName()
3913 StringRef getName() const override { return "AANoFree"; }
3914
3915 /// See AbstractAttribute::getIdAddr()
3916 const char *getIdAddr() const override { return &ID; }
3917
3918 /// This function should return true if the type of the \p AA is AANoFree
3919 static bool classof(const AbstractAttribute *AA) {
3920 return (AA->getIdAddr() == &ID);
3921 }
3922
3923 /// Unique ID (due to the unique address)
3924 LLVM_ABI static const char ID;
3925};
3926
3927/// An AbstractAttribute for noreturn.
3929 : public IRAttribute<Attribute::NoReturn,
3930 StateWrapper<BooleanState, AbstractAttribute>,
3931 AANoReturn> {
3933
3934 /// Return true if the underlying object is assumed to never return.
3935 bool isAssumedNoReturn() const { return getAssumed(); }
3936
3937 /// Return true if the underlying object is known to never return.
3938 bool isKnownNoReturn() const { return getKnown(); }
3939
3940 /// Create an abstract attribute view for the position \p IRP.
3942 Attributor &A);
3943
3944 /// See AbstractAttribute::getName()
3945 StringRef getName() const override { return "AANoReturn"; }
3946
3947 /// See AbstractAttribute::getIdAddr()
3948 const char *getIdAddr() const override { return &ID; }
3949
3950 /// This function should return true if the type of the \p AA is AANoReturn
3951 static bool classof(const AbstractAttribute *AA) {
3952 return (AA->getIdAddr() == &ID);
3953 }
3954
3955 /// Unique ID (due to the unique address)
3956 LLVM_ABI static const char ID;
3957};
3958
3959/// An abstract interface for liveness abstract attribute.
3961 : public StateWrapper<BitIntegerState<uint8_t, 3, 0>, AbstractAttribute> {
3963 AAIsDead(const IRPosition &IRP, Attributor &A) : Base(IRP) {}
3964
3965 /// See AbstractAttribute::isValidIRPositionForInit
3968 return isa<Function>(IRP.getAnchorValue()) &&
3969 !cast<Function>(IRP.getAnchorValue()).isDeclaration();
3970 return true;
3971 }
3972
3973 /// State encoding bits. A set bit in the state means the property holds.
3974 enum {
3977
3979 };
3980 static_assert(IS_DEAD == getBestState(), "Unexpected BEST_STATE value");
3981
3982protected:
3983 /// The query functions are protected such that other attributes need to go
3984 /// through the Attributor interfaces: `Attributor::isAssumedDead(...)`
3985
3986 /// Returns true if the underlying value is assumed dead.
3987 virtual bool isAssumedDead() const = 0;
3988
3989 /// Returns true if the underlying value is known dead.
3990 virtual bool isKnownDead() const = 0;
3991
3992 /// Returns true if \p BB is known dead.
3993 virtual bool isKnownDead(const BasicBlock *BB) const = 0;
3994
3995 /// Returns true if \p I is assumed dead.
3996 virtual bool isAssumedDead(const Instruction *I) const = 0;
3997
3998 /// Returns true if \p I is known dead.
3999 virtual bool isKnownDead(const Instruction *I) const = 0;
4000
4001 /// Return true if the underlying value is a store that is known to be
4002 /// removable. This is different from dead stores as the removable store
4003 /// can have an effect on live values, especially loads, but that effect
4004 /// is propagated which allows us to remove the store in turn.
4005 virtual bool isRemovableStore() const { return false; }
4006
4007public:
4008 /// Create an abstract attribute view for the position \p IRP.
4010 Attributor &A);
4011
4012 /// Determine if \p F might catch asynchronous exceptions.
4014 return F.hasPersonalityFn() && !canSimplifyInvokeNoUnwind(&F);
4015 }
4016
4017 /// Returns true if \p BB is assumed dead.
4018 virtual bool isAssumedDead(const BasicBlock *BB) const = 0;
4019
4020 /// Return if the edge from \p From BB to \p To BB is assumed dead.
4021 /// This is specifically useful in AAReachability.
4022 virtual bool isEdgeDead(const BasicBlock *From, const BasicBlock *To) const {
4023 return false;
4024 }
4025
4026 /// See AbstractAttribute::getName()
4027 StringRef getName() const override { return "AAIsDead"; }
4028
4029 /// See AbstractAttribute::getIdAddr()
4030 const char *getIdAddr() const override { return &ID; }
4031
4032 /// This function should return true if the type of the \p AA is AAIsDead
4033 static bool classof(const AbstractAttribute *AA) {
4034 return (AA->getIdAddr() == &ID);
4035 }
4036
4037 /// Unique ID (due to the unique address)
4038 LLVM_ABI static const char ID;
4039
4040 friend struct Attributor;
4041};
4042
4043/// State for dereferenceable attribute
4045
4046 static DerefState getBestState() { return DerefState(); }
4047 static DerefState getBestState(const DerefState &) { return getBestState(); }
4048
4049 /// Return the worst possible representable state.
4051 DerefState DS;
4052 DS.indicatePessimisticFixpoint();
4053 return DS;
4054 }
4056 return getWorstState();
4057 }
4058
4059 /// State representing for dereferenceable bytes.
4061
4062 /// Map representing for accessed memory offsets and sizes.
4063 /// A key is Offset and a value is size.
4064 /// If there is a load/store instruction something like,
4065 /// p[offset] = v;
4066 /// (offset, sizeof(v)) will be inserted to this map.
4067 /// std::map is used because we want to iterate keys in ascending order.
4068 std::map<int64_t, uint64_t> AccessedBytesMap;
4069
4070 /// Helper function to calculate dereferenceable bytes from current known
4071 /// bytes and accessed bytes.
4072 ///
4073 /// int f(int *A){
4074 /// *A = 0;
4075 /// *(A+2) = 2;
4076 /// *(A+1) = 1;
4077 /// *(A+10) = 10;
4078 /// }
4079 /// ```
4080 /// In that case, AccessedBytesMap is `{0:4, 4:4, 8:4, 40:4}`.
4081 /// AccessedBytesMap is std::map so it is iterated in accending order on
4082 /// key(Offset). So KnownBytes will be updated like this:
4083 ///
4084 /// |Access | KnownBytes
4085 /// |(0, 4)| 0 -> 4
4086 /// |(4, 4)| 4 -> 8
4087 /// |(8, 4)| 8 -> 12
4088 /// |(40, 4) | 12 (break)
4089 void computeKnownDerefBytesFromAccessedMap() {
4090 int64_t KnownBytes = DerefBytesState.getKnown();
4091 for (auto &Access : AccessedBytesMap) {
4092 if (KnownBytes < Access.first)
4093 break;
4094 KnownBytes = std::max(KnownBytes, Access.first + (int64_t)Access.second);
4095 }
4096
4097 DerefBytesState.takeKnownMaximum(KnownBytes);
4098 }
4099
4100 /// State representing that whether the value is globaly dereferenceable.
4101 BooleanState GlobalState;
4102
4103 /// See AbstractState::isValidState()
4104 bool isValidState() const override { return DerefBytesState.isValidState(); }
4105
4106 /// See AbstractState::isAtFixpoint()
4107 bool isAtFixpoint() const override {
4108 return !isValidState() ||
4109 (DerefBytesState.isAtFixpoint() && GlobalState.isAtFixpoint());
4110 }
4111
4112 /// See AbstractState::indicateOptimisticFixpoint(...)
4114 DerefBytesState.indicateOptimisticFixpoint();
4115 GlobalState.indicateOptimisticFixpoint();
4117 }
4118
4119 /// See AbstractState::indicatePessimisticFixpoint(...)
4121 DerefBytesState.indicatePessimisticFixpoint();
4122 GlobalState.indicatePessimisticFixpoint();
4123 return ChangeStatus::CHANGED;
4124 }
4125
4126 /// Update known dereferenceable bytes.
4127 void takeKnownDerefBytesMaximum(uint64_t Bytes) {
4128 DerefBytesState.takeKnownMaximum(Bytes);
4129
4130 // Known bytes might increase.
4131 computeKnownDerefBytesFromAccessedMap();
4132 }
4133
4134 /// Update assumed dereferenceable bytes.
4135 void takeAssumedDerefBytesMinimum(uint64_t Bytes) {
4136 DerefBytesState.takeAssumedMinimum(Bytes);
4137 }
4138
4139 /// Add accessed bytes to the map.
4140 void addAccessedBytes(int64_t Offset, uint64_t Size) {
4141 uint64_t &AccessedBytes = AccessedBytesMap[Offset];
4142 AccessedBytes = std::max(AccessedBytes, Size);
4143
4144 // Known bytes might increase.
4145 computeKnownDerefBytesFromAccessedMap();
4146 }
4147
4148 /// Equality for DerefState.
4149 bool operator==(const DerefState &R) const {
4150 return this->DerefBytesState == R.DerefBytesState &&
4151 this->GlobalState == R.GlobalState;
4152 }
4153
4154 /// Inequality for DerefState.
4155 bool operator!=(const DerefState &R) const { return !(*this == R); }
4156
4157 /// See IntegerStateBase::operator^=
4158 DerefState operator^=(const DerefState &R) {
4159 DerefBytesState ^= R.DerefBytesState;
4160 GlobalState ^= R.GlobalState;
4161 return *this;
4162 }
4163
4164 /// See IntegerStateBase::operator+=
4165 DerefState operator+=(const DerefState &R) {
4166 DerefBytesState += R.DerefBytesState;
4167 GlobalState += R.GlobalState;
4168 return *this;
4169 }
4170
4171 /// See IntegerStateBase::operator&=
4172 DerefState operator&=(const DerefState &R) {
4173 DerefBytesState &= R.DerefBytesState;
4174 GlobalState &= R.GlobalState;
4175 return *this;
4176 }
4177
4178 /// See IntegerStateBase::operator|=
4179 DerefState operator|=(const DerefState &R) {
4180 DerefBytesState |= R.DerefBytesState;
4181 GlobalState |= R.GlobalState;
4182 return *this;
4183 }
4184};
4185
4186/// An abstract interface for all dereferenceable attribute.
4188 : public IRAttribute<Attribute::Dereferenceable,
4189 StateWrapper<DerefState, AbstractAttribute>,
4190 AADereferenceable> {
4192
4193 /// See AbstractAttribute::isValidIRPositionForInit
4195 if (!IRP.getAssociatedType()->isPointerTy())
4196 return false;
4197 return IRAttribute::isValidIRPositionForInit(A, IRP);
4198 }
4199
4200 /// Return true if we assume that underlying value is
4201 /// dereferenceable(_or_null) globally.
4202 bool isAssumedGlobal() const { return GlobalState.getAssumed(); }
4203
4204 /// Return true if we know that underlying value is
4205 /// dereferenceable(_or_null) globally.
4206 bool isKnownGlobal() const { return GlobalState.getKnown(); }
4207
4208 /// Return assumed dereferenceable bytes.
4210 return DerefBytesState.getAssumed();
4211 }
4212
4213 /// Return known dereferenceable bytes.
4215 return DerefBytesState.getKnown();
4216 }
4217
4218 /// Create an abstract attribute view for the position \p IRP.
4220 Attributor &A);
4221
4222 /// See AbstractAttribute::getName()
4223 StringRef getName() const override { return "AADereferenceable"; }
4224
4225 /// See AbstractAttribute::getIdAddr()
4226 const char *getIdAddr() const override { return &ID; }
4227
4228 /// This function should return true if the type of the \p AA is
4229 /// AADereferenceable
4230 static bool classof(const AbstractAttribute *AA) {
4231 return (AA->getIdAddr() == &ID);
4232 }
4233
4234 /// Unique ID (due to the unique address)
4235 LLVM_ABI static const char ID;
4236};
4237
4240/// An abstract interface for all align attributes.
4242 : public IRAttribute<Attribute::Alignment,
4243 StateWrapper<AAAlignmentStateType, AbstractAttribute>,
4244 AAAlign> {
4246
4247 /// See AbstractAttribute::isValidIRPositionForInit
4250 return false;
4251 return IRAttribute::isValidIRPositionForInit(A, IRP);
4252 }
4253
4254 /// Return assumed alignment.
4255 Align getAssumedAlign() const { return Align(getAssumed()); }
4256
4257 /// Return known alignment.
4258 Align getKnownAlign() const { return Align(getKnown()); }
4259
4260 /// See AbstractAttribute::getName()
4261 StringRef getName() const override { return "AAAlign"; }
4262
4263 /// See AbstractAttribute::getIdAddr()
4264 const char *getIdAddr() const override { return &ID; }
4265
4266 /// This function should return true if the type of the \p AA is AAAlign
4267 static bool classof(const AbstractAttribute *AA) {
4268 return (AA->getIdAddr() == &ID);
4269 }
4270
4271 /// Create an abstract attribute view for the position \p IRP.
4273 Attributor &A);
4274
4275 /// Unique ID (due to the unique address)
4276 LLVM_ABI static const char ID;
4277};
4278
4279/// An abstract interface to track if a value leaves it's defining function
4280/// instance.
4281/// TODO: We should make it a ternary AA tracking uniqueness, and uniqueness
4282/// wrt. the Attributor analysis separately.
4283struct AAInstanceInfo : public StateWrapper<BooleanState, AbstractAttribute> {
4286
4287 /// Return true if we assume that the underlying value is unique in its scope
4288 /// wrt. the Attributor analysis. That means it might not be unique but we can
4289 /// still use pointer equality without risking to represent two instances with
4290 /// one `llvm::Value`.
4291 bool isAssumedUniqueForAnalysis() const { return isAssumed(); }
4292
4293 /// Create an abstract attribute view for the position \p IRP.
4295 Attributor &A);
4296
4297 /// See AbstractAttribute::getName()
4298 StringRef getName() const override { return "AAInstanceInfo"; }
4299
4300 /// See AbstractAttribute::getIdAddr()
4301 const char *getIdAddr() const override { return &ID; }
4302
4303 /// This function should return true if the type of the \p AA is
4304 /// AAInstanceInfo
4305 static bool classof(const AbstractAttribute *AA) {
4306 return (AA->getIdAddr() == &ID);
4307 }
4308
4309 /// Unique ID (due to the unique address)
4310 LLVM_ABI static const char ID;
4311};
4312
4313/// An abstract interface for all nocapture attributes.
4315 : public IRAttribute<
4316 Attribute::Captures,
4317 StateWrapper<BitIntegerState<uint16_t, 7, 0>, AbstractAttribute>,
4318 AANoCapture> {
4320
4321 /// See IRAttribute::isImpliedByIR
4322 LLVM_ABI static bool isImpliedByIR(Attributor &A, const IRPosition &IRP,
4323 Attribute::AttrKind ImpliedAttributeKind,
4324 bool IgnoreSubsumingPositions = false);
4325
4326 /// Update \p State according to the capture capabilities of \p F for position
4327 /// \p IRP.
4328 LLVM_ABI static void
4330 BitIntegerState &State);
4331
4332 /// See AbstractAttribute::isValidIRPositionForInit
4334 if (!IRP.getAssociatedType()->isPointerTy())
4335 return false;
4336 return IRAttribute::isValidIRPositionForInit(A, IRP);
4337 }
4338
4339 /// State encoding bits. A set bit in the state means the property holds.
4340 /// NO_CAPTURE is the best possible state, 0 the worst possible state.
4341 enum {
4345
4346 /// If we do not capture the value in memory or through integers we can only
4347 /// communicate it back as a derived pointer.
4349
4350 /// If we do not capture the value in memory, through integers, or as a
4351 /// derived pointer we know it is not captured.
4354 };
4355
4356 /// Return true if we know that the underlying value is not captured in its
4357 /// respective scope.
4358 bool isKnownNoCapture() const { return isKnown(NO_CAPTURE); }
4359
4360 /// Return true if we assume that the underlying value is not captured in its
4361 /// respective scope.
4362 bool isAssumedNoCapture() const { return isAssumed(NO_CAPTURE); }
4363
4364 /// Return true if we know that the underlying value is not captured in its
4365 /// respective scope but we allow it to escape through a "return".
4369
4370 /// Return true if we assume that the underlying value is not captured in its
4371 /// respective scope but we allow it to escape through a "return".
4375
4376 /// Create an abstract attribute view for the position \p IRP.
4378 Attributor &A);
4379
4380 /// See AbstractAttribute::getName()
4381 StringRef getName() const override { return "AANoCapture"; }
4382
4383 /// See AbstractAttribute::getIdAddr()
4384 const char *getIdAddr() const override { return &ID; }
4385
4386 /// This function should return true if the type of the \p AA is AANoCapture
4387 static bool classof(const AbstractAttribute *AA) {
4388 return (AA->getIdAddr() == &ID);
4389 }
4390
4391 /// Unique ID (due to the unique address)
4392 LLVM_ABI static const char ID;
4393};
4394
4396
4398
4403 return getBestState(VS.Ty);
4404 }
4405
4406 /// Return the worst possible representable state.
4409 DS.indicatePessimisticFixpoint();
4410 return DS;
4411 }
4414 return getWorstState(VS.Ty);
4415 }
4416
4417 /// See AbstractState::isValidState(...)
4418 bool isValidState() const override { return BS.isValidState(); }
4419
4420 /// See AbstractState::isAtFixpoint(...)
4421 bool isAtFixpoint() const override { return BS.isAtFixpoint(); }
4422
4423 /// Return the assumed state encoding.
4425 const ValueSimplifyStateType &getAssumed() const { return *this; }
4426
4427 /// See AbstractState::indicatePessimisticFixpoint(...)
4429 return BS.indicatePessimisticFixpoint();
4430 }
4431
4432 /// See AbstractState::indicateOptimisticFixpoint(...)
4434 return BS.indicateOptimisticFixpoint();
4435 }
4436
4437 /// "Clamp" this state with \p PVS.
4439 BS ^= VS.BS;
4440 unionAssumed(VS.SimplifiedAssociatedValue);
4441 return *this;
4442 }
4443
4445 if (isValidState() != RHS.isValidState())
4446 return false;
4447 if (!isValidState() && !RHS.isValidState())
4448 return true;
4449 return SimplifiedAssociatedValue == RHS.SimplifiedAssociatedValue;
4450 }
4451
4452protected:
4453 /// The type of the original value.
4455
4456 /// Merge \p Other into the currently assumed simplified value
4457 LLVM_ABI bool unionAssumed(std::optional<Value *> Other);
4458
4459 /// Helper to track validity and fixpoint
4461
4462 /// An assumed simplified value. Initially, it is set to std::nullopt, which
4463 /// means that the value is not clear under current assumption. If in the
4464 /// pessimistic state, getAssumedSimplifiedValue doesn't return this value but
4465 /// returns orignal associated value.
4466 std::optional<Value *> SimplifiedAssociatedValue;
4467};
4468
4469/// An abstract interface for value simplify abstract attribute.
4471 : public StateWrapper<ValueSimplifyStateType, AbstractAttribute, Type *> {
4474 : Base(IRP, IRP.getAssociatedType()) {}
4475
4476 /// Create an abstract attribute view for the position \p IRP.
4478 Attributor &A);
4479
4480 /// See AbstractAttribute::getName()
4481 StringRef getName() const override { return "AAValueSimplify"; }
4482
4483 /// See AbstractAttribute::getIdAddr()
4484 const char *getIdAddr() const override { return &ID; }
4485
4486 /// This function should return true if the type of the \p AA is
4487 /// AAValueSimplify
4488 static bool classof(const AbstractAttribute *AA) {
4489 return (AA->getIdAddr() == &ID);
4490 }
4491
4492 /// Unique ID (due to the unique address)
4493 LLVM_ABI static const char ID;
4494
4495private:
4496 /// Return an assumed simplified value if a single candidate is found. If
4497 /// there cannot be one, return original value. If it is not clear yet, return
4498 /// std::nullopt.
4499 ///
4500 /// Use `Attributor::getAssumedSimplified` for value simplification.
4501 virtual std::optional<Value *>
4502 getAssumedSimplifiedValue(Attributor &A) const = 0;
4503
4504 friend struct Attributor;
4505};
4506
4507struct AAHeapToStack : public StateWrapper<BooleanState, AbstractAttribute> {
4509 AAHeapToStack(const IRPosition &IRP, Attributor &A) : Base(IRP) {}
4510
4511 /// Returns true if HeapToStack conversion is assumed to be possible.
4512 virtual bool isAssumedHeapToStack(const CallBase &CB) const = 0;
4513
4514 /// Returns true if HeapToStack conversion is assumed and the CB is a
4515 /// callsite to a free operation to be removed.
4516 virtual bool isAssumedHeapToStackRemovedFree(CallBase &CB) const = 0;
4517
4518 /// Create an abstract attribute view for the position \p IRP.
4520 Attributor &A);
4521
4522 /// See AbstractAttribute::getName()
4523 StringRef getName() const override { return "AAHeapToStack"; }
4524
4525 /// See AbstractAttribute::getIdAddr()
4526 const char *getIdAddr() const override { return &ID; }
4527
4528 /// This function should return true if the type of the \p AA is AAHeapToStack
4529 static bool classof(const AbstractAttribute *AA) {
4530 return (AA->getIdAddr() == &ID);
4531 }
4532
4533 /// Unique ID (due to the unique address)
4534 LLVM_ABI static const char ID;
4535};
4536
4537/// An abstract interface for privatizability.
4538///
4539/// A pointer is privatizable if it can be replaced by a new, private one.
4540/// Privatizing pointer reduces the use count, interaction between unrelated
4541/// code parts.
4542///
4543/// In order for a pointer to be privatizable its value cannot be observed
4544/// (=nocapture), it is (for now) not written (=readonly & noalias), we know
4545/// what values are necessary to make the private copy look like the original
4546/// one, and the values we need can be loaded (=dereferenceable).
4548 : public StateWrapper<BooleanState, AbstractAttribute> {
4551
4552 /// See AbstractAttribute::isValidIRPositionForInit
4555 return false;
4557 }
4558
4559 /// Returns true if pointer privatization is assumed to be possible.
4560 bool isAssumedPrivatizablePtr() const { return getAssumed(); }
4561
4562 /// See AbstractAttribute::requiresCallersForArgOrFunction
4563 static bool requiresCallersForArgOrFunction() { return true; }
4564
4565 /// Return the type we can choose for a private copy of the underlying
4566 /// value. std::nullopt means it is not clear yet, nullptr means there is
4567 /// none.
4568 virtual std::optional<Type *> getPrivatizableType() const = 0;
4569
4570 /// Create an abstract attribute view for the position \p IRP.
4572 Attributor &A);
4573
4574 /// See AbstractAttribute::getName()
4575 StringRef getName() const override { return "AAPrivatizablePtr"; }
4576
4577 /// See AbstractAttribute::getIdAddr()
4578 const char *getIdAddr() const override { return &ID; }
4579
4580 /// This function should return true if the type of the \p AA is
4581 /// AAPricatizablePtr
4582 static bool classof(const AbstractAttribute *AA) {
4583 return (AA->getIdAddr() == &ID);
4584 }
4585
4586 /// Unique ID (due to the unique address)
4587 LLVM_ABI static const char ID;
4588};
4589
4590/// An abstract interface for memory access kind related attributes
4591/// (readnone/readonly/writeonly).
4593 : public IRAttribute<
4594 Attribute::None,
4595 StateWrapper<BitIntegerState<uint8_t, 3>, AbstractAttribute>,
4596 AAMemoryBehavior> {
4598
4599 /// See AbstractAttribute::hasTrivialInitializer.
4600 static bool hasTrivialInitializer() { return false; }
4601
4602 /// See AbstractAttribute::isValidIRPositionForInit
4604 if (!IRP.isFunctionScope() && !IRP.getAssociatedType()->isPointerTy())
4605 return false;
4606 return IRAttribute::isValidIRPositionForInit(A, IRP);
4607 }
4608
4609 /// State encoding bits. A set bit in the state means the property holds.
4610 /// BEST_STATE is the best possible state, 0 the worst possible state.
4611 enum {
4612 NO_READS = 1 << 0,
4613 NO_WRITES = 1 << 1,
4615
4617 };
4618 static_assert(BEST_STATE == getBestState(), "Unexpected BEST_STATE value");
4619
4620 /// Return true if we know that the underlying value is not read or accessed
4621 /// in its respective scope.
4622 bool isKnownReadNone() const { return isKnown(NO_ACCESSES); }
4623
4624 /// Return true if we assume that the underlying value is not read or accessed
4625 /// in its respective scope.
4626 bool isAssumedReadNone() const { return isAssumed(NO_ACCESSES); }
4627
4628 /// Return true if we know that the underlying value is not accessed
4629 /// (=written) in its respective scope.
4630 bool isKnownReadOnly() const { return isKnown(NO_WRITES); }
4631
4632 /// Return true if we assume that the underlying value is not accessed
4633 /// (=written) in its respective scope.
4634 bool isAssumedReadOnly() const { return isAssumed(NO_WRITES); }
4635
4636 /// Return true if we know that the underlying value is not read in its
4637 /// respective scope.
4638 bool isKnownWriteOnly() const { return isKnown(NO_READS); }
4639
4640 /// Return true if we assume that the underlying value is not read in its
4641 /// respective scope.
4642 bool isAssumedWriteOnly() const { return isAssumed(NO_READS); }
4643
4644 /// Create an abstract attribute view for the position \p IRP.
4646 Attributor &A);
4647
4648 /// See AbstractAttribute::getName()
4649 StringRef getName() const override { return "AAMemoryBehavior"; }
4650
4651 /// See AbstractAttribute::getIdAddr()
4652 const char *getIdAddr() const override { return &ID; }
4653
4654 /// This function should return true if the type of the \p AA is
4655 /// AAMemoryBehavior
4656 static bool classof(const AbstractAttribute *AA) {
4657 return (AA->getIdAddr() == &ID);
4658 }
4659
4660 /// Unique ID (due to the unique address)
4661 LLVM_ABI static const char ID;
4662};
4663
4664/// An abstract interface for all memory location attributes
4665/// (readnone/argmemonly/inaccessiblememonly/inaccessibleorargmemonly).
4667 : public IRAttribute<
4668 Attribute::None,
4669 StateWrapper<BitIntegerState<uint32_t, 511>, AbstractAttribute>,
4670 AAMemoryLocation> {
4671 using MemoryLocationsKind = StateType::base_t;
4672
4674
4675 /// See AbstractAttribute::requiresCalleeForCallBase.
4676 static bool requiresCalleeForCallBase() { return true; }
4677
4678 /// See AbstractAttribute::hasTrivialInitializer.
4679 static bool hasTrivialInitializer() { return false; }
4680
4681 /// See AbstractAttribute::isValidIRPositionForInit
4683 if (!IRP.isFunctionScope() &&
4685 return false;
4686 return IRAttribute::isValidIRPositionForInit(A, IRP);
4687 }
4688
4689 /// Encoding of different locations that could be accessed by a memory
4690 /// access.
4691 enum {
4705
4706 // Helper bit to track if we gave up or not.
4708
4710 };
4711 static_assert(BEST_STATE == getBestState(), "Unexpected BEST_STATE value");
4712
4713 /// Return true if we know that the associated functions has no observable
4714 /// accesses.
4715 bool isKnownReadNone() const { return isKnown(NO_LOCATIONS); }
4716
4717 /// Return true if we assume that the associated functions has no observable
4718 /// accesses.
4719 bool isAssumedReadNone() const {
4721 }
4722
4723 /// Return true if we know that the associated functions has at most
4724 /// local/stack accesses.
4725 bool isKnowStackOnly() const {
4726 return isKnown(inverseLocation(NO_LOCAL_MEM, true, true));
4727 }
4728
4729 /// Return true if we assume that the associated functions has at most
4730 /// local/stack accesses.
4731 bool isAssumedStackOnly() const {
4732 return isAssumed(inverseLocation(NO_LOCAL_MEM, true, true));
4733 }
4734
4735 /// Return true if we know that the underlying value will only access
4736 /// inaccesible memory only (see Attribute::InaccessibleMemOnly).
4738 return isKnown(inverseLocation(NO_INACCESSIBLE_MEM, true, true));
4739 }
4740
4741 /// Return true if we assume that the underlying value will only access
4742 /// inaccesible memory only (see Attribute::InaccessibleMemOnly).
4744 return isAssumed(inverseLocation(NO_INACCESSIBLE_MEM, true, true));
4745 }
4746
4747 /// Return true if we know that the underlying value will only access
4748 /// argument pointees (see Attribute::ArgMemOnly).
4749 bool isKnownArgMemOnly() const {
4750 return isKnown(inverseLocation(NO_ARGUMENT_MEM, true, true));
4751 }
4752
4753 /// Return true if we assume that the underlying value will only access
4754 /// argument pointees (see Attribute::ArgMemOnly).
4755 bool isAssumedArgMemOnly() const {
4756 return isAssumed(inverseLocation(NO_ARGUMENT_MEM, true, true));
4757 }
4758
4759 /// Return true if we know that the underlying value will only access
4760 /// inaccesible memory or argument pointees (see
4761 /// Attribute::InaccessibleOrArgMemOnly).
4763 return isKnown(
4765 }
4766
4767 /// Return true if we assume that the underlying value will only access
4768 /// inaccesible memory or argument pointees (see
4769 /// Attribute::InaccessibleOrArgMemOnly).
4774
4775 /// Return true if the underlying value may access memory through arguement
4776 /// pointers of the associated function, if any.
4777 bool mayAccessArgMem() const { return !isAssumed(NO_ARGUMENT_MEM); }
4778
4779 /// Return true if only the memory locations specififed by \p MLK are assumed
4780 /// to be accessed by the associated function.
4782 return isAssumed(MLK);
4783 }
4784
4785 /// Return the locations that are assumed to be not accessed by the associated
4786 /// function, if any.
4790
4791 /// Return the inverse of location \p Loc, thus for NO_XXX the return
4792 /// describes ONLY_XXX. The flags \p AndLocalMem and \p AndConstMem determine
4793 /// if local (=stack) and constant memory are allowed as well. Most of the
4794 /// time we do want them to be included, e.g., argmemonly allows accesses via
4795 /// argument pointers or local or constant memory accesses.
4796 static MemoryLocationsKind
4797 inverseLocation(MemoryLocationsKind Loc, bool AndLocalMem, bool AndConstMem) {
4798 return NO_LOCATIONS & ~(Loc | (AndLocalMem ? NO_LOCAL_MEM : 0) |
4799 (AndConstMem ? NO_CONST_MEM : 0));
4800 };
4801
4802 /// Return the locations encoded by \p MLK as a readable string.
4804
4805 /// Simple enum to distinguish read/write/read-write accesses.
4807 NONE = 0,
4808 READ = 1 << 0,
4809 WRITE = 1 << 1,
4811 };
4812
4813 /// Check \p Pred on all accesses to the memory kinds specified by \p MLK.
4814 ///
4815 /// This method will evaluate \p Pred on all accesses (access instruction +
4816 /// underlying accessed memory pointer) and it will return true if \p Pred
4817 /// holds every time.
4819 function_ref<bool(const Instruction *, const Value *, AccessKind,
4821 Pred,
4822 MemoryLocationsKind MLK) const = 0;
4823
4824 /// Create an abstract attribute view for the position \p IRP.
4826 Attributor &A);
4827
4828 /// See AbstractState::getAsStr(Attributor).
4829 const std::string getAsStr(Attributor *A) const override {
4831 }
4832
4833 /// See AbstractAttribute::getName()
4834 StringRef getName() const override { return "AAMemoryLocation"; }
4835
4836 /// See AbstractAttribute::getIdAddr()
4837 const char *getIdAddr() const override { return &ID; }
4838
4839 /// This function should return true if the type of the \p AA is
4840 /// AAMemoryLocation
4841 static bool classof(const AbstractAttribute *AA) {
4842 return (AA->getIdAddr() == &ID);
4843 }
4844
4845 /// Unique ID (due to the unique address)
4846 LLVM_ABI static const char ID;
4847};
4848
4849/// An abstract interface for range value analysis.
4851 : public StateWrapper<IntegerRangeState, AbstractAttribute, uint32_t> {
4854 : Base(IRP, IRP.getAssociatedType()->getIntegerBitWidth()) {}
4855
4856 /// See AbstractAttribute::isValidIRPositionForInit
4858 if (!IRP.getAssociatedType()->isIntegerTy())
4859 return false;
4861 }
4862
4863 /// See AbstractAttribute::requiresCallersForArgOrFunction
4864 static bool requiresCallersForArgOrFunction() { return true; }
4865
4866 /// See AbstractAttribute::getState(...).
4867 IntegerRangeState &getState() override { return *this; }
4868 const IntegerRangeState &getState() const override { return *this; }
4869
4870 /// Create an abstract attribute view for the position \p IRP.
4872 Attributor &A);
4873
4874 /// Return an assumed range for the associated value a program point \p CtxI.
4875 /// If \p I is nullptr, simply return an assumed range.
4876 virtual ConstantRange
4878 const Instruction *CtxI = nullptr) const = 0;
4879
4880 /// Return an assumed constant for the associated value a program point \p
4881 /// CtxI.
4882 std::optional<Constant *>
4883 getAssumedConstant(Attributor &A, const Instruction *CtxI = nullptr) const {
4884 ConstantRange RangeV = getAssumedConstantRange(A, CtxI);
4885 if (auto *C = RangeV.getSingleElement()) {
4888 AA::getWithType(*ConstantInt::get(Ty->getContext(), *C), *Ty));
4889 }
4890 if (RangeV.isEmptySet())
4891 return std::nullopt;
4892 return nullptr;
4893 }
4894
4895 /// See AbstractAttribute::getName()
4896 StringRef getName() const override { return "AAValueConstantRange"; }
4897
4898 /// See AbstractAttribute::getIdAddr()
4899 const char *getIdAddr() const override { return &ID; }
4900
4901 /// This function should return true if the type of the \p AA is
4902 /// AAValueConstantRange
4903 static bool classof(const AbstractAttribute *AA) {
4904 return (AA->getIdAddr() == &ID);
4905 }
4906
4907 /// Unique ID (due to the unique address)
4908 LLVM_ABI static const char ID;
4909};
4910
4911/// A class for a set state.
4912/// The assumed boolean state indicates whether the corresponding set is full
4913/// set or not. If the assumed state is false, this is the worst state. The
4914/// worst state (invalid state) of set of potential values is when the set
4915/// contains every possible value (i.e. we cannot in any way limit the value
4916/// that the target position can take). That never happens naturally, we only
4917/// force it. As for the conditions under which we force it, see
4918/// AAPotentialConstantValues.
4919template <typename MemberTy> struct PotentialValuesState : AbstractState {
4921
4922 PotentialValuesState() : IsValidState(true), UndefIsContained(false) {}
4923
4925 : IsValidState(IsValid), UndefIsContained(false) {}
4926
4927 /// See AbstractState::isValidState(...)
4928 bool isValidState() const override { return IsValidState.isValidState(); }
4929
4930 /// See AbstractState::isAtFixpoint(...)
4931 bool isAtFixpoint() const override { return IsValidState.isAtFixpoint(); }
4932
4933 /// See AbstractState::indicatePessimisticFixpoint(...)
4935 return IsValidState.indicatePessimisticFixpoint();
4936 }
4937
4938 /// See AbstractState::indicateOptimisticFixpoint(...)
4940 return IsValidState.indicateOptimisticFixpoint();
4941 }
4942
4943 /// Return the assumed state
4945 const PotentialValuesState &getAssumed() const { return *this; }
4946
4947 /// Return this set. We should check whether this set is valid or not by
4948 /// isValidState() before calling this function.
4949 const SetTy &getAssumedSet() const {
4950 assert(isValidState() && "This set shoud not be used when it is invalid!");
4951 return Set;
4952 }
4953
4954 /// Returns whether this state contains an undef value or not.
4955 bool undefIsContained() const {
4956 assert(isValidState() && "This flag shoud not be used when it is invalid!");
4957 return UndefIsContained;
4958 }
4959
4961 if (isValidState() != RHS.isValidState())
4962 return false;
4963 if (!isValidState() && !RHS.isValidState())
4964 return true;
4965 if (undefIsContained() != RHS.undefIsContained())
4966 return false;
4967 return Set == RHS.getAssumedSet();
4968 }
4969
4970 /// Maximum number of potential values to be tracked.
4971 /// This is set by -attributor-max-potential-values command line option
4972 static unsigned MaxPotentialValues;
4973
4974 /// Return empty set as the best state of potential values.
4976 return PotentialValuesState(true);
4977 }
4978
4980 return getBestState();
4981 }
4982
4983 /// Return full set as the worst state of potential values.
4985 return PotentialValuesState(false);
4986 }
4987
4988 /// Union assumed set with the passed value.
4989 void unionAssumed(const MemberTy &C) { insert(C); }
4990
4991 /// Union assumed set with assumed set of the passed state \p PVS.
4992 void unionAssumed(const PotentialValuesState &PVS) { unionWith(PVS); }
4993
4994 /// Union assumed set with an undef value.
4995 void unionAssumedWithUndef() { unionWithUndef(); }
4996
4997 /// "Clamp" this state with \p PVS.
4999 IsValidState ^= PVS.IsValidState;
5000 unionAssumed(PVS);
5001 return *this;
5002 }
5003
5005 IsValidState &= PVS.IsValidState;
5006 unionAssumed(PVS);
5007 return *this;
5008 }
5009
5010protected:
5012 assert(isValidState() && "This set shoud not be used when it is invalid!");
5013 return Set;
5014 }
5015
5016private:
5017 /// Check the size of this set, and invalidate when the size is no
5018 /// less than \p MaxPotentialValues threshold.
5019 void checkAndInvalidate() {
5020 if (Set.size() >= MaxPotentialValues)
5022 else
5023 reduceUndefValue();
5024 }
5025
5026 /// If this state contains both undef and not undef, we can reduce
5027 /// undef to the not undef value.
5028 void reduceUndefValue() { UndefIsContained = UndefIsContained & Set.empty(); }
5029
5030 /// Insert an element into this set.
5031 void insert(const MemberTy &C) {
5032 if (!isValidState())
5033 return;
5034 Set.insert(C);
5035 checkAndInvalidate();
5036 }
5037
5038 /// Take union with R.
5039 void unionWith(const PotentialValuesState &R) {
5040 /// If this is a full set, do nothing.
5041 if (!isValidState())
5042 return;
5043 /// If R is full set, change L to a full set.
5044 if (!R.isValidState()) {
5046 return;
5047 }
5048 Set.insert_range(R.Set);
5049 UndefIsContained |= R.undefIsContained();
5050 checkAndInvalidate();
5051 }
5052
5053 /// Take union with an undef value.
5054 void unionWithUndef() {
5055 UndefIsContained = true;
5056 reduceUndefValue();
5057 }
5058
5059 /// A helper state which indicate whether this state is valid or not.
5060 BooleanState IsValidState;
5061
5062 /// Container for potential values
5063 SetTy Set;
5064
5065 /// Flag for undef value
5066 bool UndefIsContained;
5067};
5068
5073
5074 bool operator==(const DenormalState Other) const {
5075 return Mode == Other.Mode && ModeF32 == Other.ModeF32;
5076 }
5077
5078 bool operator!=(const DenormalState Other) const {
5079 return Mode != Other.Mode || ModeF32 != Other.ModeF32;
5080 }
5081
5082 bool isValid() const { return Mode.isValid() && ModeF32.isValid(); }
5083
5087 if (Caller == Callee)
5088 return Caller;
5089 if (Callee == DenormalMode::Dynamic)
5090 return Caller;
5091 if (Caller == DenormalMode::Dynamic)
5092 return Callee;
5093 return DenormalMode::Invalid;
5094 }
5095
5097 return DenormalMode{unionDenormalKind(Callee.Output, Caller.Output),
5098 unionDenormalKind(Callee.Input, Caller.Input)};
5099 }
5100
5102 DenormalState Callee(*this);
5103 Callee.Mode = unionAssumed(Callee.Mode, Caller.Mode);
5104 Callee.ModeF32 = unionAssumed(Callee.ModeF32, Caller.ModeF32);
5105 return Callee;
5106 }
5107 };
5108
5110
5111 /// Explicitly track whether we've hit a fixed point.
5112 bool IsAtFixedpoint = false;
5113
5115
5116 DenormalState getKnown() const { return Known; }
5117
5118 // There's only really known or unknown, there's no speculatively assumable
5119 // state.
5120 DenormalState getAssumed() const { return Known; }
5121
5122 bool isValidState() const override { return Known.isValid(); }
5123
5124 /// Return true if there are no dynamic components to the denormal mode worth
5125 /// specializing.
5126 bool isModeFixed() const {
5127 return Known.Mode.Input != DenormalMode::Dynamic &&
5128 Known.Mode.Output != DenormalMode::Dynamic &&
5129 Known.ModeF32.Input != DenormalMode::Dynamic &&
5130 Known.ModeF32.Output != DenormalMode::Dynamic;
5131 }
5132
5133 bool isAtFixpoint() const override { return IsAtFixedpoint; }
5134
5140
5144
5148
5150 Known = Known.unionWith(Caller.getKnown());
5151 return *this;
5152 }
5153};
5154
5158
5162 const PotentialLLVMValuesState &R);
5163
5164/// An abstract interface for potential values analysis.
5165///
5166/// This AA collects potential values for each IR position.
5167/// An assumed set of potential values is initialized with the empty set (the
5168/// best state) and it will grow monotonically as we find more potential values
5169/// for this position.
5170/// The set might be forced to the worst state, that is, to contain every
5171/// possible value for this position in 2 cases.
5172/// 1. We surpassed the \p MaxPotentialValues threshold. This includes the
5173/// case that this position is affected (e.g. because of an operation) by a
5174/// Value that is in the worst state.
5175/// 2. We tried to initialize on a Value that we cannot handle (e.g. an
5176/// operator we do not currently handle).
5177///
5178/// For non constant integers see AAPotentialValues.
5180 : public StateWrapper<PotentialConstantIntValuesState, AbstractAttribute> {
5183
5184 /// See AbstractAttribute::isValidIRPositionForInit
5186 if (!IRP.getAssociatedType()->isIntegerTy())
5187 return false;
5189 }
5190
5191 /// See AbstractAttribute::requiresCallersForArgOrFunction
5192 static bool requiresCallersForArgOrFunction() { return true; }
5193
5194 /// See AbstractAttribute::getState(...).
5195 PotentialConstantIntValuesState &getState() override { return *this; }
5197 return *this;
5198 }
5199
5200 /// Create an abstract attribute view for the position \p IRP.
5203
5204 /// Return assumed constant for the associated value
5205 std::optional<Constant *>
5206 getAssumedConstant(Attributor &A, const Instruction *CtxI = nullptr) const {
5207 if (!isValidState())
5208 return nullptr;
5209 if (getAssumedSet().size() == 1) {
5212 *ConstantInt::get(Ty->getContext(), *(getAssumedSet().begin())),
5213 *Ty));
5214 }
5215 if (getAssumedSet().size() == 0) {
5216 if (undefIsContained())
5218 return std::nullopt;
5219 }
5220
5221 return nullptr;
5222 }
5223
5224 /// Return the minimum trailing zeros of potential constants
5226 if (!isValidState() || getAssumedSet().empty())
5227 return 0;
5228 unsigned TrailingZeros = getAssumedSet().begin()->getBitWidth() + 1;
5229 for (const APInt &It : getAssumedSet()) {
5230 if (It.countTrailingZeros() < TrailingZeros)
5231 TrailingZeros = It.countTrailingZeros();
5232 }
5233 if (TrailingZeros > getAssumedSet().begin()->getBitWidth())
5234 return 0;
5235 return TrailingZeros;
5236 }
5237 /// See AbstractAttribute::getName()
5238 StringRef getName() const override { return "AAPotentialConstantValues"; }
5239
5240 /// See AbstractAttribute::getIdAddr()
5241 const char *getIdAddr() const override { return &ID; }
5242
5243 /// This function should return true if the type of the \p AA is
5244 /// AAPotentialConstantValues
5245 static bool classof(const AbstractAttribute *AA) {
5246 return (AA->getIdAddr() == &ID);
5247 }
5248
5249 /// Unique ID (due to the unique address)
5250 LLVM_ABI static const char ID;
5251};
5252
5254 : public StateWrapper<PotentialLLVMValuesState, AbstractAttribute> {
5257
5258 /// See AbstractAttribute::requiresCallersForArgOrFunction
5259 static bool requiresCallersForArgOrFunction() { return true; }
5260
5261 /// See AbstractAttribute::getState(...).
5262 PotentialLLVMValuesState &getState() override { return *this; }
5263 const PotentialLLVMValuesState &getState() const override { return *this; }
5264
5265 /// Create an abstract attribute view for the position \p IRP.
5267 Attributor &A);
5268
5269 /// Extract the single value in \p Values if any.
5270 LLVM_ABI static Value *
5272 const IRPosition &IRP,
5274
5275 /// See AbstractAttribute::getName()
5276 StringRef getName() const override { return "AAPotentialValues"; }
5277
5278 /// See AbstractAttribute::getIdAddr()
5279 const char *getIdAddr() const override { return &ID; }
5280
5281 /// This function should return true if the type of the \p AA is
5282 /// AAPotentialValues
5283 static bool classof(const AbstractAttribute *AA) {
5284 return (AA->getIdAddr() == &ID);
5285 }
5286
5287 /// Unique ID (due to the unique address)
5288 LLVM_ABI static const char ID;
5289
5290private:
5291 virtual bool getAssumedSimplifiedValues(
5293 AA::ValueScope, bool RecurseForSelectAndPHI = false) const = 0;
5294
5295 friend struct Attributor;
5296};
5297
5298/// An abstract interface for all noundef attributes.
5300 : public IRAttribute<Attribute::NoUndef,
5301 StateWrapper<BooleanState, AbstractAttribute>,
5302 AANoUndef> {
5304
5305 /// See IRAttribute::isImpliedByUndef
5306 static bool isImpliedByUndef() { return false; }
5307
5308 /// See IRAttribute::isImpliedByPoison
5309 static bool isImpliedByPoison() { return false; }
5310
5311 /// See IRAttribute::isImpliedByIR
5312 LLVM_ABI static bool isImpliedByIR(Attributor &A, const IRPosition &IRP,
5313 Attribute::AttrKind ImpliedAttributeKind,
5314 bool IgnoreSubsumingPositions = false);
5315
5316 /// Return true if we assume that the underlying value is noundef.
5317 bool isAssumedNoUndef() const { return getAssumed(); }
5318
5319 /// Return true if we know that underlying value is noundef.
5320 bool isKnownNoUndef() const { return getKnown(); }
5321
5322 /// Create an abstract attribute view for the position \p IRP.
5324 Attributor &A);
5325
5326 /// See AbstractAttribute::getName()
5327 StringRef getName() const override { return "AANoUndef"; }
5328
5329 /// See AbstractAttribute::getIdAddr()
5330 const char *getIdAddr() const override { return &ID; }
5331
5332 /// This function should return true if the type of the \p AA is AANoUndef
5333 static bool classof(const AbstractAttribute *AA) {
5334 return (AA->getIdAddr() == &ID);
5335 }
5336
5337 /// Unique ID (due to the unique address)
5338 LLVM_ABI static const char ID;
5339};
5340
5342 : public IRAttribute<
5343 Attribute::NoFPClass,
5344 StateWrapper<BitIntegerState<uint32_t, fcAllFlags, fcNone>,
5345 AbstractAttribute>,
5346 AANoFPClass> {
5349
5351
5352 /// See AbstractAttribute::isValidIRPositionForInit
5354 return AttributeFuncs::isNoFPClassCompatibleType(IRP.getAssociatedType());
5355 }
5356
5357 /// Return the underlying assumed nofpclass.
5359 return static_cast<FPClassTest>(getAssumed());
5360 }
5361 /// Return the underlying known nofpclass.
5363 return static_cast<FPClassTest>(getKnown());
5364 }
5365
5366 /// Create an abstract attribute view for the position \p IRP.
5368 Attributor &A);
5369
5370 /// See AbstractAttribute::getName()
5371 StringRef getName() const override { return "AANoFPClass"; }
5372
5373 /// See AbstractAttribute::getIdAddr()
5374 const char *getIdAddr() const override { return &ID; }
5375
5376 /// This function should return true if the type of the \p AA is AANoFPClass
5377 static bool classof(const AbstractAttribute *AA) {
5378 return (AA->getIdAddr() == &ID);
5379 }
5380
5381 /// Unique ID (due to the unique address)
5382 LLVM_ABI static const char ID;
5383};
5384
5385struct AACallGraphNode;
5386struct AACallEdges;
5387
5388/// An Iterator for call edges, creates AACallEdges attributes in a lazy way.
5389/// This iterator becomes invalid if the underlying edge list changes.
5390/// So This shouldn't outlive a iteration of Attributor.
5391class AACallEdgeIterator
5392 : public iterator_adaptor_base<AACallEdgeIterator,
5393 SetVector<Function *>::iterator> {
5394 AACallEdgeIterator(Attributor &A, SetVector<Function *>::iterator Begin)
5395 : iterator_adaptor_base(Begin), A(A) {}
5396
5397public:
5399
5400private:
5401 Attributor &A;
5402 friend AACallEdges;
5403 friend AttributorCallGraph;
5404};
5405
5408 virtual ~AACallGraphNode() = default;
5409
5412
5413 /// Iterator range for exploring the call graph.
5418
5419protected:
5420 /// Reference to Attributor needed for GraphTraits implementation.
5422};
5423
5424/// An abstract state for querying live call edges.
5425/// This interface uses the Attributor's optimistic liveness
5426/// information to compute the edges that are alive.
5427struct AACallEdges : public StateWrapper<BooleanState, AbstractAttribute>,
5430
5432 : Base(IRP), AACallGraphNode(A) {}
5433
5434 /// See AbstractAttribute::requiresNonAsmForCallBase.
5435 static bool requiresNonAsmForCallBase() { return false; }
5436
5437 /// Get the optimistic edges.
5438 virtual const SetVector<Function *> &getOptimisticEdges() const = 0;
5439
5440 /// Is there any call with a unknown callee.
5441 virtual bool hasUnknownCallee() const = 0;
5442
5443 /// Is there any call with a unknown callee, excluding any inline asm.
5444 virtual bool hasNonAsmUnknownCallee() const = 0;
5445
5446 /// Iterator for exploring the call graph.
5450
5451 /// Iterator for exploring the call graph.
5455
5456 /// Create an abstract attribute view for the position \p IRP.
5458 Attributor &A);
5459
5460 /// See AbstractAttribute::getName()
5461 StringRef getName() const override { return "AACallEdges"; }
5462
5463 /// See AbstractAttribute::getIdAddr()
5464 const char *getIdAddr() const override { return &ID; }
5465
5466 /// This function should return true if the type of the \p AA is AACallEdges.
5467 static bool classof(const AbstractAttribute *AA) {
5468 return (AA->getIdAddr() == &ID);
5469 }
5470
5471 /// Unique ID (due to the unique address)
5472 LLVM_ABI static const char ID;
5473};
5474
5475// Synthetic root node for the Attributor's internal call graph.
5478 ~AttributorCallGraph() override = default;
5479
5481 return AACallEdgeIterator(A, A.Functions.begin());
5482 }
5483
5485 return AACallEdgeIterator(A, A.Functions.end());
5486 }
5487
5488 /// Force populate the entire call graph.
5489 void populateAll() const {
5490 for (const AACallGraphNode *AA : optimisticEdgesRange()) {
5491 // Nothing else to do here.
5492 (void)AA;
5493 }
5494 }
5495
5496 LLVM_ABI void print();
5497};
5498
5499template <> struct GraphTraits<AACallGraphNode *> {
5502
5504 return Node->optimisticEdgesBegin();
5505 }
5506
5508 return Node->optimisticEdgesEnd();
5509 }
5510};
5511
5512template <>
5516
5518 return static_cast<AACallGraphNode *>(G);
5519 }
5520
5522 return G->optimisticEdgesBegin();
5523 }
5524
5526 return G->optimisticEdgesEnd();
5527 }
5528};
5529
5530template <>
5533
5535 const AttributorCallGraph *Graph) {
5536 const AACallEdges *AACE = static_cast<const AACallEdges *>(Node);
5537 return AACE->getAssociatedFunction()->getName().str();
5538 }
5539
5541 const AttributorCallGraph *Graph) {
5542 // Hide the synth root.
5543 return static_cast<const AACallGraphNode *>(Graph) == Node;
5544 }
5545};
5546
5548 : public StateWrapper<BooleanState, AbstractAttribute> {
5551
5552 /// Summary about the execution domain of a block or instruction.
5577
5578 /// Create an abstract attribute view for the position \p IRP.
5580 Attributor &A);
5581
5582 /// See AbstractAttribute::getName().
5583 StringRef getName() const override { return "AAExecutionDomain"; }
5584
5585 /// See AbstractAttribute::getIdAddr().
5586 const char *getIdAddr() const override { return &ID; }
5587
5588 /// Check if an instruction is executed only by the initial thread.
5590 return isExecutedByInitialThreadOnly(*I.getParent());
5591 }
5592
5593 /// Check if a basic block is executed only by the initial thread.
5594 virtual bool isExecutedByInitialThreadOnly(const BasicBlock &) const = 0;
5595
5596 /// Check if the instruction \p I is executed in an aligned region, that is,
5597 /// the synchronizing effects before and after \p I are both aligned barriers.
5598 /// This effectively means all threads execute \p I together.
5600 const Instruction &I) const = 0;
5601
5603 /// Return the execution domain with which the call \p CB is entered and the
5604 /// one with which it is left.
5605 virtual std::pair<ExecutionDomainTy, ExecutionDomainTy>
5606 getExecutionDomain(const CallBase &CB) const = 0;
5608
5609 /// Helper function to determine if \p FI is a no-op given the information
5610 /// about its execution from \p ExecDomainAA.
5611 virtual bool isNoOpFence(const FenceInst &FI) const = 0;
5612
5613 /// This function should return true if the type of the \p AA is
5614 /// AAExecutionDomain.
5615 static bool classof(const AbstractAttribute *AA) {
5616 return (AA->getIdAddr() == &ID);
5617 }
5618
5619 /// Unique ID (due to the unique address)
5620 LLVM_ABI static const char ID;
5621};
5622
5623/// An abstract Attribute for computing reachability between functions.
5625 : public StateWrapper<BooleanState, AbstractAttribute> {
5627
5629
5630 /// If the function represented by this possition can reach \p Fn.
5631 bool canReach(Attributor &A, const Function &Fn) const {
5632 Function *Scope = getAnchorScope();
5633 if (!Scope || Scope->isDeclaration())
5634 return true;
5635 return instructionCanReach(A, Scope->getEntryBlock().front(), Fn);
5636 }
5637
5638 /// Can \p Inst reach \p Fn.
5639 /// See also AA::isPotentiallyReachable.
5641 Attributor &A, const Instruction &Inst, const Function &Fn,
5642 const AA::InstExclusionSetTy *ExclusionSet = nullptr) const = 0;
5643
5644 /// Create an abstract attribute view for the position \p IRP.
5647
5648 /// See AbstractAttribute::getName()
5649 StringRef getName() const override { return "AAInterFnReachability"; }
5650
5651 /// See AbstractAttribute::getIdAddr()
5652 const char *getIdAddr() const override { return &ID; }
5653
5654 /// This function should return true if the type of the \p AA is AACallEdges.
5655 static bool classof(const AbstractAttribute *AA) {
5656 return (AA->getIdAddr() == &ID);
5657 }
5658
5659 /// Unique ID (due to the unique address)
5660 LLVM_ABI static const char ID;
5661};
5662
5663/// An abstract Attribute for determining the necessity of the convergent
5664/// attribute.
5665struct AANonConvergent : public StateWrapper<BooleanState, AbstractAttribute> {
5667
5669
5670 /// Create an abstract attribute view for the position \p IRP.
5672 Attributor &A);
5673
5674 /// Return true if "non-convergent" is assumed.
5675 bool isAssumedNotConvergent() const { return getAssumed(); }
5676
5677 /// Return true if "non-convergent" is known.
5678 bool isKnownNotConvergent() const { return getKnown(); }
5679
5680 /// See AbstractAttribute::getName()
5681 StringRef getName() const override { return "AANonConvergent"; }
5682
5683 /// See AbstractAttribute::getIdAddr()
5684 const char *getIdAddr() const override { return &ID; }
5685
5686 /// This function should return true if the type of the \p AA is
5687 /// AANonConvergent.
5688 static bool classof(const AbstractAttribute *AA) {
5689 return (AA->getIdAddr() == &ID);
5690 }
5691
5692 /// Unique ID (due to the unique address)
5693 LLVM_ABI static const char ID;
5694};
5695
5696/// An abstract interface for struct information.
5699
5700 /// See AbstractAttribute::isValidIRPositionForInit
5703 return false;
5705 }
5706
5708 // First two bits to distinguish may and must accesses.
5709 AK_MUST = 1 << 0,
5710 AK_MAY = 1 << 1,
5711
5712 // Then two bits for read and write. These are not exclusive.
5713 AK_R = 1 << 2,
5714 AK_W = 1 << 3,
5716
5717 // One special case for assumptions about memory content. These
5718 // are neither reads nor writes. They are however always modeled
5719 // as read to avoid using them for write removal.
5721
5722 // Helper for easy access.
5729 };
5730
5731 /// A helper containing a list of offsets computed for a Use. Ideally this
5732 /// list should be strictly ascending, but we ensure that only when we
5733 /// actually translate the list of offsets to a RangeList.
5734 struct OffsetInfo {
5738
5739 const_iterator begin() const { return Offsets.begin(); }
5740 const_iterator end() const { return Offsets.end(); }
5741
5742 bool operator==(const OffsetInfo &RHS) const {
5743 return Offsets == RHS.Offsets;
5744 }
5745
5746 bool operator!=(const OffsetInfo &RHS) const { return !(*this == RHS); }
5747
5748 bool insert(int64_t Offset) { return Offsets.insert(Offset).second; }
5749 bool isUnassigned() const { return Offsets.size() == 0; }
5750
5751 bool isUnknown() const {
5752 if (isUnassigned())
5753 return false;
5754 if (Offsets.size() == 1)
5755 return *Offsets.begin() == AA::RangeTy::Unknown;
5756 return false;
5757 }
5758
5759 void setUnknown() {
5760 Offsets.clear();
5762 }
5763
5764 void addToAll(int64_t Inc) {
5765 VecTy NewOffsets;
5766 for (auto &Offset : Offsets)
5767 NewOffsets.insert(Offset + Inc);
5768 Offsets = std::move(NewOffsets);
5769 }
5770
5771 /// Copy offsets from \p R into the current list.
5772 ///
5773 /// Ideally all lists should be strictly ascending, but we defer that to the
5774 /// actual use of the list. So we just blindly append here.
5775 bool merge(const OffsetInfo &R) { return set_union(Offsets, R.Offsets); }
5776 };
5777
5778 /// A container for a list of ranges.
5779 struct RangeList {
5780 // The set of ranges rarely contains more than one element, and is unlikely
5781 // to contain more than say four elements. So we find the middle-ground with
5782 // a sorted vector. This avoids hard-coding a rarely used number like "four"
5783 // into every instance of a SmallSet.
5789
5790 RangeList(const RangeTy &R) { Ranges.push_back(R); }
5792 Ranges.reserve(Offsets.size());
5793 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
5794 assert(((i + 1 == e) || Offsets[i] < Offsets[i + 1]) &&
5795 "Expected strictly ascending offsets.");
5796 Ranges.emplace_back(Offsets[i], Size);
5797 }
5798 }
5799 RangeList() = default;
5800
5801 iterator begin() { return Ranges.begin(); }
5802 iterator end() { return Ranges.end(); }
5803 const_iterator begin() const { return Ranges.begin(); }
5804 const_iterator end() const { return Ranges.end(); }
5805
5806 // Helpers required for std::set_difference
5808 void push_back(const RangeTy &R) {
5809 assert((Ranges.empty() || RangeTy::LessThan(Ranges.back(), R)) &&
5810 "Ensure the last element is the greatest.");
5811 Ranges.push_back(R);
5812 }
5813
5814 /// Copy ranges from \p L that are not in \p R, into \p D.
5815 static void set_difference(const RangeList &L, const RangeList &R,
5816 RangeList &D) {
5817 std::set_difference(L.begin(), L.end(), R.begin(), R.end(),
5818 std::back_inserter(D), RangeTy::LessThan);
5819 }
5820
5821 unsigned size() const { return Ranges.size(); }
5822
5823 bool operator==(const RangeList &OI) const { return Ranges == OI.Ranges; }
5824
5825 /// Merge the ranges in \p RHS into the current ranges.
5826 /// - Merging a list of unknown ranges makes the current list unknown.
5827 /// - Ranges with the same offset are merged according to RangeTy::operator&
5828 /// \return true if the current RangeList changed.
5829 bool merge(const RangeList &RHS) {
5830 if (isUnknown())
5831 return false;
5832 if (RHS.isUnknown()) {
5833 setUnknown();
5834 return true;
5835 }
5836
5837 if (Ranges.empty()) {
5838 Ranges = RHS.Ranges;
5839 return true;
5840 }
5841
5842 bool Changed = false;
5843 auto LPos = Ranges.begin();
5844 for (auto &R : RHS.Ranges) {
5845 auto Result = insert(LPos, R);
5846 if (isUnknown())
5847 return true;
5848 LPos = Result.first;
5849 Changed |= Result.second;
5850 }
5851 return Changed;
5852 }
5853
5854 /// Insert \p R at the given iterator \p Pos, and merge if necessary.
5855 ///
5856 /// This assumes that all ranges before \p Pos are LessThan \p R, and
5857 /// then maintains the sorted order for the suffix list.
5858 ///
5859 /// \return The place of insertion and true iff anything changed.
5860 std::pair<iterator, bool> insert(iterator Pos, const RangeTy &R) {
5861 if (isUnknown())
5862 return std::make_pair(Ranges.begin(), false);
5863 if (R.offsetOrSizeAreUnknown()) {
5864 return std::make_pair(setUnknown(), true);
5865 }
5866
5867 // Maintain this as a sorted vector of unique entries.
5868 auto LB = std::lower_bound(Pos, Ranges.end(), R, RangeTy::LessThan);
5869 if (LB == Ranges.end() || LB->Offset != R.Offset)
5870 return std::make_pair(Ranges.insert(LB, R), true);
5871 bool Changed = *LB != R;
5872 *LB &= R;
5873 if (LB->offsetOrSizeAreUnknown())
5874 return std::make_pair(setUnknown(), true);
5875 return std::make_pair(LB, Changed);
5876 }
5877
5878 /// Add the increment \p Inc to the offset of every range.
5879 void addToAllOffsets(int64_t Inc) {
5880 assert(!isUnassigned() &&
5881 "Cannot increment if the offset is not yet computed!");
5882 if (isUnknown())
5883 return;
5884 for (auto &R : Ranges) {
5885 R.Offset += Inc;
5886 }
5887 }
5888
5889 /// Return true iff the list contains an unknown range.
5890 bool isUnknown() const {
5891 if (isUnassigned())
5892 return false;
5893 if (Ranges.front().offsetOrSizeAreUnknown()) {
5894 assert(Ranges.size() == 1 && "Unknown is a singleton range.");
5895 return true;
5896 }
5897 return false;
5898 }
5899
5900 /// Discard all ranges and insert a single unknown range.
5902 Ranges.clear();
5903 Ranges.push_back(RangeTy::getUnknown());
5904 return Ranges.begin();
5905 }
5906
5907 /// Return true if no ranges have been inserted.
5908 bool isUnassigned() const { return Ranges.size() == 0; }
5909 };
5910
5911 /// An access description.
5912 struct Access {
5913 Access(Instruction *I, int64_t Offset, int64_t Size,
5914 std::optional<Value *> Content, AccessKind Kind, Type *Ty)
5915 : LocalI(I), RemoteI(I), Content(Content), Ranges(Offset, Size),
5916 Kind(Kind), Ty(Ty) {
5917 verify();
5918 }
5919 Access(Instruction *LocalI, Instruction *RemoteI, const RangeList &Ranges,
5920 std::optional<Value *> Content, AccessKind K, Type *Ty)
5921 : LocalI(LocalI), RemoteI(RemoteI), Content(Content), Ranges(Ranges),
5922 Kind(K), Ty(Ty) {
5923 if (Ranges.size() > 1) {
5924 Kind = AccessKind(Kind | AK_MAY);
5925 Kind = AccessKind(Kind & ~AK_MUST);
5926 }
5927 verify();
5928 }
5929 Access(Instruction *LocalI, Instruction *RemoteI, int64_t Offset,
5930 int64_t Size, std::optional<Value *> Content, AccessKind Kind,
5931 Type *Ty)
5932 : LocalI(LocalI), RemoteI(RemoteI), Content(Content),
5933 Ranges(Offset, Size), Kind(Kind), Ty(Ty) {
5934 verify();
5935 }
5936 Access(const Access &Other) = default;
5937
5938 Access &operator=(const Access &Other) = default;
5939 bool operator==(const Access &R) const {
5940 return LocalI == R.LocalI && RemoteI == R.RemoteI && Ranges == R.Ranges &&
5941 Content == R.Content && Kind == R.Kind;
5942 }
5943 bool operator!=(const Access &R) const { return !(*this == R); }
5944
5946 assert(RemoteI == R.RemoteI && "Expected same instruction!");
5947 assert(LocalI == R.LocalI && "Expected same instruction!");
5948
5949 // Note that every Access object corresponds to a unique Value, and only
5950 // accesses to the same Value are merged. Hence we assume that all ranges
5951 // are the same size. If ranges can be different size, then the contents
5952 // must be dropped.
5953 Ranges.merge(R.Ranges);
5954 Content =
5955 AA::combineOptionalValuesInAAValueLatice(Content, R.Content, Ty);
5956
5957 // Combine the access kind, which results in a bitwise union.
5958 // If there is more than one range, then this must be a MAY.
5959 // If we combine a may and a must access we clear the must bit.
5960 Kind = AccessKind(Kind | R.Kind);
5961 if ((Kind & AK_MAY) || Ranges.size() > 1) {
5962 Kind = AccessKind(Kind | AK_MAY);
5963 Kind = AccessKind(Kind & ~AK_MUST);
5964 }
5965 verify();
5966 return *this;
5967 }
5968
5969 void verify() {
5970 assert(isMustAccess() + isMayAccess() == 1 &&
5971 "Expect must or may access, not both.");
5972 assert(isAssumption() + isWrite() <= 1 &&
5973 "Expect assumption access or write access, never both.");
5974 assert((isMayAccess() || Ranges.size() == 1) &&
5975 "Cannot be a must access if there are multiple ranges.");
5976 }
5977
5978 /// Return the access kind.
5979 AccessKind getKind() const { return Kind; }
5980
5981 /// Return true if this is a read access.
5982 bool isRead() const { return Kind & AK_R; }
5983
5984 /// Return true if this is a write access.
5985 bool isWrite() const { return Kind & AK_W; }
5986
5987 /// Return true if this is a write access.
5988 bool isWriteOrAssumption() const { return isWrite() || isAssumption(); }
5989
5990 /// Return true if this is an assumption access.
5991 bool isAssumption() const { return Kind == AK_ASSUMPTION; }
5992
5993 bool isMustAccess() const {
5994 bool MustAccess = Kind & AK_MUST;
5995 assert((!MustAccess || Ranges.size() < 2) &&
5996 "Cannot be a must access if there are multiple ranges.");
5997 return MustAccess;
5998 }
5999
6000 bool isMayAccess() const {
6001 bool MayAccess = Kind & AK_MAY;
6002 assert((MayAccess || Ranges.size() < 2) &&
6003 "Cannot be a must access if there are multiple ranges.");
6004 return MayAccess;
6005 }
6006
6007 /// Return the instruction that causes the access with respect to the local
6008 /// scope of the associated attribute.
6009 Instruction *getLocalInst() const { return LocalI; }
6010
6011 /// Return the actual instruction that causes the access.
6012 Instruction *getRemoteInst() const { return RemoteI; }
6013
6014 /// Return true if the value written is not known yet.
6015 bool isWrittenValueYetUndetermined() const { return !Content; }
6016
6017 /// Return true if the value written cannot be determined at all.
6019 return Content.has_value() && !*Content;
6020 }
6021
6022 /// Return the type associated with the access, if known.
6023 Type *getType() const { return Ty; }
6024
6025 /// Return the value writen, if any.
6028 "Value needs to be determined before accessing it.");
6029 return *Content;
6030 }
6031
6032 /// Return the written value which can be `llvm::null` if it is not yet
6033 /// determined.
6034 std::optional<Value *> getContent() const { return Content; }
6035
6036 const RangeList &getRanges() const { return Ranges; }
6037
6039 const_iterator begin() const { return Ranges.begin(); }
6040 const_iterator end() const { return Ranges.end(); }
6041
6042 private:
6043 /// The instruction responsible for the access with respect to the local
6044 /// scope of the associated attribute.
6045 Instruction *LocalI;
6046
6047 /// The instruction responsible for the access.
6048 Instruction *RemoteI;
6049
6050 /// The value written, if any. `std::nullopt` means "not known yet",
6051 /// `nullptr` cannot be determined.
6052 std::optional<Value *> Content;
6053
6054 /// Set of potential ranges accessed from the base pointer.
6055 RangeList Ranges;
6056
6057 /// The access kind, e.g., READ, as bitset (could be more than one).
6059
6060 /// The type of the content, thus the type read/written, can be null if not
6061 /// available.
6062 Type *Ty;
6063 };
6064
6065 /// Create an abstract attribute view for the position \p IRP.
6067 Attributor &A);
6068
6069 /// See AbstractAttribute::getName()
6070 StringRef getName() const override { return "AAPointerInfo"; }
6071
6072 /// See AbstractAttribute::getIdAddr()
6073 const char *getIdAddr() const override { return &ID; }
6074
6076 using const_bin_iterator = OffsetBinsTy::const_iterator;
6077 virtual const_bin_iterator begin() const = 0;
6078 virtual const_bin_iterator end() const = 0;
6079 virtual int64_t numOffsetBins() const = 0;
6080 virtual bool reachesReturn() const = 0;
6081 virtual void addReturnedOffsetsTo(OffsetInfo &) const = 0;
6082
6083 /// Call \p CB on all accesses that might interfere with \p Range and return
6084 /// true if all such accesses were known and the callback returned true for
6085 /// all of them, false otherwise. An access interferes with an offset-size
6086 /// pair if it might read or write that memory region.
6088 AA::RangeTy Range, function_ref<bool(const Access &, bool)> CB) const = 0;
6089
6090 /// Call \p CB on all accesses that might interfere with \p I and
6091 /// return true if all such accesses were known and the callback returned true
6092 /// for all of them, false otherwise. In contrast to forallInterferingAccesses
6093 /// this function will perform reasoning to exclude write accesses that cannot
6094 /// affect the load even if they on the surface look as if they would. The
6095 /// flag \p HasBeenWrittenTo will be set to true if we know that \p I does not
6096 /// read the initial value of the underlying memory. If \p SkipCB is given and
6097 /// returns false for a potentially interfering access, that access is not
6098 /// checked for actual interference.
6100 Attributor &A, const AbstractAttribute &QueryingAA, Instruction &I,
6101 bool FindInterferingWrites, bool FindInterferingReads,
6102 function_ref<bool(const Access &, bool)> CB, bool &HasBeenWrittenTo,
6104 function_ref<bool(const Access &)> SkipCB = nullptr) const = 0;
6105
6106 /// This function should return true if the type of the \p AA is AAPointerInfo
6107 static bool classof(const AbstractAttribute *AA) {
6108 return (AA->getIdAddr() == &ID);
6109 }
6110
6111 /// Unique ID (due to the unique address)
6112 LLVM_ABI static const char ID;
6113};
6114
6116
6117/// An abstract attribute for getting assumption information.
6119 : public StateWrapper<SetState<StringRef>, AbstractAttribute,
6120 DenseSet<StringRef>> {
6121 using Base =
6123
6125 const DenseSet<StringRef> &Known)
6126 : Base(IRP, Known) {}
6127
6128 /// Returns true if the assumption set contains the assumption \p Assumption.
6129 virtual bool hasAssumption(const StringRef Assumption) const = 0;
6130
6131 /// Create an abstract attribute view for the position \p IRP.
6133 Attributor &A);
6134
6135 /// See AbstractAttribute::getName()
6136 StringRef getName() const override { return "AAAssumptionInfo"; }
6137
6138 /// See AbstractAttribute::getIdAddr()
6139 const char *getIdAddr() const override { return &ID; }
6140
6141 /// This function should return true if the type of the \p AA is
6142 /// AAAssumptionInfo
6143 static bool classof(const AbstractAttribute *AA) {
6144 return (AA->getIdAddr() == &ID);
6145 }
6146
6147 /// Unique ID (due to the unique address)
6148 LLVM_ABI static const char ID;
6149};
6150
6151/// An abstract attribute for getting all assumption underlying objects.
6154
6155 /// See AbstractAttribute::isValidIRPositionForInit
6158 return false;
6160 }
6161
6162 /// See AbstractAttribute::requiresCallersForArgOrFunction
6163 static bool requiresCallersForArgOrFunction() { return true; }
6164
6165 /// Create an abstract attribute biew for the position \p IRP.
6167 Attributor &A);
6168
6169 /// See AbstractAttribute::getName()
6170 StringRef getName() const override { return "AAUnderlyingObjects"; }
6171
6172 /// See AbstractAttribute::getIdAddr()
6173 const char *getIdAddr() const override { return &ID; }
6174
6175 /// This function should return true if the type of the \p AA is
6176 /// AAUnderlyingObjects.
6177 static bool classof(const AbstractAttribute *AA) {
6178 return (AA->getIdAddr() == &ID);
6179 }
6180
6181 /// Unique ID (due to the unique address)
6182 LLVM_ABI static const char ID;
6183
6184 /// Check \p Pred on all underlying objects in \p Scope collected so far.
6185 ///
6186 /// This method will evaluate \p Pred on all underlying objects in \p Scope
6187 /// collected so far and return true if \p Pred holds on all of them.
6188 virtual bool
6190 AA::ValueScope Scope = AA::Interprocedural) const = 0;
6191};
6192
6193/// An abstract interface for identifying pointers from which loads can be
6194/// marked invariant.
6197
6198 /// See AbstractAttribute::isValidIRPositionForInit
6200 if (!IRP.getAssociatedType()->isPointerTy())
6201 return false;
6202
6204 }
6205
6206 /// Create an abstract attribute view for the position \p IRP.
6209
6210 /// Return true if the pointer's contents are known to remain invariant.
6211 virtual bool isKnownInvariant() const = 0;
6212 virtual bool isKnownLocallyInvariant() const = 0;
6213
6214 /// Return true if the pointer's contents are assumed to remain invariant.
6215 virtual bool isAssumedInvariant() const = 0;
6216 virtual bool isAssumedLocallyInvariant() const = 0;
6217
6218 /// See AbstractAttribute::getName().
6219 StringRef getName() const override { return "AAInvariantLoadPointer"; }
6220
6221 /// See AbstractAttribute::getIdAddr().
6222 const char *getIdAddr() const override { return &ID; }
6223
6224 /// This function should return true if the type of the \p AA is
6225 /// AAInvariantLoadPointer
6226 static bool classof(const AbstractAttribute *AA) {
6227 return (AA->getIdAddr() == &ID);
6228 }
6229
6230 /// Unique ID (due to the unique address).
6231 LLVM_ABI static const char ID;
6232};
6233
6234/// An abstract interface for address space information.
6235struct AAAddressSpace : public StateWrapper<BooleanState, AbstractAttribute> {
6238
6239 /// See AbstractAttribute::isValidIRPositionForInit
6242 return false;
6244 }
6245
6246 /// See AbstractAttribute::requiresCallersForArgOrFunction
6247 static bool requiresCallersForArgOrFunction() { return true; }
6248
6249 /// Return the address space of the associated value. \p NoAddressSpace is
6250 /// returned if the associated value is dead. This functions is not supposed
6251 /// to be called if the AA is invalid.
6252 virtual uint32_t getAddressSpace() const = 0;
6253
6254 /// Create an abstract attribute view for the position \p IRP.
6256 Attributor &A);
6257
6258 /// See AbstractAttribute::getName()
6259 StringRef getName() const override { return "AAAddressSpace"; }
6260
6261 /// See AbstractAttribute::getIdAddr()
6262 const char *getIdAddr() const override { return &ID; }
6263
6264 /// This function should return true if the type of the \p AA is
6265 /// AAAssumptionInfo
6266 static bool classof(const AbstractAttribute *AA) {
6267 return (AA->getIdAddr() == &ID);
6268 }
6269
6270 /// Unique ID (due to the unique address)
6271 LLVM_ABI static const char ID;
6272
6273protected:
6274 // Invalid address space which indicates the associated value is dead.
6275 static const uint32_t InvalidAddressSpace = ~0U;
6276};
6277
6278/// An abstract interface for potential address space information.
6280 : public StateWrapper<BooleanState, AbstractAttribute> {
6285
6286 /// See AbstractAttribute::isValidIRPositionForInit
6289 return false;
6291 }
6292
6293 /// See AbstractAttribute::requiresCallersForArgOrFunction
6294 static bool requiresCallersForArgOrFunction() { return true; }
6295
6296 /// Create an abstract attribute view for the position \p IRP.
6298 Attributor &A);
6299 /// See AbstractAttribute::getName()
6300 StringRef getName() const override { return "AANoAliasAddrSpace"; }
6301
6302 /// See AbstractAttribute::getIdAddr()
6303 const char *getIdAddr() const override { return &ID; }
6304
6305 /// This function should return true if the type of the \p AA is
6306 /// AAAssumptionInfo
6307 static bool classof(const AbstractAttribute *AA) {
6308 return (AA->getIdAddr() == &ID);
6309 }
6310
6311 /// Unique ID (due to the unique address)
6312 LLVM_ABI static const char ID;
6313
6314protected:
6317};
6318
6319struct AAAllocationInfo : public StateWrapper<BooleanState, AbstractAttribute> {
6322
6323 /// See AbstractAttribute::isValidIRPositionForInit
6326 return false;
6328 }
6329
6330 /// Create an abstract attribute view for the position \p IRP.
6332 Attributor &A);
6333
6334 virtual std::optional<TypeSize> getAllocatedSize() const = 0;
6335
6336 /// See AbstractAttribute::getName()
6337 StringRef getName() const override { return "AAAllocationInfo"; }
6338
6339 /// See AbstractAttribute::getIdAddr()
6340 const char *getIdAddr() const override { return &ID; }
6341
6342 /// This function should return true if the type of the \p AA is
6343 /// AAAllocationInfo
6344 static bool classof(const AbstractAttribute *AA) {
6345 return (AA->getIdAddr() == &ID);
6346 }
6347
6348 constexpr static const std::optional<TypeSize> HasNoAllocationSize =
6349 std::make_optional<TypeSize>(-1, true);
6350
6351 LLVM_ABI static const char ID;
6352};
6353
6354/// An abstract interface for llvm::GlobalValue information interference.
6356 : public StateWrapper<BooleanState, AbstractAttribute> {
6359
6360 /// See AbstractAttribute::isValidIRPositionForInit
6363 return false;
6364 auto *GV = dyn_cast<GlobalValue>(&IRP.getAnchorValue());
6365 if (!GV)
6366 return false;
6367 return GV->hasLocalLinkage();
6368 }
6369
6370 /// Create an abstract attribute view for the position \p IRP.
6372 Attributor &A);
6373
6374 /// Return true iff \p U is a potential use of the associated global value.
6375 virtual bool isPotentialUse(const Use &U) const = 0;
6376
6377 /// See AbstractAttribute::getName()
6378 StringRef getName() const override { return "AAGlobalValueInfo"; }
6379
6380 /// See AbstractAttribute::getIdAddr()
6381 const char *getIdAddr() const override { return &ID; }
6382
6383 /// This function should return true if the type of the \p AA is
6384 /// AAGlobalValueInfo
6385 static bool classof(const AbstractAttribute *AA) {
6386 return (AA->getIdAddr() == &ID);
6387 }
6388
6389 /// Unique ID (due to the unique address)
6390 LLVM_ABI static const char ID;
6391};
6392
6393/// An abstract interface for indirect call information interference.
6395 : public StateWrapper<BooleanState, AbstractAttribute> {
6398
6399 /// See AbstractAttribute::isValidIRPositionForInit
6402 return false;
6403 auto *CB = cast<CallBase>(IRP.getCtxI());
6404 return CB->getOpcode() == Instruction::Call && CB->isIndirectCall() &&
6405 !CB->isMustTailCall();
6406 }
6407
6408 /// Create an abstract attribute view for the position \p IRP.
6410 Attributor &A);
6411
6412 /// Call \CB on each potential callee value and return true if all were known
6413 /// and \p CB returned true on all of them. Otherwise, return false.
6414 virtual bool foreachCallee(function_ref<bool(Function *)> CB) const = 0;
6415
6416 /// See AbstractAttribute::getName()
6417 StringRef getName() const override { return "AAIndirectCallInfo"; }
6418
6419 /// See AbstractAttribute::getIdAddr()
6420 const char *getIdAddr() const override { return &ID; }
6421
6422 /// This function should return true if the type of the \p AA is
6423 /// AAIndirectCallInfo
6424 /// This function should return true if the type of the \p AA is
6425 /// AADenormalFPMath.
6426 static bool classof(const AbstractAttribute *AA) {
6427 return (AA->getIdAddr() == &ID);
6428 }
6429
6430 /// Unique ID (due to the unique address)
6431 LLVM_ABI static const char ID;
6432};
6433
6434/// An abstract Attribute for specializing "dynamic" components of
6435/// denormal_fpenv to a known denormal mode.
6437 : public StateWrapper<DenormalFPMathState, AbstractAttribute> {
6439
6441
6442 /// Create an abstract attribute view for the position \p IRP.
6444 Attributor &A);
6445
6446 /// See AbstractAttribute::getName()
6447 StringRef getName() const override { return "AADenormalFPMath"; }
6448
6449 /// See AbstractAttribute::getIdAddr()
6450 const char *getIdAddr() const override { return &ID; }
6451
6452 /// This function should return true if the type of the \p AA is
6453 /// AADenormalFPMath.
6454 static bool classof(const AbstractAttribute *AA) {
6455 return (AA->getIdAddr() == &ID);
6456 }
6457
6458 /// Unique ID (due to the unique address)
6459 LLVM_ABI static const char ID;
6460};
6461
6462/// Run options, used by the pass manager.
6473
6474namespace AA {
6475/// Helper to avoid creating an AA for IR Attributes that might already be set.
6476template <Attribute::AttrKind AK, typename AAType = AbstractAttribute>
6478 const IRPosition &IRP, DepClassTy DepClass, bool &IsKnown,
6479 bool IgnoreSubsumingPositions = false,
6480 const AAType **AAPtr = nullptr) {
6481 IsKnown = false;
6482 switch (AK) {
6483#define CASE(ATTRNAME, AANAME, ...) \
6484 case Attribute::ATTRNAME: { \
6485 if (AANAME::isImpliedByIR(A, IRP, AK, IgnoreSubsumingPositions)) \
6486 return IsKnown = true; \
6487 if (!QueryingAA) \
6488 return false; \
6489 const auto *AA = A.getAAFor<AANAME>(*QueryingAA, IRP, DepClass); \
6490 if (AAPtr) \
6491 *AAPtr = reinterpret_cast<const AAType *>(AA); \
6492 if (!AA || !AA->isAssumed(__VA_ARGS__)) \
6493 return false; \
6494 IsKnown = AA->isKnown(__VA_ARGS__); \
6495 return true; \
6496 }
6497 CASE(NoUnwind, AANoUnwind, );
6498 CASE(WillReturn, AAWillReturn, );
6499 CASE(NoFree, AANoFree, );
6500 CASE(Captures, AANoCapture, );
6501 CASE(NoRecurse, AANoRecurse, );
6502 CASE(NoReturn, AANoReturn, );
6503 CASE(NoSync, AANoSync, );
6504 CASE(NoAlias, AANoAlias, );
6505 CASE(NonNull, AANonNull, );
6506 CASE(MustProgress, AAMustProgress, );
6507 CASE(NoUndef, AANoUndef, );
6511#undef CASE
6512 default:
6513 llvm_unreachable("hasAssumedIRAttr not available for this attribute kind");
6514 };
6515}
6516} // namespace AA
6517
6518} // end namespace llvm
6519
6520#endif // LLVM_TRANSFORMS_IPO_ATTRIBUTOR_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
unsigned uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file defines the BumpPtrAllocator interface.
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
This file contains the simple types necessary to represent the attributes associated with functions a...
static cl::opt< unsigned, true > MaxPotentialValues("attributor-max-potential-values", cl::Hidden, cl::desc("Maximum number of potential values to be " "tracked for each position."), cl::location(llvm::PotentialConstantIntValuesState::MaxPotentialValues), cl::init(7))
#define CASE(ATTRNAME, AANAME,...)
static const Function * getParent(const Value *V)
block Block Frequency Analysis
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< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This header provides classes for managing passes over SCCs of the call graph.
This file provides interfaces used to manipulate a call graph, regardless if it is a "old style" Call...
#define LLVM_ABI
Definition Compiler.h:215
This file contains the declarations for the subclasses of Constant, which represent the different fla...
DXIL Resource Access
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
This file defines the DenseSet and SmallDenseSet classes.
This file defines the little GraphTraits<X> template class that should be specialized by classes that...
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
This file implements a coalescing interval map for small objects.
Implements a lazy call graph analysis and related passes for the new pass manager.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
#define H(x, y, z)
Definition MD5.cpp:56
This file implements a map that provides insertion order iteration.
This file provides utility analysis objects describing memory locations.
Contains a collection of routines for determining if a given instruction is guaranteed to execute if ...
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
ppc ctr loops verify
Basic Register Allocator
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file contains some templates that are useful if you are working with the STL at all.
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file defines generic set operations that may be used on set's of different types,...
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallSet class.
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
Value * RHS
Value * LHS
An Iterator for call edges, creates AACallEdges attributes in a lazy way.
LLVM_ABI AACallGraphNode * operator*() const
Class for arbitrary precision integers.
Definition APInt.h:78
CallBase * getInstruction() const
Return the underlying instruction.
int getCallArgOperandNo(Argument &Arg) const
Return the operand index of the underlying instruction associated with Arg.
unsigned getNumArgOperands() const
Return the number of parameters of the callee.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
const Function * getParent() const
Definition Argument.h:44
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
This represents the llvm.assume intrinsic.
This class stores enough information to efficiently remove some attributes from an existing AttrBuild...
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:410
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:106
static LLVM_ABI Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:125
@ None
No attributes have been set.
Definition Attributes.h:127
static bool isEnumAttrKind(AttrKind Kind)
Definition Attributes.h:139
LLVM Basic Block Representation.
Definition BasicBlock.h:62
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
const Use & getArgOperandUse(unsigned i) const
Wrappers for getting the Use of a call argument.
Wrapper to unify "old style" CallGraph and "new style" LazyCallGraph.
This class represents a range of values.
const APInt * getSingleElement() const
If this set contains a single element, return it, otherwise return null.
LLVM_ABI bool isEmptySet() const
Return true if this set contains no members.
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
static bool shouldExecute(CounterInfo &Counter)
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
An instruction for ordering other memory operations.
Argument * arg_iterator
Definition Function.h:73
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:329
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Definition Function.h:332
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:217
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:730
bool hasLocalLinkage() const
typename Sizer::Allocator Allocator
Invoke instruction.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
An SCC of the call graph.
A lazily constructed view of the call graph of a module.
An instruction for reading from memory.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:594
bool onlyReadsMemory() const
Whether this function only (at most) reads memory.
Definition ModRef.h:249
static MemoryEffectsBase unknown()
Definition ModRef.h:123
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
The optimization diagnostic interface.
Pass interface - Implemented by all 'passes'.
Definition Pass.h:99
PointerIntPair - This class implements a pair of a pointer and small integer.
PointerTy getPointer() const
void setFromOpaqueValue(void *Val) &
Analysis pass which computes a PostDominatorTree.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
A vector that has set insertion semantics.
Definition SetVector.h:57
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
typename vector_type::const_iterator iterator
Definition SetVector.h:72
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
iterator begin()
Get an iterator to the beginning of the SetVector.
Definition SetVector.h:112
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
iterator find(ConstPtrType Ptr) const
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
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
SmallSetIterator< int64_t, N, std::less< int64_t > > const_iterator
Definition SmallSet.h:150
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
LLVM_ABI SubsumingPositionIterator(const IRPosition &IRP)
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
The TimeTraceScope is a helper class to call the begin and end functions of the time trace profiler.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:280
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:712
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
An efficient, type-erasing, non-owning reference to a callable.
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:165
LLVM_ABI bool isAssumedReadNone(Attributor &A, const IRPosition &IRP, const AbstractAttribute &QueryingAA, bool &IsKnown)
Return true if IRP is readnone.
LLVM_ABI bool isAssumedReadOnly(Attributor &A, const IRPosition &IRP, const AbstractAttribute &QueryingAA, bool &IsKnown)
Return true if IRP is readonly.
raw_ostream & operator<<(raw_ostream &OS, const RangeTy &R)
Definition Attributor.h:327
LLVM_ABI std::optional< Value * > combineOptionalValuesInAAValueLatice(const std::optional< Value * > &A, const std::optional< Value * > &B, Type *Ty)
Return the combination of A and B such that the result is a possible value of both.
LLVM_ABI bool isValidAtPosition(const ValueAndContext &VAC, InformationCache &InfoCache)
Return true if the value of VAC is a valid at the position of VAC, that is a constant,...
LLVM_ABI bool isAssumedThreadLocalObject(Attributor &A, Value &Obj, const AbstractAttribute &QueryingAA)
Return true if Obj is assumed to be a thread local object.
LLVM_ABI bool isGPUConstantAddressSpace(const Module &M, unsigned AS)
Check if the given address space AS corresponds to a GPU constant address space for the target triple...
LLVM_ABI bool isDynamicallyUnique(Attributor &A, const AbstractAttribute &QueryingAA, const Value &V, bool ForAnalysisOnly=true)
Return true if V is dynamically unique, that is, there are no two "instances" of V at runtime with di...
LLVM_ABI bool getPotentialCopiesOfStoredValue(Attributor &A, StoreInst &SI, SmallSetVector< Value *, 4 > &PotentialCopies, const AbstractAttribute &QueryingAA, bool &UsedAssumedInformation, bool OnlyExact=false)
Collect all potential values of the one stored by SI into PotentialCopies.
LLVM_ABI bool isGPUSharedAddressSpace(const Module &M, unsigned AS)
Check if the given address space AS corresponds to a GPU shared address space for the target triple i...
bool operator!=(const RangeTy &A, const RangeTy &B)
Definition Attributor.h:336
LLVM_ABI bool isGPULocalAddressSpace(const Module &M, unsigned AS)
Check if the given address space AS corresponds to a GPU local/private address space for the target t...
LLVM_ABI bool isPotentiallyAffectedByBarrier(Attributor &A, const Instruction &I, const AbstractAttribute &QueryingAA)
Return true if I is potentially affected by a barrier.
SmallPtrSet< Instruction *, 4 > InstExclusionSetTy
Definition Attributor.h:166
LLVM_ABI bool isGPU(const Module &M)
Return true iff M target a GPU (and we can use GPU AS reasoning).
LLVM_ABI Constant * getInitialValueForObj(Attributor &A, const AbstractAttribute &QueryingAA, Value &Obj, Type &Ty, const TargetLibraryInfo *TLI, const DataLayout &DL, RangeTy *RangePtr=nullptr)
Return the initial value of Obj with type Ty if that is a constant.
bool operator==(const RangeTy &A, const RangeTy &B)
Definition Attributor.h:332
ValueScope
Flags to distinguish intra-procedural queries from potentially inter-procedural queries.
Definition Attributor.h:186
@ Intraprocedural
Definition Attributor.h:187
@ Interprocedural
Definition Attributor.h:188
LLVM_ABI bool isValidInScope(const Value &V, const Function *Scope)
Return true if V is a valid value in Scope, that is a constant or an instruction/argument of Scope.
LLVM_ABI bool isPotentiallyReachable(Attributor &A, const Instruction &FromI, const Instruction &ToI, const AbstractAttribute &QueryingAA, const AA::InstExclusionSetTy *ExclusionSet=nullptr, std::function< bool(const Function &F)> GoBackwardsCB=nullptr)
Return true if ToI is potentially reachable from FromI without running into any instruction in Exclus...
LLVM_ABI bool isNoSyncInst(Attributor &A, const Instruction &I, const AbstractAttribute &QueryingAA)
Return true if I is a nosync instruction.
bool hasAssumedIRAttr(Attributor &A, const AbstractAttribute *QueryingAA, const IRPosition &IRP, DepClassTy DepClass, bool &IsKnown, bool IgnoreSubsumingPositions=false, const AAType **AAPtr=nullptr)
Helper to avoid creating an AA for IR Attributes that might already be set.
LLVM_ABI bool getPotentiallyLoadedValues(Attributor &A, LoadInst &LI, SmallSetVector< Value *, 4 > &PotentialValues, SmallSetVector< Instruction *, 4 > &PotentialValueOrigins, const AbstractAttribute &QueryingAA, bool &UsedAssumedInformation, bool OnlyExact=false)
Collect all potential values LI could read into PotentialValues.
LLVM_ABI Value * getWithType(Value &V, Type &Ty)
Try to convert V to type Ty without introducing new instructions.
E & operator^=(E &LHS, E RHS)
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
bool isEqual(const GCNRPTracker::LiveRegSet &S1, const GCNRPTracker::LiveRegSet &S2)
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
LLVM_ABI unsigned MaxInitializationChainLength
The value passed to the line option that defines the maximal initialization chain length.
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
APInt operator&(APInt a, const APInt &b)
Definition APInt.h:2149
@ Known
Known to have no common set bits.
void set_intersect(S1Ty &S1, const S2Ty &S2)
set_intersect(A, B) - Compute A := A ^ B Identical to set_intersection, except that it works on set<>...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
bool operator!=(uint64_t V1, const APInt &V2)
Definition APInt.h:2139
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
LLVM_ATTRIBUTE_ALWAYS_INLINE DynamicAPInt & operator+=(DynamicAPInt &A, int64_t B)
bool set_is_subset(const S1Ty &S1, const S2Ty &S2)
set_is_subset(A, B) - Return true iff A in B
auto cast_or_null(const Y &Val)
Definition Casting.h:714
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:356
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
AttributorRunOption
Run options, used by the pass manager.
@ CGSCC_LIGHT
@ MODULE_LIGHT
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
AnalysisManager< LazyCallGraph::SCC, LazyCallGraph & > CGSCCAnalysisManager
The CGSCC analysis manager.
LLVM_ABI bool canSimplifyInvokeNoUnwind(const Function *F)
DenseMap< RetainedKnowledgeKey, Assume2KnowledgeMap > RetainedKnowledgeMap
PotentialValuesState< std::pair< AA::ValueAndContext, AA::ValueScope > > PotentialLLVMValuesState
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool set_union(S1Ty &S1, const S2Ty &S2)
set_union(A, B) - Compute A := A u B, return whether A changed.
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
@ Success
The lock was released successfully.
iterator_range(Container &&) -> iterator_range< llvm::detail::IterOfRange< Container > >
@ Other
Any other memory.
Definition ModRef.h:68
PotentialValuesState< APInt > PotentialConstantIntValuesState
bool operator&=(SparseBitVector< ElementSize > *LHS, const SparseBitVector< ElementSize > &RHS)
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ChangeStatus clampStateAndIndicateChange(StateType &S, const StateType &R)
Helper function to clamp a state S of type StateType with the information in R and indicate/return if...
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
ChangeStatus
{
Definition Attributor.h:477
bool operator|=(SparseBitVector< ElementSize > &LHS, const SparseBitVector< ElementSize > *RHS)
@ OPTIONAL
The target may be valid if the source is not.
Definition Attributor.h:489
@ NONE
Do not track a dependence between source and target.
Definition Attributor.h:490
@ REQUIRED
The target cannot be valid if the source is not.
Definition Attributor.h:488
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
APInt operator|(APInt a, const APInt &b)
Definition APInt.h:2169
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:390
IncIntegerState< uint64_t, Value::MaximumAlignment, 1 > AAAlignmentStateType
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
static LLVM_ABI AAAddressSpace & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
static bool requiresCallersForArgOrFunction()
See AbstractAttribute::requiresCallersForArgOrFunction.
StringRef getName() const override
See AbstractAttribute::getName()
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AAAssumptionInfo.
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
See AbstractAttribute::isValidIRPositionForInit.
virtual uint32_t getAddressSpace() const =0
Return the address space of the associated value.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
AAAddressSpace(const IRPosition &IRP, Attributor &A)
static const uint32_t InvalidAddressSpace
AAAlign(const IRPosition &IRP, Attributor &A)
static LLVM_ABI AAAlign & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
See AbstractAttribute::isValidIRPositionForInit.
Align getAssumedAlign() const
Return assumed alignment.
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AAAlign.
Align getKnownAlign() const
Return known alignment.
StringRef getName() const override
See AbstractAttribute::getName()
static LLVM_ABI const char ID
virtual std::optional< TypeSize > getAllocatedSize() const =0
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
See AbstractAttribute::isValidIRPositionForInit.
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
static LLVM_ABI AAAllocationInfo & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
StringRef getName() const override
See AbstractAttribute::getName()
AAAllocationInfo(const IRPosition &IRP, Attributor &A)
static constexpr const std::optional< TypeSize > HasNoAllocationSize
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AAAllocationInfo.
AAAssumptionInfo(const IRPosition &IRP, Attributor &A, const DenseSet< StringRef > &Known)
static LLVM_ABI const char ID
Unique ID (due to the unique address)
StringRef getName() const override
See AbstractAttribute::getName()
static LLVM_ABI AAAssumptionInfo & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
StateWrapper< SetState< StringRef >, AbstractAttribute, DenseSet< StringRef > > Base
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AAAssumptionInfo.
virtual bool hasAssumption(const StringRef Assumption) const =0
Returns true if the assumption set contains the assumption Assumption.
An abstract state for querying live call edges.
AACallEdges(const IRPosition &IRP, Attributor &A)
virtual const SetVector< Function * > & getOptimisticEdges() const =0
Get the optimistic edges.
static bool requiresNonAsmForCallBase()
See AbstractAttribute::requiresNonAsmForCallBase.
StateWrapper< BooleanState, AbstractAttribute > Base
AACallEdgeIterator optimisticEdgesBegin() const override
Iterator for exploring the call graph.
virtual bool hasUnknownCallee() const =0
Is there any call with a unknown callee.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
StringRef getName() const override
See AbstractAttribute::getName()
virtual bool hasNonAsmUnknownCallee() const =0
Is there any call with a unknown callee, excluding any inline asm.
AACallEdgeIterator optimisticEdgesEnd() const override
Iterator for exploring the call graph.
static LLVM_ABI AACallEdges & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AACallEdges.
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
iterator_range< AACallEdgeIterator > optimisticEdgesRange() const
Iterator range for exploring the call graph.
virtual AACallEdgeIterator optimisticEdgesBegin() const =0
AACallGraphNode(Attributor &A)
virtual AACallEdgeIterator optimisticEdgesEnd() const =0
virtual ~AACallGraphNode()=default
Attributor & A
Reference to Attributor needed for GraphTraits implementation.
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
StringRef getName() const override
See AbstractAttribute::getName()
AADenormalFPMath(const IRPosition &IRP, Attributor &A)
static LLVM_ABI const char ID
Unique ID (due to the unique address)
StateWrapper< DenormalFPMathState, AbstractAttribute > Base
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AADenormalFPMath.
static LLVM_ABI AADenormalFPMath & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
static AbstractAttribute * DepGetValAA(const DepTy &DT)
Definition Attributor.h:507
friend struct Attributor
Definition Attributor.h:528
mapped_iterator< DepSetTy::iterator, decltype(&DepGetVal)> iterator
Definition Attributor.h:514
mapped_iterator< DepSetTy::iterator, decltype(&DepGetValAA)> aaiterator
Definition Attributor.h:515
virtual ~AADepGraphNode()=default
SmallSetVector< DepTy, 2 > DepSetTy
Definition Attributor.h:499
static AADepGraphNode * DepGetVal(const DepTy &DT)
Definition Attributor.h:506
iterator child_begin()
Definition Attributor.h:520
DepSetTy Deps
Set of dependency graph nodes which should be updated if this one is updated.
Definition Attributor.h:504
friend struct AADepGraph
Definition Attributor.h:529
virtual void print(Attributor *, raw_ostream &OS) const
Definition Attributor.h:524
aaiterator begin()
Definition Attributor.h:518
PointerIntPair< AADepGraphNode *, 1 > DepTy
Definition Attributor.h:498
void print(raw_ostream &OS) const
Definition Attributor.h:523
The data structure for the dependency graph.
Definition Attributor.h:537
~AADepGraph()=default
iterator begin()
Definition Attributor.h:552
mapped_iterator< AADepGraphNode::DepSetTy::iterator, decltype(&DepGetVal)> iterator
Definition Attributor.h:543
LLVM_ABI void viewGraph()
AADepGraphNode SyntheticRoot
There is no root node for the dependency graph.
Definition Attributor.h:549
LLVM_ABI void print()
Print dependency graph.
static AADepGraphNode * DepGetVal(const DepTy &DT)
Definition Attributor.h:542
iterator end()
Definition Attributor.h:553
LLVM_ABI void dumpGraph()
Dump graph to file.
AADepGraphNode * GetEntryNode()
Definition Attributor.h:550
AADepGraph()=default
AADepGraphNode::DepTy DepTy
Definition Attributor.h:541
uint32_t getKnownDereferenceableBytes() const
Return known dereferenceable bytes.
bool isAssumedGlobal() const
Return true if we assume that underlying value is dereferenceable(_or_null) globally.
bool isKnownGlobal() const
Return true if we know that underlying value is dereferenceable(_or_null) globally.
AADereferenceable(const IRPosition &IRP, Attributor &A)
uint32_t getAssumedDereferenceableBytes() const
Return assumed dereferenceable bytes.
StringRef getName() const override
See AbstractAttribute::getName()
static LLVM_ABI const char ID
Unique ID (due to the unique address)
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AADereferenceable.
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
See AbstractAttribute::isValidIRPositionForInit.
static LLVM_ABI AADereferenceable & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
Summary about the execution domain of a block or instruction.
void addAssumeInst(Attributor &A, AssumeInst &AI)
SmallPtrSet< AssumeInst *, 4 > AssumesSetTy
void addAlignedBarrier(Attributor &A, CallBase &CB)
SmallPtrSet< CallBase *, 2 > BarriersSetTy
virtual bool isExecutedByInitialThreadOnly(const BasicBlock &) const =0
Check if a basic block is executed only by the initial thread.
StateWrapper< BooleanState, AbstractAttribute > Base
bool isExecutedByInitialThreadOnly(const Instruction &I) const
Check if an instruction is executed only by the initial thread.
static LLVM_ABI AAExecutionDomain & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AAExecutionDomain.
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr().
virtual ExecutionDomainTy getFunctionExecutionDomain() const =0
virtual ExecutionDomainTy getExecutionDomain(const BasicBlock &) const =0
virtual bool isExecutedInAlignedRegion(Attributor &A, const Instruction &I) const =0
Check if the instruction I is executed in an aligned region, that is, the synchronizing effects befor...
AAExecutionDomain(const IRPosition &IRP, Attributor &A)
virtual bool isNoOpFence(const FenceInst &FI) const =0
Helper function to determine if FI is a no-op given the information about its execution from ExecDoma...
StringRef getName() const override
See AbstractAttribute::getName().
virtual std::pair< ExecutionDomainTy, ExecutionDomainTy > getExecutionDomain(const CallBase &CB) const =0
Return the execution domain with which the call CB is entered and the one with which it is left.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AAGlobalValueInfo.
AAGlobalValueInfo(const IRPosition &IRP, Attributor &A)
StringRef getName() const override
See AbstractAttribute::getName()
static LLVM_ABI AAGlobalValueInfo & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
See AbstractAttribute::isValidIRPositionForInit.
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
static LLVM_ABI const char ID
Unique ID (due to the unique address)
virtual bool isPotentialUse(const Use &U) const =0
Return true iff U is a potential use of the associated global value.
StringRef getName() const override
See AbstractAttribute::getName()
StateWrapper< BooleanState, AbstractAttribute > Base
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AAHeapToStack.
virtual bool isAssumedHeapToStack(const CallBase &CB) const =0
Returns true if HeapToStack conversion is assumed to be possible.
virtual bool isAssumedHeapToStackRemovedFree(CallBase &CB) const =0
Returns true if HeapToStack conversion is assumed and the CB is a callsite to a free operation to be ...
static LLVM_ABI const char ID
Unique ID (due to the unique address)
static LLVM_ABI AAHeapToStack & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
AAHeapToStack(const IRPosition &IRP, Attributor &A)
StringRef getName() const override
See AbstractAttribute::getName()
virtual bool foreachCallee(function_ref< bool(Function *)> CB) const =0
Call \CB on each potential callee value and return true if all were known and CB returned true on all...
AAIndirectCallInfo(const IRPosition &IRP, Attributor &A)
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AAIndirectCallInfo This function should ret...
static LLVM_ABI const char ID
Unique ID (due to the unique address)
static LLVM_ABI AAIndirectCallInfo & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
See AbstractAttribute::isValidIRPositionForInit.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
StringRef getName() const override
See AbstractAttribute::getName()
AAInstanceInfo(const IRPosition &IRP, Attributor &A)
bool isAssumedUniqueForAnalysis() const
Return true if we assume that the underlying value is unique in its scope wrt.
static LLVM_ABI AAInstanceInfo & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AAInstanceInfo.
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AACallEdges.
static LLVM_ABI AAInterFnReachability & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
bool canReach(Attributor &A, const Function &Fn) const
If the function represented by this possition can reach Fn.
StringRef getName() const override
See AbstractAttribute::getName()
virtual bool instructionCanReach(Attributor &A, const Instruction &Inst, const Function &Fn, const AA::InstExclusionSetTy *ExclusionSet=nullptr) const =0
Can Inst reach Fn.
AAInterFnReachability(const IRPosition &IRP, Attributor &A)
StateWrapper< BooleanState, AbstractAttribute > Base
static LLVM_ABI AAIntraFnReachability & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AAIntraFnReachability.
AAIntraFnReachability(const IRPosition &IRP, Attributor &A)
StringRef getName() const override
See AbstractAttribute::getName()
static LLVM_ABI const char ID
Unique ID (due to the unique address)
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
virtual bool isAssumedReachable(Attributor &A, const Instruction &From, const Instruction &To, const AA::InstExclusionSetTy *ExclusionSet=nullptr) const =0
Returns true if 'From' instruction is assumed to reach, 'To' instruction.
StateWrapper< BooleanState, AbstractAttribute > Base
An abstract interface for identifying pointers from which loads can be marked invariant.
virtual bool isAssumedInvariant() const =0
Return true if the pointer's contents are assumed to remain invariant.
static LLVM_ABI AAInvariantLoadPointer & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
virtual bool isAssumedLocallyInvariant() const =0
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AAInvariantLoadPointer.
static LLVM_ABI const char ID
Unique ID (due to the unique address).
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr().
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
See AbstractAttribute::isValidIRPositionForInit.
StringRef getName() const override
See AbstractAttribute::getName().
virtual bool isKnownInvariant() const =0
Return true if the pointer's contents are known to remain invariant.
AAInvariantLoadPointer(const IRPosition &IRP)
virtual bool isKnownLocallyInvariant() const =0
An abstract interface for liveness abstract attribute.
friend struct Attributor
virtual bool isKnownDead(const BasicBlock *BB) const =0
Returns true if BB is known dead.
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AAIsDead.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
virtual bool isKnownDead() const =0
Returns true if the underlying value is known dead.
virtual bool isEdgeDead(const BasicBlock *From, const BasicBlock *To) const
Return if the edge from From BB to To BB is assumed dead.
virtual bool isAssumedDead(const Instruction *I) const =0
Returns true if I is assumed dead.
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
See AbstractAttribute::isValidIRPositionForInit.
StringRef getName() const override
See AbstractAttribute::getName()
virtual bool isAssumedDead() const =0
The query functions are protected such that other attributes need to go through the Attributor interf...
virtual bool isRemovableStore() const
Return true if the underlying value is a store that is known to be removable.
virtual bool isAssumedDead(const BasicBlock *BB) const =0
Returns true if BB is assumed dead.
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
StateWrapper< BitIntegerState< uint8_t, 3, 0 >, AbstractAttribute > Base
static LLVM_ABI AAIsDead & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
static bool mayCatchAsynchronousExceptions(const Function &F)
Determine if F might catch asynchronous exceptions.
AAIsDead(const IRPosition &IRP, Attributor &A)
virtual bool isKnownDead(const Instruction *I) const =0
Returns true if I is known dead.
An abstract interface for memory access kind related attributes (readnone/readonly/writeonly).
StringRef getName() const override
See AbstractAttribute::getName()
bool isAssumedReadOnly() const
Return true if we assume that the underlying value is not accessed (=written) in its respective scope...
static LLVM_ABI AAMemoryBehavior & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
static bool hasTrivialInitializer()
See AbstractAttribute::hasTrivialInitializer.
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AAMemoryBehavior.
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
See AbstractAttribute::isValidIRPositionForInit.
bool isKnownReadNone() const
Return true if we know that the underlying value is not read or accessed in its respective scope.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
bool isKnownWriteOnly() const
Return true if we know that the underlying value is not read in its respective scope.
bool isAssumedReadNone() const
Return true if we assume that the underlying value is not read or accessed in its respective scope.
bool isAssumedWriteOnly() const
Return true if we assume that the underlying value is not read in its respective scope.
AAMemoryBehavior(const IRPosition &IRP, Attributor &A)
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
bool isKnownReadOnly() const
Return true if we know that the underlying value is not accessed (=written) in its respective scope.
StringRef getName() const override
See AbstractAttribute::getName()
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
bool isAssumedStackOnly() const
Return true if we assume that the associated functions has at most local/stack accesses.
static LLVM_ABI std::string getMemoryLocationsAsStr(MemoryLocationsKind MLK)
Return the locations encoded by MLK as a readable string.
bool isKnownArgMemOnly() const
Return true if we know that the underlying value will only access argument pointees (see Attribute::A...
bool isKnownInaccessibleOrArgMemOnly() const
Return true if we know that the underlying value will only access inaccesible memory or argument poin...
static LLVM_ABI const char ID
Unique ID (due to the unique address)
AAMemoryLocation(const IRPosition &IRP, Attributor &A)
bool isKnownReadNone() const
Return true if we know that the associated functions has no observable accesses.
bool isAssumedSpecifiedMemOnly(MemoryLocationsKind MLK) const
Return true if only the memory locations specififed by MLK are assumed to be accessed by the associat...
bool isAssumedInaccessibleMemOnly() const
Return true if we assume that the underlying value will only access inaccesible memory only (see Attr...
bool isKnownInaccessibleMemOnly() const
Return true if we know that the underlying value will only access inaccesible memory only (see Attrib...
static LLVM_ABI AAMemoryLocation & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
bool isAssumedInaccessibleOrArgMemOnly() const
Return true if we assume that the underlying value will only access inaccesible memory or argument po...
bool isKnowStackOnly() const
Return true if we know that the associated functions has at most local/stack accesses.
static bool requiresCalleeForCallBase()
See AbstractAttribute::requiresCalleeForCallBase.
AccessKind
Simple enum to distinguish read/write/read-write accesses.
StateType::base_t MemoryLocationsKind
MemoryLocationsKind getAssumedNotAccessedLocation() const
Return the locations that are assumed to be not accessed by the associated function,...
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AAMemoryLocation.
static bool hasTrivialInitializer()
See AbstractAttribute::hasTrivialInitializer.
bool isAssumedReadNone() const
Return true if we assume that the associated functions has no observable accesses.
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
See AbstractAttribute::isValidIRPositionForInit.
virtual bool checkForAllAccessesToMemoryKind(function_ref< bool(const Instruction *, const Value *, AccessKind, MemoryLocationsKind)> Pred, MemoryLocationsKind MLK) const =0
Check Pred on all accesses to the memory kinds specified by MLK.
const std::string getAsStr(Attributor *A) const override
See AbstractState::getAsStr(Attributor).
bool mayAccessArgMem() const
Return true if the underlying value may access memory through arguement pointers of the associated fu...
bool isAssumedArgMemOnly() const
Return true if we assume that the underlying value will only access argument pointees (see Attribute:...
static MemoryLocationsKind inverseLocation(MemoryLocationsKind Loc, bool AndLocalMem, bool AndConstMem)
Return the inverse of location Loc, thus for NO_XXX the return describes ONLY_XXX.
An abstract interface for all nonnull attributes.
StringRef getName() const override
See AbstractAttribute::getName()
bool isKnownMustProgress() const
Return true if we know that underlying value is nonnull.
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AAMustProgress.
bool isAssumedMustProgress() const
Return true if we assume that the underlying value is nonnull.
static bool isImpliedByIR(Attributor &A, const IRPosition &IRP, Attribute::AttrKind ImpliedAttributeKind, bool IgnoreSubsumingPositions=false)
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
static LLVM_ABI AAMustProgress & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
AAMustProgress(const IRPosition &IRP, Attributor &A)
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AAAssumptionInfo.
static bool requiresCallersForArgOrFunction()
See AbstractAttribute::requiresCallersForArgOrFunction.
IntervalMap< unsigned, bool > RangeMap
static LLVM_ABI AANoAliasAddrSpace & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
See AbstractAttribute::isValidIRPositionForInit.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
AANoAliasAddrSpace(const IRPosition &IRP, Attributor &A)
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
StateWrapper< BooleanState, AbstractAttribute > Base
RangeMap::Allocator Allocator
StringRef getName() const override
See AbstractAttribute::getName()
An abstract interface for all noalias attributes.
static LLVM_ABI bool isImpliedByIR(Attributor &A, const IRPosition &IRP, Attribute::AttrKind ImpliedAttributeKind, bool IgnoreSubsumingPositions=false)
See IRAttribute::isImpliedByIR.
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AANoAlias.
StringRef getName() const override
See AbstractAttribute::getName()
static bool requiresCallersForArgOrFunction()
See AbstractAttribute::requiresCallersForArgOrFunction.
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
bool isKnownNoAlias() const
Return true if we know that underlying value is noalias.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
bool isAssumedNoAlias() const
Return true if we assume that the underlying value is alias.
static LLVM_ABI AANoAlias & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
AANoAlias(const IRPosition &IRP, Attributor &A)
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
See AbstractAttribute::isValidIRPositionForInit.
An abstract interface for all nocapture attributes.
static LLVM_ABI AANoCapture & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
See AbstractAttribute::isValidIRPositionForInit.
@ NO_CAPTURE_MAYBE_RETURNED
If we do not capture the value in memory or through integers we can only communicate it back as a der...
@ NO_CAPTURE
If we do not capture the value in memory, through integers, or as a derived pointer we know it is not...
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
AANoCapture(const IRPosition &IRP, Attributor &A)
StringRef getName() const override
See AbstractAttribute::getName()
static LLVM_ABI const char ID
Unique ID (due to the unique address)
bool isAssumedNoCaptureMaybeReturned() const
Return true if we assume that the underlying value is not captured in its respective scope but we all...
bool isKnownNoCapture() const
Return true if we know that the underlying value is not captured in its respective scope.
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AANoCapture.
bool isKnownNoCaptureMaybeReturned() const
Return true if we know that the underlying value is not captured in its respective scope but we allow...
static LLVM_ABI bool isImpliedByIR(Attributor &A, const IRPosition &IRP, Attribute::AttrKind ImpliedAttributeKind, bool IgnoreSubsumingPositions=false)
See IRAttribute::isImpliedByIR.
bool isAssumedNoCapture() const
Return true if we assume that the underlying value is not captured in its respective scope.
static LLVM_ABI void determineFunctionCaptureCapabilities(const IRPosition &IRP, const Function &F, BitIntegerState &State)
Update State according to the capture capabilities of F for position IRP.
FPClassTest getAssumedNoFPClass() const
Return the underlying assumed nofpclass.
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
See AbstractAttribute::isValidIRPositionForInit.
AANoFPClass(const IRPosition &IRP, Attributor &A)
StringRef getName() const override
See AbstractAttribute::getName()
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AANoFPClass.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
FPClassTest getKnownNoFPClass() const
Return the underlying known nofpclass.
StateWrapper< BitIntegerState< uint32_t, fcAllFlags, fcNone >, AbstractAttribute > Base
static LLVM_ABI AANoFPClass & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
An AbstractAttribute for nofree.
bool isKnownNoFree() const
Return true if "nofree" is known.
static LLVM_ABI AANoFree & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
AANoFree(const IRPosition &IRP, Attributor &A)
static bool isImpliedByIR(Attributor &A, const IRPosition &IRP, Attribute::AttrKind ImpliedAttributeKind, bool IgnoreSubsumingPositions=false)
See IRAttribute::isImpliedByIR.
bool isAssumedNoFree() const
Return true if "nofree" is assumed.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
See AbstractAttribute::isValidIRPositionForInit.
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AANoFree.
StringRef getName() const override
See AbstractAttribute::getName()
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
An abstract attribute for norecurse.
StringRef getName() const override
See AbstractAttribute::getName()
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AANoRecurse.
AANoRecurse(const IRPosition &IRP, Attributor &A)
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
bool isAssumedNoRecurse() const
Return true if "norecurse" is assumed.
static LLVM_ABI AANoRecurse & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
bool isKnownNoRecurse() const
Return true if "norecurse" is known.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An AbstractAttribute for noreturn.
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AANoReturn.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
bool isAssumedNoReturn() const
Return true if the underlying object is assumed to never return.
static LLVM_ABI AANoReturn & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
StringRef getName() const override
See AbstractAttribute::getName()
AANoReturn(const IRPosition &IRP, Attributor &A)
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
bool isKnownNoReturn() const
Return true if the underlying object is known to never return.
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
See AbstractAttribute::isValidIRPositionForInit.
AANoSync(const IRPosition &IRP, Attributor &A)
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
StringRef getName() const override
See AbstractAttribute::getName()
static bool isImpliedByIR(Attributor &A, const IRPosition &IRP, Attribute::AttrKind ImpliedAttributeKind, bool IgnoreSubsumingPositions=false)
static LLVM_ABI const char ID
Unique ID (due to the unique address)
static LLVM_ABI bool isAlignedBarrier(const CallBase &CB, bool ExecutedAligned)
Helper function to determine if CB is an aligned (GPU) barrier.
bool isAssumedNoSync() const
Returns true if "nosync" is assumed.
static LLVM_ABI bool isNonRelaxedAtomic(const Instruction *I)
Helper function used to determine whether an instruction is non-relaxed atomic.
bool isKnownNoSync() const
Returns true if "nosync" is known.
static LLVM_ABI AANoSync & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AANoSync.
An abstract interface for all noundef attributes.
bool isKnownNoUndef() const
Return true if we know that underlying value is noundef.
static bool isImpliedByUndef()
See IRAttribute::isImpliedByUndef.
StringRef getName() const override
See AbstractAttribute::getName()
bool isAssumedNoUndef() const
Return true if we assume that the underlying value is noundef.
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AANoUndef.
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
static LLVM_ABI AANoUndef & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
AANoUndef(const IRPosition &IRP, Attributor &A)
static LLVM_ABI const char ID
Unique ID (due to the unique address)
static bool isImpliedByPoison()
See IRAttribute::isImpliedByPoison.
static LLVM_ABI bool isImpliedByIR(Attributor &A, const IRPosition &IRP, Attribute::AttrKind ImpliedAttributeKind, bool IgnoreSubsumingPositions=false)
See IRAttribute::isImpliedByIR.
AANoUnwind(const IRPosition &IRP, Attributor &A)
bool isAssumedNoUnwind() const
Returns true if nounwind is assumed.
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AANoUnwind.
StringRef getName() const override
See AbstractAttribute::getName()
static LLVM_ABI AANoUnwind & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
bool isKnownNoUnwind() const
Returns true if nounwind is known.
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
static LLVM_ABI const char ID
Unique ID (due to the unique address)
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
StateWrapper< BooleanState, AbstractAttribute > Base
static LLVM_ABI AANonConvergent & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
StringRef getName() const override
See AbstractAttribute::getName()
bool isAssumedNotConvergent() const
Return true if "non-convergent" is assumed.
bool isKnownNotConvergent() const
Return true if "non-convergent" is known.
AANonConvergent(const IRPosition &IRP, Attributor &A)
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AANonConvergent.
An abstract interface for all nonnull attributes.
static bool isImpliedByUndef()
See IRAttribute::isImpliedByUndef.
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
See AbstractAttribute::isValidIRPositionForInit.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AANonNull.
static LLVM_ABI AANonNull & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
AANonNull(const IRPosition &IRP, Attributor &A)
StringRef getName() const override
See AbstractAttribute::getName()
static LLVM_ABI bool isImpliedByIR(Attributor &A, const IRPosition &IRP, Attribute::AttrKind ImpliedAttributeKind, bool IgnoreSubsumingPositions=false)
See AbstractAttribute::isImpliedByIR(...).
bool isAssumedNonNull() const
Return true if we assume that the underlying value is nonnull.
bool isKnownNonNull() const
Return true if we know that underlying value is nonnull.
static bool hasTrivialInitializer()
See AbstractAttribute::hasTrivialInitializer.
An access description.
bool isWrittenValueUnknown() const
Return true if the value written cannot be determined at all.
const_iterator end() const
bool operator!=(const Access &R) const
std::optional< Value * > getContent() const
Return the written value which can be llvm::null if it is not yet determined.
Access & operator=(const Access &Other)=default
bool isAssumption() const
Return true if this is an assumption access.
const RangeList & getRanges() const
bool isWriteOrAssumption() const
Return true if this is a write access.
bool isRead() const
Return true if this is a read access.
bool isWrite() const
Return true if this is a write access.
Value * getWrittenValue() const
Return the value writen, if any.
Instruction * getLocalInst() const
Return the instruction that causes the access with respect to the local scope of the associated attri...
Access(Instruction *LocalI, Instruction *RemoteI, const RangeList &Ranges, std::optional< Value * > Content, AccessKind K, Type *Ty)
Access(Instruction *LocalI, Instruction *RemoteI, int64_t Offset, int64_t Size, std::optional< Value * > Content, AccessKind Kind, Type *Ty)
Access(Instruction *I, int64_t Offset, int64_t Size, std::optional< Value * > Content, AccessKind Kind, Type *Ty)
Access(const Access &Other)=default
Type * getType() const
Return the type associated with the access, if known.
Access & operator&=(const Access &R)
const_iterator begin() const
RangeList::const_iterator const_iterator
Instruction * getRemoteInst() const
Return the actual instruction that causes the access.
bool operator==(const Access &R) const
bool isWrittenValueYetUndetermined() const
Return true if the value written is not known yet.
AccessKind getKind() const
Return the access kind.
A helper containing a list of offsets computed for a Use.
SmallSet< int64_t, 4 > VecTy
VecTy::const_iterator const_iterator
bool operator==(const OffsetInfo &RHS) const
bool insert(int64_t Offset)
bool operator!=(const OffsetInfo &RHS) const
const_iterator begin() const
const_iterator end() const
bool merge(const OffsetInfo &R)
Copy offsets from R into the current list.
A container for a list of ranges.
const_iterator end() const
SmallVector< RangeTy > VecTy
void addToAllOffsets(int64_t Inc)
Add the increment Inc to the offset of every range.
bool operator==(const RangeList &OI) const
RangeList(ArrayRef< int64_t > Offsets, int64_t Size)
std::pair< iterator, bool > insert(iterator Pos, const RangeTy &R)
Insert R at the given iterator Pos, and merge if necessary.
bool isUnknown() const
Return true iff the list contains an unknown range.
VecTy::const_iterator const_iterator
const_iterator begin() const
bool isUnassigned() const
Return true if no ranges have been inserted.
static void set_difference(const RangeList &L, const RangeList &R, RangeList &D)
Copy ranges from L that are not in R, into D.
bool merge(const RangeList &RHS)
Merge the ranges in RHS into the current ranges.
iterator setUnknown()
Discard all ranges and insert a single unknown range.
void push_back(const RangeTy &R)
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
See AbstractAttribute::isValidIRPositionForInit.
virtual bool reachesReturn() const =0
StringRef getName() const override
See AbstractAttribute::getName()
virtual bool forallInterferingAccesses(Attributor &A, const AbstractAttribute &QueryingAA, Instruction &I, bool FindInterferingWrites, bool FindInterferingReads, function_ref< bool(const Access &, bool)> CB, bool &HasBeenWrittenTo, AA::RangeTy &Range, function_ref< bool(const Access &)> SkipCB=nullptr) const =0
Call CB on all accesses that might interfere with I and return true if all such accesses were known a...
virtual void addReturnedOffsetsTo(OffsetInfo &) const =0
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AAPointerInfo.
OffsetBinsTy::const_iterator const_bin_iterator
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
virtual const_bin_iterator begin() const =0
DenseMap< AA::RangeTy, SmallSet< unsigned, 4 > > OffsetBinsTy
virtual bool forallInterferingAccesses(AA::RangeTy Range, function_ref< bool(const Access &, bool)> CB) const =0
Call CB on all accesses that might interfere with Range and return true if all such accesses were kno...
virtual const_bin_iterator end() const =0
static LLVM_ABI const char ID
Unique ID (due to the unique address)
static LLVM_ABI AAPointerInfo & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
AAPointerInfo(const IRPosition &IRP)
virtual int64_t numOffsetBins() const =0
An abstract interface for potential values analysis.
PotentialConstantIntValuesState & getState() override
See AbstractAttribute::getState(...).
const PotentialConstantIntValuesState & getState() const override
AAPotentialConstantValues(const IRPosition &IRP, Attributor &A)
static LLVM_ABI const char ID
Unique ID (due to the unique address)
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AAPotentialConstantValues.
static bool requiresCallersForArgOrFunction()
See AbstractAttribute::requiresCallersForArgOrFunction.
unsigned getAssumedMinTrailingZeros() const
Return the minimum trailing zeros of potential constants.
std::optional< Constant * > getAssumedConstant(Attributor &A, const Instruction *CtxI=nullptr) const
Return assumed constant for the associated value.
StateWrapper< PotentialConstantIntValuesState, AbstractAttribute > Base
static LLVM_ABI AAPotentialConstantValues & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
StringRef getName() const override
See AbstractAttribute::getName()
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
See AbstractAttribute::isValidIRPositionForInit.
friend struct Attributor
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AAPotentialValues.
PotentialLLVMValuesState & getState() override
See AbstractAttribute::getState(...).
AAPotentialValues(const IRPosition &IRP, Attributor &A)
static LLVM_ABI AAPotentialValues & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
static bool requiresCallersForArgOrFunction()
See AbstractAttribute::requiresCallersForArgOrFunction.
StateWrapper< PotentialLLVMValuesState, AbstractAttribute > Base
const PotentialLLVMValuesState & getState() const override
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
static LLVM_ABI const char ID
Unique ID (due to the unique address)
StringRef getName() const override
See AbstractAttribute::getName()
static LLVM_ABI Value * getSingleValue(Attributor &A, const AbstractAttribute &AA, const IRPosition &IRP, SmallVectorImpl< AA::ValueAndContext > &Values)
Extract the single value in Values if any.
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
See AbstractAttribute::isValidIRPositionForInit.
bool isAssumedPrivatizablePtr() const
Returns true if pointer privatization is assumed to be possible.
virtual std::optional< Type * > getPrivatizableType() const =0
Return the type we can choose for a private copy of the underlying value.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
StringRef getName() const override
See AbstractAttribute::getName()
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AAPricatizablePtr.
static bool requiresCallersForArgOrFunction()
See AbstractAttribute::requiresCallersForArgOrFunction.
static LLVM_ABI AAPrivatizablePtr & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
AAPrivatizablePtr(const IRPosition &IRP, Attributor &A)
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
StateWrapper< BooleanState, AbstractAttribute > Base
static LLVM_ABI AAUndefinedBehavior & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
static LLVM_ABI const char ID
Unique ID (due to the unique address)
virtual bool isAssumedToCauseUB(Instruction *I) const =0
Return true if "undefined behavior" is assumed for a specific instruction.
StateWrapper< BooleanState, AbstractAttribute > Base
AAUndefinedBehavior(const IRPosition &IRP, Attributor &A)
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AAUndefineBehavior.
StringRef getName() const override
See AbstractAttribute::getName()
virtual bool isKnownToCauseUB(Instruction *I) const =0
Return true if "undefined behavior" is known for a specific instruction.
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
See AbstractAttribute::isValidIRPositionForInit.
virtual bool forallUnderlyingObjects(function_ref< bool(Value &)> Pred, AA::ValueScope Scope=AA::Interprocedural) const =0
Check Pred on all underlying objects in Scope collected so far.
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AAUnderlyingObjects.
static LLVM_ABI AAUnderlyingObjects & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute biew for the position IRP.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
AAUnderlyingObjects(const IRPosition &IRP)
static bool requiresCallersForArgOrFunction()
See AbstractAttribute::requiresCallersForArgOrFunction.
StringRef getName() const override
See AbstractAttribute::getName()
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
See AbstractAttribute::isValidIRPositionForInit.
StringRef getName() const override
See AbstractAttribute::getName()
std::optional< Constant * > getAssumedConstant(Attributor &A, const Instruction *CtxI=nullptr) const
Return an assumed constant for the associated value a program point CtxI.
virtual ConstantRange getAssumedConstantRange(Attributor &A, const Instruction *CtxI=nullptr) const =0
Return an assumed range for the associated value a program point CtxI.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
static bool requiresCallersForArgOrFunction()
See AbstractAttribute::requiresCallersForArgOrFunction.
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AAValueConstantRange.
AAValueConstantRange(const IRPosition &IRP, Attributor &A)
static LLVM_ABI AAValueConstantRange & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
StateWrapper< IntegerRangeState, AbstractAttribute, uint32_t > Base
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
IntegerRangeState & getState() override
See AbstractAttribute::getState(...).
const IntegerRangeState & getState() const override
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AAValueSimplify.
friend struct Attributor
StringRef getName() const override
See AbstractAttribute::getName()
StateWrapper< ValueSimplifyStateType, AbstractAttribute, Type * > Base
static LLVM_ABI const char ID
Unique ID (due to the unique address)
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
static LLVM_ABI AAValueSimplify & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
AAValueSimplify(const IRPosition &IRP, Attributor &A)
An abstract attribute for willreturn.
bool isKnownWillReturn() const
Return true if "willreturn" is known.
const char * getIdAddr() const override
See AbstractAttribute::getIdAddr()
static LLVM_ABI const char ID
Unique ID (due to the unique address)
static LLVM_ABI AAWillReturn & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
StringRef getName() const override
See AbstractAttribute::getName()
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AAWillReturn.
AAWillReturn(const IRPosition &IRP, Attributor &A)
static bool isImpliedByMustprogressAndReadonly(Attributor &A, const IRPosition &IRP)
Check for mustprogress and readonly as they imply willreturn.
static bool isImpliedByIR(Attributor &A, const IRPosition &IRP, Attribute::AttrKind ImpliedAttributeKind, bool IgnoreSubsumingPositions=false)
bool isAssumedWillReturn() const
Return true if "willreturn" is assumed.
Helper to represent an access offset and size, with logic to deal with uncertainty and check for over...
Definition Attributor.h:245
bool offsetAndSizeAreUnknown() const
Return true if offset and size are unknown, thus this is the default unknown object.
Definition Attributor.h:260
static constexpr int64_t Unknown
Definition Attributor.h:324
bool offsetOrSizeAreUnknown() const
Return true if offset or size are unknown.
Definition Attributor.h:254
static constexpr int64_t Unassigned
Constants used to represent special offsets or sizes.
Definition Attributor.h:323
RangeTy & operator&=(const RangeTy &R)
Definition Attributor.h:283
static RangeTy getUnknown()
Definition Attributor.h:251
bool isUnassigned() const
Return true if the offset and size are unassigned.
Definition Attributor.h:265
static bool LessThan(const RangeTy &L, const RangeTy &R)
Comparison for sorting ranges.
Definition Attributor.h:309
bool mayOverlap(const RangeTy &Range) const
Return true if this offset and size pair might describe an address that overlaps with Range.
Definition Attributor.h:273
RangeTy(int64_t Offset, int64_t Size)
Definition Attributor.h:249
Value * getValue() const
Definition Attributor.h:198
std::pair< Value *, const Instruction * > Base
Definition Attributor.h:193
ValueAndContext(Value &V, const Instruction *CtxI)
Definition Attributor.h:195
const Instruction * getCtxI() const
Definition Attributor.h:199
ValueAndContext(Value &V, const Instruction &CtxI)
Definition Attributor.h:196
ValueAndContext(const Base &B)
Definition Attributor.h:194
Base struct for all "concrete attribute" deductions.
ChangeStatus update(Attributor &A)
Hook for the Attributor to trigger an update of the internal state.
friend struct Attributor
}
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
Return false if an AA should not be created for IRP.
virtual ChangeStatus manifest(Attributor &A)
Hook for the Attributor to trigger the manifestation of the information represented by the abstract a...
static bool classof(const AADepGraphNode *DGN)
This function is used to identify if an DGN is of type AbstractAttribute so that the dyn_cast and cas...
static bool requiresCalleeForCallBase()
Return true if this AA requires a "callee" (or an associted function) for a call site positon.
void print(raw_ostream &OS) const
Helper functions, for debug purposes only.
IRPosition & getIRPosition()
virtual StateType & getState()=0
Return the internal abstract state for inspection.
virtual void initialize(Attributor &A)
Initialize the state with the information in the Attributor A.
static bool isValidIRPositionForUpdate(Attributor &A, const IRPosition &IRP)
Return false if an AA should not be updated for IRP.
AbstractState StateType
virtual const std::string getAsStr(Attributor *A) const =0
This function should return the "summarized" assumed state as string.
~AbstractAttribute() override=default
Virtual destructor.
static constexpr Attribute::AttrKind IRAttributeKind
Compile time access to the IR attribute kind.
virtual bool isQueryAA() const
A query AA is always scheduled as long as we do updates because it does lazy computation that cannot ...
virtual const StateType & getState() const =0
AbstractAttribute(const IRPosition &IRP)
static bool requiresNonAsmForCallBase()
Return true if this AA requires non-asm "callee" for a call site positon.
virtual ChangeStatus updateImpl(Attributor &A)=0
The actual update/transfer function which has to be implemented by the derived classes.
virtual void trackStatistics() const =0
Hook to enable custom statistic tracking, called after manifest that resulted in a change if statisti...
static bool requiresCallersForArgOrFunction()
Return true if this AA requires all callees for an argument or function positon.
virtual StringRef getName() const =0
This function should return the name of the AbstractAttribute.
const IRPosition & getIRPosition() const
Return an IR position, see struct IRPosition.
virtual const char * getIdAddr() const =0
This function should return the address of the ID of the AbstractAttribute.
static bool hasTrivialInitializer()
Return false if this AA does anything non-trivial (hence not done by default) in its initializer.
An interface to query the internal state of an abstract attribute.
virtual ~AbstractState()=default
virtual ChangeStatus indicatePessimisticFixpoint()=0
Indicate that the abstract state should converge to the pessimistic state.
virtual bool isAtFixpoint() const =0
Return if this abstract state is fixed, thus does not need to be updated if information changes as it...
virtual bool isValidState() const =0
Return if this abstract state is in a valid state.
virtual ChangeStatus indicateOptimisticFixpoint()=0
Indicate that the abstract state should converge to the optimistic state.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Wrapper for FunctionAnalysisManager.
AnalysisGetter()=default
static constexpr bool HasLegacyWrapper
Analysis::Result * getAnalysis(const Function &F, bool RequestCachedOnly=false)
AnalysisGetter(FunctionAnalysisManager &FAM, bool CachedOnly=false)
void invalidateAnalyses()
Invalidates the analyses. Valid only when using the new pass manager.
AnalysisGetter(Pass *P, bool CachedOnly=false)
LLVM_ABI PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &AM, LazyCallGraph &CG, CGSCCUpdateResult &UR)
~AttributorCallGraph() override=default
AACallEdgeIterator optimisticEdgesEnd() const override
AttributorCallGraph(Attributor &A)
AACallEdgeIterator optimisticEdgesBegin() const override
void populateAll() const
Force populate the entire call graph.
Configuration for the Attributor.
bool UseLiveness
Flag to determine if we should skip all liveness checks early on.
std::function< void(Attributor &A, const Function &F)> InitializationCallback
Callback function to be invoked on internal functions marked live.
std::optional< unsigned > MaxFixpointIterations
Maximum number of iterations to run until fixpoint.
DenseSet< const char * > * Allowed
If not null, a set limiting the attribute opportunities.
bool RewriteSignatures
Flag to determine if we rewrite function signatures.
const char * PassName
}
OptimizationRemarkGetter OREGetter
bool DeleteFns
Flag to determine if we can delete functions or keep dead ones around.
std::function< bool(const Function &F)> IPOAmendableCBTy
bool IsClosedWorldModule
Flag to indicate if the entire world is contained in this module, that is, no outside functions exist...
function_ref< OptimizationRemarkEmitter &(Function *)> OptimizationRemarkGetter
A callback function that returns an ORE object from a Function pointer.
CallGraphUpdater & CGUpdater
Helper to update an underlying call graph and to delete functions.
IPOAmendableCBTy IPOAmendableCB
bool IsModulePass
Is the user of the Attributor a module pass or not.
std::function< bool(Attributor &A, const AbstractAttribute &AA, CallBase &CB, Function &AssumedCallee, unsigned NumAssumedCallees)> IndirectCalleeSpecializationCallback
Callback function to determine if an indirect call targets should be made direct call targets (with a...
bool DefaultInitializeLiveInternals
Flag to determine if we want to initialize all default AAs for an internal function marked live.
AttributorConfig(CallGraphUpdater &CGUpdater)
A more lightweight version of the Attributor which only runs attribute inference but no simplificatio...
LLVM_ABI PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &AM, LazyCallGraph &CG, CGSCCUpdateResult &UR)
A more lightweight version of the Attributor which only runs attribute inference but no simplificatio...
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
Helper struct used in the communication between an abstract attribute (AA) that wants to change the s...
friend struct Attributor
Allow access to the private members from the Attributor.
std::function< void( const ArgumentReplacementInfo &, Function &, Function::arg_iterator)> CalleeRepairCBTy
Callee repair callback type.
const Argument & getReplacedArg() const
Attributor & getAttributor() const
Simple getters, see the corresponding members for details.
const Function & getReplacedFn() const
std::function< void(const ArgumentReplacementInfo &, AbstractCallSite, SmallVectorImpl< Value * > &)> ACSRepairCBTy
Abstract call site (ACS) repair callback type.
The fixpoint analysis framework that orchestrates the attribute deduction.
LLVM_ABI bool registerFunctionSignatureRewrite(Argument &Arg, ArrayRef< Type * > ReplacementTypes, ArgumentReplacementInfo::CalleeRepairCBTy &&CalleeRepairCB, ArgumentReplacementInfo::ACSRepairCBTy &&ACSRepairCB)
Register a rewrite for a function signature.
AAType & registerAA(AAType &AA)
Introduce a new abstract attribute into the fixpoint analysis.
LLVM_ABI ~Attributor()
LLVM_ABI bool checkForAllCallees(function_ref< bool(ArrayRef< const Function * > Callees)> Pred, const AbstractAttribute &QueryingAA, const CallBase &CB)
Check Pred on all potential Callees of CB.
bool isModulePass() const
Return true if this is a module pass, false otherwise.
void registerInvokeWithDeadSuccessor(InvokeInst &II)
Record that II has at least one dead successor block.
void registerSimplificationCallback(const IRPosition &IRP, const SimplifictionCallbackTy &CB)
bool changeAfterManifest(const IRPosition IRP, Value &NV, bool ChangeDroppable=true)
Helper function to replace all uses associated with IRP with NV.
LLVM_ABI bool isValidFunctionSignatureRewrite(Argument &Arg, ArrayRef< Type * > ReplacementTypes)
Check if we can rewrite a function signature.
static LLVM_ABI bool isInternalizable(Function &F)
Returns true if the function F can be internalized.
LLVM_ABI ChangeStatus removeAttrs(const IRPosition &IRP, ArrayRef< Attribute::AttrKind > AttrKinds)
Remove all AttrKinds attached to IRP.
void emitRemark(Instruction *I, StringRef RemarkName, RemarkCallBack &&RemarkCB) const
Emit a remark generically.
bool isRunOn(Function &Fn) const
Return true if we derive attributes for Fn.
LLVM_ABI bool isAssumedDead(const AbstractAttribute &AA, const AAIsDead *LivenessAA, bool &UsedAssumedInformation, bool CheckBBLivenessOnly=false, DepClassTy DepClass=DepClassTy::OPTIONAL)
Return true if AA (or its context instruction) is assumed dead.
LLVM_ABI bool checkForAllInstructions(function_ref< bool(Instruction &)> Pred, const Function *Fn, const AbstractAttribute *QueryingAA, ArrayRef< unsigned > Opcodes, bool &UsedAssumedInformation, bool CheckBBLivenessOnly=false, bool CheckPotentiallyDead=false)
Check Pred on all instructions in Fn with an opcode present in Opcodes.
LLVM_ABI void recordDependence(const AbstractAttribute &FromAA, const AbstractAttribute &ToAA, DepClassTy DepClass)
Explicitly record a dependence from FromAA to ToAA, that is if FromAA changes ToAA should be updated ...
static LLVM_ABI void createShallowWrapper(Function &F)
Create a shallow wrapper for F such that F has internal linkage afterwards.
bool isRunOn(Function *Fn) const
bool isDuringDeduction() const
Return whether attributes can participate in fixed-point deduction.
const AAType * getAAFor(const AbstractAttribute &QueryingAA, const IRPosition &IRP, DepClassTy DepClass)
Lookup an abstract attribute of type AAType at position IRP.
std::function< std::optional< Value * >( const IRPosition &, const AbstractAttribute *, bool &)> SimplifictionCallbackTy
Register CB as a simplification callback.
std::optional< Constant * > getAssumedInitializerFromCallBack(const GlobalVariable &GV, const AbstractAttribute *AA, bool &UsedAssumedInformation)
Return std::nullopt if there is no call back registered for GV or the call back is still not sure if ...
void deleteAfterManifest(Function &F)
Record that F is deleted after information was manifested.
std::optional< Value * > getAssumedSimplified(const IRPosition &IRP, const AbstractAttribute &AA, bool &UsedAssumedInformation, AA::ValueScope S)
If V is assumed simplified, return it, if it is unclear yet, return std::nullopt, otherwise return nu...
void emitRemark(Function *F, StringRef RemarkName, RemarkCallBack &&RemarkCB) const
Emit a remark on a function.
static LLVM_ABI Function * internalizeFunction(Function &F, bool Force=false)
Make another copy of the function F such that the copied version has internal linkage afterwards and ...
bool isFunctionIPOAmendable(const Function &F)
Determine whether the function F is IPO amendable.
const AAType * getOrCreateAAFor(IRPosition IRP, const AbstractAttribute *QueryingAA, DepClassTy DepClass, bool ForceUpdate=false, bool UpdateAfterInit=true)
The version of getAAFor that allows to omit a querying abstract attribute.
const SmallSetVector< Function *, 8 > & getModifiedFunctions()
LLVM_ABI bool checkForAllReadWriteInstructions(function_ref< bool(Instruction &)> Pred, AbstractAttribute &QueryingAA, bool &UsedAssumedInformation)
Check Pred on all Read/Write instructions.
void changeToUnreachableAfterManifest(Instruction *I)
Record that I is to be replaced with unreachable after information was manifested.
bool hasGlobalVariableSimplificationCallback(const GlobalVariable &GV)
Return true if there is a simplification callback for GV.
std::optional< Constant * > getAssumedConstant(const Value &V, const AbstractAttribute &AA, bool &UsedAssumedInformation)
LLVM_ABI bool checkForAllReturnedValues(function_ref< bool(Value &)> Pred, const AbstractAttribute &QueryingAA, AA::ValueScope S=AA::ValueScope::Intraprocedural, bool RecurseForSelectAndPHI=true)
Check Pred on all values potentially returned by the function associated with QueryingAA.
bool hasSimplificationCallback(const IRPosition &IRP)
Return true if there is a simplification callback for IRP.
std::function< std::optional< Constant * >( const GlobalVariable &, const AbstractAttribute *, bool &)> GlobalVariableSimplifictionCallbackTy
Register CB as a simplification callback.
LLVM_ABI bool isClosedWorldModule() const
Return true if the module contains the whole world, thus, no outside functions exist.
LLVM_ABI std::optional< Constant * > getAssumedConstant(const IRPosition &IRP, const AbstractAttribute &AA, bool &UsedAssumedInformation)
If IRP is assumed to be a constant, return it, if it is unclear yet, return std::nullopt,...
const AAType * getOrCreateAAFor(const IRPosition &IRP)
LLVM_ABI Attributor(SetVector< Function * > &Functions, InformationCache &InfoCache, AttributorConfig Configuration)
Constructor.
void registerGlobalVariableSimplificationCallback(const GlobalVariable &GV, const GlobalVariableSimplifictionCallbackTy &CB)
const DataLayout & getDataLayout() const
Return the data layout associated with the anchor scope.
LLVM_ABI void getAttrs(const IRPosition &IRP, ArrayRef< Attribute::AttrKind > AKs, SmallVectorImpl< Attribute > &Attrs, bool IgnoreSubsumingPositions=false)
Return the attributes of any kind in AKs existing in the IR at a position that will affect this one.
InformationCache & getInfoCache()
Return the internal information cache.
bool changeUseAfterManifest(Use &U, Value &NV)
Record that U is to be replaces with NV after information was manifested.
LLVM_ABI std::optional< Value * > translateArgumentToCallSiteContent(std::optional< Value * > V, CallBase &CB, const AbstractAttribute &AA, bool &UsedAssumedInformation)
Translate V from the callee context into the call site context.
AAType * lookupAAFor(const IRPosition &IRP, const AbstractAttribute *QueryingAA=nullptr, DepClassTy DepClass=DepClassTy::OPTIONAL, bool AllowInvalidState=false)
Return the attribute of AAType for IRP if existing and valid.
void markLiveInternalFunction(const Function &F)
Mark the internal function F as live.
void registerManifestAddedBasicBlock(BasicBlock &BB)
void registerVirtualUseCallback(const Value &V, const VirtualUseCallbackTy &CB)
LLVM_ABI bool checkForAllUses(function_ref< bool(const Use &, bool &)> Pred, const AbstractAttribute &QueryingAA, const Value &V, bool CheckBBLivenessOnly=false, DepClassTy LivenessDepClass=DepClassTy::OPTIONAL, bool IgnoreDroppableUses=true, function_ref< bool(const Use &OldU, const Use &NewU)> EquivalentUseCB=nullptr)
Check Pred on all (transitive) uses of V.
LLVM_ABI ChangeStatus manifestAttrs(const IRPosition &IRP, ArrayRef< Attribute > DeducedAttrs, bool ForceReplace=false)
Attach DeducedAttrs to IRP, if ForceReplace is set we do this even if the same attribute kind was alr...
LLVM_ABI bool hasAttr(const IRPosition &IRP, ArrayRef< Attribute::AttrKind > AKs, bool IgnoreSubsumingPositions=false, Attribute::AttrKind ImpliedAttributeKind=Attribute::None)
Return true if any kind in AKs existing in the IR at a position that will affect this one.
LLVM_ABI void registerForUpdate(AbstractAttribute &AA)
Allows a query AA to request an update if a new query was received.
const Module & getModule()
Return the module.
void deleteAfterManifest(Instruction &I)
Record that I is deleted after information was manifested.
std::function< bool(Attributor &, const AbstractAttribute *)> VirtualUseCallbackTy
void deleteAfterManifest(BasicBlock &BB)
Record that BB is deleted after information was manifested.
LLVM_ABI void identifyDefaultAbstractAttributes(Function &F)
Determine opportunities to derive 'default' attributes in F and create abstract attribute objects for...
bool shouldInitialize(const IRPosition &IRP, bool &ShouldUpdateAA)
LLVM_ABI bool getAssumedSimplifiedValues(const IRPosition &IRP, const AbstractAttribute *AA, SmallVectorImpl< AA::ValueAndContext > &Values, AA::ValueScope S, bool &UsedAssumedInformation, bool RecurseForSelectAndPHI=true)
Try to simplify IRP and in the scope S.
BumpPtrAllocator & Allocator
The allocator used to allocate memory, e.g. for AbstractAttributes.
bool checkForAllCallLikeInstructions(function_ref< bool(Instruction &)> Pred, const AbstractAttribute &QueryingAA, bool &UsedAssumedInformation, bool CheckBBLivenessOnly=false, bool CheckPotentiallyDead=false)
Check Pred on all call-like instructions (=CallBased derived).
bool shouldSpecializeCallSiteForCallee(const AbstractAttribute &AA, CallBase &CB, Function &Callee, unsigned NumAssumedCallees)
Return true if we should specialize the call site CB for the potential callee Fn.
LLVM_ABI ChangeStatus run()
Run the analyses until a fixpoint is reached or enforced (timeout).
static LLVM_ABI bool internalizeFunctions(SmallPtrSetImpl< Function * > &FnSet, DenseMap< Function *, Function * > &FnMap)
Make copies of each function in the set FnSet such that the copied version has internal linkage after...
std::optional< Value * > getAssumedSimplified(const Value &V, const AbstractAttribute &AA, bool &UsedAssumedInformation, AA::ValueScope S)
bool shouldUpdateAA(const IRPosition &IRP)
LLVM_ABI bool checkForAllCallSites(function_ref< bool(AbstractCallSite)> Pred, const AbstractAttribute &QueryingAA, bool RequireAllCallSites, bool &UsedAssumedInformation)
Check Pred on all function call sites.
LLVM_ABI bool getAttrsFromAssumes(const IRPosition &IRP, Attribute::AttrKind AK, SmallVectorImpl< Attribute > &Attrs)
Return the attributes of kind AK existing in the IR as operand bundles of an llvm....
Specialization of the integer state for a bit-wise encoding.
BitIntegerState & removeKnownBits(base_t BitsEncoding)
Remove the bits in BitsEncoding from the "known bits".
bool isAssumed(base_t BitsEncoding=BestState) const
Return true if the bits set in BitsEncoding are "assumed bits".
IntegerStateBase< base_ty, BestState, WorstState > super
BitIntegerState(base_t Assumed)
BitIntegerState & removeAssumedBits(base_t BitsEncoding)
Remove the bits in BitsEncoding from the "assumed bits" if not known.
BitIntegerState & intersectAssumedBits(base_t BitsEncoding)
Keep only "assumed bits" also set in BitsEncoding but all known ones.
bool isKnown(base_t BitsEncoding=BestState) const
Return true if the bits set in BitsEncoding are "known bits".
BitIntegerState & addKnownBits(base_t Bits)
Add the bits in BitsEncoding to the "known bits".
Simple wrapper for a single bit (boolean) state.
IntegerStateBase< bool, true, false > super
bool isKnown() const
Return true if the state is known to hold.
void setKnown(bool Value)
Set the known and asssumed value to Value.
IntegerStateBase::base_t base_t
BooleanState(base_t Assumed)
BooleanState()=default
bool isAssumed() const
Return true if the state is assumed to hold.
Support structure for SCC passes to communicate updates the call graph back to the CGSCC pass manager...
static bool isNodeHidden(const AACallGraphNode *Node, const AttributorCallGraph *Graph)
std::string getNodeLabel(const AACallGraphNode *Node, const AttributorCallGraph *Graph)
Specialization of the integer state for a decreasing value, hence 0 is the best state and ~0u the wor...
DecIntegerState & takeKnownMinimum(base_t Value)
Take minimum of known and Value.
DecIntegerState & takeAssumedMaximum(base_t Value)
Take maximum of assumed and Value.
static DenormalMode unionAssumed(DenormalMode Callee, DenormalMode Caller)
DenormalState unionWith(DenormalState Caller) const
bool operator!=(const DenormalState Other) const
bool operator==(const DenormalState Other) const
static DenormalMode::DenormalModeKind unionDenormalKind(DenormalMode::DenormalModeKind Callee, DenormalMode::DenormalModeKind Caller)
bool IsAtFixedpoint
Explicitly track whether we've hit a fixed point.
ChangeStatus indicateOptimisticFixpoint() override
Indicate that the abstract state should converge to the optimistic state.
DenormalState getKnown() const
DenormalState getAssumed() const
bool isValidState() const override
Return if this abstract state is in a valid state.
ChangeStatus indicatePessimisticFixpoint() override
Indicate that the abstract state should converge to the pessimistic state.
DenormalFPMathState operator^=(const DenormalFPMathState &Caller)
ChangeStatus indicateFixpoint()
bool isModeFixed() const
Return true if there are no dynamic components to the denormal mode worth specializing.
bool isAtFixpoint() const override
Return if this abstract state is fixed, thus does not need to be updated if information changes as it...
Represent subnormal handling kind for floating point instruction inputs and outputs.
DenormalModeKind
Represent handled modes for denormal (aka subnormal) modes in the floating point environment.
@ Dynamic
Denormals have unknown treatment.
static constexpr DenormalMode getInvalid()
static bool isEqual(const AA::ValueAndContext &LHS, const AA::ValueAndContext &RHS)
Definition Attributor.h:430
static unsigned getHashValue(const AA::ValueAndContext &VAC)
Definition Attributor.h:426
DenseMapInfo< AA::ValueAndContext::Base > Base
Definition Attributor.h:425
static bool isEqual(const AA::ValueScope &LHS, const AA::ValueScope &RHS)
Definition Attributor.h:443
DenseMapInfo< unsigned char > Base
Definition Attributor.h:438
static unsigned getHashValue(const AA::ValueScope &S)
Definition Attributor.h:439
static bool isEqual(const IRPosition &a, const IRPosition &b)
static unsigned getHashValue(const IRPosition &IRP)
An information struct used to provide DenseMap with the various necessary components for a given valu...
State for dereferenceable attribute.
IncIntegerState DerefBytesState
State representing for dereferenceable bytes.
static DerefState getBestState(const DerefState &)
static DerefState getWorstState()
Return the worst possible representable state.
static DerefState getBestState()
static DerefState getWorstState(const DerefState &)
std::map< int64_t, uint64_t > AccessedBytesMap
Map representing for accessed memory offsets and sizes.
static AACallEdgeIterator child_end(AACallGraphNode *Node)
static AACallEdgeIterator child_begin(AACallGraphNode *Node)
static AACallGraphNode * getEntryNode(AttributorCallGraph *G)
static AACallEdgeIterator nodes_begin(const AttributorCallGraph *G)
static AACallEdgeIterator nodes_end(const AttributorCallGraph *G)
Attribute::AttrKind getAttrKind() const
Return the kind that identifies the abstract attribute implementation.
static constexpr Attribute::AttrKind IRAttributeKind
Compile time access to the IR attribute kind.
static bool hasTrivialInitializer()
Most boolean IRAttribute AAs don't do anything non-trivial in their initializers while non-boolean on...
static bool isImpliedByUndef()
Return true if the IR attribute(s) associated with this AA are implied for an undef value.
ChangeStatus manifest(Attributor &A) override
See AbstractAttribute::manifest(...).
static bool isImpliedByPoison()
Return true if the IR attribute(s) associated with this AA are implied for an poison value.
static bool isImpliedByIR(Attributor &A, const IRPosition &IRP, Attribute::AttrKind ImpliedAttributeKind=AK, bool IgnoreSubsumingPositions=false)
IRAttribute(const IRPosition &IRP)
virtual void getDeducedAttributes(Attributor &A, LLVMContext &Ctx, SmallVectorImpl< Attribute > &Attrs) const
Return the deduced attributes in Attrs.
Helper to describe and deal with positions in the LLVM-IR.
Definition Attributor.h:573
Function * getAssociatedFunction() const
Return the associated function, if any.
Definition Attributor.h:704
void setAttrList(const AttributeList &AttrList) const
Update the attributes associated with this function or call site scope.
Definition Attributor.h:840
unsigned getAttrIdx() const
Return the index in the attribute list for this position.
Definition Attributor.h:805
bool hasCallBaseContext() const
Check if the position has any call base context.
Definition Attributor.h:900
static const IRPosition callsite_returned(const CallBase &CB)
Create a position describing the returned value of CB.
Definition Attributor.h:641
static const IRPosition returned(const Function &F, const CallBaseContext *CBContext=nullptr)
Create a position describing the returned value of F.
Definition Attributor.h:623
LLVM_ABI Argument * getAssociatedArgument() const
Return the associated argument, if any.
bool isAnyCallSitePosition() const
Definition Attributor.h:867
bool operator!=(const IRPosition &RHS) const
Definition Attributor.h:682
static const IRPosition value(const Value &V, const CallBaseContext *CBContext=nullptr)
Create a position describing the value of V.
Definition Attributor.h:597
CallBase CallBaseContext
Definition Attributor.h:576
AttributeList getAttrList() const
Return the attributes associated with this function or call site scope.
Definition Attributor.h:833
int getCalleeArgNo() const
Return the callee argument number of the associated value if it is an argument or call site argument,...
Definition Attributor.h:791
static const IRPosition inst(const Instruction &I, const CallBaseContext *CBContext=nullptr)
Create a position describing the instruction I.
Definition Attributor.h:609
static const IRPosition callsite_argument(const CallBase &CB, unsigned ArgNo)
Create a position describing the argument of CB at position ArgNo.
Definition Attributor.h:646
Kind
The positions we distinguish in the IR.
Definition Attributor.h:579
@ IRP_ARGUMENT
An attribute for a function argument.
Definition Attributor.h:587
@ IRP_RETURNED
An attribute for the function return value.
Definition Attributor.h:583
@ IRP_CALL_SITE
An attribute for a call site (function scope).
Definition Attributor.h:586
@ IRP_CALL_SITE_RETURNED
An attribute for a call site return value.
Definition Attributor.h:584
@ IRP_FUNCTION
An attribute for a function (scope).
Definition Attributor.h:585
@ IRP_FLOAT
A position that is not associated with a spot suitable for attributes.
Definition Attributor.h:581
@ IRP_CALL_SITE_ARGUMENT
An attribute for a call site argument.
Definition Attributor.h:588
@ IRP_INVALID
An invalid position.
Definition Attributor.h:580
Instruction * getCtxI() const
Return the context instruction, if any.
Definition Attributor.h:757
static const IRPosition argument(const Argument &Arg, const CallBaseContext *CBContext=nullptr)
Create a position describing the argument Arg.
Definition Attributor.h:630
Type * getAssociatedType() const
Return the type this abstract attribute is associated with.
Definition Attributor.h:780
bool isFunctionScope() const
Return true if this is a function or call site position.
Definition Attributor.h:734
bool operator==(const IRPosition &RHS) const
Definition Attributor.h:679
static const IRPosition callsite_argument(AbstractCallSite ACS, unsigned ArgNo)
Create a position describing the argument of ACS at position ArgNo.
Definition Attributor.h:653
static const IRPosition function(const Function &F, const CallBaseContext *CBContext=nullptr)
Create a position describing the function scope of F.
Definition Attributor.h:616
const CallBaseContext * getCallBaseContext() const
Get the call base context from the position.
Definition Attributor.h:897
Value & getAssociatedValue() const
Return the value this abstract attribute is associated with.
Definition Attributor.h:771
Value & getAnchorValue() const
Return the value this abstract attribute is anchored with.
Definition Attributor.h:690
Value * getAttrListAnchor() const
Return the value attributes are attached to.
Definition Attributor.h:826
int getCallSiteArgNo() const
Return the call site argument number of the associated value if it is an argument or call site argume...
Definition Attributor.h:800
bool isFnInterfaceKind() const
Return true if the position refers to a function interface, that is the function scope,...
Definition Attributor.h:722
static const IRPosition function_scope(const IRPosition &IRP, const CallBaseContext *CBContext=nullptr)
Create a position with function scope matching the "context" of IRP.
Definition Attributor.h:669
IRPosition stripCallBaseContext() const
Return the same position without the call base context.
Definition Attributor.h:890
Kind getPositionKind() const
Return the associated position kind.
Definition Attributor.h:847
bool isArgumentPosition() const
Return true if the position is an argument or call site argument.
Definition Attributor.h:879
static const IRPosition callsite_function(const CallBase &CB)
Create a position describing the function scope of CB.
Definition Attributor.h:636
IRPosition()
Default constructor available to create invalid positions implicitly.
Definition Attributor.h:594
Function * getAnchorScope() const
Return the Function surrounding the anchor value.
Definition Attributor.h:745
Specialization of the integer state for an increasing value, hence ~0u is the best state and 0 the wo...
IntegerStateBase< base_ty, BestState, WorstState > super
static constexpr base_t getBestState(const IncIntegerState< base_ty, BestState, WorstState > &)
IncIntegerState(base_t Assumed)
static constexpr base_t getBestState()
Return the best possible representable state.
IncIntegerState & takeAssumedMinimum(base_t Value)
Take minimum of assumed and Value.
IncIntegerState & takeKnownMaximum(base_t Value)
Take maximum of known and Value.
Data structure to hold cached (LLVM-IR) information.
bool IsTargetGPU() const
Return true if the target is a GPU.
friend struct Attributor
Give the Attributor access to the members so Attributor::identifyDefaultAbstractAttributes(....
const SetVector< Function * > *const CGSCC
The CG-SCC the pass is run on, or nullptr if it is a module pass.
bool stackIsAccessibleByOtherThreads()
Return true if the stack (llvm::Alloca) can be accessed by other threads.
bool isInvolvedInMustTailCall(const Argument &Arg)
Return true if Arg is involved in a must-tail call, thus the argument of the caller or callee.
MustBeExecutedContextExplorer * getMustBeExecutedContextExplorer()
Return MustBeExecutedContextExplorer.
void invalidateAnalyses()
Invalidates the cached analyses.
virtual unsigned getMaxAddrSpace() const
const AA::InstExclusionSetTy * getOrCreateUniqueBlockExecutionSet(const AA::InstExclusionSetTy *BES)
Given BES, return a uniqued version.
static void foreachUse(Function &F, CBTy CB, bool LookThroughConstantExprUses=true)
Apply CB to all uses of F.
TargetLibraryInfo * getTargetLibraryInfoForFunction(const Function &F)
Return TargetLibraryInfo for function F.
InformationCache(const Module &M, AnalysisGetter &AG, BumpPtrAllocator &Allocator, SetVector< Function * > *CGSCC, bool UseExplorer=true)
const Module & getModule() const
const DataLayout & getDL() const
Return datalayout used in the module.
LLVM_ABI std::optional< unsigned > getFlatAddressSpace() const
Return the flat address space if the associated target has.
OpcodeInstMapTy & getOpcodeInstMapForFunction(const Function &F)
Return the map that relates "interesting" opcodes with all instructions with that opcode in F.
DenseMap< unsigned, InstructionVectorTy * > OpcodeInstMapTy
A map type from opcodes to instructions with this opcode.
const RetainedKnowledgeMap & getKnowledgeMap() const
Return the map conaining all the knowledge we have from llvm.assumes.
LLVM_ABI ArrayRef< Function * > getIndirectlyCallableFunctions(Attributor &A) const
Return all functions that might be called indirectly, only valid for closed world modules (see isClos...
SmallVector< Instruction *, 8 > InstructionVectorTy
A vector type to hold instructions.
InstructionVectorTy & getReadOrWriteInstsForFunction(const Function &F)
Return the instructions in F that may read or write memory.
bool isOnlyUsedByAssume(const Instruction &I) const
bool isKernel(const Function &F)
Return true if F has the "kernel" function attribute.
AP::Result * getAnalysisResultForFunction(const Function &F, bool CachedOnly=false)
Return the analysis result from a pass AP for function F.
State for an integer range.
IntegerRangeState operator^=(const IntegerRangeState &R)
"Clamp" this state with R.
IntegerRangeState operator&=(const IntegerRangeState &R)
bool isAtFixpoint() const override
See AbstractState::isAtFixpoint()
void unionAssumed(const IntegerRangeState &R)
See IntegerRangeState::unionAssumed(..).
ConstantRange Assumed
State representing assumed range, initially set to empty.
IntegerRangeState(const ConstantRange &CR)
IntegerRangeState(uint32_t BitWidth)
bool operator==(const IntegerRangeState &R) const
Equality for IntegerRangeState.
void intersectKnown(const IntegerRangeState &R)
See IntegerRangeState::intersectKnown(..).
static ConstantRange getBestState(const IntegerRangeState &IRS)
bool isValidState() const override
See AbstractState::isValidState()
uint32_t BitWidth
Bitwidth of the associated value.
ConstantRange Known
State representing known range, initially set to [-inf, inf].
void unionAssumed(const ConstantRange &R)
Unite assumed range with the passed state.
ChangeStatus indicatePessimisticFixpoint() override
See AbstractState::indicatePessimisticFixpoint(...)
ConstantRange getKnown() const
Return the known state encoding.
void intersectKnown(const ConstantRange &R)
Intersect known range with the passed state.
ConstantRange getAssumed() const
Return the assumed state encoding.
uint32_t getBitWidth() const
Return associated values' bit width.
ChangeStatus indicateOptimisticFixpoint() override
See AbstractState::indicateOptimisticFixpoint(...)
static ConstantRange getWorstState(uint32_t BitWidth)
Return the worst possible representable state.
static ConstantRange getBestState(uint32_t BitWidth)
Return the best possible representable state.
Simple state with integers encoding.
bool isValidState() const override
See AbstractState::isValidState() NOTE: For now we simply pretend that the worst possible state is in...
virtual void handleNewAssumedValue(base_t Value)=0
Handle a new assumed value Value. Subtype dependent.
bool isAtFixpoint() const override
See AbstractState::isAtFixpoint()
void operator|=(const IntegerStateBase< base_t, BestState, WorstState > &R)
virtual void handleNewKnownValue(base_t Value)=0
Handle a new known value Value. Subtype dependent.
base_t getKnown() const
Return the known state encoding.
ChangeStatus indicateOptimisticFixpoint() override
See AbstractState::indicateOptimisticFixpoint(...)
void operator^=(const IntegerStateBase< base_t, BestState, WorstState > &R)
"Clamp" this state with R.
virtual void joinOR(base_t AssumedValue, base_t KnownValue)=0
Handle a value Value. Subtype dependent.
virtual void joinAND(base_t AssumedValue, base_t KnownValue)=0
Handle a new assumed value Value. Subtype dependent.
IntegerStateBase(base_t Assumed)
void operator+=(const IntegerStateBase< base_t, BestState, WorstState > &R)
"Clamp" this state with R.
base_t getAssumed() const
Return the assumed state encoding.
static constexpr base_t getWorstState()
Return the worst possible representable state.
static constexpr base_t getBestState()
Return the best possible representable state.
ChangeStatus indicatePessimisticFixpoint() override
See AbstractState::indicatePessimisticFixpoint(...)
static constexpr base_t getWorstState(const IntegerStateBase &)
bool operator!=(const IntegerStateBase< base_t, BestState, WorstState > &R) const
Inequality for IntegerStateBase.
bool operator==(const IntegerStateBase< base_t, BestState, WorstState > &R) const
Equality for IntegerStateBase.
void operator&=(const IntegerStateBase< base_t, BestState, WorstState > &R)
static constexpr base_t getBestState(const IntegerStateBase &)
A "must be executed context" for a given program point PP is the set of instructions,...
A CRTP mix-in for passes that can be skipped.
static constexpr int NumLowBitsAvailable
Note, we assume here that void* is related to raw malloc'ed memory and that malloc returns objects at...
A class for a set state.
static PotentialValuesState getBestState(const PotentialValuesState &PVS)
PotentialValuesState & getAssumed()
Return the assumed state.
bool undefIsContained() const
Returns whether this state contains an undef value or not.
bool isAtFixpoint() const override
See AbstractState::isAtFixpoint(...)
void unionAssumed(const MemberTy &C)
Union assumed set with the passed value.
static PotentialValuesState getBestState()
Return empty set as the best state of potential values.
SmallSetVector< MemberTy, 8 > SetTy
ChangeStatus indicatePessimisticFixpoint() override
See AbstractState::indicatePessimisticFixpoint(...)
void unionAssumed(const PotentialValuesState &PVS)
Union assumed set with assumed set of the passed state PVS.
PotentialValuesState(bool IsValid)
bool operator==(const PotentialValuesState &RHS) const
bool isValidState() const override
See AbstractState::isValidState(...)
PotentialValuesState operator&=(const PotentialValuesState &PVS)
static PotentialValuesState getWorstState()
Return full set as the worst state of potential values.
const PotentialValuesState & getAssumed() const
ChangeStatus indicateOptimisticFixpoint() override
See AbstractState::indicateOptimisticFixpoint(...)
PotentialValuesState operator^=(const PotentialValuesState &PVS)
"Clamp" this state with PVS.
void unionAssumedWithUndef()
Union assumed set with an undef value.
const SetTy & getAssumedSet() const
Return this set.
A wrapper around a set that has semantics for handling unions and intersections with a "universal" se...
SetContents(bool Universal)
Creates a universal set with no concrete elements or an empty set.
SetContents(bool Universal, const DenseSet< BaseTy > &Assumptions)
bool getIntersection(const SetContents &RHS)
Finds A := A ^ B where A or B could be the "Universal" set which contains every possible attribute.
bool getUnion(const SetContents &RHS)
Finds A := A u B where A or B could be the "Universal" set which contains every possible attribute.
const DenseSet< BaseTy > & getSet() const
SetContents(const DenseSet< BaseTy > &Assumptions)
Creates a non-universal set with concrete values.
bool setContains(const BaseTy &Elem) const
Returns if the set state contains the element.
bool getIntersection(const SetContents &RHS)
Performs the set intersection between this set and RHS.
bool isValidState() const override
See AbstractState::isValidState()
bool isAtFixpoint() const override
See AbstractState::isAtFixpoint()
const SetContents & getAssumed() const
Return the assumed state encoding.
const SetContents & getKnown() const
Return the known state encoding.
ChangeStatus indicateOptimisticFixpoint() override
See AbstractState::indicateOptimisticFixpoint(...)
bool getUnion(const SetContents &RHS)
Performs the set union between this set and RHS.
SetState(const DenseSet< BaseTy > &Known)
Initializes the known state with an initial set and initializes the assumed state as universal.
ChangeStatus indicatePessimisticFixpoint() override
See AbstractState::indicatePessimisticFixpoint(...)
Helper to tie a abstract state implementation to an abstract attribute.
StateType & getState() override
See AbstractAttribute::getState(...).
StateTy StateType
Provide static access to the type of the state.
StateWrapper(const IRPosition &IRP, Ts... Args)
const StateType & getState() const override
See AbstractAttribute::getState(...).
static ValueSimplifyStateType getWorstState(Type *Ty)
Return the worst possible representable state.
static ValueSimplifyStateType getBestState(const ValueSimplifyStateType &VS)
LLVM_ABI bool unionAssumed(std::optional< Value * > Other)
Merge Other into the currently assumed simplified value.
ChangeStatus indicateOptimisticFixpoint() override
See AbstractState::indicateOptimisticFixpoint(...)
ValueSimplifyStateType operator^=(const ValueSimplifyStateType &VS)
"Clamp" this state with PVS.
ChangeStatus indicatePessimisticFixpoint() override
See AbstractState::indicatePessimisticFixpoint(...)
static ValueSimplifyStateType getBestState(Type *Ty)
bool isAtFixpoint() const override
See AbstractState::isAtFixpoint(...)
bool isValidState() const override
See AbstractState::isValidState(...)
std::optional< Value * > SimplifiedAssociatedValue
An assumed simplified value.
static ValueSimplifyStateType getWorstState(const ValueSimplifyStateType &VS)
BooleanState BS
Helper to track validity and fixpoint.
Type * Ty
The type of the original value.
bool operator==(const ValueSimplifyStateType &RHS) const
ValueSimplifyStateType getAssumed()
Return the assumed state encoding.
const ValueSimplifyStateType & getAssumed() const