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"
136#include "llvm/Support/ModRef.h"
141
142#include <array>
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 IPOOptions;
154struct AADepGraphNode;
155struct AADepGraph;
156struct Attributor;
157struct AbstractAttribute;
158struct InformationCache;
159struct AAIsDead;
161struct IRPosition;
162
163class Function;
164
165/// Abstract Attribute helper functions.
166namespace AA {
168
169/// Return true iff \p M target a GPU (and we can use GPU AS reasoning).
170LLVM_ABI bool isGPU(const Module &M);
171
172/// Check if the given address space \p AS corresponds to a GPU shared
173/// address space for the target triple in module \p M.
174LLVM_ABI bool isGPUSharedAddressSpace(const Module &M, unsigned AS);
175
176/// Check if the given address space \p AS corresponds to a GPU constant
177/// address space for the target triple in module \p M.
178LLVM_ABI bool isGPUConstantAddressSpace(const Module &M, unsigned AS);
179
180/// Check if the given address space \p AS corresponds to a GPU local/private
181/// address space for the target triple in module \p M.
182LLVM_ABI bool isGPULocalAddressSpace(const Module &M, unsigned AS);
183
184/// Flags to distinguish intra-procedural queries from *potentially*
185/// inter-procedural queries. Not that information can be valid for both and
186/// therefore both bits might be set.
192
193struct ValueAndContext : public std::pair<Value *, const Instruction *> {
194 using Base = std::pair<Value *, const Instruction *>;
196 ValueAndContext(Value &V, const Instruction *CtxI) : Base(&V, CtxI) {}
197 ValueAndContext(Value &V, const Instruction &CtxI) : Base(&V, &CtxI) {}
198
199 Value *getValue() const { return this->first; }
200 const Instruction *getCtxI() const { return this->second; }
201};
202
203/// Return true if \p I is a `nosync` instruction. Use generic reasoning and
204/// potentially the corresponding AANoSync.
206 const AbstractAttribute &QueryingAA);
207
208/// Return true if \p V is dynamically unique, that is, there are no two
209/// "instances" of \p V at runtime with different values.
210/// Note: If \p ForAnalysisOnly is set we only check that the Attributor will
211/// never use \p V to represent two "instances" not that \p V could not
212/// technically represent them.
214 const AbstractAttribute &QueryingAA,
215 const Value &V, bool ForAnalysisOnly = true);
216
217/// Return true if \p V is a valid value in \p Scope, that is a constant or an
218/// instruction/argument of \p Scope.
219LLVM_ABI bool isValidInScope(const Value &V, const Function *Scope);
220
221/// Return true if the value of \p VAC is a valid at the position of \p VAC,
222/// that is a constant, an argument of the same function, or an instruction in
223/// that function that dominates the position.
224LLVM_ABI bool isValidAtPosition(const ValueAndContext &VAC,
225 InformationCache &InfoCache);
226
227/// Try to convert \p V to type \p Ty without introducing new instructions. If
228/// this is not possible return `nullptr`. Note: this function basically knows
229/// how to cast various constants.
231
232/// Return the combination of \p A and \p B such that the result is a possible
233/// value of both. \p B is potentially casted to match the type \p Ty or the
234/// type of \p A if \p Ty is null.
235///
236/// Examples:
237/// X + none => X
238/// not_none + undef => not_none
239/// V1 + V2 => nullptr
240LLVM_ABI std::optional<Value *>
241combineOptionalValuesInAAValueLatice(const std::optional<Value *> &A,
242 const std::optional<Value *> &B, Type *Ty);
243
244/// Helper to represent an access offset and size, with logic to deal with
245/// uncertainty and check for overlapping accesses.
246struct RangeTy {
248 int64_t Size = Unassigned;
249
250 RangeTy(int64_t Offset, int64_t Size) : Offset(Offset), Size(Size) {}
251 RangeTy() = default;
252 static RangeTy getUnknown() { return RangeTy{Unknown, Unknown}; }
253
254 /// Return true if offset or size are unknown.
257 }
258
259 /// Return true if offset and size are unknown, thus this is the default
260 /// unknown object.
263 }
264
265 /// Return true if the offset and size are unassigned.
266 bool isUnassigned() const {
268 "Inconsistent state!");
269 return Offset == RangeTy::Unassigned;
270 }
271
272 /// Return true if this offset and size pair might describe an address that
273 /// overlaps with \p Range.
274 bool mayOverlap(const RangeTy &Range) const {
275 // Any unknown value and we are giving up -> overlap.
276 if (offsetOrSizeAreUnknown() || Range.offsetOrSizeAreUnknown())
277 return true;
278
279 // Check if one offset point is in the other interval [offset,
280 // offset+size].
281 return Range.Offset + Range.Size > Offset && Range.Offset < Offset + Size;
282 }
283
285 if (R.isUnassigned())
286 return *this;
287 if (isUnassigned())
288 return *this = R;
289 if (Offset == Unknown || R.Offset == Unknown)
290 Offset = Unknown;
291 if (Size == Unknown || R.Size == Unknown)
292 Size = Unknown;
294 return *this;
295 if (Offset == Unknown) {
296 Size = std::max(Size, R.Size);
297 } else if (Size == Unknown) {
298 Offset = std::min(Offset, R.Offset);
299 } else {
300 Offset = std::min(Offset, R.Offset);
301 Size = std::max(Offset + Size, R.Offset + R.Size) - Offset;
302 }
303 return *this;
304 }
305
306 /// Comparison for sorting ranges.
307 ///
308 /// Returns true if the offset of \p L is less than that of \p R. If the two
309 /// offsets are same, compare the sizes instead.
310 inline static bool LessThan(const RangeTy &L, const RangeTy &R) {
311 if (L.Offset < R.Offset)
312 return true;
313 if (L.Offset == R.Offset)
314 return L.Size < R.Size;
315 return false;
316 }
317
318 /// Constants used to represent special offsets or sizes.
319 /// - We cannot assume that Offsets and Size are non-negative.
320 /// - The constants should not clash with DenseMapInfo, such as EmptyKey
321 /// (INT64_MAX).
322 /// We use values "in the middle" of the 64 bit range to represent these
323 /// special cases.
324 static constexpr int64_t Unassigned = std::numeric_limits<int32_t>::min();
325 static constexpr int64_t Unknown = std::numeric_limits<int32_t>::max();
326};
327
329 OS << "[" << R.Offset << ", " << R.Size << "]";
330 return OS;
331}
332
333inline bool operator==(const RangeTy &A, const RangeTy &B) {
334 return A.Offset == B.Offset && A.Size == B.Size;
335}
336
337inline bool operator!=(const RangeTy &A, const RangeTy &B) { return !(A == B); }
338
339/// Return the initial value of \p Obj with type \p Ty if that is a constant.
342 Value &Obj, Type &Ty, const TargetLibraryInfo *TLI,
343 const DataLayout &DL, RangeTy *RangePtr = nullptr);
344
345/// Collect all potential values \p LI could read into \p PotentialValues. That
346/// is, the only values read by \p LI are assumed to be known and all are in
347/// \p PotentialValues. \p PotentialValueOrigins will contain all the
348/// instructions that might have put a potential value into \p PotentialValues.
349/// Dependences onto \p QueryingAA are properly tracked, \p
350/// UsedAssumedInformation will inform the caller if assumed information was
351/// used.
352///
353/// \returns True if the assumed potential copies are all in \p PotentialValues,
354/// false if something went wrong and the copies could not be
355/// determined.
357 Attributor &A, LoadInst &LI, SmallSetVector<Value *, 4> &PotentialValues,
358 SmallSetVector<Instruction *, 4> &PotentialValueOrigins,
359 const AbstractAttribute &QueryingAA, bool &UsedAssumedInformation,
360 bool OnlyExact = false);
361
362/// Collect all potential values of the one stored by \p SI into
363/// \p PotentialCopies. That is, the only copies that were made via the
364/// store are assumed to be known and all are in \p PotentialCopies. Dependences
365/// onto \p QueryingAA are properly tracked, \p UsedAssumedInformation will
366/// inform the caller if assumed information was used.
367///
368/// \returns True if the assumed potential copies are all in \p PotentialCopies,
369/// false if something went wrong and the copies could not be
370/// determined.
373 const AbstractAttribute &QueryingAA, bool &UsedAssumedInformation,
374 bool OnlyExact = false);
375
376/// Return true if \p IRP is readonly. This will query respective AAs that
377/// deduce the information and introduce dependences for \p QueryingAA.
379 const AbstractAttribute &QueryingAA,
380 bool &IsKnown);
381
382/// Return true if \p IRP is readnone. This will query respective AAs that
383/// deduce the information and introduce dependences for \p QueryingAA.
385 const AbstractAttribute &QueryingAA,
386 bool &IsKnown);
387
388/// Return true if \p ToI is potentially reachable from \p FromI without running
389/// into any instruction in \p ExclusionSet The two instructions do not need to
390/// be in the same function. \p GoBackwardsCB can be provided to convey domain
391/// knowledge about the "lifespan" the user is interested in. By default, the
392/// callers of \p FromI are checked as well to determine if \p ToI can be
393/// reached. If the query is not interested in callers beyond a certain point,
394/// e.g., a GPU kernel entry or the function containing an alloca, the
395/// \p GoBackwardsCB should return false.
397 Attributor &A, const Instruction &FromI, const Instruction &ToI,
398 const AbstractAttribute &QueryingAA,
399 const AA::InstExclusionSetTy *ExclusionSet = nullptr,
400 std::function<bool(const Function &F)> GoBackwardsCB = nullptr);
401
402/// Same as above but it is sufficient to reach any instruction in \p ToFn.
404 Attributor &A, const Instruction &FromI, const Function &ToFn,
405 const AbstractAttribute &QueryingAA,
406 const AA::InstExclusionSetTy *ExclusionSet = nullptr,
407 std::function<bool(const Function &F)> GoBackwardsCB = nullptr);
408
409/// Return true if \p Obj is assumed to be a thread local object.
411 const AbstractAttribute &QueryingAA);
412
413/// Return true if \p I is potentially affected by a barrier.
414LLVM_ABI bool
416 const AbstractAttribute &QueryingAA);
417LLVM_ABI bool
419 const AbstractAttribute &QueryingAA,
420 const Instruction *CtxI);
421} // namespace AA
422
423template <>
424struct DenseMapInfo<AA::ValueAndContext>
425 : public DenseMapInfo<AA::ValueAndContext::Base> {
427 static unsigned getHashValue(const AA::ValueAndContext &VAC) {
428 return Base::getHashValue(VAC);
429 }
430
431 static bool isEqual(const AA::ValueAndContext &LHS,
432 const AA::ValueAndContext &RHS) {
433 return Base::isEqual(LHS, RHS);
434 }
435};
436
437template <>
438struct DenseMapInfo<AA::ValueScope> : public DenseMapInfo<unsigned char> {
440 static unsigned getHashValue(const AA::ValueScope &S) {
441 return Base::getHashValue(S);
442 }
443
444 static bool isEqual(const AA::ValueScope &LHS, const AA::ValueScope &RHS) {
445 return Base::isEqual(LHS, RHS);
446 }
447};
448
449template <>
450struct DenseMapInfo<const AA::InstExclusionSetTy *>
451 : public DenseMapInfo<void *> {
452 static unsigned getHashValue(const AA::InstExclusionSetTy *BES) {
453 unsigned H = 0;
454 if (BES)
455 for (const auto *II : *BES)
456 H += DenseMapInfo<const Instruction *>::getHashValue(II);
457 return H;
458 }
459 static bool isEqual(const AA::InstExclusionSetTy *LHS,
461 if (LHS == RHS)
462 return true;
463 auto SizeLHS = LHS ? LHS->size() : 0;
464 auto SizeRHS = RHS ? RHS->size() : 0;
465 if (SizeLHS != SizeRHS)
466 return false;
467 if (SizeRHS == 0)
468 return true;
469 return llvm::set_is_subset(*LHS, *RHS);
470 }
471};
472
473///{
478
483
484enum class DepClassTy {
485 REQUIRED, ///< The target cannot be valid if the source is not.
486 OPTIONAL, ///< The target may be valid if the source is not.
487 NONE, ///< Do not track a dependence between source and target.
488};
489///}
490
491/// The data structure for the nodes of a dependency graph
493public:
494 virtual ~AADepGraphNode() = default;
497
498protected:
499 /// Set of dependency graph nodes which should be updated if this one
500 /// is updated. The bit encodes if it is optional.
502
503 static AADepGraphNode *DepGetVal(const DepTy &DT) { return DT.getPointer(); }
506 }
507
508 operator AbstractAttribute *() { return cast<AbstractAttribute>(this); }
509
510public:
514
515 aaiterator begin() { return aaiterator(Deps.begin(), &DepGetValAA); }
516 aaiterator end() { return aaiterator(Deps.end(), &DepGetValAA); }
517 iterator child_begin() { return iterator(Deps.begin(), &DepGetVal); }
518 iterator child_end() { return iterator(Deps.end(), &DepGetVal); }
519
520 void print(raw_ostream &OS) const { print(nullptr, OS); }
521 virtual void print(Attributor *, raw_ostream &OS) const {
522 OS << "AADepNode Impl\n";
523 }
524
525 friend struct Attributor;
526 friend struct AADepGraph;
527};
528
529/// The data structure for the dependency graph
530///
531/// Note that in this graph if there is an edge from A to B (A -> B),
532/// then it means that B depends on A, and when the state of A is
533/// updated, node B should also be updated
535 AADepGraph() = default;
536 ~AADepGraph() = default;
537
539 static AADepGraphNode *DepGetVal(const DepTy &DT) { return DT.getPointer(); }
540 using iterator =
542
543 /// There is no root node for the dependency graph. But the SCCIterator
544 /// requires a single entry point, so we maintain a fake("synthetic") root
545 /// node that depends on every node.
548
549 iterator begin() { return SyntheticRoot.child_begin(); }
550 iterator end() { return SyntheticRoot.child_end(); }
551
552 LLVM_ABI void viewGraph();
553
554 /// Dump graph to file
555 LLVM_ABI void dumpGraph(StringRef DotFileNamePrefix);
556
557 /// Print dependency graph
558 LLVM_ABI void print();
559};
560
561/// Helper to describe and deal with positions in the LLVM-IR.
562///
563/// A position in the IR is described by an anchor value and an "offset" that
564/// could be the argument number, for call sites and arguments, or an indicator
565/// of the "position kind". The kinds, specified in the Kind enum below, include
566/// the locations in the attribute list, i.a., function scope and return value,
567/// as well as a distinction between call sites and functions. Finally, there
568/// are floating values that do not have a corresponding attribute list
569/// position.
571 // NOTE: In the future this definition can be changed to support recursive
572 // functions.
574
575 /// The positions we distinguish in the IR.
576 enum Kind : char {
577 IRP_INVALID, ///< An invalid position.
578 IRP_FLOAT, ///< A position that is not associated with a spot suitable
579 ///< for attributes. This could be any value or instruction.
580 IRP_RETURNED, ///< An attribute for the function return value.
581 IRP_CALL_SITE_RETURNED, ///< An attribute for a call site return value.
582 IRP_FUNCTION, ///< An attribute for a function (scope).
583 IRP_CALL_SITE, ///< An attribute for a call site (function scope).
584 IRP_ARGUMENT, ///< An attribute for a function argument.
585 IRP_CALL_SITE_ARGUMENT, ///< An attribute for a call site argument.
586 };
587
588 /// Default constructor available to create invalid positions implicitly. All
589 /// other positions need to be created explicitly through the appropriate
590 /// static member function.
591 IRPosition() : Enc(nullptr, ENC_VALUE) { verify(); }
592
593 /// Create a position describing the value of \p V.
594 static const IRPosition value(const Value &V,
595 const CallBaseContext *CBContext = nullptr) {
596 if (auto *Arg = dyn_cast<Argument>(&V))
597 return IRPosition::argument(*Arg, CBContext);
598 if (auto *CB = dyn_cast<CallBase>(&V))
600 return IRPosition(const_cast<Value &>(V), IRP_FLOAT, CBContext);
601 }
602
603 /// Create a position describing the instruction \p I. This is different from
604 /// the value version because call sites are treated as intrusctions rather
605 /// than their return value in this function.
606 static const IRPosition inst(const Instruction &I,
607 const CallBaseContext *CBContext = nullptr) {
608 return IRPosition(const_cast<Instruction &>(I), IRP_FLOAT, CBContext);
609 }
610
611 /// Create a position describing the function scope of \p F.
612 /// \p CBContext is used for call base specific analysis.
613 static const IRPosition function(const Function &F,
614 const CallBaseContext *CBContext = nullptr) {
615 return IRPosition(const_cast<Function &>(F), IRP_FUNCTION, CBContext);
616 }
617
618 /// Create a position describing the returned value of \p F.
619 /// \p CBContext is used for call base specific analysis.
620 static const IRPosition returned(const Function &F,
621 const CallBaseContext *CBContext = nullptr) {
622 return IRPosition(const_cast<Function &>(F), IRP_RETURNED, CBContext);
623 }
624
625 /// Create a position describing the argument \p Arg.
626 /// \p CBContext is used for call base specific analysis.
627 static const IRPosition argument(const Argument &Arg,
628 const CallBaseContext *CBContext = nullptr) {
629 return IRPosition(const_cast<Argument &>(Arg), IRP_ARGUMENT, CBContext);
630 }
631
632 /// Create a position describing the function scope of \p CB.
633 static const IRPosition callsite_function(const CallBase &CB) {
634 return IRPosition(const_cast<CallBase &>(CB), IRP_CALL_SITE);
635 }
636
637 /// Create a position describing the returned value of \p CB.
638 static const IRPosition callsite_returned(const CallBase &CB) {
639 return IRPosition(const_cast<CallBase &>(CB), IRP_CALL_SITE_RETURNED);
640 }
641
642 /// Create a position describing the argument of \p CB at position \p ArgNo.
643 static const IRPosition callsite_argument(const CallBase &CB,
644 unsigned ArgNo) {
645 return IRPosition(const_cast<Use &>(CB.getArgOperandUse(ArgNo)),
647 }
648
649 /// Create a position describing the argument of \p ACS at position \p ArgNo.
651 unsigned ArgNo) {
652 if (ACS.getNumArgOperands() <= ArgNo)
653 return IRPosition();
654 int CSArgNo = ACS.getCallArgOperandNo(ArgNo);
655 if (CSArgNo >= 0)
657 cast<CallBase>(*ACS.getInstruction()), CSArgNo);
658 return IRPosition();
659 }
660
661 /// Create a position with function scope matching the "context" of \p IRP.
662 /// If \p IRP is a call site (see isAnyCallSitePosition()) then the result
663 /// will be a call site position, otherwise the function position of the
664 /// associated function.
665 static const IRPosition
667 const CallBaseContext *CBContext = nullptr) {
668 if (IRP.isAnyCallSitePosition()) {
671 }
673 return IRPosition::function(*IRP.getAssociatedFunction(), CBContext);
674 }
675
676 bool operator==(const IRPosition &RHS) const {
677 return Enc == RHS.Enc && RHS.CBContext == CBContext;
678 }
679 bool operator!=(const IRPosition &RHS) const { return !(*this == RHS); }
680
681 /// Return the value this abstract attribute is anchored with.
682 ///
683 /// The anchor value might not be the associated value if the latter is not
684 /// sufficient to determine where arguments will be manifested. This is, so
685 /// far, only the case for call site arguments as the value is not sufficient
686 /// to pinpoint them. Instead, we can use the call site as an anchor.
688 switch (getEncodingBits()) {
689 case ENC_VALUE:
690 case ENC_RETURNED_VALUE:
691 case ENC_FLOATING_FUNCTION:
692 return *getAsValuePtr();
693 case ENC_CALL_SITE_ARGUMENT_USE:
694 return *(getAsUsePtr()->getUser());
695 default:
696 llvm_unreachable("Unkown encoding!");
697 };
698 }
699
700 /// Return the associated function, if any.
702 if (auto *CB = dyn_cast<CallBase>(&getAnchorValue())) {
703 // We reuse the logic that associates callback calles to arguments of a
704 // call site here to identify the callback callee as the associated
705 // function.
706 if (Argument *Arg = getAssociatedArgument())
707 return Arg->getParent();
709 CB->getCalledOperand()->stripPointerCasts());
710 }
711 return getAnchorScope();
712 }
713
714 /// Return the associated argument, if any.
716
717 /// Return true if the position refers to a function interface, that is the
718 /// function scope, the function return, or an argument.
719 bool isFnInterfaceKind() const {
720 switch (getPositionKind()) {
724 return true;
725 default:
726 return false;
727 }
728 }
729
730 /// Return true if this is a function or call site position.
731 bool isFunctionScope() const {
732 switch (getPositionKind()) {
735 return true;
736 default:
737 return false;
738 };
739 }
740
741 /// Return the Function surrounding the anchor value.
744 if (isa<Function>(V))
745 return &cast<Function>(V);
746 if (isa<Argument>(V))
747 return cast<Argument>(V).getParent();
748 if (isa<Instruction>(V))
749 return cast<Instruction>(V).getFunction();
750 return nullptr;
751 }
752
753 /// Return the context instruction, if any.
756 if (auto *I = dyn_cast<Instruction>(&V))
757 return I;
758 if (auto *Arg = dyn_cast<Argument>(&V))
759 if (!Arg->getParent()->isDeclaration())
760 return &Arg->getParent()->getEntryBlock().front();
761 if (auto *F = dyn_cast<Function>(&V))
762 if (!F->isDeclaration())
763 return &(F->getEntryBlock().front());
764 return nullptr;
765 }
766
767 /// Return the value this abstract attribute is associated with.
769 // A call site argument position is encoded by the argument operand use.
770 if (getEncodingBits() == ENC_CALL_SITE_ARGUMENT_USE)
771 return *getAsUsePtr()->get();
772 return getAnchorValue();
773 }
774
775 /// Return the type this abstract attribute is associated with.
781
782 /// Return the callee argument number of the associated value if it is an
783 /// argument or call site argument, otherwise a negative value. In contrast to
784 /// `getCallSiteArgNo` this method will always return the "argument number"
785 /// from the perspective of the callee. This may not the same as the call site
786 /// if this is a callback call.
787 int getCalleeArgNo() const {
788 return getArgNo(/* CallbackCalleeArgIfApplicable */ true);
789 }
790
791 /// Return the call site argument number of the associated value if it is an
792 /// argument or call site argument, otherwise a negative value. In contrast to
793 /// `getCalleArgNo` this method will always return the "operand number" from
794 /// the perspective of the call site. This may not the same as the callee
795 /// perspective if this is a callback call.
796 int getCallSiteArgNo() const {
797 return getArgNo(/* CallbackCalleeArgIfApplicable */ false);
798 }
799
800 /// Return the index in the attribute list for this position.
801 unsigned getAttrIdx() const {
802 switch (getPositionKind()) {
805 break;
808 return AttributeList::FunctionIndex;
811 return AttributeList::ReturnIndex;
813 return getCalleeArgNo() + AttributeList::FirstArgIndex;
815 return getCallSiteArgNo() + AttributeList::FirstArgIndex;
816 }
818 "There is no attribute index for a floating or invalid position!");
819 }
820
821 /// Return the value attributes are attached to.
823 if (auto *CB = dyn_cast<CallBase>(&getAnchorValue()))
824 return CB;
825 return getAssociatedFunction();
826 }
827
828 /// Return the attributes associated with this function or call site scope.
830 if (auto *CB = dyn_cast<CallBase>(&getAnchorValue()))
831 return CB->getAttributes();
833 }
834
835 /// Update the attributes associated with this function or call site scope.
836 void setAttrList(const AttributeList &AttrList) const {
837 if (auto *CB = dyn_cast<CallBase>(&getAnchorValue()))
838 return CB->setAttributes(AttrList);
839 return getAssociatedFunction()->setAttributes(AttrList);
840 }
841
842 /// Return the associated position kind.
844 char EncodingBits = getEncodingBits();
845 if (EncodingBits == ENC_CALL_SITE_ARGUMENT_USE)
847 if (EncodingBits == ENC_FLOATING_FUNCTION)
848 return IRP_FLOAT;
849
850 Value *V = getAsValuePtr();
851 if (!V)
852 return IRP_INVALID;
853 if (isa<Argument>(V))
854 return IRP_ARGUMENT;
855 if (isa<Function>(V))
856 return isReturnPosition(EncodingBits) ? IRP_RETURNED : IRP_FUNCTION;
857 if (isa<CallBase>(V))
858 return isReturnPosition(EncodingBits) ? IRP_CALL_SITE_RETURNED
860 return IRP_FLOAT;
861 }
862
864 switch (getPositionKind()) {
868 return true;
869 default:
870 return false;
871 }
872 }
873
874 /// Return true if the position is an argument or call site argument.
875 bool isArgumentPosition() const {
876 switch (getPositionKind()) {
879 return true;
880 default:
881 return false;
882 }
883 }
884
885 /// Return the same position without the call base context.
887 IRPosition Result = *this;
888 Result.CBContext = nullptr;
889 return Result;
890 }
891
892 /// Get the call base context from the position.
893 const CallBaseContext *getCallBaseContext() const { return CBContext; }
894
895 /// Check if the position has any call base context.
896 bool hasCallBaseContext() const { return CBContext != nullptr; }
897
898 /// Conversion into a void * to allow reuse of pointer hashing.
899 operator void *() const { return Enc.getOpaqueValue(); }
900
901private:
902 /// Private constructor for special values only!
903 explicit IRPosition(void *Ptr, const CallBaseContext *CBContext = nullptr)
904 : CBContext(CBContext) {
905 Enc.setFromOpaqueValue(Ptr);
906 }
907
908 /// IRPosition anchored at \p AnchorVal with kind/argument numbet \p PK.
909 explicit IRPosition(Value &AnchorVal, Kind PK,
910 const CallBaseContext *CBContext = nullptr)
911 : CBContext(CBContext) {
912 switch (PK) {
914 llvm_unreachable("Cannot create invalid IRP with an anchor value!");
915 break;
917 // Special case for floating functions.
918 if (isa<Function>(AnchorVal) || isa<CallBase>(AnchorVal))
919 Enc = {&AnchorVal, ENC_FLOATING_FUNCTION};
920 else
921 Enc = {&AnchorVal, ENC_VALUE};
922 break;
925 Enc = {&AnchorVal, ENC_VALUE};
926 break;
929 Enc = {&AnchorVal, ENC_RETURNED_VALUE};
930 break;
932 Enc = {&AnchorVal, ENC_VALUE};
933 break;
936 "Cannot create call site argument IRP with an anchor value!");
937 break;
938 }
939 verify();
940 }
941
942 /// Return the callee argument number of the associated value if it is an
943 /// argument or call site argument. See also `getCalleeArgNo` and
944 /// `getCallSiteArgNo`.
945 int getArgNo(bool CallbackCalleeArgIfApplicable) const {
946 switch (getPositionKind()) {
948 return cast<Argument>(getAsValuePtr())->getArgNo();
950 // Only call site arguments can be associated with a callback callee
951 // argument.
952 if (CallbackCalleeArgIfApplicable) {
953 if (Argument *Arg = getAssociatedArgument())
954 return Arg->getArgNo();
955 }
956 Use &U = *getAsUsePtr();
957 return cast<CallBase>(U.getUser())->getArgOperandNo(&U);
958 }
959 default:
960 return -1;
961 }
962 }
963
964 /// IRPosition for the use \p U. The position kind \p PK needs to be
965 /// IRP_CALL_SITE_ARGUMENT, the anchor value is the user, the associated value
966 /// the used value.
967 explicit IRPosition(Use &U, Kind PK) {
969 "Use constructor is for call site arguments only!");
970 Enc = {&U, ENC_CALL_SITE_ARGUMENT_USE};
971 verify();
972 }
973
974 /// Verify internal invariants.
975#ifdef EXPENSIVE_CHECKS
976 LLVM_ABI void verify();
977#else
978 void verify() {}
979#endif
980
981 /// Return the underlying pointer as Value *, valid for all positions but
982 /// IRP_CALL_SITE_ARGUMENT.
983 Value *getAsValuePtr() const {
984 assert(getEncodingBits() != ENC_CALL_SITE_ARGUMENT_USE &&
985 "Not a value pointer!");
986 return reinterpret_cast<Value *>(Enc.getPointer());
987 }
988
989 /// Return the underlying pointer as Use *, valid only for
990 /// IRP_CALL_SITE_ARGUMENT positions.
991 Use *getAsUsePtr() const {
992 assert(getEncodingBits() == ENC_CALL_SITE_ARGUMENT_USE &&
993 "Not a value pointer!");
994 return reinterpret_cast<Use *>(Enc.getPointer());
995 }
996
997 /// Return true if \p EncodingBits describe a returned or call site returned
998 /// position.
999 static bool isReturnPosition(char EncodingBits) {
1000 return EncodingBits == ENC_RETURNED_VALUE;
1001 }
1002
1003 /// The encoding of the IRPosition is a combination of a pointer and two
1004 /// encoding bits. The values of the encoding bits are defined in the enum
1005 /// below. The pointer is either a Value* (for the first three encoding bit
1006 /// combinations) or Use* (for ENC_CALL_SITE_ARGUMENT_USE).
1007 ///
1008 ///{
1009 enum {
1010 ENC_VALUE = 0b00,
1011 ENC_RETURNED_VALUE = 0b01,
1012 ENC_FLOATING_FUNCTION = 0b10,
1013 ENC_CALL_SITE_ARGUMENT_USE = 0b11,
1014 };
1015
1016 // Reserve the maximal amount of bits so there is no need to mask out the
1017 // remaining ones. We will not encode anything else in the pointer anyway.
1018 static constexpr int NumEncodingBits =
1020 static_assert(NumEncodingBits >= 2, "At least two bits are required!");
1021
1022 /// The pointer with the encoding bits.
1023 PointerIntPair<void *, NumEncodingBits, char> Enc;
1024 ///}
1025
1026 /// Call base context. Used for callsite specific analysis.
1027 const CallBaseContext *CBContext = nullptr;
1028
1029 /// Return the encoding bits.
1030 char getEncodingBits() const { return Enc.getInt(); }
1031};
1032
1033/// Helper that allows IRPosition as a key in a DenseMap.
1034template <> struct DenseMapInfo<IRPosition> {
1035 static unsigned getHashValue(const IRPosition &IRP) {
1036 return (DenseMapInfo<void *>::getHashValue(IRP) << 4) ^
1038 }
1039
1040 static bool isEqual(const IRPosition &a, const IRPosition &b) {
1041 return a == b;
1042 }
1043};
1044
1045/// A visitor class for IR positions.
1046///
1047/// Given a position P, the SubsumingPositionIterator allows to visit "subsuming
1048/// positions" wrt. attributes/information. Thus, if a piece of information
1049/// holds for a subsuming position, it also holds for the position P.
1050///
1051/// The subsuming positions always include the initial position and then,
1052/// depending on the position kind, additionally the following ones:
1053/// - for IRP_RETURNED:
1054/// - the function (IRP_FUNCTION)
1055/// - for IRP_ARGUMENT:
1056/// - the function (IRP_FUNCTION)
1057/// - for IRP_CALL_SITE:
1058/// - the callee (IRP_FUNCTION), if known
1059/// - for IRP_CALL_SITE_RETURNED:
1060/// - the callee (IRP_RETURNED), if known
1061/// - the call site (IRP_FUNCTION)
1062/// - the callee (IRP_FUNCTION), if known
1063/// - for IRP_CALL_SITE_ARGUMENT:
1064/// - the argument of the callee (IRP_ARGUMENT), if known
1065/// - the callee (IRP_FUNCTION), if known
1066/// - the position the call site argument is associated with if it is not
1067/// anchored to the call site, e.g., if it is an argument then the argument
1068/// (IRP_ARGUMENT)
1070 SmallVector<IRPosition, 4> IRPositions;
1071 using iterator = decltype(IRPositions)::iterator;
1072
1073public:
1075 iterator begin() { return IRPositions.begin(); }
1076 iterator end() { return IRPositions.end(); }
1077};
1078
1079/// Wrapper for FunctionAnalysisManager.
1081 // The client may be running the old pass manager, in which case, we need to
1082 // map the requested Analysis to its equivalent wrapper in the old pass
1083 // manager. The scheme implemented here does not require every Analysis to be
1084 // updated. Only those new analyses that the client cares about in the old
1085 // pass manager need to expose a LegacyWrapper type, and that wrapper should
1086 // support a getResult() method that matches the new Analysis.
1087 //
1088 // We need SFINAE to check for the LegacyWrapper, but function templates don't
1089 // allow partial specialization, which is needed in this case. So instead, we
1090 // use a constexpr bool to perform the SFINAE, and then use this information
1091 // inside the function template.
1092 template <typename, typename = void>
1093 static constexpr bool HasLegacyWrapper = false;
1094
1095 template <typename Analysis>
1096 typename Analysis::Result *getAnalysis(const Function &F,
1097 bool RequestCachedOnly = false) {
1098 if (!LegacyPass && !FAM)
1099 return nullptr;
1100 if (FAM) {
1101 if (CachedOnly || RequestCachedOnly)
1102 return FAM->getCachedResult<Analysis>(const_cast<Function &>(F));
1103 return &FAM->getResult<Analysis>(const_cast<Function &>(F));
1104 }
1105 if constexpr (HasLegacyWrapper<Analysis>) {
1106 if (!CachedOnly && !RequestCachedOnly)
1107 return &LegacyPass
1108 ->getAnalysis<typename Analysis::LegacyWrapper>(
1109 const_cast<Function &>(F))
1110 .getResult();
1111 if (auto *P =
1112 LegacyPass
1113 ->getAnalysisIfAvailable<typename Analysis::LegacyWrapper>())
1114 return &P->getResult();
1115 }
1116 return nullptr;
1117 }
1118
1119 /// Invalidates the analyses of each function in \p M individually, which
1120 /// allows preserving invariant function analyses like TargetLibraryInfo.
1122 assert(FAM && "Can only be used from the new PM!");
1123 for (Function &F : M)
1124 FAM->invalidate(F, PreservedAnalyses::none());
1125 }
1126
1127 AnalysisGetter(FunctionAnalysisManager &FAM, bool CachedOnly = false)
1128 : FAM(&FAM), CachedOnly(CachedOnly) {}
1129 AnalysisGetter(Pass *P, bool CachedOnly = false)
1130 : LegacyPass(P), CachedOnly(CachedOnly) {}
1131 AnalysisGetter() = default;
1132
1133private:
1134 FunctionAnalysisManager *FAM = nullptr;
1135 Pass *LegacyPass = nullptr;
1136
1137 /// If \p CachedOnly is true, no pass is created, just existing results are
1138 /// used. Also available per request.
1139 bool CachedOnly = false;
1140};
1141
1142template <typename Analysis>
1144 Analysis, std::void_t<typename Analysis::LegacyWrapper>> = true;
1145
1146/// Data structure to hold cached (LLVM-IR) information.
1147///
1148/// All attributes are given an InformationCache object at creation time to
1149/// avoid inspection of the IR by all of them individually. This default
1150/// InformationCache will hold information required by 'default' attributes,
1151/// thus the ones deduced when Attributor::identifyDefaultAbstractAttributes(..)
1152/// is called.
1153///
1154/// If custom abstract attributes, registered manually through
1155/// Attributor::registerAA(...), need more information, especially if it is not
1156/// reusable, it is advised to inherit from the InformationCache and cast the
1157/// instance down in the abstract attributes.
1161 bool UseExplorer = true)
1162 : CGSCC(CGSCC), M(M), Allocator(Allocator), AG(AG) {
1163 if (UseExplorer)
1164 Explorer = new (Allocator) MustBeExecutedContextExplorer(
1165 /* ExploreInterBlock */
1166 true, /* ExploreCFGForward */ true,
1167 /* ExploreCFGBackward */ true,
1168 /* LIGetter */
1169 [&](const Function &F) { return AG.getAnalysis<LoopAnalysis>(F); },
1170 /* DTGetter */
1171 [&](const Function &F) {
1172 return AG.getAnalysis<DominatorTreeAnalysis>(F);
1173 },
1174 /* PDTGetter */
1175 [&](const Function &F) {
1176 return AG.getAnalysis<PostDominatorTreeAnalysis>(F);
1177 });
1178 }
1179
1181 // The FunctionInfo objects are allocated via a BumpPtrAllocator, we call
1182 // the destructor manually.
1183 for (auto &It : FuncInfoMap)
1184 It.getSecond()->~FunctionInfo();
1185 // Same is true for the instruction exclusions sets.
1187 for (auto *BES : BESets)
1188 BES->~InstExclusionSetTy();
1189 if (Explorer)
1190 Explorer->~MustBeExecutedContextExplorer();
1191 }
1192
1193 /// Apply \p CB to all uses of \p F. If \p LookThroughConstantExprUses is
1194 /// true, constant expression users are not given to \p CB but their uses are
1195 /// traversed transitively.
1196 template <typename CBTy>
1197 static void foreachUse(Function &F, CBTy CB,
1198 bool LookThroughConstantExprUses = true) {
1199 SmallVector<Use *, 8> Worklist(make_pointer_range(F.uses()));
1200
1201 for (unsigned Idx = 0; Idx < Worklist.size(); ++Idx) {
1202 Use &U = *Worklist[Idx];
1203
1204 // Allow use in constant bitcasts and simply look through them.
1205 if (LookThroughConstantExprUses && isa<ConstantExpr>(U.getUser())) {
1206 for (Use &CEU : cast<ConstantExpr>(U.getUser())->uses())
1207 Worklist.push_back(&CEU);
1208 continue;
1209 }
1210
1211 CB(U);
1212 }
1213 }
1214
1215 /// The CG-SCC the pass is run on, or nullptr if it is a module pass.
1216 const SetVector<Function *> *const CGSCC = nullptr;
1217
1218 /// A vector type to hold instructions.
1220
1221 /// A map type from opcodes to instructions with this opcode.
1223 std::array<InstructionVectorTy *, Instruction::OtherOpsEnd>;
1224
1225 /// Return the map that relates "interesting" opcodes with all instructions
1226 /// with that opcode in \p F.
1228 return getFunctionInfo(F).OpcodeInstMap;
1229 }
1230
1231 /// Return the instructions in \p F that may read or write memory.
1233 return getFunctionInfo(F).RWInsts;
1234 }
1235
1236 /// Return MustBeExecutedContextExplorer
1240
1241 /// Return TargetLibraryInfo for function \p F.
1245
1246 /// Return true if \p F has the "kernel" function attribute
1247 bool isKernel(const Function &F) {
1248 FunctionInfo &FI = getFunctionInfo(F);
1249 return FI.IsKernel;
1250 }
1251
1252 /// Return true if \p Arg is involved in a must-tail call, thus the argument
1253 /// of the caller or callee.
1255 FunctionInfo &FI = getFunctionInfo(*Arg.getParent());
1256 return FI.CalledViaMustTail || FI.ContainsMustTailCall;
1257 }
1258
1260 const Function &F = *I.getFunction();
1261 FunctionInfo &FI = getFunctionInfo(F);
1262 if (!FI.AssumeOnlyValuesCollected)
1263 collectAssumeOnlyValues(FI);
1264 return AssumeOnlyValues.contains(&I);
1265 }
1266
1267 /// Invalidates the cached analyses of \p M.
1268 void invalidateAnalyses(Module &M) { AG.invalidateAnalyses(M); }
1269
1270 /// Return the analysis result from a pass \p AP for function \p F.
1271 template <typename AP>
1272 typename AP::Result *getAnalysisResultForFunction(const Function &F,
1273 bool CachedOnly = false) {
1274 return AG.getAnalysis<AP>(F, CachedOnly);
1275 }
1276
1277 const Module &getModule() const { return M; }
1278
1279 /// Return datalayout used in the module.
1280 const DataLayout &getDL() const { return M.getDataLayout(); }
1281
1282 /// Return the map conaining all the knowledge we have from `llvm.assume`s.
1283 const RetainedKnowledgeMap &getKnowledgeMap() const { return KnowledgeMap; }
1284
1285 /// Given \p BES, return a uniqued version.
1288 auto It = BESets.find(BES);
1289 if (It != BESets.end())
1290 return *It;
1291 auto *UniqueBES = new (Allocator) AA::InstExclusionSetTy(*BES);
1292 bool Success = BESets.insert(UniqueBES).second;
1293 (void)Success;
1294 assert(Success && "Expected only new entries to be added");
1295 return UniqueBES;
1296 }
1297
1298 /// Return true if the stack (llvm::Alloca) can be accessed by other threads.
1300
1301 /// Return true if the target is a GPU.
1302 bool IsTargetGPU() const { return M.getTargetTriple().isGPU(); }
1303
1304 /// Return all functions that might be called indirectly, only valid for
1305 /// closed world modules (see isClosedWorldModule).
1308
1309 /// Return true if \p F has an exact definition or is inlineable.
1310 ///
1311 /// This is computed once when the information of \p F is initialized. For
1312 /// functions that are not initialized yet, only the definition is checked,
1313 /// as InlineableFunctions is also only filled on initialization.
1314 bool isExactOrInlineable(const Function &F) const {
1315 if (const FunctionInfo *FI = FuncInfoMap.lookup(&F))
1316 return FI->IsExactOrInlineable;
1317 return F.hasExactDefinition();
1318 }
1319
1320 /// Return the flat address space if the associated target has.
1321 LLVM_ABI std::optional<unsigned> getFlatAddressSpace() const;
1322
1323 virtual unsigned getMaxAddrSpace() const { return ~0U; }
1324
1325private:
1326 struct FunctionInfo {
1327 LLVM_ABI ~FunctionInfo();
1328
1329 /// Whether the function has an exact definition or is inlineable.
1330 bool IsExactOrInlineable = false;
1331
1332 /// A nested map that remembers all instructions in a function with a
1333 /// certain instruction opcode (Instruction::getOpcode()).
1334 OpcodeInstMapTy OpcodeInstMap = {};
1335
1336 /// A map from functions to their instructions that may read or write
1337 /// memory.
1338 InstructionVectorTy RWInsts;
1339
1340 /// Function is called by a `musttail` call.
1341 bool CalledViaMustTail;
1342
1343 /// Function contains a `musttail` call.
1344 bool ContainsMustTailCall;
1345
1346 /// Function has the `"kernel"` attribute
1347 bool IsKernel;
1348
1349 /// The values only used by `llvm.assume`s in the function have been added
1350 /// to AssumeOnlyValues.
1351 bool AssumeOnlyValuesCollected = false;
1352 };
1353
1354 /// A map type from functions to informatio about it.
1355 DenseMap<const Function *, FunctionInfo *> FuncInfoMap;
1356
1357 /// Return information about the function \p F, potentially by creating it.
1358 FunctionInfo &getFunctionInfo(const Function &F) {
1359 auto [It, Inserted] = FuncInfoMap.try_emplace(&F);
1360 if (!Inserted)
1361 return *It->second;
1362
1363 // Initialization can grow the map, so don't keep a reference into it.
1364 FunctionInfo *FI = new (Allocator) FunctionInfo();
1365 It->second = FI;
1366 initializeInformationCache(F, *FI);
1367 return *FI;
1368 }
1369
1370 /// Vector of functions that might be callable indirectly, i.a., via a
1371 /// function pointer.
1372 SmallVector<Function *> IndirectlyCallableFunctions;
1373
1374 /// Add the values only used by `llvm.assume`s in the function of \p FI to
1375 /// AssumeOnlyValues. This is done on demand, as few users need them.
1376 LLVM_ABI void collectAssumeOnlyValues(FunctionInfo &FI);
1377
1378 /// Initialize the function information cache \p FI for the function \p F.
1379 ///
1380 /// This method needs to be called for all function that might be looked at
1381 /// through the information cache interface *prior* to looking at them.
1382 LLVM_ABI void initializeInformationCache(const Function &F, FunctionInfo &FI);
1383
1384 /// The module.
1385 const Module &M;
1386
1387 /// The allocator used to allocate memory, e.g. for `FunctionInfo`s.
1388 BumpPtrAllocator &Allocator;
1389
1390 /// MustBeExecutedContextExplorer
1391 MustBeExecutedContextExplorer *Explorer = nullptr;
1392
1393 /// A map with knowledge retained in `llvm.assume` instructions.
1394 RetainedKnowledgeMap KnowledgeMap;
1395
1396 /// A container for all instructions that are only used by `llvm.assume`.
1397 SetVector<const Instruction *> AssumeOnlyValues;
1398
1399 /// Cache for block sets to allow reuse.
1400 DenseSet<const AA::InstExclusionSetTy *> BESets;
1401
1402 /// Getters for analysis.
1403 AnalysisGetter &AG;
1404
1405 /// Set of inlineable functions
1406 SmallPtrSet<const Function *, 8> InlineableFunctions;
1407
1408 /// Give the Attributor access to the members so
1409 /// Attributor::identifyDefaultAbstractAttributes(...) can initialize them.
1410 friend struct Attributor;
1411};
1412
1413/// A set of kinds of abstract attributes. The kinds declared here are tested
1414/// with a bit mask, others with a list of IDs.
1415class AAKindSet {
1416public:
1417 /// Return the set of the kinds of abstract attributes of types \p AATypes.
1418 template <typename... AATypes> static constexpr AAKindSet get();
1419
1420 /// Return true if abstract attributes of type \p AAType are in the set.
1421 template <typename AAType> bool contains() const;
1422
1423private:
1424 constexpr AAKindSet(uint64_t Mask, ArrayRef<const char *> IDs)
1425 : Mask(Mask), IDs(IDs) {}
1426
1427 uint64_t Mask;
1429};
1430
1431/// Configuration for the Attributor.
1433
1435
1436 /// Is the user of the Attributor a module pass or not. This determines what
1437 /// IR we can look at and modify. If it is a module pass we might deduce facts
1438 /// outside the initial function set and modify functions outside that set,
1439 /// but only as part of the optimization of the functions in the initial
1440 /// function set. For CGSCC passes we can look at the IR of the module slice
1441 /// but never run any deduction, or perform any modification, outside the
1442 /// initial function set (which we assume is the SCC).
1443 bool IsModulePass = true;
1444
1445 /// Flag to determine if we can delete functions or keep dead ones around.
1446 bool DeleteFns = true;
1447
1448 /// Flag to determine if we rewrite function signatures.
1450
1451 /// Flag to determine if we want to initialize all default AAs for an internal
1452 /// function marked live. See also: InitializationCallback>
1454
1455 /// Flag to determine if we should skip all liveness checks early on.
1456 bool UseLiveness = true;
1457
1458 /// Flag to indicate if the entire world is contained in this module, that
1459 /// is, no outside functions exist.
1461
1462 /// Callback function to be invoked on internal functions marked live.
1463 std::function<void(Attributor &A, const Function &F)> InitializationCallback =
1464 nullptr;
1465
1466 /// Callback function to determine if an indirect call targets should be made
1467 /// direct call targets (with an if-cascade).
1468 std::function<bool(Attributor &A, const AbstractAttribute &AA, CallBase &CB,
1469 Function &AssumedCallee, unsigned NumAssumedCallees)>
1471
1472 /// Helper to update an underlying call graph and to delete functions.
1474
1475 /// If set, the only kinds of abstract attributes to create.
1476 std::optional<AAKindSet> Allowed;
1477
1478 /// Maximum number of iterations to run until fixpoint.
1479 std::optional<unsigned> MaxFixpointIterations;
1480
1481 /// A callback function that returns an ORE object from a Function pointer.
1482 ///{
1486 ///}
1487
1488 /// The name of the pass running the attributor, used to emit remarks.
1489 const char *PassName = nullptr;
1490
1491 using IPOAmendableCBTy = std::function<bool(const Function &F)>;
1493};
1494
1495/// Check the debug counter used to limit the number of AAs created. Returns
1496/// false if no further AA should be created.
1498
1499/// The fixpoint analysis framework that orchestrates the attribute deduction.
1500///
1501/// The Attributor provides a general abstract analysis framework (guided
1502/// fixpoint iteration) as well as helper functions for the deduction of
1503/// (LLVM-IR) attributes. However, also other code properties can be deduced,
1504/// propagated, and ultimately manifested through the Attributor framework. This
1505/// is particularly useful if these properties interact with attributes and a
1506/// co-scheduled deduction allows to improve the solution. Even if not, thus if
1507/// attributes/properties are completely isolated, they should use the
1508/// Attributor framework to reduce the number of fixpoint iteration frameworks
1509/// in the code base. Note that the Attributor design makes sure that isolated
1510/// attributes are not impacted, in any way, by others derived at the same time
1511/// if there is no cross-reasoning performed.
1512///
1513/// The public facing interface of the Attributor is kept simple and basically
1514/// allows abstract attributes to one thing, query abstract attributes
1515/// in-flight. There are two reasons to do this:
1516/// a) The optimistic state of one abstract attribute can justify an
1517/// optimistic state of another, allowing to framework to end up with an
1518/// optimistic (=best possible) fixpoint instead of one based solely on
1519/// information in the IR.
1520/// b) This avoids reimplementing various kinds of lookups, e.g., to check
1521/// for existing IR attributes, in favor of a single lookups interface
1522/// provided by an abstract attribute subclass.
1523///
1524/// NOTE: The mechanics of adding a new "concrete" abstract attribute are
1525/// described in the file comment.
1527
1528 /// Constructor
1529 ///
1530 /// \param Functions The set of functions we are deriving attributes for.
1531 /// \param InfoCache Cache to hold various information accessible for
1532 /// the abstract attributes.
1533 /// \param Configuration The Attributor configuration which determines what
1534 /// generic features to use.
1536 InformationCache &InfoCache,
1537 AttributorConfig Configuration);
1538
1540
1541 const IPOOptions &Opts;
1542
1543 /// Run the analyses until a fixpoint is reached or enforced (timeout).
1544 ///
1545 /// The attributes registered with this Attributor can be used after as long
1546 /// as the Attributor is not destroyed (it owns the attributes now).
1547 ///
1548 /// \Returns CHANGED if the IR was changed, otherwise UNCHANGED.
1550
1551 /// Lookup an abstract attribute of type \p AAType at position \p IRP. While
1552 /// no abstract attribute is found equivalent positions are checked, see
1553 /// SubsumingPositionIterator. Thus, the returned abstract attribute
1554 /// might be anchored at a different position, e.g., the callee if \p IRP is a
1555 /// call base.
1556 ///
1557 /// This method is the only (supported) way an abstract attribute can retrieve
1558 /// information from another abstract attribute. As an example, take an
1559 /// abstract attribute that determines the memory access behavior for a
1560 /// argument (readnone, readonly, ...). It should use `getAAFor` to get the
1561 /// most optimistic information for other abstract attributes in-flight, e.g.
1562 /// the one reasoning about the "captured" state for the argument or the one
1563 /// reasoning on the memory access behavior of the function as a whole.
1564 ///
1565 /// If the DepClass enum is set to `DepClassTy::None` the dependence from
1566 /// \p QueryingAA to the return abstract attribute is not automatically
1567 /// recorded. This should only be used if the caller will record the
1568 /// dependence explicitly if necessary, thus if it the returned abstract
1569 /// attribute is used for reasoning. To record the dependences explicitly use
1570 /// the `Attributor::recordDependence` method.
1571 template <typename AAType>
1572 const AAType *getAAFor(const AbstractAttribute &QueryingAA,
1573 const IRPosition &IRP, DepClassTy DepClass) {
1574 return getOrCreateAAFor<AAType>(IRP, &QueryingAA, DepClass,
1575 /* ForceUpdate */ false);
1576 }
1577
1578 /// The version of getAAFor that allows to omit a querying abstract
1579 /// attribute. Using this after Attributor started running is restricted to
1580 /// only the Attributor itself. Initial seeding of AAs can be done via this
1581 /// function.
1582 /// NOTE: ForceUpdate is ignored in any stage other than the update stage.
1583 template <typename AAType>
1584 const AAType *getOrCreateAAFor(IRPosition IRP,
1585 const AbstractAttribute *QueryingAA,
1586 DepClassTy DepClass, bool ForceUpdate = false,
1587 bool UpdateAfterInit = true) {
1588 if (!shouldPropagateCallBaseContext(IRP))
1589 IRP = IRP.stripCallBaseContext();
1590
1591 if (AAType *AAPtr = lookupAAFor<AAType>(IRP, QueryingAA, DepClass,
1592 /* AllowInvalidState */ true)) {
1593 if (ForceUpdate && Phase == AttributorPhase::UPDATE)
1594 updateAA(*AAPtr);
1595 return AAPtr;
1596 }
1597
1598 bool ShouldUpdateAA;
1599 if (!shouldInitialize<AAType>(IRP, ShouldUpdateAA))
1600 return nullptr;
1601
1603 return nullptr;
1604
1605 // No matching attribute found, create one.
1606 // Use the static create method.
1607 auto &AA = AAType::createForPosition(IRP, *this);
1608
1609 // Always register a new attribute to make sure we clean up the allocated
1610 // memory properly.
1611 registerAA(AA);
1612
1613 // If we are currenty seeding attributes, enforce seeding rules.
1614 if (Phase == AttributorPhase::SEEDING && !shouldSeedAttribute(AA)) {
1615 AA.getState().indicatePessimisticFixpoint();
1616 return &AA;
1617 }
1618
1619 // Bootstrap the new attribute with an initial update to propagate
1620 // information, e.g., function -> call site.
1621 {
1622 std::optional<TimeTraceScope> TimeScope;
1623 if (TimeTraceEnabled) {
1624 TimeScope.emplace("initialize", [&]() {
1625 return AA.getName().str() +
1626 std::to_string(AA.getIRPosition().getPositionKind());
1627 });
1628 }
1629
1630 ++InitializationChainLength;
1631 AA.initialize(*this);
1632 --InitializationChainLength;
1633 }
1634
1635 if (!ShouldUpdateAA) {
1636 AA.getState().indicatePessimisticFixpoint();
1637 return &AA;
1638 }
1639
1640 // Allow seeded attributes to declare dependencies.
1641 // Remember the seeding state.
1642 if (UpdateAfterInit) {
1643 AttributorPhase OldPhase = Phase;
1644 Phase = AttributorPhase::UPDATE;
1645
1646 updateAA(AA);
1647
1648 Phase = OldPhase;
1649 }
1650
1651 if (QueryingAA && AA.getState().isValidState())
1652 recordDependence(AA, const_cast<AbstractAttribute &>(*QueryingAA),
1653 DepClass);
1654 return &AA;
1655 }
1656
1657 template <typename AAType>
1658 const AAType *getOrCreateAAFor(const IRPosition &IRP) {
1659 return getOrCreateAAFor<AAType>(IRP, /* QueryingAA */ nullptr,
1661 }
1662
1663 /// Return the attribute of \p AAType for \p IRP if existing and valid. This
1664 /// also allows non-AA users lookup.
1665 template <typename AAType>
1666 AAType *lookupAAFor(const IRPosition &IRP,
1667 const AbstractAttribute *QueryingAA = nullptr,
1669 bool AllowInvalidState = false) {
1670 static_assert(std::is_base_of<AbstractAttribute, AAType>::value,
1671 "Cannot query an attribute with a type not derived from "
1672 "'AbstractAttribute'!");
1673 // Lookup the abstract attribute of type AAType. If found, return it after
1674 // registering a dependence of QueryingAA on the one returned attribute.
1675 AbstractAttribute *AAPtr = AAMap.lookup({&AAType::ID, IRP});
1676 if (!AAPtr)
1677 return nullptr;
1678
1679 AAType *AA = static_cast<AAType *>(AAPtr);
1680
1681 // Do not register a dependence on an attribute with an invalid state.
1682 if (DepClass != DepClassTy::NONE && QueryingAA &&
1683 AA->getState().isValidState())
1684 recordDependence(*AA, const_cast<AbstractAttribute &>(*QueryingAA),
1685 DepClass);
1686
1687 // Return nullptr if this attribute has an invalid state.
1688 if (!AllowInvalidState && !AA->getState().isValidState())
1689 return nullptr;
1690 return AA;
1691 }
1692
1693 /// Allows a query AA to request an update if a new query was received.
1695
1696 /// Explicitly record a dependence from \p FromAA to \p ToAA, that is if
1697 /// \p FromAA changes \p ToAA should be updated as well.
1698 ///
1699 /// This method should be used in conjunction with the `getAAFor` method and
1700 /// with the DepClass enum passed to the method set to None. This can
1701 /// be beneficial to avoid false dependences but it requires the users of
1702 /// `getAAFor` to explicitly record true dependences through this method.
1703 /// The \p DepClass flag indicates if the dependence is striclty necessary.
1704 /// That means for required dependences, if \p FromAA changes to an invalid
1705 /// state, \p ToAA can be moved to a pessimistic fixpoint because it required
1706 /// information from \p FromAA but none are available anymore.
1707 LLVM_ABI void recordDependence(const AbstractAttribute &FromAA,
1708 const AbstractAttribute &ToAA,
1709 DepClassTy DepClass);
1710
1711 /// Introduce a new abstract attribute into the fixpoint analysis.
1712 ///
1713 /// Note that ownership of the attribute is given to the Attributor. It will
1714 /// invoke delete for the Attributor on destruction of the Attributor.
1715 ///
1716 /// Attributes are identified by their IR position (AAType::getIRPosition())
1717 /// and the address of their static member (see AAType::ID).
1718 template <typename AAType> AAType &registerAA(AAType &AA) {
1719 static_assert(std::is_base_of<AbstractAttribute, AAType>::value,
1720 "Cannot register an attribute with a type not derived from "
1721 "'AbstractAttribute'!");
1722 // Put the attribute in the lookup map structure and the container we use to
1723 // keep track of all attributes.
1724 const IRPosition &IRP = AA.getIRPosition();
1725 AbstractAttribute *&AAPtr = AAMap[{&AAType::ID, IRP}];
1726
1727 assert(!AAPtr && "Attribute already in map!");
1728 AAPtr = &AA;
1729
1730 // Register AA with the synthetic root only before the manifest stage.
1731 if (isDuringDeduction())
1732 DG.SyntheticRoot.Deps.insert(
1734
1735 return AA;
1736 }
1737
1738 /// Return the internal information cache.
1739 InformationCache &getInfoCache() { return InfoCache; }
1740
1741 /// Return the module.
1742 const Module &getModule() { return InfoCache.getModule(); }
1743
1744 /// Return true if this is a module pass, false otherwise.
1745 bool isModulePass() const { return Configuration.IsModulePass; }
1746
1747 /// Return true if we should specialize the call site \b CB for the potential
1748 /// callee \p Fn.
1750 CallBase &CB, Function &Callee,
1751 unsigned NumAssumedCallees) {
1752 return Configuration.IndirectCalleeSpecializationCallback
1753 ? Configuration.IndirectCalleeSpecializationCallback(
1754 *this, AA, CB, Callee, NumAssumedCallees)
1755 : true;
1756 }
1757
1758 /// Return true if the module contains the whole world, thus, no outside
1759 /// functions exist.
1760 LLVM_ABI bool isClosedWorldModule() const;
1761
1762 /// Return true if we derive attributes for \p Fn
1763 bool isRunOn(Function &Fn) const { return isRunOn(&Fn); }
1764 bool isRunOn(Function *Fn) const {
1765 return Functions.empty() || Functions.count(Fn);
1766 }
1767
1768 template <typename AAType> bool shouldUpdateAA(const IRPosition &IRP) {
1769 // If this is queried in the manifest stage, we force the AA to indicate
1770 // pessimistic fixpoint immediately.
1771 if (!isDuringDeduction())
1772 return false;
1773
1774 Function *AssociatedFn = IRP.getAssociatedFunction();
1775
1776 if (IRP.isAnyCallSitePosition()) {
1777 // Check if we require a callee but there is none.
1778 if (!AssociatedFn && AAType::requiresCalleeForCallBase())
1779 return false;
1780
1781 // Check if we require non-asm but it is inline asm.
1782 if (AAType::requiresNonAsmForCallBase() &&
1783 cast<CallBase>(IRP.getAnchorValue()).isInlineAsm())
1784 return false;
1785 }
1786
1787 // Check if we require a calles but we can't see all.
1788 if (AAType::requiresCallersForArgOrFunction())
1791 if (!AssociatedFn->hasLocalLinkage())
1792 return false;
1793
1794 if (!AAType::isValidIRPositionForUpdate(*this, IRP))
1795 return false;
1796
1797 // We update only AAs associated with functions in the Functions set or
1798 // call sites of them.
1799 return (!AssociatedFn || isModulePass() || isRunOn(AssociatedFn) ||
1800 isRunOn(IRP.getAnchorScope()));
1801 }
1802
1803 template <typename AAType>
1804 bool shouldInitialize(const IRPosition &IRP, bool &ShouldUpdateAA) {
1805 if (!AAType::isValidIRPositionForInit(*this, IRP))
1806 return false;
1807
1808 if (Configuration.Allowed && !Configuration.Allowed->contains<AAType>())
1809 return false;
1810
1811 // For now we skip anything in naked and optnone functions.
1812 const Function *AnchorFn = IRP.getAnchorScope();
1813 if (AnchorFn && (AnchorFn->hasFnAttribute(Attribute::Naked) ||
1814 AnchorFn->hasFnAttribute(Attribute::OptimizeNone)))
1815 return false;
1816
1817 // Avoid too many nested initializations to prevent a stack overflow.
1818 if (InitializationChainLength > MaxInitializationChainLength)
1819 return false;
1820
1821 ShouldUpdateAA = shouldUpdateAA<AAType>(IRP);
1822
1823 return !AAType::hasTrivialInitializer() || ShouldUpdateAA;
1824 }
1825
1826 /// Determine opportunities to derive 'default' attributes in \p F and create
1827 /// abstract attribute objects for them.
1828 ///
1829 /// \param F The function that is checked for attribute opportunities.
1830 ///
1831 /// Note that abstract attribute instances are generally created even if the
1832 /// IR already contains the information they would deduce. The most important
1833 /// reason for this is the single interface, the one of the abstract attribute
1834 /// instance, which can be queried without the need to look at the IR in
1835 /// various places.
1837
1838 /// Determine whether the function \p F is IPO amendable
1839 ///
1840 /// If a function is exactly defined or it has alwaysinline attribute
1841 /// and is viable to be inlined, we say it is IPO amendable
1843 return InfoCache.isExactOrInlineable(F) ||
1844 (Configuration.IPOAmendableCB && Configuration.IPOAmendableCB(F));
1845 }
1846
1847 /// Return true if the body of the associated function can be used to derive
1848 /// information for \p IRP.
1849 ///
1850 /// That is not the case for the interface (function, argument and return
1851 /// positions) of a function that might be replaced by another definition,
1852 /// e.g. a linkonce_odr function.
1853 bool canUseBodyFor(const IRPosition &IRP) {
1854 return !IRP.isFnInterfaceKind() ||
1856 }
1857
1858 /// Return whether attributes can participate in fixed-point deduction.
1859 bool isDuringDeduction() const {
1860 return Phase == AttributorPhase::SEEDING ||
1861 Phase == AttributorPhase::UPDATE;
1862 }
1863
1864 /// Mark the internal function \p F as live.
1865 ///
1866 /// This will trigger the identification and initialization of attributes for
1867 /// \p F.
1869 assert(F.hasLocalLinkage() &&
1870 "Only local linkage is assumed dead initially.");
1871
1872 if (Configuration.DefaultInitializeLiveInternals)
1874 if (Configuration.InitializationCallback)
1875 Configuration.InitializationCallback(*this, F);
1876 }
1877
1878 /// Record that \p U is to be replaces with \p NV after information was
1879 /// manifested. This also triggers deletion of trivially dead istructions.
1881 Value *&V = ToBeChangedUses[&U];
1882 if (V && (V->stripPointerCasts() == NV.stripPointerCasts() ||
1884 return false;
1885 assert((!V || V == &NV || isa<UndefValue>(NV)) &&
1886 "Use was registered twice for replacement with different values!");
1887 V = &NV;
1888 return true;
1889 }
1890
1891 /// Helper function to replace all uses associated with \p IRP with \p NV.
1892 /// Return true if there is any change. The flag \p ChangeDroppable indicates
1893 /// if dropppable uses should be changed too.
1895 bool ChangeDroppable = true) {
1897 auto *CB = cast<CallBase>(IRP.getCtxI());
1899 CB->getArgOperandUse(IRP.getCallSiteArgNo()), NV);
1900 }
1901 Value &V = IRP.getAssociatedValue();
1902 auto &Entry = ToBeChangedValues[&V];
1903 Value *CurNV = get<0>(Entry);
1904 if (CurNV && (CurNV->stripPointerCasts() == NV.stripPointerCasts() ||
1905 isa<UndefValue>(CurNV)))
1906 return false;
1907 assert((!CurNV || CurNV == &NV || isa<UndefValue>(NV)) &&
1908 "Value replacement was registered twice with different values!");
1909 Entry = {&NV, ChangeDroppable};
1910 return true;
1911 }
1912
1913 /// Record that \p I is to be replaced with `unreachable` after information
1914 /// was manifested.
1916 ToBeChangedToUnreachableInsts.insert(I);
1917 }
1918
1919 /// Record that \p II has at least one dead successor block. This information
1920 /// is used, e.g., to replace \p II with a call, after information was
1921 /// manifested.
1923 InvokeWithDeadSuccessor.insert(&II);
1924 }
1925
1926 /// Record that \p I is deleted after information was manifested. This also
1927 /// triggers deletion of trivially dead istructions.
1928 void deleteAfterManifest(Instruction &I) { ToBeDeletedInsts.insert(&I); }
1929
1930 /// Record that \p BB is deleted after information was manifested. This also
1931 /// triggers deletion of trivially dead istructions.
1932 void deleteAfterManifest(BasicBlock &BB) { ToBeDeletedBlocks.insert(&BB); }
1933
1934 // Record that \p BB is added during the manifest of an AA. Added basic blocks
1935 // are preserved in the IR.
1937 ManifestAddedBlocks.insert(&BB);
1938 }
1939
1940 /// Record that \p F is deleted after information was manifested.
1942 if (Configuration.DeleteFns)
1943 ToBeDeletedFunctions.insert(&F);
1944 }
1945
1946 /// Return the attributes of kind \p AK existing in the IR as operand bundles
1947 /// of an llvm.assume.
1948 LLVM_ABI bool getAttrsFromAssumes(const IRPosition &IRP,
1951
1952 /// Return true if any kind in \p AKs existing in the IR at a position that
1953 /// will affect this one. See also getAttrs(...).
1954 /// \param IgnoreSubsumingPositions Flag to determine if subsuming positions,
1955 /// e.g., the function position if this is an
1956 /// argument position, should be ignored.
1957 LLVM_ABI bool
1959 bool IgnoreSubsumingPositions = false,
1960 Attribute::AttrKind ImpliedAttributeKind = Attribute::None);
1961
1962 /// Return the attributes of any kind in \p AKs existing in the IR at a
1963 /// position that will affect this one. While each position can only have a
1964 /// single attribute of any kind in \p AKs, there are "subsuming" positions
1965 /// that could have an attribute as well. This method returns all attributes
1966 /// found in \p Attrs.
1967 /// \param IgnoreSubsumingPositions Flag to determine if subsuming positions,
1968 /// e.g., the function position if this is an
1969 /// argument position, should be ignored.
1970 LLVM_ABI void getAttrs(const IRPosition &IRP,
1973 bool IgnoreSubsumingPositions = false);
1974
1975 /// Remove all \p AttrKinds attached to \p IRP.
1979 ArrayRef<StringRef> Attrs);
1980
1981 /// Attach \p DeducedAttrs to \p IRP, if \p ForceReplace is set we do this
1982 /// even if the same attribute kind was already present. \p DeducedAttrs
1983 /// must be sorted like an attribute set, with at most one attribute of each
1984 /// kind.
1986 ArrayRef<Attribute> DeducedAttrs,
1987 bool ForceReplace = false);
1988
1989private:
1990 /// Helper to check \p Attrs for \p AK, if not found, check if \p
1991 /// AAType::isImpliedByIR is true, and if not, create AAType for \p IRP.
1992 /// If \p SkipHasAttrCheck is true, don't check whether the attribute is set
1993 /// first. This should be used if only some values of a complex IR attribute
1994 /// imply the AAType.
1995 template <Attribute::AttrKind AK, typename AAType>
1996 void checkAndQueryIRAttr(const IRPosition &IRP, AttributeSet Attrs,
1997 bool SkipHasAttrCheck = false);
1998
1999 /// Helper to apply \p CB on all attributes of type \p AttrDescs of \p IRP.
2000 template <typename DescTy>
2001 ChangeStatus updateAttrMap(const IRPosition &IRP, ArrayRef<DescTy> AttrDescs,
2002 function_ref<bool(const DescTy &, AttributeSet,
2003 AttributeMask &, AttrBuilder &)>
2004 CB);
2005
2006 /// Mapping from functions/call sites to their attributes.
2008
2009public:
2010 /// If \p IRP is assumed to be a constant, return it, if it is unclear yet,
2011 /// return std::nullopt, otherwise return `nullptr`.
2012 LLVM_ABI std::optional<Constant *>
2014 bool &UsedAssumedInformation);
2015 std::optional<Constant *> getAssumedConstant(const Value &V,
2016 const AbstractAttribute &AA,
2017 bool &UsedAssumedInformation) {
2018 return getAssumedConstant(IRPosition::value(V), AA, UsedAssumedInformation);
2019 }
2020
2021 /// If \p V is assumed simplified, return it, if it is unclear yet,
2022 /// return std::nullopt, otherwise return `nullptr`.
2023 std::optional<Value *> getAssumedSimplified(const IRPosition &IRP,
2024 const AbstractAttribute &AA,
2025 bool &UsedAssumedInformation,
2026 AA::ValueScope S) {
2027 return getAssumedSimplified(IRP, &AA, UsedAssumedInformation, S);
2028 }
2029 std::optional<Value *> getAssumedSimplified(const Value &V,
2030 const AbstractAttribute &AA,
2031 bool &UsedAssumedInformation,
2032 AA::ValueScope S) {
2034 UsedAssumedInformation, S);
2035 }
2036
2037 /// If \p V is assumed simplified, return it, if it is unclear yet,
2038 /// return std::nullopt, otherwise return `nullptr`. Same as the public
2039 /// version except that it can be used without recording dependences on any \p
2040 /// AA.
2041 LLVM_ABI std::optional<Value *>
2043 bool &UsedAssumedInformation, AA::ValueScope S);
2044
2045 /// Try to simplify \p IRP and in the scope \p S. If successful, true is
2046 /// returned and all potential values \p IRP can take are put into \p Values.
2047 /// If the result in \p Values contains select or PHI instructions it means
2048 /// those could not be simplified to a single value. Recursive calls with
2049 /// these instructions will yield their respective potential values. If false
2050 /// is returned no other information is valid.
2051 LLVM_ABI bool
2054 AA::ValueScope S, bool &UsedAssumedInformation,
2055 bool RecurseForSelectAndPHI = true);
2056
2057 /// Register \p CB as a simplification callback.
2058 /// `Attributor::getAssumedSimplified` will use these callbacks before
2059 /// we it will ask `AAValueSimplify`. It is important to ensure this
2060 /// is called before `identifyDefaultAbstractAttributes`, assuming the
2061 /// latter is called at all.
2062 using SimplifictionCallbackTy = std::function<std::optional<Value *>(
2063 const IRPosition &, const AbstractAttribute *, bool &)>;
2065 const SimplifictionCallbackTy &CB) {
2066 SimplificationCallbacks[IRP].emplace_back(CB);
2067 }
2068
2069 /// Return true if there is a simplification callback for \p IRP.
2071 return SimplificationCallbacks.count(IRP);
2072 }
2073
2074 /// Register \p CB as a simplification callback.
2075 /// Similar to \p registerSimplificationCallback, the call back will be called
2076 /// first when we simplify a global variable \p GV.
2078 std::function<std::optional<Constant *>(
2079 const GlobalVariable &, const AbstractAttribute *, bool &)>;
2081 const GlobalVariable &GV,
2083 GlobalVariableSimplificationCallbacks[&GV].emplace_back(CB);
2084 }
2085
2086 /// Return true if there is a simplification callback for \p GV.
2088 return GlobalVariableSimplificationCallbacks.count(&GV);
2089 }
2090
2091 /// Return \p std::nullopt if there is no call back registered for \p GV or
2092 /// the call back is still not sure if \p GV can be simplified. Return \p
2093 /// nullptr if \p GV can't be simplified.
2094 std::optional<Constant *>
2096 const AbstractAttribute *AA,
2097 bool &UsedAssumedInformation) {
2098 assert(GlobalVariableSimplificationCallbacks.contains(&GV));
2099 for (auto &CB : GlobalVariableSimplificationCallbacks.lookup(&GV)) {
2100 auto SimplifiedGV = CB(GV, AA, UsedAssumedInformation);
2101 // For now we assume the call back will not return a std::nullopt.
2102 assert(SimplifiedGV.has_value() && "SimplifiedGV has not value");
2103 return *SimplifiedGV;
2104 }
2105 llvm_unreachable("there must be a callback registered");
2106 }
2107
2109 std::function<bool(Attributor &, const AbstractAttribute *)>;
2111 const VirtualUseCallbackTy &CB) {
2112 VirtualUseCallbacks[&V].emplace_back(CB);
2113 }
2114
2115private:
2116 /// The vector with all simplification callbacks registered by outside AAs.
2118 SimplificationCallbacks;
2119
2120 /// The vector with all simplification callbacks for global variables
2121 /// registered by outside AAs.
2122 DenseMap<const GlobalVariable *,
2124 GlobalVariableSimplificationCallbacks;
2125
2127 VirtualUseCallbacks;
2128
2129public:
2130 /// Translate \p V from the callee context into the call site context.
2131 LLVM_ABI std::optional<Value *>
2132 translateArgumentToCallSiteContent(std::optional<Value *> V, CallBase &CB,
2133 const AbstractAttribute &AA,
2134 bool &UsedAssumedInformation);
2135
2136 /// Return true if \p AA (or its context instruction) is assumed dead.
2137 ///
2138 /// If \p LivenessAA is not provided it is queried.
2140 const AAIsDead *LivenessAA,
2141 bool &UsedAssumedInformation,
2142 bool CheckBBLivenessOnly = false,
2143 DepClassTy DepClass = DepClassTy::OPTIONAL);
2144
2145 /// Return true if \p I is assumed dead.
2146 ///
2147 /// If \p LivenessAA is not provided it is queried.
2148 LLVM_ABI bool isAssumedDead(const Instruction &I,
2149 const AbstractAttribute *QueryingAA,
2150 const AAIsDead *LivenessAA,
2151 bool &UsedAssumedInformation,
2152 bool CheckBBLivenessOnly = false,
2154 bool CheckForDeadStore = false);
2155
2156 /// Return true if \p U is assumed dead.
2157 ///
2158 /// If \p FnLivenessAA is not provided it is queried.
2159 LLVM_ABI bool isAssumedDead(const Use &U, const AbstractAttribute *QueryingAA,
2160 const AAIsDead *FnLivenessAA,
2161 bool &UsedAssumedInformation,
2162 bool CheckBBLivenessOnly = false,
2163 DepClassTy DepClass = DepClassTy::OPTIONAL);
2164
2165 /// Return true if \p IRP is assumed dead.
2166 ///
2167 /// If \p FnLivenessAA is not provided it is queried.
2168 LLVM_ABI bool isAssumedDead(const IRPosition &IRP,
2169 const AbstractAttribute *QueryingAA,
2170 const AAIsDead *FnLivenessAA,
2171 bool &UsedAssumedInformation,
2172 bool CheckBBLivenessOnly = false,
2173 DepClassTy DepClass = DepClassTy::OPTIONAL);
2174
2175 /// Return true if \p BB is assumed dead.
2176 ///
2177 /// If \p LivenessAA is not provided it is queried.
2178 LLVM_ABI bool isAssumedDead(const BasicBlock &BB,
2179 const AbstractAttribute *QueryingAA,
2180 const AAIsDead *FnLivenessAA,
2181 DepClassTy DepClass = DepClassTy::OPTIONAL);
2182
2183 /// Check \p Pred on all potential Callees of \p CB.
2184 ///
2185 /// This method will evaluate \p Pred with all potential callees of \p CB as
2186 /// input and return true if \p Pred does. If some callees might be unknown
2187 /// this function will return false.
2190 const AbstractAttribute &QueryingAA, const CallBase &CB);
2191
2192 /// Check \p Pred on all (transitive) uses of \p V.
2193 ///
2194 /// This method will evaluate \p Pred on all (transitive) uses of the
2195 /// associated value and return true if \p Pred holds every time.
2196 /// If uses are skipped in favor of equivalent ones, e.g., if we look through
2197 /// memory, the \p EquivalentUseCB will be used to give the caller an idea
2198 /// what original used was replaced by a new one (or new ones). The visit is
2199 /// cut short if \p EquivalentUseCB returns false and the function will return
2200 /// false as well.
2202 function_ref<bool(const Use &, bool &)> Pred,
2203 const AbstractAttribute &QueryingAA, const Value &V,
2204 bool CheckBBLivenessOnly = false,
2205 DepClassTy LivenessDepClass = DepClassTy::OPTIONAL,
2206 bool IgnoreDroppableUses = true,
2207 function_ref<bool(const Use &OldU, const Use &NewU)> EquivalentUseCB =
2208 nullptr);
2209
2210 /// Emit a remark generically.
2211 ///
2212 /// This template function can be used to generically emit a remark. The
2213 /// RemarkKind should be one of the following:
2214 /// - OptimizationRemark to indicate a successful optimization attempt
2215 /// - OptimizationRemarkMissed to report a failed optimization attempt
2216 /// - OptimizationRemarkAnalysis to provide additional information about an
2217 /// optimization attempt
2218 ///
2219 /// The remark is built using a callback function \p RemarkCB that takes a
2220 /// RemarkKind as input and returns a RemarkKind.
2221 template <typename RemarkKind, typename RemarkCallBack>
2223 RemarkCallBack &&RemarkCB) const {
2224 if (!Configuration.OREGetter)
2225 return;
2226
2227 Function *F = I->getFunction();
2228 auto &ORE = Configuration.OREGetter(F);
2229
2230 if (RemarkName.starts_with("OMP"))
2231 ORE.emit([&]() {
2232 return RemarkCB(RemarkKind(Configuration.PassName, RemarkName, I))
2233 << " [" << RemarkName << "]";
2234 });
2235 else
2236 ORE.emit([&]() {
2237 return RemarkCB(RemarkKind(Configuration.PassName, RemarkName, I));
2238 });
2239 }
2240
2241 /// Emit a remark on a function.
2242 template <typename RemarkKind, typename RemarkCallBack>
2243 void emitRemark(Function *F, StringRef RemarkName,
2244 RemarkCallBack &&RemarkCB) const {
2245 if (!Configuration.OREGetter)
2246 return;
2247
2248 auto &ORE = Configuration.OREGetter(F);
2249
2250 if (RemarkName.starts_with("OMP"))
2251 ORE.emit([&]() {
2252 return RemarkCB(RemarkKind(Configuration.PassName, RemarkName, F))
2253 << " [" << RemarkName << "]";
2254 });
2255 else
2256 ORE.emit([&]() {
2257 return RemarkCB(RemarkKind(Configuration.PassName, RemarkName, F));
2258 });
2259 }
2260
2261 /// Helper struct used in the communication between an abstract attribute (AA)
2262 /// that wants to change the signature of a function and the Attributor which
2263 /// applies the changes. The struct is partially initialized with the
2264 /// information from the AA (see the constructor). All other members are
2265 /// provided by the Attributor prior to invoking any callbacks.
2266 struct ArgumentReplacementInfo {
2267 /// Callee repair callback type
2268 ///
2269 /// The function repair callback is invoked once to rewire the replacement
2270 /// arguments in the body of the new function. The argument replacement info
2271 /// is passed, as build from the registerFunctionSignatureRewrite call, as
2272 /// well as the replacement function and an iteratore to the first
2273 /// replacement argument.
2274 using CalleeRepairCBTy = std::function<void(
2275 const ArgumentReplacementInfo &, Function &, Function::arg_iterator)>;
2276
2277 /// Abstract call site (ACS) repair callback type
2278 ///
2279 /// The abstract call site repair callback is invoked once on every abstract
2280 /// call site of the replaced function (\see ReplacedFn). The callback needs
2281 /// to provide the operands for the call to the new replacement function.
2282 /// The number and type of the operands appended to the provided vector
2283 /// (second argument) is defined by the number and types determined through
2284 /// the replacement type vector (\see ReplacementTypes). The first argument
2285 /// is the ArgumentReplacementInfo object registered with the Attributor
2286 /// through the registerFunctionSignatureRewrite call.
2288 std::function<void(const ArgumentReplacementInfo &, AbstractCallSite,
2290
2291 /// Simple getters, see the corresponding members for details.
2292 ///{
2293
2294 Attributor &getAttributor() const { return A; }
2295 const Function &getReplacedFn() const { return ReplacedFn; }
2296 const Argument &getReplacedArg() const { return ReplacedArg; }
2297 unsigned getNumReplacementArgs() const { return ReplacementTypes.size(); }
2298
2299 ///}
2300
2301 private:
2302 /// Constructor that takes the argument to be replaced, the types of
2303 /// the replacement arguments, as well as callbacks to repair the call sites
2304 /// and new function after the replacement happened.
2306 ArrayRef<Type *> ReplacementTypes,
2307 CalleeRepairCBTy &&CalleeRepairCB,
2308 ACSRepairCBTy &&ACSRepairCB)
2309 : A(A), ReplacedFn(*Arg.getParent()), ReplacedArg(Arg),
2310 ReplacementTypes(ReplacementTypes),
2311 CalleeRepairCB(std::move(CalleeRepairCB)),
2312 ACSRepairCB(std::move(ACSRepairCB)) {}
2313
2314 /// Reference to the attributor to allow access from the callbacks.
2315 Attributor &A;
2316
2317 /// The "old" function replaced by ReplacementFn.
2318 const Function &ReplacedFn;
2319
2320 /// The "old" argument replaced by new ones defined via ReplacementTypes.
2321 const Argument &ReplacedArg;
2322
2323 /// The types of the arguments replacing ReplacedArg.
2324 const SmallVector<Type *, 8> ReplacementTypes;
2325
2326 /// Callee repair callback, see CalleeRepairCBTy.
2327 const CalleeRepairCBTy CalleeRepairCB;
2328
2329 /// Abstract call site (ACS) repair callback, see ACSRepairCBTy.
2330 const ACSRepairCBTy ACSRepairCB;
2331
2332 /// Allow access to the private members from the Attributor.
2333 friend struct Attributor;
2334 };
2335
2336 /// Check if we can rewrite a function signature.
2337 ///
2338 /// The argument \p Arg is replaced with new ones defined by the number,
2339 /// order, and types in \p ReplacementTypes.
2340 ///
2341 /// \returns True, if the replacement can be registered, via
2342 /// registerFunctionSignatureRewrite, false otherwise.
2343 LLVM_ABI bool
2345 ArrayRef<Type *> ReplacementTypes);
2346
2347 /// Register a rewrite for a function signature.
2348 ///
2349 /// The argument \p Arg is replaced with new ones defined by the number,
2350 /// order, and types in \p ReplacementTypes. The rewiring at the call sites is
2351 /// done through \p ACSRepairCB and at the callee site through
2352 /// \p CalleeRepairCB.
2353 ///
2354 /// \returns True, if the replacement was registered, false otherwise.
2356 Argument &Arg, ArrayRef<Type *> ReplacementTypes,
2359
2360 /// Check \p Pred on all function call sites.
2361 ///
2362 /// This method will evaluate \p Pred on call sites and return
2363 /// true if \p Pred holds in every call sites. However, this is only possible
2364 /// all call sites are known, hence the function has internal linkage.
2365 /// If true is returned, \p UsedAssumedInformation is set if assumed
2366 /// information was used to skip or simplify potential call sites.
2368 const AbstractAttribute &QueryingAA,
2369 bool RequireAllCallSites,
2370 bool &UsedAssumedInformation);
2371
2372 /// Check \p Pred on all call sites of \p Fn.
2373 ///
2374 /// This method will evaluate \p Pred on call sites and return
2375 /// true if \p Pred holds in every call sites. However, this is only possible
2376 /// all call sites are known, hence the function has internal linkage.
2377 /// If true is returned, \p UsedAssumedInformation is set if assumed
2378 /// information was used to skip or simplify potential call sites.
2380 const Function &Fn,
2381 bool RequireAllCallSites,
2382 const AbstractAttribute *QueryingAA,
2383 bool &UsedAssumedInformation,
2384 bool CheckPotentiallyDead = false);
2385
2386 /// Check \p Pred on all values potentially returned by the function
2387 /// associated with \p QueryingAA.
2388 ///
2389 /// This is the context insensitive version of the method above.
2390 LLVM_ABI bool
2392 const AbstractAttribute &QueryingAA,
2394 bool RecurseForSelectAndPHI = true);
2395
2396 /// Check \p Pred on all instructions in \p Fn with an opcode present in
2397 /// \p Opcodes.
2398 ///
2399 /// This method will evaluate \p Pred on all instructions with an opcode
2400 /// present in \p Opcode and return true if \p Pred holds on all of them.
2402 const Function *Fn,
2403 const AbstractAttribute *QueryingAA,
2404 ArrayRef<unsigned> Opcodes,
2405 bool &UsedAssumedInformation,
2406 bool CheckBBLivenessOnly = false,
2407 bool CheckPotentiallyDead = false);
2408
2409 /// Check \p Pred on all instructions with an opcode present in \p Opcodes.
2410 ///
2411 /// This method will evaluate \p Pred on all instructions with an opcode
2412 /// present in \p Opcode and return true if \p Pred holds on all of them.
2414 const AbstractAttribute &QueryingAA,
2415 ArrayRef<unsigned> Opcodes,
2416 bool &UsedAssumedInformation,
2417 bool CheckBBLivenessOnly = false,
2418 bool CheckPotentiallyDead = false);
2419
2420 /// Check \p Pred on all call-like instructions (=CallBased derived).
2421 ///
2422 /// See checkForAllCallLikeInstructions(...) for more information.
2424 const AbstractAttribute &QueryingAA,
2425 bool &UsedAssumedInformation,
2426 bool CheckBBLivenessOnly = false,
2427 bool CheckPotentiallyDead = false) {
2429 Pred, QueryingAA,
2430 {(unsigned)Instruction::Invoke, (unsigned)Instruction::CallBr,
2431 (unsigned)Instruction::Call},
2432 UsedAssumedInformation, CheckBBLivenessOnly, CheckPotentiallyDead);
2433 }
2434
2435 /// Check \p Pred on all Read/Write instructions.
2436 ///
2437 /// This method will evaluate \p Pred on all instructions that read or write
2438 /// to memory present in the information cache and return true if \p Pred
2439 /// holds on all of them.
2440 LLVM_ABI bool
2442 AbstractAttribute &QueryingAA,
2443 bool &UsedAssumedInformation);
2444
2445 /// Create a shallow wrapper for \p F such that \p F has internal linkage
2446 /// afterwards. It also sets the original \p F 's name to anonymous
2447 ///
2448 /// A wrapper is a function with the same type (and attributes) as \p F
2449 /// that will only call \p F and return the result, if any.
2450 ///
2451 /// Assuming the declaration of looks like:
2452 /// rty F(aty0 arg0, ..., atyN argN);
2453 ///
2454 /// The wrapper will then look as follows:
2455 /// rty wrapper(aty0 arg0, ..., atyN argN) {
2456 /// return F(arg0, ..., argN);
2457 /// }
2458 ///
2460
2461 /// Returns true if the function \p F can be internalized. i.e. it has a
2462 /// compatible linkage.
2463 LLVM_ABI static bool isInternalizable(Function &F);
2464
2465 /// Make another copy of the function \p F such that the copied version has
2466 /// internal linkage afterwards and can be analysed. Then we replace all uses
2467 /// of the original function to the copied one
2468 ///
2469 /// Only non-locally linked functions that have `linkonce_odr` or `weak_odr`
2470 /// linkage can be internalized because these linkages guarantee that other
2471 /// definitions with the same name have the same semantics as this one.
2472 ///
2473 /// This will only be run if the `attributor-allow-deep-wrappers` option is
2474 /// set, or if the function is called with \p Force set to true.
2475 ///
2476 /// If the function \p F failed to be internalized the return value will be a
2477 /// null pointer.
2479 bool Force = false);
2480
2481 /// Make copies of each function in the set \p FnSet such that the copied
2482 /// version has internal linkage afterwards and can be analysed. Then we
2483 /// replace all uses of the original function to the copied one. The map
2484 /// \p FnMap contains a mapping of functions to their internalized versions.
2485 ///
2486 /// Only non-locally linked functions that have `linkonce_odr` or `weak_odr`
2487 /// linkage can be internalized because these linkages guarantee that other
2488 /// definitions with the same name have the same semantics as this one.
2489 ///
2490 /// This version will internalize all the functions in the set \p FnSet at
2491 /// once and then replace the uses. This prevents internalized functions being
2492 /// called by external functions when there is an internalized version in the
2493 /// module.
2494 LLVM_ABI static bool
2497
2498 /// Return the data layout associated with the anchor scope.
2499 const DataLayout &getDataLayout() const { return InfoCache.getDL(); }
2500
2501 /// The allocator used to allocate memory, e.g. for `AbstractAttribute`s.
2503
2505 return CGModifiedFunctions;
2506 }
2507
2508 /// Return the functions whose attributes, or whose call site attributes,
2509 /// were changed.
2511 return AttrModifiedFunctions;
2512 }
2513
2514private:
2515 /// This method will do fixpoint iteration until fixpoint or the
2516 /// maximum iteration count is reached.
2517 ///
2518 /// If the maximum iteration count is reached, This method will
2519 /// indicate pessimistic fixpoint on attributes that transitively depend
2520 /// on attributes that were scheduled for an update.
2521 void runTillFixpoint();
2522
2523 /// Gets called after scheduling, manifests attributes to the LLVM IR.
2524 ChangeStatus manifestAttributes();
2525
2526 /// Gets called after attributes have been manifested, cleans up the IR.
2527 /// Deletes dead functions, blocks and instructions.
2528 /// Rewrites function signitures and updates the call graph.
2529 ChangeStatus cleanupIR();
2530
2531 /// Identify internal functions that are effectively dead, thus not reachable
2532 /// from a live entry point. The functions are added to ToBeDeletedFunctions.
2533 void identifyDeadInternalFunctions();
2534
2535 /// Run `::update` on \p AA and track the dependences queried while doing so.
2536 /// Also adjust the state if we know further updates are not necessary.
2538
2539 /// Remember the dependences on the top of the dependence stack such that they
2540 /// may trigger further updates. (\see DependenceStack)
2541 void rememberDependences();
2542
2543 /// Determine if CallBase context in \p IRP should be propagated.
2544 LLVM_ABI bool shouldPropagateCallBaseContext(const IRPosition &IRP);
2545
2546 /// Apply all requested function signature rewrites
2547 /// (\see registerFunctionSignatureRewrite) and return Changed if the module
2548 /// was altered.
2550 rewriteFunctionSignatures(SmallSetVector<Function *, 8> &ModifiedFns);
2551
2552 /// Check if the Attribute \p AA should be seeded.
2553 /// See getOrCreateAAFor.
2554 LLVM_ABI bool shouldSeedAttribute(AbstractAttribute &AA);
2555
2556 /// A nested map to lookup abstract attributes based on the argument position
2557 /// on the outer level, and the addresses of the static member (AAType::ID) on
2558 /// the inner level.
2559 ///{
2560 using AAMapKeyTy = std::pair<const char *, IRPosition>;
2561 /// The IDs are adjacent bytes and the positions of a value differ only in
2562 /// the low bits, both of which the default hash functions mostly ignore.
2563 struct AAMapKeyInfo : DenseMapInfo<AAMapKeyTy> {
2564 static unsigned getHashValue(const AAMapKeyTy &Key) {
2565 const IRPosition &IRP = Key.second;
2566 auto ID = reinterpret_cast<uintptr_t>(Key.first);
2567 auto Pos = reinterpret_cast<uintptr_t>(static_cast<void *>(IRP));
2568 auto Ctx = reinterpret_cast<uintptr_t>(IRP.getCallBaseContext());
2569 return detail::combineHashValue(unsigned(ID), unsigned(Pos ^ Ctx));
2570 }
2571 };
2572 DenseMap<AAMapKeyTy, AbstractAttribute *, AAMapKeyInfo> AAMap;
2573 ///}
2574
2575 /// Map to remember all requested signature changes (= argument replacements).
2576 /// A MapVector so the functions are rewritten in a deterministic order.
2577 MapVector<Function *,
2579 ArgumentReplacementMap;
2580
2581 /// The set of functions we are deriving attributes for.
2582 SetVector<Function *> &Functions;
2583
2584 /// The information cache that holds pre-processed (LLVM-IR) information.
2585 InformationCache &InfoCache;
2586
2587 /// Abstract Attribute dependency graph
2588 AADepGraph DG;
2589
2590 /// Set of functions for which we modified the content such that it might
2591 /// impact the call graph.
2592 SmallSetVector<Function *, 8> CGModifiedFunctions;
2593
2594 /// Set of functions whose attributes, or whose call site attributes, were
2595 /// changed during manifest.
2596 SmallSetVector<Function *, 8> AttrModifiedFunctions;
2597
2598 /// Information about a dependence. If FromAA is changed ToAA needs to be
2599 /// updated as well.
2600 struct DepInfo {
2601 const AbstractAttribute *FromAA;
2602 const AbstractAttribute *ToAA;
2603 DepClassTy DepClass;
2604 };
2605
2606 /// The dependence stack is used to track dependences during an
2607 /// `AbstractAttribute::update` call. As `AbstractAttribute::update` can be
2608 /// recursive we might have multiple vectors of dependences in here. The stack
2609 /// size, should be adjusted according to the expected recursion depth and the
2610 /// inner dependence vector size to the expected number of dependences per
2611 /// abstract attribute. Since the inner vectors are actually allocated on the
2612 /// stack we can be generous with their size.
2613 using DependenceVector = SmallVector<DepInfo, 8>;
2615
2616 /// A set to remember the functions we already assume to be live and visited.
2617 DenseSet<const Function *> VisitedFunctions;
2618
2619 /// Uses we replace with a new value after manifest is done. We will remove
2620 /// then trivially dead instructions as well.
2621 SmallMapVector<Use *, Value *, 32> ToBeChangedUses;
2622
2623 /// Values we replace with a new value after manifest is done. We will remove
2624 /// then trivially dead instructions as well.
2625 SmallMapVector<Value *, PointerIntPair<Value *, 1, bool>, 32>
2626 ToBeChangedValues;
2627
2628 /// Instructions we replace with `unreachable` insts after manifest is done.
2629 SmallSetVector<WeakVH, 16> ToBeChangedToUnreachableInsts;
2630
2631 /// Invoke instructions with at least a single dead successor block.
2632 SmallSetVector<WeakVH, 16> InvokeWithDeadSuccessor;
2633
2634 /// A flag that indicates which stage of the process we are in. Initially, the
2635 /// phase is SEEDING. Phase is changed in `Attributor::run()`
2636 enum class AttributorPhase {
2637 SEEDING,
2638 UPDATE,
2639 MANIFEST,
2640 CLEANUP,
2641 } Phase = AttributorPhase::SEEDING;
2642
2643 /// The current initialization chain length. Tracked to avoid stack overflows.
2644 unsigned InitializationChainLength = 0;
2645 const unsigned MaxInitializationChainLength;
2646
2647 /// Whether time trace scopes are recorded for every initialization and
2648 /// update.
2649 const bool TimeTraceEnabled = timeTraceProfilerEnabled();
2650
2651 /// Functions, blocks, and instructions we delete after manifest is done.
2652 ///
2653 ///{
2654 SmallPtrSet<BasicBlock *, 8> ManifestAddedBlocks;
2655 SmallSetVector<Function *, 8> ToBeDeletedFunctions;
2656 SmallSetVector<BasicBlock *, 8> ToBeDeletedBlocks;
2657 SmallSetVector<WeakVH, 8> ToBeDeletedInsts;
2658 ///}
2659
2660 /// Container with all the query AAs that requested an update via
2661 /// registerForUpdate.
2662 SmallSetVector<AbstractAttribute *, 16> QueryAAsAwaitingUpdate;
2663
2664 /// User provided configuration for this Attributor instance.
2665 const AttributorConfig Configuration;
2666
2667 friend AADepGraph;
2668 friend AttributorCallGraph;
2669};
2670
2671/// An interface to query the internal state of an abstract attribute.
2672///
2673/// The abstract state is a minimal interface that allows the Attributor to
2674/// communicate with the abstract attributes about their internal state without
2675/// enforcing or exposing implementation details, e.g., the (existence of an)
2676/// underlying lattice.
2677///
2678/// It is sufficient to be able to query if a state is (1) valid or invalid, (2)
2679/// at a fixpoint, and to indicate to the state that (3) an optimistic fixpoint
2680/// was reached or (4) a pessimistic fixpoint was enforced.
2681///
2682/// All methods need to be implemented by the subclass. For the common use case,
2683/// a single boolean state or a bit-encoded state, the BooleanState and
2684/// {Inc,Dec,Bit}IntegerState classes are already provided. An abstract
2685/// attribute can inherit from them to get the abstract state interface and
2686/// additional methods to directly modify the state based if needed. See the
2687/// class comments for help.
2689 virtual ~AbstractState() = default;
2690
2691 /// Return if this abstract state is in a valid state. If false, no
2692 /// information provided should be used.
2693 virtual bool isValidState() const = 0;
2694
2695 /// Return if this abstract state is fixed, thus does not need to be updated
2696 /// if information changes as it cannot change itself.
2697 virtual bool isAtFixpoint() const = 0;
2698
2699 /// Indicate that the abstract state should converge to the optimistic state.
2700 ///
2701 /// This will usually make the optimistically assumed state the known to be
2702 /// true state.
2703 ///
2704 /// \returns ChangeStatus::UNCHANGED as the assumed value should not change.
2706
2707 /// Indicate that the abstract state should converge to the pessimistic state.
2708 ///
2709 /// This will usually revert the optimistically assumed state to the known to
2710 /// be true state.
2711 ///
2712 /// \returns ChangeStatus::CHANGED as the assumed value may change.
2714};
2715
2716/// Simple state with integers encoding.
2717///
2718/// The interface ensures that the assumed bits are always a subset of the known
2719/// bits. Users can only add known bits and, except through adding known bits,
2720/// they can only remove assumed bits. This should guarantee monotonicity and
2721/// thereby the existence of a fixpoint (if used correctly). The fixpoint is
2722/// reached when the assumed and known state/bits are equal. Users can
2723/// force/inidicate a fixpoint. If an optimistic one is indicated, the known
2724/// state will catch up with the assumed one, for a pessimistic fixpoint it is
2725/// the other way around.
2726template <typename base_ty, base_ty BestState, base_ty WorstState>
2728 using base_t = base_ty;
2729
2730 IntegerStateBase() = default;
2732
2733 /// Return the best possible representable state.
2734 static constexpr base_t getBestState() { return BestState; }
2735 static constexpr base_t getBestState(const IntegerStateBase &) {
2736 return getBestState();
2737 }
2738
2739 /// Return the worst possible representable state.
2740 static constexpr base_t getWorstState() { return WorstState; }
2741 static constexpr base_t getWorstState(const IntegerStateBase &) {
2742 return getWorstState();
2743 }
2744
2745 /// NOTE: For now we simply pretend that the worst possible state is invalid.
2746 bool isValidState() const override { return Assumed != getWorstState(); }
2747
2748 bool isAtFixpoint() const override { return Assumed == Known; }
2749
2754
2759
2760 /// Return the known state encoding
2761 base_t getKnown() const { return Known; }
2762
2763 /// Return the assumed state encoding.
2764 base_t getAssumed() const { return Assumed; }
2765
2766 /// Equality for IntegerStateBase.
2767 bool
2769 return this->getAssumed() == R.getAssumed() &&
2770 this->getKnown() == R.getKnown();
2771 }
2772
2773 /// Inequality for IntegerStateBase.
2774 bool
2776 return !(*this == R);
2777 }
2778
2779 /// "Clamp" this state with \p R. The result is subtype dependent but it is
2780 /// intended that only information assumed in both states will be assumed in
2781 /// this one afterwards.
2785
2786 /// "Clamp" this state with \p R. The result is subtype dependent but it is
2787 /// intended that information known in either state will be known in
2788 /// this one afterwards.
2792
2794 joinOR(R.getAssumed(), R.getKnown());
2795 }
2796
2798 joinAND(R.getAssumed(), R.getKnown());
2799 }
2800
2801protected:
2802 /// Handle a new assumed value \p Value. Subtype dependent.
2804
2805 /// Handle a new known value \p Value. Subtype dependent.
2807
2808 /// Handle a value \p Value. Subtype dependent.
2809 virtual void joinOR(base_t AssumedValue, base_t KnownValue) = 0;
2810
2811 /// Handle a new assumed value \p Value. Subtype dependent.
2812 virtual void joinAND(base_t AssumedValue, base_t KnownValue) = 0;
2813
2814 /// The known state encoding in an integer of type base_t.
2816
2817 /// The assumed state encoding in an integer of type base_t.
2819};
2820
2821/// Specialization of the integer state for a bit-wise encoding.
2822template <typename base_ty = uint32_t, base_ty BestState = ~base_ty(0),
2823 base_ty WorstState = 0>
2825 : public IntegerStateBase<base_ty, BestState, WorstState> {
2827 using base_t = base_ty;
2828 BitIntegerState() = default;
2830
2831 /// Return true if the bits set in \p BitsEncoding are "known bits".
2832 bool isKnown(base_t BitsEncoding = BestState) const {
2833 return (this->Known & BitsEncoding) == BitsEncoding;
2834 }
2835
2836 /// Return true if the bits set in \p BitsEncoding are "assumed bits".
2837 bool isAssumed(base_t BitsEncoding = BestState) const {
2838 return (this->Assumed & BitsEncoding) == BitsEncoding;
2839 }
2840
2841 /// Add the bits in \p BitsEncoding to the "known bits".
2843 // Make sure we never miss any "known bits".
2844 this->Assumed |= Bits;
2845 this->Known |= Bits;
2846 return *this;
2847 }
2848
2849 /// Remove the bits in \p BitsEncoding from the "assumed bits" if not known.
2851 return intersectAssumedBits(~BitsEncoding);
2852 }
2853
2854 /// Remove the bits in \p BitsEncoding from the "known bits".
2856 this->Known = (this->Known & ~BitsEncoding);
2857 return *this;
2858 }
2859
2860 /// Keep only "assumed bits" also set in \p BitsEncoding but all known ones.
2862 // Make sure we never lose any "known bits".
2863 this->Assumed = (this->Assumed & BitsEncoding) | this->Known;
2864 return *this;
2865 }
2866
2867private:
2868 void handleNewAssumedValue(base_t Value) override {
2870 }
2871 void handleNewKnownValue(base_t Value) override { addKnownBits(Value); }
2872 void joinOR(base_t AssumedValue, base_t KnownValue) override {
2873 this->Known |= KnownValue;
2874 this->Assumed |= AssumedValue;
2875 }
2876 void joinAND(base_t AssumedValue, base_t KnownValue) override {
2877 this->Known &= KnownValue;
2878 this->Assumed &= AssumedValue;
2879 }
2880};
2881
2882/// Specialization of the integer state for an increasing value, hence ~0u is
2883/// the best state and 0 the worst.
2884template <typename base_ty = uint32_t, base_ty BestState = ~base_ty(0),
2885 base_ty WorstState = 0>
2887 : public IntegerStateBase<base_ty, BestState, WorstState> {
2889 using base_t = base_ty;
2890
2893
2894 /// Return the best possible representable state.
2895 static constexpr base_t getBestState() { return BestState; }
2896 static constexpr base_t
2900
2901 /// Take minimum of assumed and \p Value.
2903 // Make sure we never lose "known value".
2904 this->Assumed = std::max(std::min(this->Assumed, Value), this->Known);
2905 return *this;
2906 }
2907
2908 /// Take maximum of known and \p Value.
2910 // Make sure we never lose "known value".
2911 this->Assumed = std::max(Value, this->Assumed);
2912 this->Known = std::max(Value, this->Known);
2913 return *this;
2914 }
2915
2916private:
2917 void handleNewAssumedValue(base_t Value) override {
2919 }
2920 void handleNewKnownValue(base_t Value) override { takeKnownMaximum(Value); }
2921 void joinOR(base_t AssumedValue, base_t KnownValue) override {
2922 this->Known = std::max(this->Known, KnownValue);
2923 this->Assumed = std::max(this->Assumed, AssumedValue);
2924 }
2925 void joinAND(base_t AssumedValue, base_t KnownValue) override {
2926 this->Known = std::min(this->Known, KnownValue);
2927 this->Assumed = std::min(this->Assumed, AssumedValue);
2928 }
2929};
2930
2931/// Specialization of the integer state for a decreasing value, hence 0 is the
2932/// best state and ~0u the worst.
2933template <typename base_ty = uint32_t>
2934struct DecIntegerState : public IntegerStateBase<base_ty, 0, ~base_ty(0)> {
2935 using base_t = base_ty;
2936
2937 /// Take maximum of assumed and \p Value.
2939 // Make sure we never lose "known value".
2940 this->Assumed = std::min(std::max(this->Assumed, Value), this->Known);
2941 return *this;
2942 }
2943
2944 /// Take minimum of known and \p Value.
2946 // Make sure we never lose "known value".
2947 this->Assumed = std::min(Value, this->Assumed);
2948 this->Known = std::min(Value, this->Known);
2949 return *this;
2950 }
2951
2952private:
2953 void handleNewAssumedValue(base_t Value) override {
2955 }
2956 void handleNewKnownValue(base_t Value) override { takeKnownMinimum(Value); }
2957 void joinOR(base_t AssumedValue, base_t KnownValue) override {
2958 this->Assumed = std::min(this->Assumed, KnownValue);
2959 this->Assumed = std::min(this->Assumed, AssumedValue);
2960 }
2961 void joinAND(base_t AssumedValue, base_t KnownValue) override {
2962 this->Assumed = std::max(this->Assumed, KnownValue);
2963 this->Assumed = std::max(this->Assumed, AssumedValue);
2964 }
2965};
2966
2967/// Simple wrapper for a single bit (boolean) state.
2968struct BooleanState : public IntegerStateBase<bool, true, false> {
2971
2972 BooleanState() = default;
2974
2975 /// Set the known and asssumed value to \p Value.
2976 void setKnown(bool Value) {
2977 Known |= Value;
2978 Assumed |= Value;
2979 }
2980
2981 /// Return true if the state is assumed to hold.
2982 bool isAssumed() const { return getAssumed(); }
2983
2984 /// Return true if the state is known to hold.
2985 bool isKnown() const { return getKnown(); }
2986
2987private:
2988 void handleNewAssumedValue(base_t Value) override {
2989 if (!Value)
2990 Assumed = Known;
2991 }
2992 void handleNewKnownValue(base_t Value) override {
2993 if (Value)
2994 Known = (Assumed = Value);
2995 }
2996 void joinOR(base_t AssumedValue, base_t KnownValue) override {
2997 Known |= KnownValue;
2998 Assumed |= AssumedValue;
2999 }
3000 void joinAND(base_t AssumedValue, base_t KnownValue) override {
3001 Known &= KnownValue;
3002 Assumed &= AssumedValue;
3003 }
3004};
3005
3006/// State for an integer range.
3008
3009 /// Bitwidth of the associated value.
3011
3012 /// State representing assumed range, initially set to empty.
3014
3015 /// State representing known range, initially set to [-inf, inf].
3017
3021
3025
3026 /// Return the worst possible representable state.
3028 return ConstantRange::getFull(BitWidth);
3029 }
3030
3031 /// Return the best possible representable state.
3033 return ConstantRange::getEmpty(BitWidth);
3034 }
3036 return getBestState(IRS.getBitWidth());
3037 }
3038
3039 /// Return associated values' bit width.
3040 uint32_t getBitWidth() const { return BitWidth; }
3041
3042 bool isValidState() const override {
3043 return BitWidth > 0 && !Assumed.isFullSet();
3044 }
3045
3046 bool isAtFixpoint() const override { return Assumed == Known; }
3047
3052
3057
3058 /// Return the known state encoding
3059 ConstantRange getKnown() const { return Known; }
3060
3061 /// Return the assumed state encoding.
3063
3064 /// Unite assumed range with the passed state.
3066 // Don't lose a known range.
3067 Assumed = Assumed.unionWith(R).intersectWith(Known);
3068 }
3069
3070 /// See IntegerRangeState::unionAssumed(..).
3072 unionAssumed(R.getAssumed());
3073 }
3074
3075 /// Intersect known range with the passed state.
3077 Assumed = Assumed.intersectWith(R);
3078 Known = Known.intersectWith(R);
3079 }
3080
3081 /// See IntegerRangeState::intersectKnown(..).
3083 intersectKnown(R.getKnown());
3084 }
3085
3086 /// Equality for IntegerRangeState.
3087 bool operator==(const IntegerRangeState &R) const {
3088 return getAssumed() == R.getAssumed() && getKnown() == R.getKnown();
3089 }
3090
3091 /// "Clamp" this state with \p R. The result is subtype dependent but it is
3092 /// intended that only information assumed in both states will be assumed in
3093 /// this one afterwards.
3095 // NOTE: `^=` operator seems like `intersect` but in this case, we need to
3096 // take `union`.
3097 unionAssumed(R);
3098 return *this;
3099 }
3100
3102 // NOTE: `&=` operator seems like `intersect` but in this case, we need to
3103 // take `union`.
3104 Known = Known.unionWith(R.getKnown());
3105 Assumed = Assumed.unionWith(R.getAssumed());
3106 return *this;
3107 }
3108};
3109
3110/// Simple state for a set.
3111///
3112/// This represents a state containing a set of values. The interface supports
3113/// modelling sets that contain all possible elements. The state's internal
3114/// value is modified using union or intersection operations.
3115template <typename BaseTy> struct SetState : public AbstractState {
3116 /// A wrapper around a set that has semantics for handling unions and
3117 /// intersections with a "universal" set that contains all elements.
3119 /// Creates a universal set with no concrete elements or an empty set.
3120 SetContents(bool Universal) : Universal(Universal) {}
3121
3122 /// Creates a non-universal set with concrete values.
3123 SetContents(const DenseSet<BaseTy> &Assumptions)
3124 : Universal(false), Set(Assumptions) {}
3125
3126 SetContents(bool Universal, const DenseSet<BaseTy> &Assumptions)
3127 : Universal(Universal), Set(Assumptions) {}
3128
3129 const DenseSet<BaseTy> &getSet() const { return Set; }
3130
3131 bool isUniversal() const { return Universal; }
3132
3133 bool empty() const { return Set.empty() && !Universal; }
3134
3135 /// Finds A := A ^ B where A or B could be the "Universal" set which
3136 /// contains every possible attribute. Returns true if changes were made.
3138 bool IsUniversal = Universal;
3139 unsigned Size = Set.size();
3140
3141 // A := A ^ U = A
3142 if (RHS.isUniversal())
3143 return false;
3144
3145 // A := U ^ B = B
3146 if (Universal)
3147 Set = RHS.getSet();
3148 else
3149 set_intersect(Set, RHS.getSet());
3150
3151 Universal &= RHS.isUniversal();
3152 return IsUniversal != Universal || Size != Set.size();
3153 }
3154
3155 /// Finds A := A u B where A or B could be the "Universal" set which
3156 /// contains every possible attribute. returns true if changes were made.
3157 bool getUnion(const SetContents &RHS) {
3158 bool IsUniversal = Universal;
3159 unsigned Size = Set.size();
3160
3161 // A := A u U = U = U u B
3162 if (!RHS.isUniversal() && !Universal)
3163 set_union(Set, RHS.getSet());
3164
3165 Universal |= RHS.isUniversal();
3166 return IsUniversal != Universal || Size != Set.size();
3167 }
3168
3169 private:
3170 /// Indicates if this set is "universal", containing every possible element.
3171 bool Universal;
3172
3173 /// The set of currently active assumptions.
3174 DenseSet<BaseTy> Set;
3175 };
3176
3177 SetState() : Known(false), Assumed(true), IsAtFixedpoint(false) {}
3178
3179 /// Initializes the known state with an initial set and initializes the
3180 /// assumed state as universal.
3182 : Known(Known), Assumed(true), IsAtFixedpoint(false) {}
3183
3184 bool isValidState() const override { return !Assumed.empty(); }
3185
3186 bool isAtFixpoint() const override { return IsAtFixedpoint; }
3187
3189 IsAtFixedpoint = true;
3190 Known = Assumed;
3192 }
3193
3195 IsAtFixedpoint = true;
3196 Assumed = Known;
3197 return ChangeStatus::CHANGED;
3198 }
3199
3200 /// Return the known state encoding.
3201 const SetContents &getKnown() const { return Known; }
3202
3203 /// Return the assumed state encoding.
3204 const SetContents &getAssumed() const { return Assumed; }
3205
3206 /// Returns if the set state contains the element.
3207 bool setContains(const BaseTy &Elem) const {
3208 return Assumed.getSet().contains(Elem) || Known.getSet().contains(Elem);
3209 }
3210
3211 /// Performs the set intersection between this set and \p RHS. Returns true if
3212 /// changes were made.
3214 bool IsUniversal = Assumed.isUniversal();
3215 unsigned SizeBefore = Assumed.getSet().size();
3216
3217 // Get intersection and make sure that the known set is still a proper
3218 // subset of the assumed set. A := K u (A ^ R).
3219 Assumed.getIntersection(RHS);
3220 Assumed.getUnion(Known);
3221
3222 return SizeBefore != Assumed.getSet().size() ||
3223 IsUniversal != Assumed.isUniversal();
3224 }
3225
3226 /// Performs the set union between this set and \p RHS. Returns true if
3227 /// changes were made.
3228 bool getUnion(const SetContents &RHS) { return Assumed.getUnion(RHS); }
3229
3230private:
3231 /// The set of values known for this state.
3232 SetContents Known;
3233
3234 /// The set of assumed values for this state.
3235 SetContents Assumed;
3236
3237 bool IsAtFixedpoint;
3238};
3239
3240/// Helper to tie a abstract state implementation to an abstract attribute.
3241template <typename StateTy, typename BaseType, class... Ts>
3242struct StateWrapper : public BaseType, public StateTy {
3243 /// Provide static access to the type of the state.
3245
3246 StateWrapper(const IRPosition &IRP, Ts... Args)
3247 : BaseType(IRP), StateTy(Args...) {}
3248
3249 StateType &getState() override { return *this; }
3250
3251 const StateType &getState() const override { return *this; }
3252
3253 bool isAtFixpoint() const final { return StateTy::isAtFixpoint(); }
3254
3255 bool isStateAtFixpoint() const final { return StateTy::isAtFixpoint(); }
3256};
3257
3258/// Helper class that provides common functionality to manifest IR attributes.
3259template <Attribute::AttrKind AK, typename BaseType, typename AAType>
3260struct IRAttribute : public BaseType {
3261 IRAttribute(const IRPosition &IRP) : BaseType(IRP) {}
3262
3263 /// Most boolean IRAttribute AAs don't do anything non-trivial
3264 /// in their initializers while non-boolean ones often do. Subclasses can
3265 /// change this.
3267
3268 /// Compile time access to the IR attribute kind.
3270
3271 /// Return true if the IR attribute(s) associated with this AA are implied for
3272 /// an undef value.
3273 static bool isImpliedByUndef() { return true; }
3274
3275 /// Return true if the IR attribute(s) associated with this AA are implied for
3276 /// an poison value.
3277 static bool isImpliedByPoison() { return true; }
3278
3279 static bool isImpliedByIR(Attributor &A, const IRPosition &IRP,
3280 Attribute::AttrKind ImpliedAttributeKind = AK,
3281 bool IgnoreSubsumingPositions = false) {
3282 if (AAType::isImpliedByUndef() && isa<UndefValue>(IRP.getAssociatedValue()))
3283 return true;
3284 if (AAType::isImpliedByPoison() &&
3286 return true;
3287 return A.hasAttr(IRP, {ImpliedAttributeKind}, IgnoreSubsumingPositions,
3288 ImpliedAttributeKind);
3289 }
3290
3292 if (isa<UndefValue>(this->getIRPosition().getAssociatedValue()))
3294 SmallVector<Attribute, 4> DeducedAttrs;
3295 getDeducedAttributes(A, this->getAnchorValue().getContext(), DeducedAttrs);
3296 if (DeducedAttrs.empty())
3298 return A.manifestAttrs(this->getIRPosition(), DeducedAttrs);
3299 }
3300
3301 /// Return the kind that identifies the abstract attribute implementation.
3302 Attribute::AttrKind getAttrKind() const { return AK; }
3303
3304 /// Return the deduced attributes in \p Attrs.
3306 SmallVectorImpl<Attribute> &Attrs) const {
3307 Attrs.emplace_back(Attribute::get(Ctx, getAttrKind()));
3308 }
3309};
3310
3311/// Base struct for all "concrete attribute" deductions.
3312///
3313/// The abstract attribute is a minimal interface that allows the Attributor to
3314/// orchestrate the abstract/fixpoint analysis. The design allows to hide away
3315/// implementation choices made for the subclasses but also to structure their
3316/// implementation and simplify the use of other abstract attributes in-flight.
3317///
3318/// To allow easy creation of new attributes, most methods have default
3319/// implementations. The ones that do not are generally straight forward, except
3320/// `AbstractAttribute::updateImpl` which is the location of most reasoning
3321/// associated with the abstract attribute. The update is invoked by the
3322/// Attributor in case the situation used to justify the current optimistic
3323/// state might have changed. The Attributor determines this automatically
3324/// by monitoring the `Attributor::getAAFor` calls made by abstract attributes.
3325///
3326/// The `updateImpl` method should inspect the IR and other abstract attributes
3327/// in-flight to justify the best possible (=optimistic) state. The actual
3328/// implementation is, similar to the underlying abstract state encoding, not
3329/// exposed. In the most common case, the `updateImpl` will go through a list of
3330/// reasons why its optimistic state is valid given the current information. If
3331/// any combination of them holds and is sufficient to justify the current
3332/// optimistic state, the method shall return UNCHAGED. If not, the optimistic
3333/// state is adjusted to the situation and the method shall return CHANGED.
3334///
3335/// If the manifestation of the "concrete attribute" deduced by the subclass
3336/// differs from the "default" behavior, which is a (set of) LLVM-IR
3337/// attribute(s) for an argument, call site argument, function return value, or
3338/// function, the `AbstractAttribute::manifest` method should be overloaded.
3339///
3340/// NOTE: If the state obtained via getState() is INVALID, thus if
3341/// AbstractAttribute::getState().isValidState() returns false, no
3342/// information provided by the methods of this class should be used.
3343/// NOTE: The Attributor currently has certain limitations to what we can do.
3344/// As a general rule of thumb, "concrete" abstract attributes should *for
3345/// now* only perform "backward" information propagation. That means
3346/// optimistic information obtained through abstract attributes should
3347/// only be used at positions that precede the origin of the information
3348/// with regards to the program flow. More practically, information can
3349/// *now* be propagated from instructions to their enclosing function, but
3350/// *not* from call sites to the called function. The mechanisms to allow
3351/// both directions will be added in the future.
3352/// NOTE: The mechanics of adding a new "concrete" abstract attribute are
3353/// described in the file comment.
3356
3358
3359 /// Virtual destructor.
3360 ~AbstractAttribute() override = default;
3361
3362 /// Compile time access to the IR attribute kind.
3364
3365 /// This function is used to identify if an \p DGN is of type
3366 /// AbstractAttribute so that the dyn_cast and cast can use such information
3367 /// to cast an AADepGraphNode to an AbstractAttribute.
3368 ///
3369 /// We eagerly return true here because all AADepGraphNodes except for the
3370 /// Synthethis Node are of type AbstractAttribute
3371 static bool classof(const AADepGraphNode *DGN) { return true; }
3372
3373 /// Return false if this AA does anything non-trivial (hence not done by
3374 /// default) in its initializer.
3375 static bool hasTrivialInitializer() { return false; }
3376
3377 /// Return true if this AA requires a "callee" (or an associted function) for
3378 /// a call site positon. Default is optimistic to minimize AAs.
3379 static bool requiresCalleeForCallBase() { return false; }
3380
3381 /// Return true if this AA requires non-asm "callee" for a call site positon.
3382 static bool requiresNonAsmForCallBase() { return true; }
3383
3384 /// Return true if this AA requires all callees for an argument or function
3385 /// positon.
3386 static bool requiresCallersForArgOrFunction() { return false; }
3387
3388 /// Return false if an AA should not be created for \p IRP.
3390 return true;
3391 }
3392
3393 /// Return false if an AA should not be updated for \p IRP.
3395 if (!IRP.isFnInterfaceKind())
3396 return true;
3397 Function *AssociatedFn = IRP.getAssociatedFunction();
3398 assert(AssociatedFn && "Function interface without a function?");
3399
3400 // TODO: Not all attributes require an exact definition. Find a way to
3401 // enable deduction for some but not all attributes in case the
3402 // definition might be changed at runtime, see also
3403 // http://lists.llvm.org/pipermail/llvm-dev/2018-February/121275.html.
3404 // TODO: We could always determine abstract attributes and if sufficient
3405 // information was found we could duplicate the functions that do not
3406 // have an exact definition.
3407 return A.isFunctionIPOAmendable(*AssociatedFn);
3408 }
3409
3410 /// Initialize the state with the information in the Attributor \p A.
3411 ///
3412 /// This function is called by the Attributor once all abstract attributes
3413 /// have been identified. It can and shall be used for task like:
3414 /// - identify existing knowledge in the IR and use it for the "known state"
3415 /// - perform any work that is not going to change over time, e.g., determine
3416 /// a subset of the IR, or attributes in-flight, that have to be looked at
3417 /// in the `updateImpl` method.
3418 virtual void initialize(Attributor &A) {}
3419
3420 /// A query AA is always scheduled as long as we do updates because it does
3421 /// lazy computation that cannot be determined to be done from the outside.
3422 /// However, while query AAs will not be fixed if they do not have outstanding
3423 /// dependences, we will only schedule them like other AAs. If a query AA that
3424 /// received a new query it needs to request an update via
3425 /// `Attributor::requestUpdateForAA`.
3426 virtual bool isQueryAA() const { return false; }
3427
3428 /// Return the internal abstract state for inspection.
3429 virtual StateType &getState() = 0;
3430 virtual const StateType &getState() const = 0;
3431
3432 /// Return true if the state is at a fixpoint, like
3433 /// getState().isAtFixpoint() but with a single virtual call.
3434 virtual bool isStateAtFixpoint() const { return getState().isAtFixpoint(); }
3435
3436 /// Return an IR position, see struct IRPosition.
3437 const IRPosition &getIRPosition() const { return *this; };
3438 IRPosition &getIRPosition() { return *this; };
3439
3440 /// Helper functions, for debug purposes only.
3441 ///{
3442 void print(raw_ostream &OS) const { print(nullptr, OS); }
3443 void print(Attributor *, raw_ostream &OS) const override;
3444 virtual void printWithDeps(raw_ostream &OS) const;
3445 void dump() const { this->print(dbgs()); }
3446
3447 /// This function should return the "summarized" assumed state as string.
3448 virtual const std::string getAsStr(Attributor *A) const = 0;
3449
3450 /// This function should return the name of the AbstractAttribute
3451 virtual StringRef getName() const = 0;
3452
3453 /// This function should return the address of the ID of the AbstractAttribute
3454 virtual const char *getIdAddr() const = 0;
3455 ///}
3456
3457 /// Allow the Attributor access to the protected methods.
3458 friend struct Attributor;
3459
3460protected:
3461 /// Hook for the Attributor to trigger an update of the internal state.
3462 ///
3463 /// If this attribute is already fixed, this method will return UNCHANGED,
3464 /// otherwise it delegates to `AbstractAttribute::updateImpl`.
3465 ///
3466 /// \Return CHANGED if the internal state changed, otherwise UNCHANGED.
3468
3469 /// Hook for the Attributor to trigger the manifestation of the information
3470 /// represented by the abstract attribute in the LLVM-IR.
3471 ///
3472 /// \Return CHANGED if the IR was altered, otherwise UNCHANGED.
3476
3477 /// Hook to enable custom statistic tracking, called after manifest that
3478 /// resulted in a change if statistics are enabled.
3479 ///
3480 /// We require subclasses to provide an implementation so we remember to
3481 /// add statistics for them.
3482 virtual void trackStatistics() const = 0;
3483
3484 /// The actual update/transfer function which has to be implemented by the
3485 /// derived classes.
3486 ///
3487 /// If it is called, the environment has changed and we have to determine if
3488 /// the current information is still valid or adjust it otherwise.
3489 ///
3490 /// \Return CHANGED if the internal state changed, otherwise UNCHANGED.
3492};
3493
3494/// Forward declarations of output streams for debug purposes.
3495///
3496///{
3502template <typename base_ty, base_ty BestState, base_ty WorstState>
3506 return OS << "(" << S.getKnown() << "-" << S.getAssumed() << ")"
3507 << static_cast<const AbstractState &>(S);
3508}
3509LLVM_ABI raw_ostream &operator<<(raw_ostream &OS,
3510 const IntegerRangeState &State);
3511///}
3512
3521
3522/// A more lightweight version of the Attributor which only runs attribute
3523/// inference but no simplifications.
3524struct AttributorLightPass : public OptionalPassInfoMixin<AttributorLightPass> {
3526};
3527
3528/// A more lightweight version of the Attributor which only runs attribute
3529/// inference but no simplifications.
3531 : public OptionalPassInfoMixin<AttributorLightCGSCCPass> {
3534 CGSCCUpdateResult &UR);
3535};
3536
3537/// Helper function to clamp a state \p S of type \p StateType with the
3538/// information in \p R and indicate/return if \p S did change (as-in update is
3539/// required to be run again).
3540template <typename StateType>
3541ChangeStatus clampStateAndIndicateChange(StateType &S, const StateType &R) {
3542 auto Assumed = S.getAssumed();
3543 S ^= R;
3544 return Assumed == S.getAssumed() ? ChangeStatus::UNCHANGED
3546}
3547
3548/// ----------------------------------------------------------------------------
3549/// Abstract Attribute Classes
3550/// ----------------------------------------------------------------------------
3551
3553 : public IRAttribute<Attribute::NoUnwind,
3554 StateWrapper<BooleanState, AbstractAttribute>,
3555 AANoUnwind> {
3557
3558 /// Returns true if nounwind is assumed.
3559 bool isAssumedNoUnwind() const { return getAssumed(); }
3560
3561 /// Returns true if nounwind is known.
3562 bool isKnownNoUnwind() const { return getKnown(); }
3563
3564 /// Create an abstract attribute view for the position \p IRP.
3566 Attributor &A);
3567
3568 StringRef getName() const override { return "AANoUnwind"; }
3569
3570 const char *getIdAddr() const override { return &ID; }
3571
3572 /// This function should return true if the type of the \p AA is AANoUnwind
3573 static bool classof(const AbstractAttribute *AA) {
3574 return (AA->getIdAddr() == &ID);
3575 }
3576
3577 /// Unique ID (due to the unique address)
3578 LLVM_ABI static const char ID;
3579};
3580
3582 : public IRAttribute<Attribute::NoSync,
3583 StateWrapper<BooleanState, AbstractAttribute>,
3584 AANoSync> {
3586
3587 static bool isImpliedByIR(Attributor &A, const IRPosition &IRP,
3588 Attribute::AttrKind ImpliedAttributeKind,
3589 bool IgnoreSubsumingPositions = false) {
3590 // Note: This is also run for non-IPO amendable functions.
3591 assert(ImpliedAttributeKind == Attribute::NoSync);
3592 if (A.hasAttr(IRP, {Attribute::NoSync}, IgnoreSubsumingPositions,
3593 Attribute::NoSync))
3594 return true;
3595
3596 // Check for readonly + non-convergent.
3597 // TODO: We should be able to use hasAttr for Attributes, not only
3598 // AttrKinds.
3600 if (!F || F->isConvergent())
3601 return false;
3602
3604 A.getAttrs(IRP, {Attribute::Memory}, Attrs, IgnoreSubsumingPositions);
3605
3607 for (const Attribute &Attr : Attrs)
3608 ME &= Attr.getMemoryEffects();
3609
3610 if (!ME.onlyReadsMemory())
3611 return false;
3612
3613 A.manifestAttrs(IRP, Attribute::get(F->getContext(), Attribute::NoSync));
3614 return true;
3615 }
3616
3618 if (!IRP.isFunctionScope() &&
3620 return false;
3621 return IRAttribute::isValidIRPositionForInit(A, IRP);
3622 }
3623
3624 /// Returns true if "nosync" is assumed.
3625 bool isAssumedNoSync() const { return getAssumed(); }
3626
3627 /// Returns true if "nosync" is known.
3628 bool isKnownNoSync() const { return getKnown(); }
3629
3630 /// Helper function used to determine whether an instruction is non-relaxed
3631 /// atomic. In other words, if an atomic instruction does not have unordered
3632 /// or monotonic ordering
3633 LLVM_ABI static bool isNonRelaxedAtomic(const Instruction *I);
3634
3635 /// Helper function to determine if \p CB is an aligned (GPU) barrier. Aligned
3636 /// barriers have to be executed by all threads. The flag \p ExecutedAligned
3637 /// indicates if the call is executed by all threads in a (thread) block in an
3638 /// aligned way. If that is the case, non-aligned barriers are effectively
3639 /// aligned barriers.
3640 LLVM_ABI static bool isAlignedBarrier(const CallBase &CB,
3641 bool ExecutedAligned);
3642
3643 /// Create an abstract attribute view for the position \p IRP.
3645 Attributor &A);
3646
3647 StringRef getName() const override { return "AANoSync"; }
3648
3649 const char *getIdAddr() const override { return &ID; }
3650
3651 /// This function should return true if the type of the \p AA is AANoSync
3652 static bool classof(const AbstractAttribute *AA) {
3653 return (AA->getIdAddr() == &ID);
3654 }
3655
3656 /// Unique ID (due to the unique address)
3657 LLVM_ABI static const char ID;
3658};
3659
3660/// An abstract interface for all nonnull attributes.
3662 : public IRAttribute<Attribute::MustProgress,
3663 StateWrapper<BooleanState, AbstractAttribute>,
3664 AAMustProgress> {
3666
3667 static bool isImpliedByIR(Attributor &A, const IRPosition &IRP,
3668 Attribute::AttrKind ImpliedAttributeKind,
3669 bool IgnoreSubsumingPositions = false) {
3670 // Note: This is also run for non-IPO amendable functions.
3671 assert(ImpliedAttributeKind == Attribute::MustProgress);
3672 return A.hasAttr(IRP, {Attribute::MustProgress, Attribute::WillReturn},
3673 IgnoreSubsumingPositions, Attribute::MustProgress);
3674 }
3675
3676 /// Return true if we assume that the underlying value is nonnull.
3677 bool isAssumedMustProgress() const { return getAssumed(); }
3678
3679 /// Return true if we know that underlying value is nonnull.
3680 bool isKnownMustProgress() const { return getKnown(); }
3681
3682 /// Create an abstract attribute view for the position \p IRP.
3684 Attributor &A);
3685
3686 StringRef getName() const override { return "AAMustProgress"; }
3687
3688 const char *getIdAddr() const override { return &ID; }
3689
3690 /// This function should return true if the type of the \p AA is
3691 /// AAMustProgress
3692 static bool classof(const AbstractAttribute *AA) {
3693 return (AA->getIdAddr() == &ID);
3694 }
3695
3696 /// Unique ID (due to the unique address)
3697 LLVM_ABI static const char ID;
3698};
3699
3700/// An abstract interface for all nonnull attributes.
3702 : public IRAttribute<Attribute::NonNull,
3703 StateWrapper<BooleanState, AbstractAttribute>,
3704 AANonNull> {
3706
3707 static bool hasTrivialInitializer() { return false; }
3708
3709 /// Undef is not necessarily nonnull as nonnull + noundef would cause poison.
3710 /// Poison implies nonnull though.
3711 static bool isImpliedByUndef() { return false; }
3712
3715 return false;
3716 return IRAttribute::isValidIRPositionForInit(A, IRP);
3717 }
3718
3719 LLVM_ABI static bool isImpliedByIR(Attributor &A, const IRPosition &IRP,
3720 Attribute::AttrKind ImpliedAttributeKind,
3721 bool IgnoreSubsumingPositions = false);
3722
3723 /// Return true if we assume that the underlying value is nonnull.
3724 bool isAssumedNonNull() const { return getAssumed(); }
3725
3726 /// Return true if we know that underlying value is nonnull.
3727 bool isKnownNonNull() const { return getKnown(); }
3728
3729 /// Create an abstract attribute view for the position \p IRP.
3731 Attributor &A);
3732
3733 StringRef getName() const override { return "AANonNull"; }
3734
3735 const char *getIdAddr() const override { return &ID; }
3736
3737 /// This function should return true if the type of the \p AA is AANonNull
3738 static bool classof(const AbstractAttribute *AA) {
3739 return (AA->getIdAddr() == &ID);
3740 }
3741
3742 /// Unique ID (due to the unique address)
3743 LLVM_ABI static const char ID;
3744};
3745
3746/// An abstract attribute for norecurse.
3748 : public IRAttribute<Attribute::NoRecurse,
3749 StateWrapper<BooleanState, AbstractAttribute>,
3750 AANoRecurse> {
3752
3753 /// Return true if "norecurse" is assumed.
3754 bool isAssumedNoRecurse() const { return getAssumed(); }
3755
3756 /// Return true if "norecurse" is known.
3757 bool isKnownNoRecurse() const { return getKnown(); }
3758
3759 /// Create an abstract attribute view for the position \p IRP.
3761 Attributor &A);
3762
3763 StringRef getName() const override { return "AANoRecurse"; }
3764
3765 const char *getIdAddr() const override { return &ID; }
3766
3767 /// This function should return true if the type of the \p AA is AANoRecurse
3768 static bool classof(const AbstractAttribute *AA) {
3769 return (AA->getIdAddr() == &ID);
3770 }
3771
3772 /// Unique ID (due to the unique address)
3773 LLVM_ABI static const char ID;
3774};
3775
3776/// An abstract attribute for willreturn.
3778 : public IRAttribute<Attribute::WillReturn,
3779 StateWrapper<BooleanState, AbstractAttribute>,
3780 AAWillReturn> {
3782
3783 static bool isImpliedByIR(Attributor &A, const IRPosition &IRP,
3784 Attribute::AttrKind ImpliedAttributeKind,
3785 bool IgnoreSubsumingPositions = false) {
3786 // Note: This is also run for non-IPO amendable functions.
3787 assert(ImpliedAttributeKind == Attribute::WillReturn);
3788 if (IRAttribute::isImpliedByIR(A, IRP, ImpliedAttributeKind,
3789 IgnoreSubsumingPositions))
3790 return true;
3792 return false;
3793 A.manifestAttrs(IRP, Attribute::get(IRP.getAnchorValue().getContext(),
3794 Attribute::WillReturn));
3795 return true;
3796 }
3797
3798 /// Check for `mustprogress` and `readonly` as they imply `willreturn`.
3800 const IRPosition &IRP) {
3801 // Check for `mustprogress` in the scope and the associated function which
3802 // might be different if this is a call site.
3803 if (!A.hasAttr(IRP, {Attribute::MustProgress}))
3804 return false;
3805
3807 A.getAttrs(IRP, {Attribute::Memory}, Attrs,
3808 /* IgnoreSubsumingPositions */ false);
3809
3811 for (const Attribute &Attr : Attrs)
3812 ME &= Attr.getMemoryEffects();
3813 return ME.onlyReadsMemory();
3814 }
3815
3816 /// Return true if "willreturn" is assumed.
3817 bool isAssumedWillReturn() const { return getAssumed(); }
3818
3819 /// Return true if "willreturn" is known.
3820 bool isKnownWillReturn() const { return getKnown(); }
3821
3822 /// Create an abstract attribute view for the position \p IRP.
3824 Attributor &A);
3825
3826 StringRef getName() const override { return "AAWillReturn"; }
3827
3828 const char *getIdAddr() const override { return &ID; }
3829
3830 /// This function should return true if the type of the \p AA is AAWillReturn
3831 static bool classof(const AbstractAttribute *AA) {
3832 return (AA->getIdAddr() == &ID);
3833 }
3834
3835 /// Unique ID (due to the unique address)
3836 LLVM_ABI static const char ID;
3837};
3838
3839/// An abstract attribute for undefined behavior.
3841 : public StateWrapper<BooleanState, AbstractAttribute> {
3844
3845 /// Return true if "undefined behavior" is assumed for a specific instruction.
3846 virtual bool isAssumedToCauseUB(Instruction *I) const = 0;
3847
3848 /// Return true if "undefined behavior" is known for a specific instruction.
3849 virtual bool isKnownToCauseUB(Instruction *I) const = 0;
3850
3851 /// Create an abstract attribute view for the position \p IRP.
3853 Attributor &A);
3854
3855 StringRef getName() const override { return "AAUndefinedBehavior"; }
3856
3857 const char *getIdAddr() const override { return &ID; }
3858
3859 /// This function should return true if the type of the \p AA is
3860 /// AAUndefineBehavior
3861 static bool classof(const AbstractAttribute *AA) {
3862 return (AA->getIdAddr() == &ID);
3863 }
3864
3865 /// Unique ID (due to the unique address)
3866 LLVM_ABI static const char ID;
3867};
3868
3869/// An abstract interface to determine reachability of point A to B.
3871 : public StateWrapper<BooleanState, AbstractAttribute> {
3874
3875 /// Returns true if 'From' instruction is assumed to reach, 'To' instruction.
3876 /// Users should provide two positions they are interested in, and the class
3877 /// determines (and caches) reachability.
3879 Attributor &A, const Instruction &From, const Instruction &To,
3880 const AA::InstExclusionSetTy *ExclusionSet = nullptr) const = 0;
3881
3882 /// Create an abstract attribute view for the position \p IRP.
3885
3886 StringRef getName() const override { return "AAIntraFnReachability"; }
3887
3888 const char *getIdAddr() const override { return &ID; }
3889
3890 /// This function should return true if the type of the \p AA is
3891 /// AAIntraFnReachability
3892 static bool classof(const AbstractAttribute *AA) {
3893 return (AA->getIdAddr() == &ID);
3894 }
3895
3896 /// Unique ID (due to the unique address)
3897 LLVM_ABI static const char ID;
3898};
3899
3900/// An abstract interface for all noalias attributes.
3902 : public IRAttribute<Attribute::NoAlias,
3903 StateWrapper<BooleanState, AbstractAttribute>,
3904 AANoAlias> {
3906
3908 if (!IRP.getAssociatedType()->isPointerTy())
3909 return false;
3910 return IRAttribute::isValidIRPositionForInit(A, IRP);
3911 }
3912
3913 LLVM_ABI static bool isImpliedByIR(Attributor &A, const IRPosition &IRP,
3914 Attribute::AttrKind ImpliedAttributeKind,
3915 bool IgnoreSubsumingPositions = false);
3916
3917 static bool requiresCallersForArgOrFunction() { return true; }
3918
3919 /// Return true if we assume that the underlying value is alias.
3920 bool isAssumedNoAlias() const { return getAssumed(); }
3921
3922 /// Return true if we know that underlying value is noalias.
3923 bool isKnownNoAlias() const { return getKnown(); }
3924
3925 /// Create an abstract attribute view for the position \p IRP.
3927 Attributor &A);
3928
3929 StringRef getName() const override { return "AANoAlias"; }
3930
3931 const char *getIdAddr() const override { return &ID; }
3932
3933 /// This function should return true if the type of the \p AA is AANoAlias
3934 static bool classof(const AbstractAttribute *AA) {
3935 return (AA->getIdAddr() == &ID);
3936 }
3937
3938 /// Unique ID (due to the unique address)
3939 LLVM_ABI static const char ID;
3940};
3941
3942/// An AbstractAttribute for nofree.
3944 : public IRAttribute<Attribute::NoFree,
3945 StateWrapper<BooleanState, AbstractAttribute>,
3946 AANoFree> {
3948
3949 static bool isImpliedByIR(Attributor &A, const IRPosition &IRP,
3950 Attribute::AttrKind ImpliedAttributeKind,
3951 bool IgnoreSubsumingPositions = false) {
3952 // Note: This is also run for non-IPO amendable functions.
3953 assert(ImpliedAttributeKind == Attribute::NoFree);
3954 return A.hasAttr(
3955 IRP, {Attribute::ReadNone, Attribute::ReadOnly, Attribute::NoFree},
3956 IgnoreSubsumingPositions, Attribute::NoFree);
3957 }
3958
3960 if (!IRP.isFunctionScope() &&
3962 return false;
3963 return IRAttribute::isValidIRPositionForInit(A, IRP);
3964 }
3965
3966 /// Return true if "nofree" is assumed.
3967 bool isAssumedNoFree() const { return getAssumed(); }
3968
3969 /// Return true if "nofree" is known.
3970 bool isKnownNoFree() const { return getKnown(); }
3971
3972 /// Create an abstract attribute view for the position \p IRP.
3974 Attributor &A);
3975
3976 StringRef getName() const override { return "AANoFree"; }
3977
3978 const char *getIdAddr() const override { return &ID; }
3979
3980 /// This function should return true if the type of the \p AA is AANoFree
3981 static bool classof(const AbstractAttribute *AA) {
3982 return (AA->getIdAddr() == &ID);
3983 }
3984
3985 /// Unique ID (due to the unique address)
3986 LLVM_ABI static const char ID;
3987};
3988
3989/// An AbstractAttribute for noreturn.
3991 : public IRAttribute<Attribute::NoReturn,
3992 StateWrapper<BooleanState, AbstractAttribute>,
3993 AANoReturn> {
3995
3996 /// Return true if the underlying object is assumed to never return.
3997 bool isAssumedNoReturn() const { return getAssumed(); }
3998
3999 /// Return true if the underlying object is known to never return.
4000 bool isKnownNoReturn() const { return getKnown(); }
4001
4002 /// Create an abstract attribute view for the position \p IRP.
4004 Attributor &A);
4005
4006 StringRef getName() const override { return "AANoReturn"; }
4007
4008 const char *getIdAddr() const override { return &ID; }
4009
4010 /// This function should return true if the type of the \p AA is AANoReturn
4011 static bool classof(const AbstractAttribute *AA) {
4012 return (AA->getIdAddr() == &ID);
4013 }
4014
4015 /// Unique ID (due to the unique address)
4016 LLVM_ABI static const char ID;
4017};
4018
4019/// An abstract interface for liveness abstract attribute.
4021 : public StateWrapper<BitIntegerState<uint8_t, 3, 0>, AbstractAttribute> {
4023 AAIsDead(const IRPosition &IRP, Attributor &A) : Base(IRP) {}
4024
4027 return isa<Function>(IRP.getAnchorValue()) &&
4028 !cast<Function>(IRP.getAnchorValue()).isDeclaration();
4029 return true;
4030 }
4031
4032 /// State encoding bits. A set bit in the state means the property holds.
4033 enum {
4036
4038 };
4039 static_assert(IS_DEAD == getBestState(), "Unexpected BEST_STATE value");
4040
4041protected:
4042 /// The query functions are protected such that other attributes need to go
4043 /// through the Attributor interfaces: `Attributor::isAssumedDead(...)`
4044
4045 /// Returns true if the underlying value is assumed dead.
4046 virtual bool isAssumedDead() const = 0;
4047
4048 /// Returns true if the underlying value is known dead.
4049 virtual bool isKnownDead() const = 0;
4050
4051 /// Returns true if \p BB is known dead.
4052 virtual bool isKnownDead(const BasicBlock *BB) const = 0;
4053
4054 /// Returns true if \p I is assumed dead.
4055 virtual bool isAssumedDead(const Instruction *I) const = 0;
4056
4057 /// Returns true if \p I is known dead.
4058 virtual bool isKnownDead(const Instruction *I) const = 0;
4059
4060 /// Return true if the underlying value is a store that is known to be
4061 /// removable. This is different from dead stores as the removable store
4062 /// can have an effect on live values, especially loads, but that effect
4063 /// is propagated which allows us to remove the store in turn.
4064 virtual bool isRemovableStore() const { return false; }
4065
4066public:
4067 /// Create an abstract attribute view for the position \p IRP.
4069 Attributor &A);
4070
4071 /// Determine if \p F might catch asynchronous exceptions.
4073 return F.hasPersonalityFn() && !canSimplifyInvokeNoUnwind(&F);
4074 }
4075
4076 /// Returns true if \p BB is assumed dead.
4077 virtual bool isAssumedDead(const BasicBlock *BB) const = 0;
4078
4079 /// Return if the edge from \p From BB to \p To BB is assumed dead.
4080 /// This is specifically useful in AAReachability.
4081 virtual bool isEdgeDead(const BasicBlock *From, const BasicBlock *To) const {
4082 return false;
4083 }
4084
4085 StringRef getName() const override { return "AAIsDead"; }
4086
4087 const char *getIdAddr() const override { return &ID; }
4088
4089 /// This function should return true if the type of the \p AA is AAIsDead
4090 static bool classof(const AbstractAttribute *AA) {
4091 return (AA->getIdAddr() == &ID);
4092 }
4093
4094 /// Unique ID (due to the unique address)
4095 LLVM_ABI static const char ID;
4096
4097 friend struct Attributor;
4098};
4099
4100/// State for dereferenceable attribute
4102
4103 static DerefState getBestState() { return DerefState(); }
4104 static DerefState getBestState(const DerefState &) { return getBestState(); }
4105
4106 /// Return the worst possible representable state.
4108 DerefState DS;
4109 DS.indicatePessimisticFixpoint();
4110 return DS;
4111 }
4113 return getWorstState();
4114 }
4115
4116 /// State representing for dereferenceable bytes.
4118
4119 /// Map representing for accessed memory offsets and sizes.
4120 /// A key is Offset and a value is size.
4121 /// If there is a load/store instruction something like,
4122 /// p[offset] = v;
4123 /// (offset, sizeof(v)) will be inserted to this map.
4124 /// std::map is used because we want to iterate keys in ascending order.
4125 std::map<int64_t, uint64_t> AccessedBytesMap;
4126
4127 /// Helper function to calculate dereferenceable bytes from current known
4128 /// bytes and accessed bytes.
4129 ///
4130 /// int f(int *A){
4131 /// *A = 0;
4132 /// *(A+2) = 2;
4133 /// *(A+1) = 1;
4134 /// *(A+10) = 10;
4135 /// }
4136 /// ```
4137 /// In that case, AccessedBytesMap is `{0:4, 4:4, 8:4, 40:4}`.
4138 /// AccessedBytesMap is std::map so it is iterated in accending order on
4139 /// key(Offset). So KnownBytes will be updated like this:
4140 ///
4141 /// |Access | KnownBytes
4142 /// |(0, 4)| 0 -> 4
4143 /// |(4, 4)| 4 -> 8
4144 /// |(8, 4)| 8 -> 12
4145 /// |(40, 4) | 12 (break)
4146 void computeKnownDerefBytesFromAccessedMap() {
4147 int64_t KnownBytes = DerefBytesState.getKnown();
4148 for (auto &Access : AccessedBytesMap) {
4149 if (KnownBytes < Access.first)
4150 break;
4151 KnownBytes = std::max(KnownBytes, Access.first + (int64_t)Access.second);
4152 }
4153
4154 DerefBytesState.takeKnownMaximum(KnownBytes);
4155 }
4156
4157 /// State representing that whether the value is globaly dereferenceable.
4158 BooleanState GlobalState;
4159
4160 bool isValidState() const override { return DerefBytesState.isValidState(); }
4161
4162 bool isAtFixpoint() const override {
4163 return !isValidState() ||
4164 (DerefBytesState.isAtFixpoint() && GlobalState.isAtFixpoint());
4165 }
4166
4168 DerefBytesState.indicateOptimisticFixpoint();
4169 GlobalState.indicateOptimisticFixpoint();
4171 }
4172
4174 DerefBytesState.indicatePessimisticFixpoint();
4175 GlobalState.indicatePessimisticFixpoint();
4176 return ChangeStatus::CHANGED;
4177 }
4178
4179 /// Update known dereferenceable bytes.
4180 void takeKnownDerefBytesMaximum(uint64_t Bytes) {
4181 DerefBytesState.takeKnownMaximum(Bytes);
4182
4183 // Known bytes might increase.
4184 computeKnownDerefBytesFromAccessedMap();
4185 }
4186
4187 /// Update assumed dereferenceable bytes.
4188 void takeAssumedDerefBytesMinimum(uint64_t Bytes) {
4189 DerefBytesState.takeAssumedMinimum(Bytes);
4190 }
4191
4192 /// Add accessed bytes to the map.
4193 void addAccessedBytes(int64_t Offset, uint64_t Size) {
4194 uint64_t &AccessedBytes = AccessedBytesMap[Offset];
4195 AccessedBytes = std::max(AccessedBytes, Size);
4196
4197 // Known bytes might increase.
4198 computeKnownDerefBytesFromAccessedMap();
4199 }
4200
4201 /// Equality for DerefState.
4202 bool operator==(const DerefState &R) const {
4203 return this->DerefBytesState == R.DerefBytesState &&
4204 this->GlobalState == R.GlobalState;
4205 }
4206
4207 /// Inequality for DerefState.
4208 bool operator!=(const DerefState &R) const { return !(*this == R); }
4209
4210 /// See IntegerStateBase::operator^=
4211 DerefState operator^=(const DerefState &R) {
4212 DerefBytesState ^= R.DerefBytesState;
4213 GlobalState ^= R.GlobalState;
4214 return *this;
4215 }
4216
4217 /// See IntegerStateBase::operator+=
4218 DerefState operator+=(const DerefState &R) {
4219 DerefBytesState += R.DerefBytesState;
4220 GlobalState += R.GlobalState;
4221 return *this;
4222 }
4223
4224 /// See IntegerStateBase::operator&=
4225 DerefState operator&=(const DerefState &R) {
4226 DerefBytesState &= R.DerefBytesState;
4227 GlobalState &= R.GlobalState;
4228 return *this;
4229 }
4230
4231 /// See IntegerStateBase::operator|=
4232 DerefState operator|=(const DerefState &R) {
4233 DerefBytesState |= R.DerefBytesState;
4234 GlobalState |= R.GlobalState;
4235 return *this;
4236 }
4237};
4238
4239/// An abstract interface for all dereferenceable attribute.
4241 : public IRAttribute<Attribute::Dereferenceable,
4242 StateWrapper<DerefState, AbstractAttribute>,
4243 AADereferenceable> {
4245
4247 if (!IRP.getAssociatedType()->isPointerTy())
4248 return false;
4249 return IRAttribute::isValidIRPositionForInit(A, IRP);
4250 }
4251
4252 /// Return true if we assume that underlying value is
4253 /// dereferenceable(_or_null) globally.
4254 bool isAssumedGlobal() const { return GlobalState.getAssumed(); }
4255
4256 /// Return true if we know that underlying value is
4257 /// dereferenceable(_or_null) globally.
4258 bool isKnownGlobal() const { return GlobalState.getKnown(); }
4259
4260 /// Return assumed dereferenceable bytes.
4262 return DerefBytesState.getAssumed();
4263 }
4264
4265 /// Return known dereferenceable bytes.
4267 return DerefBytesState.getKnown();
4268 }
4269
4270 /// Create an abstract attribute view for the position \p IRP.
4272 Attributor &A);
4273
4274 StringRef getName() const override { return "AADereferenceable"; }
4275
4276 const char *getIdAddr() const override { return &ID; }
4277
4278 /// This function should return true if the type of the \p AA is
4279 /// AADereferenceable
4280 static bool classof(const AbstractAttribute *AA) {
4281 return (AA->getIdAddr() == &ID);
4282 }
4283
4284 /// Unique ID (due to the unique address)
4285 LLVM_ABI static const char ID;
4286};
4287
4290/// An abstract interface for all align attributes.
4292 : public IRAttribute<Attribute::Alignment,
4293 StateWrapper<AAAlignmentStateType, AbstractAttribute>,
4294 AAAlign> {
4296
4298 if (!IRP.getAssociatedType()->isPointerTy())
4299 return false;
4300 return IRAttribute::isValidIRPositionForInit(A, IRP);
4301 }
4302
4303 /// Return assumed alignment.
4304 Align getAssumedAlign() const { return Align(getAssumed()); }
4305
4306 /// Return known alignment.
4307 Align getKnownAlign() const { return Align(getKnown()); }
4308
4309 StringRef getName() const override { return "AAAlign"; }
4310
4311 const char *getIdAddr() const override { return &ID; }
4312
4313 /// This function should return true if the type of the \p AA is AAAlign
4314 static bool classof(const AbstractAttribute *AA) {
4315 return (AA->getIdAddr() == &ID);
4316 }
4317
4318 /// Create an abstract attribute view for the position \p IRP.
4320 Attributor &A);
4321
4322 /// Unique ID (due to the unique address)
4323 LLVM_ABI static const char ID;
4324};
4325
4326/// An abstract interface to track if a value leaves it's defining function
4327/// instance.
4328/// TODO: We should make it a ternary AA tracking uniqueness, and uniqueness
4329/// wrt. the Attributor analysis separately.
4330struct AAInstanceInfo : public StateWrapper<BooleanState, AbstractAttribute> {
4333
4334 /// Return true if we assume that the underlying value is unique in its scope
4335 /// wrt. the Attributor analysis. That means it might not be unique but we can
4336 /// still use pointer equality without risking to represent two instances with
4337 /// one `llvm::Value`.
4338 bool isAssumedUniqueForAnalysis() const { return isAssumed(); }
4339
4340 /// Create an abstract attribute view for the position \p IRP.
4342 Attributor &A);
4343
4344 StringRef getName() const override { return "AAInstanceInfo"; }
4345
4346 const char *getIdAddr() const override { return &ID; }
4347
4348 /// This function should return true if the type of the \p AA is
4349 /// AAInstanceInfo
4350 static bool classof(const AbstractAttribute *AA) {
4351 return (AA->getIdAddr() == &ID);
4352 }
4353
4354 /// Unique ID (due to the unique address)
4355 LLVM_ABI static const char ID;
4356};
4357
4358/// An abstract interface for all nocapture attributes.
4360 : public IRAttribute<
4361 Attribute::Captures,
4362 StateWrapper<BitIntegerState<uint16_t, 7, 0>, AbstractAttribute>,
4363 AANoCapture> {
4365
4366 LLVM_ABI static bool isImpliedByIR(Attributor &A, const IRPosition &IRP,
4367 Attribute::AttrKind ImpliedAttributeKind,
4368 bool IgnoreSubsumingPositions = false);
4369
4370 /// Update \p State according to the capture capabilities of \p F for position
4371 /// \p IRP.
4372 LLVM_ABI static void
4374 BitIntegerState &State);
4375
4377 if (!IRP.getAssociatedType()->isPointerTy())
4378 return false;
4379 return IRAttribute::isValidIRPositionForInit(A, IRP);
4380 }
4381
4382 /// State encoding bits. A set bit in the state means the property holds.
4383 /// NO_CAPTURE is the best possible state, 0 the worst possible state.
4384 enum {
4388
4389 /// If we do not capture the value in memory or through integers we can only
4390 /// communicate it back as a derived pointer.
4392
4393 /// If we do not capture the value in memory, through integers, or as a
4394 /// derived pointer we know it is not captured.
4397 };
4398
4399 /// Return true if we know that the underlying value is not captured in its
4400 /// respective scope.
4401 bool isKnownNoCapture() const { return isKnown(NO_CAPTURE); }
4402
4403 /// Return true if we assume that the underlying value is not captured in its
4404 /// respective scope.
4405 bool isAssumedNoCapture() const { return isAssumed(NO_CAPTURE); }
4406
4407 /// Return true if we know that the underlying value is not captured in its
4408 /// respective scope but we allow it to escape through a "return".
4412
4413 /// Return true if we assume that the underlying value is not captured in its
4414 /// respective scope but we allow it to escape through a "return".
4418
4419 /// Create an abstract attribute view for the position \p IRP.
4421 Attributor &A);
4422
4423 StringRef getName() const override { return "AANoCapture"; }
4424
4425 const char *getIdAddr() const override { return &ID; }
4426
4427 /// This function should return true if the type of the \p AA is AANoCapture
4428 static bool classof(const AbstractAttribute *AA) {
4429 return (AA->getIdAddr() == &ID);
4430 }
4431
4432 /// Unique ID (due to the unique address)
4433 LLVM_ABI static const char ID;
4434};
4435
4437
4439
4444 return getBestState(VS.Ty);
4445 }
4446
4447 /// Return the worst possible representable state.
4450 DS.indicatePessimisticFixpoint();
4451 return DS;
4452 }
4455 return getWorstState(VS.Ty);
4456 }
4457
4458 bool isValidState() const override { return BS.isValidState(); }
4459
4460 bool isAtFixpoint() const override { return BS.isAtFixpoint(); }
4461
4462 /// Return the assumed state encoding.
4464 const ValueSimplifyStateType &getAssumed() const { return *this; }
4465
4467 return BS.indicatePessimisticFixpoint();
4468 }
4469
4471 return BS.indicateOptimisticFixpoint();
4472 }
4473
4474 /// "Clamp" this state with \p PVS.
4476 BS ^= VS.BS;
4477 unionAssumed(VS.SimplifiedAssociatedValue);
4478 return *this;
4479 }
4480
4482 if (isValidState() != RHS.isValidState())
4483 return false;
4484 if (!isValidState() && !RHS.isValidState())
4485 return true;
4486 return SimplifiedAssociatedValue == RHS.SimplifiedAssociatedValue;
4487 }
4488
4489protected:
4490 /// The type of the original value.
4492
4493 /// Merge \p Other into the currently assumed simplified value
4494 LLVM_ABI bool unionAssumed(std::optional<Value *> Other);
4495
4496 /// Helper to track validity and fixpoint
4498
4499 /// An assumed simplified value. Initially, it is set to std::nullopt, which
4500 /// means that the value is not clear under current assumption. If in the
4501 /// pessimistic state, getAssumedSimplifiedValue doesn't return this value but
4502 /// returns orignal associated value.
4503 std::optional<Value *> SimplifiedAssociatedValue;
4504};
4505
4506/// An abstract interface for value simplify abstract attribute.
4508 : public StateWrapper<ValueSimplifyStateType, AbstractAttribute, Type *> {
4511 : Base(IRP, IRP.getAssociatedType()) {}
4512
4513 /// Create an abstract attribute view for the position \p IRP.
4515 Attributor &A);
4516
4517 StringRef getName() const override { return "AAValueSimplify"; }
4518
4519 const char *getIdAddr() const override { return &ID; }
4520
4521 /// This function should return true if the type of the \p AA is
4522 /// AAValueSimplify
4523 static bool classof(const AbstractAttribute *AA) {
4524 return (AA->getIdAddr() == &ID);
4525 }
4526
4527 /// Unique ID (due to the unique address)
4528 LLVM_ABI static const char ID;
4529
4530private:
4531 /// Return an assumed simplified value if a single candidate is found. If
4532 /// there cannot be one, return original value. If it is not clear yet, return
4533 /// std::nullopt.
4534 ///
4535 /// Use `Attributor::getAssumedSimplified` for value simplification.
4536 virtual std::optional<Value *>
4537 getAssumedSimplifiedValue(Attributor &A) const = 0;
4538
4539 friend struct Attributor;
4540};
4541
4542struct AAHeapToStack : public StateWrapper<BooleanState, AbstractAttribute> {
4544 AAHeapToStack(const IRPosition &IRP, Attributor &A) : Base(IRP) {}
4545
4546 /// Returns true if HeapToStack conversion is assumed to be possible.
4547 virtual bool isAssumedHeapToStack(const CallBase &CB) const = 0;
4548
4549 /// Returns true if HeapToStack conversion is assumed and the CB is a
4550 /// callsite to a free operation to be removed.
4551 virtual bool isAssumedHeapToStackRemovedFree(CallBase &CB) const = 0;
4552
4553 /// Create an abstract attribute view for the position \p IRP.
4555 Attributor &A);
4556
4557 StringRef getName() const override { return "AAHeapToStack"; }
4558
4559 const char *getIdAddr() const override { return &ID; }
4560
4561 /// This function should return true if the type of the \p AA is AAHeapToStack
4562 static bool classof(const AbstractAttribute *AA) {
4563 return (AA->getIdAddr() == &ID);
4564 }
4565
4566 /// Unique ID (due to the unique address)
4567 LLVM_ABI static const char ID;
4568};
4569
4570/// An abstract interface for privatizability.
4571///
4572/// A pointer is privatizable if it can be replaced by a new, private one.
4573/// Privatizing pointer reduces the use count, interaction between unrelated
4574/// code parts.
4575///
4576/// In order for a pointer to be privatizable its value cannot be observed
4577/// (=nocapture), it is (for now) not written (=readonly & noalias), we know
4578/// what values are necessary to make the private copy look like the original
4579/// one, and the values we need can be loaded (=dereferenceable).
4581 : public StateWrapper<BooleanState, AbstractAttribute> {
4584
4587 return false;
4589 }
4590
4591 /// Returns true if pointer privatization is assumed to be possible.
4592 bool isAssumedPrivatizablePtr() const { return getAssumed(); }
4593
4594 static bool requiresCallersForArgOrFunction() { return true; }
4595
4596 /// Return the type we can choose for a private copy of the underlying
4597 /// value. std::nullopt means it is not clear yet, nullptr means there is
4598 /// none.
4599 virtual std::optional<Type *> getPrivatizableType() const = 0;
4600
4601 /// Create an abstract attribute view for the position \p IRP.
4603 Attributor &A);
4604
4605 StringRef getName() const override { return "AAPrivatizablePtr"; }
4606
4607 const char *getIdAddr() const override { return &ID; }
4608
4609 /// This function should return true if the type of the \p AA is
4610 /// AAPricatizablePtr
4611 static bool classof(const AbstractAttribute *AA) {
4612 return (AA->getIdAddr() == &ID);
4613 }
4614
4615 /// Unique ID (due to the unique address)
4616 LLVM_ABI static const char ID;
4617};
4618
4619/// An abstract interface for memory access kind related attributes
4620/// (readnone/readonly/writeonly).
4622 : public IRAttribute<
4623 Attribute::None,
4624 StateWrapper<BitIntegerState<uint8_t, 3>, AbstractAttribute>,
4625 AAMemoryBehavior> {
4627
4628 static bool hasTrivialInitializer() { return false; }
4629
4631 if (!IRP.isFunctionScope() && !IRP.getAssociatedType()->isPointerTy())
4632 return false;
4633 return IRAttribute::isValidIRPositionForInit(A, IRP);
4634 }
4635
4636 /// State encoding bits. A set bit in the state means the property holds.
4637 /// BEST_STATE is the best possible state, 0 the worst possible state.
4638 enum {
4639 NO_READS = 1 << 0,
4640 NO_WRITES = 1 << 1,
4642
4644 };
4645 static_assert(BEST_STATE == getBestState(), "Unexpected BEST_STATE value");
4646
4647 /// Return true if we know that the underlying value is not read or accessed
4648 /// in its respective scope.
4649 bool isKnownReadNone() const { return isKnown(NO_ACCESSES); }
4650
4651 /// Return true if we assume that the underlying value is not read or accessed
4652 /// in its respective scope.
4653 bool isAssumedReadNone() const { return isAssumed(NO_ACCESSES); }
4654
4655 /// Return true if we know that the underlying value is not accessed
4656 /// (=written) in its respective scope.
4657 bool isKnownReadOnly() const { return isKnown(NO_WRITES); }
4658
4659 /// Return true if we assume that the underlying value is not accessed
4660 /// (=written) in its respective scope.
4661 bool isAssumedReadOnly() const { return isAssumed(NO_WRITES); }
4662
4663 /// Return true if we know that the underlying value is not read in its
4664 /// respective scope.
4665 bool isKnownWriteOnly() const { return isKnown(NO_READS); }
4666
4667 /// Return true if we assume that the underlying value is not read in its
4668 /// respective scope.
4669 bool isAssumedWriteOnly() const { return isAssumed(NO_READS); }
4670
4671 /// Create an abstract attribute view for the position \p IRP.
4673 Attributor &A);
4674
4675 StringRef getName() const override { return "AAMemoryBehavior"; }
4676
4677 const char *getIdAddr() const override { return &ID; }
4678
4679 /// This function should return true if the type of the \p AA is
4680 /// AAMemoryBehavior
4681 static bool classof(const AbstractAttribute *AA) {
4682 return (AA->getIdAddr() == &ID);
4683 }
4684
4685 /// Unique ID (due to the unique address)
4686 LLVM_ABI static const char ID;
4687};
4688
4689/// An abstract interface for all memory location attributes
4690/// (readnone/argmemonly/inaccessiblememonly/inaccessibleorargmemonly).
4692 : public IRAttribute<
4693 Attribute::None,
4694 StateWrapper<BitIntegerState<uint32_t, 511>, AbstractAttribute>,
4695 AAMemoryLocation> {
4696 using MemoryLocationsKind = StateType::base_t;
4697
4699
4700 static bool requiresCalleeForCallBase() { return true; }
4701
4702 static bool hasTrivialInitializer() { return false; }
4703
4705 if (!IRP.isFunctionScope() &&
4707 return false;
4708 return IRAttribute::isValidIRPositionForInit(A, IRP);
4709 }
4710
4711 /// Encoding of different locations that could be accessed by a memory
4712 /// access.
4713 enum {
4727
4728 // Helper bit to track if we gave up or not.
4730
4732 };
4733 static_assert(BEST_STATE == getBestState(), "Unexpected BEST_STATE value");
4734
4735 /// Return true if we know that the associated functions has no observable
4736 /// accesses.
4737 bool isKnownReadNone() const { return isKnown(NO_LOCATIONS); }
4738
4739 /// Return true if we assume that the associated functions has no observable
4740 /// accesses.
4741 bool isAssumedReadNone() const {
4743 }
4744
4745 /// Return true if we know that the associated functions has at most
4746 /// local/stack accesses.
4747 bool isKnowStackOnly() const {
4748 return isKnown(inverseLocation(NO_LOCAL_MEM, true, true));
4749 }
4750
4751 /// Return true if we assume that the associated functions has at most
4752 /// local/stack accesses.
4753 bool isAssumedStackOnly() const {
4754 return isAssumed(inverseLocation(NO_LOCAL_MEM, true, true));
4755 }
4756
4757 /// Return true if we know that the underlying value will only access
4758 /// inaccesible memory only (see Attribute::InaccessibleMemOnly).
4760 return isKnown(inverseLocation(NO_INACCESSIBLE_MEM, true, true));
4761 }
4762
4763 /// Return true if we assume that the underlying value will only access
4764 /// inaccesible memory only (see Attribute::InaccessibleMemOnly).
4766 return isAssumed(inverseLocation(NO_INACCESSIBLE_MEM, true, true));
4767 }
4768
4769 /// Return true if we know that the underlying value will only access
4770 /// argument pointees (see Attribute::ArgMemOnly).
4771 bool isKnownArgMemOnly() const {
4772 return isKnown(inverseLocation(NO_ARGUMENT_MEM, true, true));
4773 }
4774
4775 /// Return true if we assume that the underlying value will only access
4776 /// argument pointees (see Attribute::ArgMemOnly).
4777 bool isAssumedArgMemOnly() const {
4778 return isAssumed(inverseLocation(NO_ARGUMENT_MEM, true, true));
4779 }
4780
4781 /// Return true if we know that the underlying value will only access
4782 /// inaccesible memory or argument pointees (see
4783 /// Attribute::InaccessibleOrArgMemOnly).
4785 return isKnown(
4787 }
4788
4789 /// Return true if we assume that the underlying value will only access
4790 /// inaccesible memory or argument pointees (see
4791 /// Attribute::InaccessibleOrArgMemOnly).
4796
4797 /// Return true if the underlying value may access memory through arguement
4798 /// pointers of the associated function, if any.
4799 bool mayAccessArgMem() const { return !isAssumed(NO_ARGUMENT_MEM); }
4800
4801 /// Return true if only the memory locations specififed by \p MLK are assumed
4802 /// to be accessed by the associated function.
4804 return isAssumed(MLK);
4805 }
4806
4807 /// Return the locations that are assumed to be not accessed by the associated
4808 /// function, if any.
4812
4813 /// Return the inverse of location \p Loc, thus for NO_XXX the return
4814 /// describes ONLY_XXX. The flags \p AndLocalMem and \p AndConstMem determine
4815 /// if local (=stack) and constant memory are allowed as well. Most of the
4816 /// time we do want them to be included, e.g., argmemonly allows accesses via
4817 /// argument pointers or local or constant memory accesses.
4818 static MemoryLocationsKind
4819 inverseLocation(MemoryLocationsKind Loc, bool AndLocalMem, bool AndConstMem) {
4820 return NO_LOCATIONS & ~(Loc | (AndLocalMem ? NO_LOCAL_MEM : 0) |
4821 (AndConstMem ? NO_CONST_MEM : 0));
4822 };
4823
4824 /// Return the locations encoded by \p MLK as a readable string.
4826
4827 /// Simple enum to distinguish read/write/read-write accesses.
4829 NONE = 0,
4830 READ = 1 << 0,
4831 WRITE = 1 << 1,
4833 };
4834
4835 /// Check \p Pred on all accesses to the memory kinds specified by \p MLK.
4836 ///
4837 /// This method will evaluate \p Pred on all accesses (access instruction +
4838 /// underlying accessed memory pointer) and it will return true if \p Pred
4839 /// holds every time.
4841 function_ref<bool(const Instruction *, const Value *, AccessKind,
4843 Pred,
4844 MemoryLocationsKind MLK) const = 0;
4845
4846 /// Create an abstract attribute view for the position \p IRP.
4848 Attributor &A);
4849
4850 const std::string getAsStr(Attributor *A) const override {
4852 }
4853
4854 StringRef getName() const override { return "AAMemoryLocation"; }
4855
4856 const char *getIdAddr() const override { return &ID; }
4857
4858 /// This function should return true if the type of the \p AA is
4859 /// AAMemoryLocation
4860 static bool classof(const AbstractAttribute *AA) {
4861 return (AA->getIdAddr() == &ID);
4862 }
4863
4864 /// Unique ID (due to the unique address)
4865 LLVM_ABI static const char ID;
4866};
4867
4868/// An abstract interface for range value analysis.
4870 : public StateWrapper<IntegerRangeState, AbstractAttribute, uint32_t> {
4873 : Base(IRP, IRP.getAssociatedType()->getIntegerBitWidth()) {}
4874
4876 if (!IRP.getAssociatedType()->isIntegerTy())
4877 return false;
4879 }
4880
4881 static bool requiresCallersForArgOrFunction() { return true; }
4882
4883 IntegerRangeState &getState() override { return *this; }
4884 const IntegerRangeState &getState() const override { return *this; }
4885
4886 /// Create an abstract attribute view for the position \p IRP.
4888 Attributor &A);
4889
4890 /// Return an assumed range for the associated value a program point \p CtxI.
4891 /// If \p I is nullptr, simply return an assumed range.
4892 virtual ConstantRange
4894 const Instruction *CtxI = nullptr) const = 0;
4895
4896 /// Return an assumed constant for the associated value a program point \p
4897 /// CtxI.
4898 std::optional<Constant *>
4899 getAssumedConstant(Attributor &A, const Instruction *CtxI = nullptr) const {
4900 ConstantRange RangeV = getAssumedConstantRange(A, CtxI);
4901 if (auto *C = RangeV.getSingleElement()) {
4904 AA::getWithType(*ConstantInt::get(Ty->getContext(), *C), *Ty));
4905 }
4906 if (RangeV.isEmptySet())
4907 return std::nullopt;
4908 return nullptr;
4909 }
4910
4911 StringRef getName() const override { return "AAValueConstantRange"; }
4912
4913 const char *getIdAddr() const override { return &ID; }
4914
4915 /// This function should return true if the type of the \p AA is
4916 /// AAValueConstantRange
4917 static bool classof(const AbstractAttribute *AA) {
4918 return (AA->getIdAddr() == &ID);
4919 }
4920
4921 /// Unique ID (due to the unique address)
4922 LLVM_ABI static const char ID;
4923};
4924
4925/// A class for a set state.
4926/// The assumed boolean state indicates whether the corresponding set is full
4927/// set or not. If the assumed state is false, this is the worst state. The
4928/// worst state (invalid state) of set of potential values is when the set
4929/// contains every possible value (i.e. we cannot in any way limit the value
4930/// that the target position can take). That never happens naturally, we only
4931/// force it. As for the conditions under which we force it, see
4932/// AAPotentialConstantValues.
4933template <typename MemberTy> struct PotentialValuesState : AbstractState {
4935
4936 PotentialValuesState() : IsValidState(true), UndefIsContained(false) {}
4937
4939 : IsValidState(IsValid), UndefIsContained(false) {}
4940
4941 PotentialValuesState(bool IsValid, unsigned MaxPotentialValues)
4942 : IsValidState(IsValid), UndefIsContained(false),
4943 MaxPotentialValues(MaxPotentialValues) {}
4944
4945 bool isValidState() const override { return IsValidState.isValidState(); }
4946
4947 bool isAtFixpoint() const override { return IsValidState.isAtFixpoint(); }
4948
4950 return IsValidState.indicatePessimisticFixpoint();
4951 }
4952
4954 return IsValidState.indicateOptimisticFixpoint();
4955 }
4956
4957 /// Return the assumed state
4959 const PotentialValuesState &getAssumed() const { return *this; }
4960
4961 /// Return this set. We should check whether this set is valid or not by
4962 /// isValidState() before calling this function.
4963 const SetTy &getAssumedSet() const {
4964 assert(isValidState() && "This set shoud not be used when it is invalid!");
4965 return Set;
4966 }
4967
4968 /// Returns whether this state contains an undef value or not.
4969 bool undefIsContained() const {
4970 assert(isValidState() && "This flag shoud not be used when it is invalid!");
4971 return UndefIsContained;
4972 }
4973
4975 if (isValidState() != RHS.isValidState())
4976 return false;
4977 if (!isValidState() && !RHS.isValidState())
4978 return true;
4979 if (undefIsContained() != RHS.undefIsContained())
4980 return false;
4981 return Set == RHS.getAssumedSet();
4982 }
4983
4984 /// Return empty set as the best state of potential values.
4986 return PotentialValuesState(true, PVS.MaxPotentialValues);
4987 }
4988
4989 /// Return full set as the worst state of potential values.
4991 return PotentialValuesState(false);
4992 }
4993
4994 /// Union assumed set with the passed value.
4995 void unionAssumed(const MemberTy &C) { insert(C); }
4996
4997 /// Union assumed set with assumed set of the passed state \p PVS.
4998 void unionAssumed(const PotentialValuesState &PVS) { unionWith(PVS); }
4999
5000 /// Union assumed set with an undef value.
5001 void unionAssumedWithUndef() { unionWithUndef(); }
5002
5003 /// "Clamp" this state with \p PVS.
5005 IsValidState ^= PVS.IsValidState;
5006 unionAssumed(PVS);
5007 return *this;
5008 }
5009
5011 IsValidState &= PVS.IsValidState;
5012 unionAssumed(PVS);
5013 return *this;
5014 }
5015
5016protected:
5018 assert(isValidState() && "This set shoud not be used when it is invalid!");
5019 return Set;
5020 }
5021
5022private:
5023 /// Check the size of this set, and invalidate when the size is no
5024 /// less than \p MaxPotentialValues threshold.
5025 void checkAndInvalidate() {
5026 if (Set.size() >= MaxPotentialValues)
5028 else
5029 reduceUndefValue();
5030 }
5031
5032 /// If this state contains both undef and not undef, we can reduce
5033 /// undef to the not undef value.
5034 void reduceUndefValue() { UndefIsContained = UndefIsContained & Set.empty(); }
5035
5036 /// Insert an element into this set.
5037 void insert(const MemberTy &C) {
5038 if (!isValidState())
5039 return;
5040 Set.insert(C);
5041 checkAndInvalidate();
5042 }
5043
5044 /// Take union with R.
5045 void unionWith(const PotentialValuesState &R) {
5046 /// If this is a full set, do nothing.
5047 if (!isValidState())
5048 return;
5049 /// If R is full set, change L to a full set.
5050 if (!R.isValidState()) {
5052 return;
5053 }
5054 Set.insert_range(R.Set);
5055 UndefIsContained |= R.undefIsContained();
5056 checkAndInvalidate();
5057 }
5058
5059 /// Take union with an undef value.
5060 void unionWithUndef() {
5061 UndefIsContained = true;
5062 reduceUndefValue();
5063 }
5064
5065 /// A helper state which indicate whether this state is valid or not.
5066 BooleanState IsValidState;
5067
5068 /// Container for potential values
5069 SetTy Set;
5070
5071 /// Flag for undef value
5072 bool UndefIsContained;
5073
5074 /// Maximum number of potential values to be tracked.
5075 unsigned MaxPotentialValues = std::numeric_limits<unsigned>::max();
5076};
5077
5082
5083 bool operator==(const DenormalState Other) const {
5084 return Mode == Other.Mode && ModeF32 == Other.ModeF32;
5085 }
5086
5087 bool operator!=(const DenormalState Other) const {
5088 return Mode != Other.Mode || ModeF32 != Other.ModeF32;
5089 }
5090
5091 bool isValid() const { return Mode.isValid() && ModeF32.isValid(); }
5092
5096 if (Caller == Callee)
5097 return Caller;
5098 if (Callee == DenormalMode::Dynamic)
5099 return Caller;
5100 if (Caller == DenormalMode::Dynamic)
5101 return Callee;
5102 return DenormalMode::Invalid;
5103 }
5104
5106 return DenormalMode{unionDenormalKind(Callee.Output, Caller.Output),
5107 unionDenormalKind(Callee.Input, Caller.Input)};
5108 }
5109
5111 DenormalState Callee(*this);
5112 Callee.Mode = unionAssumed(Callee.Mode, Caller.Mode);
5113 Callee.ModeF32 = unionAssumed(Callee.ModeF32, Caller.ModeF32);
5114 return Callee;
5115 }
5116 };
5117
5119
5120 /// Explicitly track whether we've hit a fixed point.
5121 bool IsAtFixedpoint = false;
5122
5124
5125 DenormalState getKnown() const { return Known; }
5126
5127 // There's only really known or unknown, there's no speculatively assumable
5128 // state.
5129 DenormalState getAssumed() const { return Known; }
5130
5131 bool isValidState() const override { return Known.isValid(); }
5132
5133 /// Return true if there are no dynamic components to the denormal mode worth
5134 /// specializing.
5135 bool isModeFixed() const {
5136 return Known.Mode.Input != DenormalMode::Dynamic &&
5137 Known.Mode.Output != DenormalMode::Dynamic &&
5138 Known.ModeF32.Input != DenormalMode::Dynamic &&
5139 Known.ModeF32.Output != DenormalMode::Dynamic;
5140 }
5141
5142 bool isAtFixpoint() const override { return IsAtFixedpoint; }
5143
5149
5153
5157
5159 Known = Known.unionWith(Caller.getKnown());
5160 return *this;
5161 }
5162};
5163
5167
5171 const PotentialLLVMValuesState &R);
5172
5173/// An abstract interface for potential values analysis.
5174///
5175/// This AA collects potential values for each IR position.
5176/// An assumed set of potential values is initialized with the empty set (the
5177/// best state) and it will grow monotonically as we find more potential values
5178/// for this position.
5179/// The set might be forced to the worst state, that is, to contain every
5180/// possible value for this position in 2 cases.
5181/// 1. We surpassed the \p MaxPotentialValues threshold. This includes the
5182/// case that this position is affected (e.g. because of an operation) by a
5183/// Value that is in the worst state.
5184/// 2. We tried to initialize on a Value that we cannot handle (e.g. an
5185/// operator we do not currently handle).
5186///
5187/// For non constant integers see AAPotentialValues.
5189 : public StateWrapper<PotentialConstantIntValuesState, AbstractAttribute,
5190 bool, unsigned> {
5192 bool, unsigned>;
5194
5196 if (!IRP.getAssociatedType()->isIntegerTy())
5197 return false;
5199 }
5200
5201 static bool requiresCallersForArgOrFunction() { return true; }
5202
5203 PotentialConstantIntValuesState &getState() override { return *this; }
5205 return *this;
5206 }
5207
5208 /// Create an abstract attribute view for the position \p IRP.
5211
5212 /// Return assumed constant for the associated value
5213 std::optional<Constant *>
5214 getAssumedConstant(Attributor &A, const Instruction *CtxI = nullptr) const {
5215 if (!isValidState())
5216 return nullptr;
5217 if (getAssumedSet().size() == 1) {
5220 *ConstantInt::get(Ty->getContext(), *(getAssumedSet().begin())),
5221 *Ty));
5222 }
5223 if (getAssumedSet().size() == 0) {
5224 if (undefIsContained())
5226 return std::nullopt;
5227 }
5228
5229 return nullptr;
5230 }
5231
5232 /// Return the minimum trailing zeros of potential constants
5234 if (!isValidState() || getAssumedSet().empty())
5235 return 0;
5236 unsigned TrailingZeros = getAssumedSet().begin()->getBitWidth() + 1;
5237 for (const APInt &It : getAssumedSet()) {
5238 if (It.countTrailingZeros() < TrailingZeros)
5239 TrailingZeros = It.countTrailingZeros();
5240 }
5241 if (TrailingZeros > getAssumedSet().begin()->getBitWidth())
5242 return 0;
5243 return TrailingZeros;
5244 }
5245 StringRef getName() const override { return "AAPotentialConstantValues"; }
5246
5247 const char *getIdAddr() const override { return &ID; }
5248
5249 /// This function should return true if the type of the \p AA is
5250 /// AAPotentialConstantValues
5251 static bool classof(const AbstractAttribute *AA) {
5252 return (AA->getIdAddr() == &ID);
5253 }
5254
5255 /// Unique ID (due to the unique address)
5256 LLVM_ABI static const char ID;
5257};
5258
5260 : public StateWrapper<PotentialLLVMValuesState, AbstractAttribute> {
5263
5264 static bool requiresCallersForArgOrFunction() { return true; }
5265
5266 PotentialLLVMValuesState &getState() override { return *this; }
5267 const PotentialLLVMValuesState &getState() const override { return *this; }
5268
5269 /// Create an abstract attribute view for the position \p IRP.
5271 Attributor &A);
5272
5273 /// Extract the single value in \p Values if any.
5274 LLVM_ABI static Value *
5276 const IRPosition &IRP,
5278
5279 StringRef getName() const override { return "AAPotentialValues"; }
5280
5281 const char *getIdAddr() const override { return &ID; }
5282
5283 /// This function should return true if the type of the \p AA is
5284 /// AAPotentialValues
5285 static bool classof(const AbstractAttribute *AA) {
5286 return (AA->getIdAddr() == &ID);
5287 }
5288
5289 /// Unique ID (due to the unique address)
5290 LLVM_ABI static const char ID;
5291
5292private:
5293 virtual bool getAssumedSimplifiedValues(
5295 AA::ValueScope, bool RecurseForSelectAndPHI = false) const = 0;
5296
5297 friend struct Attributor;
5298};
5299
5300/// An abstract interface for all noundef attributes.
5302 : public IRAttribute<Attribute::NoUndef,
5303 StateWrapper<BooleanState, AbstractAttribute>,
5304 AANoUndef> {
5306
5307 static bool isImpliedByUndef() { return false; }
5308
5309 static bool isImpliedByPoison() { return false; }
5310
5311 LLVM_ABI static bool isImpliedByIR(Attributor &A, const IRPosition &IRP,
5312 Attribute::AttrKind ImpliedAttributeKind,
5313 bool IgnoreSubsumingPositions = false);
5314
5315 /// Return true if we assume that the underlying value is noundef.
5316 bool isAssumedNoUndef() const { return getAssumed(); }
5317
5318 /// Return true if we know that underlying value is noundef.
5319 bool isKnownNoUndef() const { return getKnown(); }
5320
5321 /// Create an abstract attribute view for the position \p IRP.
5323 Attributor &A);
5324
5325 StringRef getName() const override { return "AANoUndef"; }
5326
5327 const char *getIdAddr() const override { return &ID; }
5328
5329 /// This function should return true if the type of the \p AA is AANoUndef
5330 static bool classof(const AbstractAttribute *AA) {
5331 return (AA->getIdAddr() == &ID);
5332 }
5333
5334 /// Unique ID (due to the unique address)
5335 LLVM_ABI static const char ID;
5336};
5337
5339 : public IRAttribute<
5340 Attribute::NoFPClass,
5341 StateWrapper<BitIntegerState<uint32_t, fcAllFlags, fcNone>,
5342 AbstractAttribute>,
5343 AANoFPClass> {
5346
5348
5350 return AttributeFuncs::isNoFPClassCompatibleType(IRP.getAssociatedType());
5351 }
5352
5353 /// Return the underlying assumed nofpclass.
5355 return static_cast<FPClassTest>(getAssumed());
5356 }
5357 /// Return the underlying known nofpclass.
5359 return static_cast<FPClassTest>(getKnown());
5360 }
5361
5362 /// Create an abstract attribute view for the position \p IRP.
5364 Attributor &A);
5365
5366 StringRef getName() const override { return "AANoFPClass"; }
5367
5368 const char *getIdAddr() const override { return &ID; }
5369
5370 /// This function should return true if the type of the \p AA is AANoFPClass
5371 static bool classof(const AbstractAttribute *AA) {
5372 return (AA->getIdAddr() == &ID);
5373 }
5374
5375 /// Unique ID (due to the unique address)
5376 LLVM_ABI static const char ID;
5377};
5378
5379struct AACallGraphNode;
5380struct AACallEdges;
5381
5382/// An Iterator for call edges, creates AACallEdges attributes in a lazy way.
5383/// This iterator becomes invalid if the underlying edge list changes.
5384/// So This shouldn't outlive a iteration of Attributor.
5385class AACallEdgeIterator
5386 : public iterator_adaptor_base<AACallEdgeIterator,
5387 SetVector<Function *>::iterator> {
5388 AACallEdgeIterator(Attributor &A, SetVector<Function *>::iterator Begin)
5389 : iterator_adaptor_base(Begin), A(A) {}
5390
5391public:
5393
5394private:
5395 Attributor &A;
5396 friend AACallEdges;
5397 friend AttributorCallGraph;
5398};
5399
5402 virtual ~AACallGraphNode() = default;
5403
5406
5407 /// Iterator range for exploring the call graph.
5412
5413protected:
5414 /// Reference to Attributor needed for GraphTraits implementation.
5416};
5417
5418/// An abstract state for querying live call edges.
5419/// This interface uses the Attributor's optimistic liveness
5420/// information to compute the edges that are alive.
5421struct AACallEdges : public StateWrapper<BooleanState, AbstractAttribute>,
5424
5426 : Base(IRP), AACallGraphNode(A) {}
5427
5428 static bool requiresNonAsmForCallBase() { return false; }
5429
5430 /// Get the optimistic edges.
5431 virtual const SetVector<Function *> &getOptimisticEdges() const = 0;
5432
5433 /// Is there any call with a unknown callee.
5434 virtual bool hasUnknownCallee() const = 0;
5435
5436 /// Is there any call with a unknown callee, excluding any inline asm.
5437 virtual bool hasNonAsmUnknownCallee() const = 0;
5438
5439 /// Iterator for exploring the call graph.
5443
5444 /// Iterator for exploring the call graph.
5448
5449 /// Create an abstract attribute view for the position \p IRP.
5451 Attributor &A);
5452
5453 StringRef getName() const override { return "AACallEdges"; }
5454
5455 const char *getIdAddr() const override { return &ID; }
5456
5457 /// This function should return true if the type of the \p AA is AACallEdges.
5458 static bool classof(const AbstractAttribute *AA) {
5459 return (AA->getIdAddr() == &ID);
5460 }
5461
5462 /// Unique ID (due to the unique address)
5463 LLVM_ABI static const char ID;
5464};
5465
5466// Synthetic root node for the Attributor's internal call graph.
5469 ~AttributorCallGraph() override = default;
5470
5472 return AACallEdgeIterator(A, A.Functions.begin());
5473 }
5474
5476 return AACallEdgeIterator(A, A.Functions.end());
5477 }
5478
5479 /// Force populate the entire call graph.
5480 void populateAll() const {
5481 for (const AACallGraphNode *AA : optimisticEdgesRange()) {
5482 // Nothing else to do here.
5483 (void)AA;
5484 }
5485 }
5486
5487 LLVM_ABI void print();
5488};
5489
5490template <> struct GraphTraits<AACallGraphNode *> {
5493
5495 return Node->optimisticEdgesBegin();
5496 }
5497
5499 return Node->optimisticEdgesEnd();
5500 }
5501};
5502
5503template <>
5507
5509 return static_cast<AACallGraphNode *>(G);
5510 }
5511
5513 return G->optimisticEdgesBegin();
5514 }
5515
5517 return G->optimisticEdgesEnd();
5518 }
5519};
5520
5521template <>
5524
5526 const AttributorCallGraph *Graph) {
5527 const AACallEdges *AACE = static_cast<const AACallEdges *>(Node);
5528 return AACE->getAssociatedFunction()->getName().str();
5529 }
5530
5532 const AttributorCallGraph *Graph) {
5533 // Hide the synth root.
5534 return static_cast<const AACallGraphNode *>(Graph) == Node;
5535 }
5536};
5537
5539 : public StateWrapper<BooleanState, AbstractAttribute> {
5542
5543 /// Summary about the execution domain of a block or instruction.
5568
5569 /// Create an abstract attribute view for the position \p IRP.
5571 Attributor &A);
5572
5573 StringRef getName() const override { return "AAExecutionDomain"; }
5574
5575 const char *getIdAddr() const override { return &ID; }
5576
5577 /// Check if an instruction is executed only by the initial thread.
5579 return isExecutedByInitialThreadOnly(*I.getParent());
5580 }
5581
5582 /// Check if a basic block is executed only by the initial thread.
5583 virtual bool isExecutedByInitialThreadOnly(const BasicBlock &) const = 0;
5584
5585 /// Check if the instruction \p I is executed in an aligned region, that is,
5586 /// the synchronizing effects before and after \p I are both aligned barriers.
5587 /// This effectively means all threads execute \p I together.
5589 const Instruction &I) const = 0;
5590
5592 /// Return the execution domain with which the call \p CB is entered and the
5593 /// one with which it is left.
5594 virtual std::pair<ExecutionDomainTy, ExecutionDomainTy>
5595 getExecutionDomain(const CallBase &CB) const = 0;
5597
5598 /// Helper function to determine if \p FI is a no-op given the information
5599 /// about its execution from \p ExecDomainAA.
5600 virtual bool isNoOpFence(const FenceInst &FI) const = 0;
5601
5602 /// This function should return true if the type of the \p AA is
5603 /// AAExecutionDomain.
5604 static bool classof(const AbstractAttribute *AA) {
5605 return (AA->getIdAddr() == &ID);
5606 }
5607
5608 /// Unique ID (due to the unique address)
5609 LLVM_ABI static const char ID;
5610};
5611
5612/// An abstract Attribute for computing reachability between functions.
5614 : public StateWrapper<BooleanState, AbstractAttribute> {
5616
5618
5619 /// If the function represented by this possition can reach \p Fn.
5620 bool canReach(Attributor &A, const Function &Fn) const {
5621 Function *Scope = getAnchorScope();
5622 if (!Scope || Scope->isDeclaration())
5623 return true;
5624 return instructionCanReach(A, Scope->getEntryBlock().front(), Fn);
5625 }
5626
5627 /// Can \p Inst reach \p Fn.
5628 /// See also AA::isPotentiallyReachable.
5630 Attributor &A, const Instruction &Inst, const Function &Fn,
5631 const AA::InstExclusionSetTy *ExclusionSet = nullptr) const = 0;
5632
5633 /// Create an abstract attribute view for the position \p IRP.
5636
5637 StringRef getName() const override { return "AAInterFnReachability"; }
5638
5639 const char *getIdAddr() const override { return &ID; }
5640
5641 /// This function should return true if the type of the \p AA is AACallEdges.
5642 static bool classof(const AbstractAttribute *AA) {
5643 return (AA->getIdAddr() == &ID);
5644 }
5645
5646 /// Unique ID (due to the unique address)
5647 LLVM_ABI static const char ID;
5648};
5649
5650/// An abstract Attribute for determining the necessity of the convergent
5651/// attribute.
5652struct AANonConvergent : public StateWrapper<BooleanState, AbstractAttribute> {
5654
5656
5657 /// Create an abstract attribute view for the position \p IRP.
5659 Attributor &A);
5660
5661 /// Return true if "non-convergent" is assumed.
5662 bool isAssumedNotConvergent() const { return getAssumed(); }
5663
5664 /// Return true if "non-convergent" is known.
5665 bool isKnownNotConvergent() const { return getKnown(); }
5666
5667 StringRef getName() const override { return "AANonConvergent"; }
5668
5669 const char *getIdAddr() const override { return &ID; }
5670
5671 /// This function should return true if the type of the \p AA is
5672 /// AANonConvergent.
5673 static bool classof(const AbstractAttribute *AA) {
5674 return (AA->getIdAddr() == &ID);
5675 }
5676
5677 /// Unique ID (due to the unique address)
5678 LLVM_ABI static const char ID;
5679};
5680
5681/// An abstract interface for struct information.
5684
5687 return false;
5689 }
5690
5692 // First two bits to distinguish may and must accesses.
5693 AK_MUST = 1 << 0,
5694 AK_MAY = 1 << 1,
5695
5696 // Then two bits for read and write. These are not exclusive.
5697 AK_R = 1 << 2,
5698 AK_W = 1 << 3,
5700
5701 // One special case for assumptions about memory content. These
5702 // are neither reads nor writes. They are however always modeled
5703 // as read to avoid using them for write removal.
5705
5706 // Helper for easy access.
5713 };
5714
5715 /// A helper containing a list of offsets computed for a Use. Ideally this
5716 /// list should be strictly ascending, but we ensure that only when we
5717 /// actually translate the list of offsets to a RangeList.
5718 struct OffsetInfo {
5722
5723 const_iterator begin() const { return Offsets.begin(); }
5724 const_iterator end() const { return Offsets.end(); }
5725
5726 bool operator==(const OffsetInfo &RHS) const {
5727 return Offsets == RHS.Offsets;
5728 }
5729
5730 bool operator!=(const OffsetInfo &RHS) const { return !(*this == RHS); }
5731
5732 bool insert(int64_t Offset) { return Offsets.insert(Offset).second; }
5733 bool isUnassigned() const { return Offsets.size() == 0; }
5734
5735 bool isUnknown() const {
5736 if (isUnassigned())
5737 return false;
5738 if (Offsets.size() == 1)
5739 return *Offsets.begin() == AA::RangeTy::Unknown;
5740 return false;
5741 }
5742
5743 void setUnknown() {
5744 Offsets.clear();
5746 }
5747
5748 void addToAll(int64_t Inc) {
5749 VecTy NewOffsets;
5750 for (auto &Offset : Offsets)
5751 NewOffsets.insert(Offset + Inc);
5752 Offsets = std::move(NewOffsets);
5753 }
5754
5755 /// Copy offsets from \p R into the current list.
5756 ///
5757 /// Ideally all lists should be strictly ascending, but we defer that to the
5758 /// actual use of the list. So we just blindly append here.
5759 bool merge(const OffsetInfo &R) { return set_union(Offsets, R.Offsets); }
5760 };
5761
5762 /// A container for a list of ranges.
5763 struct RangeList {
5764 // The set of ranges rarely contains more than one element, and is unlikely
5765 // to contain more than say four elements. So we find the middle-ground with
5766 // a sorted vector. This avoids hard-coding a rarely used number like "four"
5767 // into every instance of a SmallSet.
5773
5774 RangeList(const RangeTy &R) { Ranges.push_back(R); }
5776 Ranges.reserve(Offsets.size());
5777 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
5778 assert(((i + 1 == e) || Offsets[i] < Offsets[i + 1]) &&
5779 "Expected strictly ascending offsets.");
5780 Ranges.emplace_back(Offsets[i], Size);
5781 }
5782 }
5783 RangeList() = default;
5784
5785 iterator begin() { return Ranges.begin(); }
5786 iterator end() { return Ranges.end(); }
5787 const_iterator begin() const { return Ranges.begin(); }
5788 const_iterator end() const { return Ranges.end(); }
5789
5790 // Helpers required for std::set_difference
5792 void push_back(const RangeTy &R) {
5793 assert((Ranges.empty() || RangeTy::LessThan(Ranges.back(), R)) &&
5794 "Ensure the last element is the greatest.");
5795 Ranges.push_back(R);
5796 }
5797
5798 /// Copy ranges from \p L that are not in \p R, into \p D.
5799 static void set_difference(const RangeList &L, const RangeList &R,
5800 RangeList &D) {
5801 std::set_difference(L.begin(), L.end(), R.begin(), R.end(),
5802 std::back_inserter(D), RangeTy::LessThan);
5803 }
5804
5805 unsigned size() const { return Ranges.size(); }
5806
5807 bool operator==(const RangeList &OI) const { return Ranges == OI.Ranges; }
5808
5809 /// Merge the ranges in \p RHS into the current ranges.
5810 /// - Merging a list of unknown ranges makes the current list unknown.
5811 /// - Ranges with the same offset are merged according to RangeTy::operator&
5812 /// \return true if the current RangeList changed.
5813 bool merge(const RangeList &RHS) {
5814 if (isUnknown())
5815 return false;
5816 if (RHS.isUnknown()) {
5817 setUnknown();
5818 return true;
5819 }
5820
5821 if (Ranges.empty()) {
5822 Ranges = RHS.Ranges;
5823 return true;
5824 }
5825
5826 bool Changed = false;
5827 auto LPos = Ranges.begin();
5828 for (auto &R : RHS.Ranges) {
5829 auto Result = insert(LPos, R);
5830 if (isUnknown())
5831 return true;
5832 LPos = Result.first;
5833 Changed |= Result.second;
5834 }
5835 return Changed;
5836 }
5837
5838 /// Insert \p R at the given iterator \p Pos, and merge if necessary.
5839 ///
5840 /// This assumes that all ranges before \p Pos are LessThan \p R, and
5841 /// then maintains the sorted order for the suffix list.
5842 ///
5843 /// \return The place of insertion and true iff anything changed.
5844 std::pair<iterator, bool> insert(iterator Pos, const RangeTy &R) {
5845 if (isUnknown())
5846 return std::make_pair(Ranges.begin(), false);
5847 if (R.offsetOrSizeAreUnknown()) {
5848 return std::make_pair(setUnknown(), true);
5849 }
5850
5851 // Maintain this as a sorted vector of unique entries.
5852 auto LB = std::lower_bound(Pos, Ranges.end(), R, RangeTy::LessThan);
5853 if (LB == Ranges.end() || LB->Offset != R.Offset)
5854 return std::make_pair(Ranges.insert(LB, R), true);
5855 bool Changed = *LB != R;
5856 *LB &= R;
5857 if (LB->offsetOrSizeAreUnknown())
5858 return std::make_pair(setUnknown(), true);
5859 return std::make_pair(LB, Changed);
5860 }
5861
5862 /// Add the increment \p Inc to the offset of every range.
5863 void addToAllOffsets(int64_t Inc) {
5864 assert(!isUnassigned() &&
5865 "Cannot increment if the offset is not yet computed!");
5866 if (isUnknown())
5867 return;
5868 for (auto &R : Ranges) {
5869 R.Offset += Inc;
5870 }
5871 }
5872
5873 /// Return true iff the list contains an unknown range.
5874 bool isUnknown() const {
5875 if (isUnassigned())
5876 return false;
5877 if (Ranges.front().offsetOrSizeAreUnknown()) {
5878 assert(Ranges.size() == 1 && "Unknown is a singleton range.");
5879 return true;
5880 }
5881 return false;
5882 }
5883
5884 /// Discard all ranges and insert a single unknown range.
5886 Ranges.clear();
5887 Ranges.push_back(RangeTy::getUnknown());
5888 return Ranges.begin();
5889 }
5890
5891 /// Return true if no ranges have been inserted.
5892 bool isUnassigned() const { return Ranges.size() == 0; }
5893 };
5894
5895 /// An access description.
5896 struct Access {
5897 Access(Instruction *I, int64_t Offset, int64_t Size,
5898 std::optional<Value *> Content, AccessKind Kind, Type *Ty)
5899 : LocalI(I), RemoteI(I), Content(Content), Ranges(Offset, Size),
5900 Kind(Kind), Ty(Ty) {
5901 verify();
5902 }
5903 Access(Instruction *LocalI, Instruction *RemoteI, const RangeList &Ranges,
5904 std::optional<Value *> Content, AccessKind K, Type *Ty)
5905 : LocalI(LocalI), RemoteI(RemoteI), Content(Content), Ranges(Ranges),
5906 Kind(K), Ty(Ty) {
5907 if (Ranges.size() > 1) {
5908 Kind = AccessKind(Kind | AK_MAY);
5909 Kind = AccessKind(Kind & ~AK_MUST);
5910 }
5911 verify();
5912 }
5913 Access(Instruction *LocalI, Instruction *RemoteI, int64_t Offset,
5914 int64_t Size, std::optional<Value *> Content, AccessKind Kind,
5915 Type *Ty)
5916 : LocalI(LocalI), RemoteI(RemoteI), Content(Content),
5917 Ranges(Offset, Size), Kind(Kind), Ty(Ty) {
5918 verify();
5919 }
5920 Access(const Access &Other) = default;
5921
5922 Access &operator=(const Access &Other) = default;
5923 bool operator==(const Access &R) const {
5924 return LocalI == R.LocalI && RemoteI == R.RemoteI && Ranges == R.Ranges &&
5925 Content == R.Content && Kind == R.Kind;
5926 }
5927 bool operator!=(const Access &R) const { return !(*this == R); }
5928
5930 assert(RemoteI == R.RemoteI && "Expected same instruction!");
5931 assert(LocalI == R.LocalI && "Expected same instruction!");
5932
5933 // Note that every Access object corresponds to a unique Value, and only
5934 // accesses to the same Value are merged. Hence we assume that all ranges
5935 // are the same size. If ranges can be different size, then the contents
5936 // must be dropped.
5937 Ranges.merge(R.Ranges);
5938 Content =
5939 AA::combineOptionalValuesInAAValueLatice(Content, R.Content, Ty);
5940
5941 // Combine the access kind, which results in a bitwise union.
5942 // If there is more than one range, then this must be a MAY.
5943 // If we combine a may and a must access we clear the must bit.
5944 Kind = AccessKind(Kind | R.Kind);
5945 if ((Kind & AK_MAY) || Ranges.size() > 1) {
5946 Kind = AccessKind(Kind | AK_MAY);
5947 Kind = AccessKind(Kind & ~AK_MUST);
5948 }
5949 verify();
5950 return *this;
5951 }
5952
5953 void verify() {
5954 assert(isMustAccess() + isMayAccess() == 1 &&
5955 "Expect must or may access, not both.");
5956 assert(isAssumption() + isWrite() <= 1 &&
5957 "Expect assumption access or write access, never both.");
5958 assert((isMayAccess() || Ranges.size() == 1) &&
5959 "Cannot be a must access if there are multiple ranges.");
5960 }
5961
5962 /// Return the access kind.
5963 AccessKind getKind() const { return Kind; }
5964
5965 /// Return true if this is a read access.
5966 bool isRead() const { return Kind & AK_R; }
5967
5968 /// Return true if this is a write access.
5969 bool isWrite() const { return Kind & AK_W; }
5970
5971 /// Return true if this is a write access.
5972 bool isWriteOrAssumption() const { return isWrite() || isAssumption(); }
5973
5974 /// Return true if this is an assumption access.
5975 bool isAssumption() const { return Kind == AK_ASSUMPTION; }
5976
5977 bool isMustAccess() const {
5978 bool MustAccess = Kind & AK_MUST;
5979 assert((!MustAccess || Ranges.size() < 2) &&
5980 "Cannot be a must access if there are multiple ranges.");
5981 return MustAccess;
5982 }
5983
5984 bool isMayAccess() const {
5985 bool MayAccess = Kind & AK_MAY;
5986 assert((MayAccess || Ranges.size() < 2) &&
5987 "Cannot be a must access if there are multiple ranges.");
5988 return MayAccess;
5989 }
5990
5991 /// Return the instruction that causes the access with respect to the local
5992 /// scope of the associated attribute.
5993 Instruction *getLocalInst() const { return LocalI; }
5994
5995 /// Return the actual instruction that causes the access.
5996 Instruction *getRemoteInst() const { return RemoteI; }
5997
5998 /// Return true if the value written is not known yet.
5999 bool isWrittenValueYetUndetermined() const { return !Content; }
6000
6001 /// Return true if the value written cannot be determined at all.
6003 return Content.has_value() && !*Content;
6004 }
6005
6006 /// Return the type associated with the access, if known.
6007 Type *getType() const { return Ty; }
6008
6009 /// Return the value writen, if any.
6012 "Value needs to be determined before accessing it.");
6013 return *Content;
6014 }
6015
6016 /// Return the written value which can be `llvm::null` if it is not yet
6017 /// determined.
6018 std::optional<Value *> getContent() const { return Content; }
6019
6020 const RangeList &getRanges() const { return Ranges; }
6021
6023 const_iterator begin() const { return Ranges.begin(); }
6024 const_iterator end() const { return Ranges.end(); }
6025
6026 private:
6027 /// The instruction responsible for the access with respect to the local
6028 /// scope of the associated attribute.
6029 Instruction *LocalI;
6030
6031 /// The instruction responsible for the access.
6032 Instruction *RemoteI;
6033
6034 /// The value written, if any. `std::nullopt` means "not known yet",
6035 /// `nullptr` cannot be determined.
6036 std::optional<Value *> Content;
6037
6038 /// Set of potential ranges accessed from the base pointer.
6039 RangeList Ranges;
6040
6041 /// The access kind, e.g., READ, as bitset (could be more than one).
6043
6044 /// The type of the content, thus the type read/written, can be null if not
6045 /// available.
6046 Type *Ty;
6047 };
6048
6049 /// Create an abstract attribute view for the position \p IRP.
6051 Attributor &A);
6052
6053 StringRef getName() const override { return "AAPointerInfo"; }
6054
6055 const char *getIdAddr() const override { return &ID; }
6056
6058 using const_bin_iterator = OffsetBinsTy::const_iterator;
6059 virtual const_bin_iterator begin() const = 0;
6060 virtual const_bin_iterator end() const = 0;
6061 virtual int64_t numOffsetBins() const = 0;
6062 virtual bool reachesReturn() const = 0;
6063 virtual void addReturnedOffsetsTo(OffsetInfo &) const = 0;
6064
6065 /// Call \p CB on all accesses that might interfere with \p Range and return
6066 /// true if all such accesses were known and the callback returned true for
6067 /// all of them, false otherwise. An access interferes with an offset-size
6068 /// pair if it might read or write that memory region.
6070 AA::RangeTy Range, function_ref<bool(const Access &, bool)> CB) const = 0;
6071
6072 /// Call \p CB on all accesses that might interfere with \p I and
6073 /// return true if all such accesses were known and the callback returned true
6074 /// for all of them, false otherwise. In contrast to forallInterferingAccesses
6075 /// this function will perform reasoning to exclude write accesses that cannot
6076 /// affect the load even if they on the surface look as if they would. The
6077 /// flag \p HasBeenWrittenTo will be set to true if we know that \p I does not
6078 /// read the initial value of the underlying memory. If \p SkipCB is given and
6079 /// returns false for a potentially interfering access, that access is not
6080 /// checked for actual interference.
6082 Attributor &A, const AbstractAttribute &QueryingAA, Instruction &I,
6083 bool FindInterferingWrites, bool FindInterferingReads,
6084 function_ref<bool(const Access &, bool)> CB, bool &HasBeenWrittenTo,
6086 function_ref<bool(const Access &)> SkipCB = nullptr) const = 0;
6087
6088 /// This function should return true if the type of the \p AA is AAPointerInfo
6089 static bool classof(const AbstractAttribute *AA) {
6090 return (AA->getIdAddr() == &ID);
6091 }
6092
6093 /// Unique ID (due to the unique address)
6094 LLVM_ABI static const char ID;
6095};
6096
6098
6099/// An abstract attribute for getting assumption information.
6101 : public StateWrapper<SetState<StringRef>, AbstractAttribute,
6102 DenseSet<StringRef>> {
6103 using Base =
6105
6107 const DenseSet<StringRef> &Known)
6108 : Base(IRP, Known) {}
6109
6110 /// Returns true if the assumption set contains the assumption \p Assumption.
6111 virtual bool hasAssumption(const StringRef Assumption) const = 0;
6112
6113 /// Create an abstract attribute view for the position \p IRP.
6115 Attributor &A);
6116
6117 StringRef getName() const override { return "AAAssumptionInfo"; }
6118
6119 const char *getIdAddr() const override { return &ID; }
6120
6121 /// This function should return true if the type of the \p AA is
6122 /// AAAssumptionInfo
6123 static bool classof(const AbstractAttribute *AA) {
6124 return (AA->getIdAddr() == &ID);
6125 }
6126
6127 /// Unique ID (due to the unique address)
6128 LLVM_ABI static const char ID;
6129};
6130
6131/// An abstract attribute for getting all assumption underlying objects.
6134
6137 return false;
6139 }
6140
6141 static bool requiresCallersForArgOrFunction() { return true; }
6142
6143 /// Create an abstract attribute biew for the position \p IRP.
6145 Attributor &A);
6146
6147 StringRef getName() const override { return "AAUnderlyingObjects"; }
6148
6149 const char *getIdAddr() const override { return &ID; }
6150
6151 /// This function should return true if the type of the \p AA is
6152 /// AAUnderlyingObjects.
6153 static bool classof(const AbstractAttribute *AA) {
6154 return (AA->getIdAddr() == &ID);
6155 }
6156
6157 /// Unique ID (due to the unique address)
6158 LLVM_ABI static const char ID;
6159
6160 /// Check \p Pred on all underlying objects in \p Scope collected so far.
6161 ///
6162 /// This method will evaluate \p Pred on all underlying objects in \p Scope
6163 /// collected so far and return true if \p Pred holds on all of them.
6164 virtual bool
6166 AA::ValueScope Scope = AA::Interprocedural) const = 0;
6167};
6168
6169/// An abstract interface for identifying pointers from which loads can be
6170/// marked invariant.
6173
6175 if (!IRP.getAssociatedType()->isPointerTy())
6176 return false;
6177
6179 }
6180
6181 /// Create an abstract attribute view for the position \p IRP.
6184
6185 /// Return true if the pointer's contents are known to remain invariant.
6186 virtual bool isKnownInvariant() const = 0;
6187 virtual bool isKnownLocallyInvariant() const = 0;
6188
6189 /// Return true if the pointer's contents are assumed to remain invariant.
6190 virtual bool isAssumedInvariant() const = 0;
6191 virtual bool isAssumedLocallyInvariant() const = 0;
6192
6193 StringRef getName() const override { return "AAInvariantLoadPointer"; }
6194
6195 const char *getIdAddr() const override { return &ID; }
6196
6197 /// This function should return true if the type of the \p AA is
6198 /// AAInvariantLoadPointer
6199 static bool classof(const AbstractAttribute *AA) {
6200 return (AA->getIdAddr() == &ID);
6201 }
6202
6203 /// Unique ID (due to the unique address).
6204 LLVM_ABI static const char ID;
6205};
6206
6207/// An abstract interface for address space information.
6208struct AAAddressSpace : public StateWrapper<BooleanState, AbstractAttribute> {
6211
6214 return false;
6216 }
6217
6218 static bool requiresCallersForArgOrFunction() { return true; }
6219
6220 /// Return the address space of the associated value. \p NoAddressSpace is
6221 /// returned if the associated value is dead. This functions is not supposed
6222 /// to be called if the AA is invalid.
6223 virtual uint32_t getAddressSpace() const = 0;
6224
6225 /// Create an abstract attribute view for the position \p IRP.
6227 Attributor &A);
6228
6229 StringRef getName() const override { return "AAAddressSpace"; }
6230
6231 const char *getIdAddr() const override { return &ID; }
6232
6233 /// This function should return true if the type of the \p AA is
6234 /// AAAssumptionInfo
6235 static bool classof(const AbstractAttribute *AA) {
6236 return (AA->getIdAddr() == &ID);
6237 }
6238
6239 /// Unique ID (due to the unique address)
6240 LLVM_ABI static const char ID;
6241
6242protected:
6243 // Invalid address space which indicates the associated value is dead.
6244 static const uint32_t InvalidAddressSpace = ~0U;
6245};
6246
6247/// An abstract interface for potential address space information.
6249 : public StateWrapper<BooleanState, AbstractAttribute> {
6254
6257 return false;
6259 }
6260
6261 static bool requiresCallersForArgOrFunction() { return true; }
6262
6263 /// Create an abstract attribute view for the position \p IRP.
6265 Attributor &A);
6266 StringRef getName() const override { return "AANoAliasAddrSpace"; }
6267
6268 const char *getIdAddr() const override { return &ID; }
6269
6270 /// This function should return true if the type of the \p AA is
6271 /// AAAssumptionInfo
6272 static bool classof(const AbstractAttribute *AA) {
6273 return (AA->getIdAddr() == &ID);
6274 }
6275
6276 /// Unique ID (due to the unique address)
6277 LLVM_ABI static const char ID;
6278
6279protected:
6282};
6283
6284struct AAAllocationInfo : public StateWrapper<BooleanState, AbstractAttribute> {
6287
6290 return false;
6292 }
6293
6294 /// Create an abstract attribute view for the position \p IRP.
6296 Attributor &A);
6297
6298 virtual std::optional<TypeSize> getAllocatedSize() const = 0;
6299
6300 StringRef getName() const override { return "AAAllocationInfo"; }
6301
6302 const char *getIdAddr() const override { return &ID; }
6303
6304 /// This function should return true if the type of the \p AA is
6305 /// AAAllocationInfo
6306 static bool classof(const AbstractAttribute *AA) {
6307 return (AA->getIdAddr() == &ID);
6308 }
6309
6310 constexpr static const std::optional<TypeSize> HasNoAllocationSize =
6311 std::make_optional<TypeSize>(-1, true);
6312
6313 LLVM_ABI static const char ID;
6314};
6315
6316/// An abstract interface for llvm::GlobalValue information interference.
6318 : public StateWrapper<BooleanState, AbstractAttribute> {
6321
6324 return false;
6325 auto *GV = dyn_cast<GlobalValue>(&IRP.getAnchorValue());
6326 if (!GV)
6327 return false;
6328 return GV->hasLocalLinkage();
6329 }
6330
6331 /// Create an abstract attribute view for the position \p IRP.
6333 Attributor &A);
6334
6335 /// Return true iff \p U is a potential use of the associated global value.
6336 virtual bool isPotentialUse(const Use &U) const = 0;
6337
6338 StringRef getName() const override { return "AAGlobalValueInfo"; }
6339
6340 const char *getIdAddr() const override { return &ID; }
6341
6342 /// This function should return true if the type of the \p AA is
6343 /// AAGlobalValueInfo
6344 static bool classof(const AbstractAttribute *AA) {
6345 return (AA->getIdAddr() == &ID);
6346 }
6347
6348 /// Unique ID (due to the unique address)
6349 LLVM_ABI static const char ID;
6350};
6351
6352/// An abstract interface for indirect call information interference.
6354 : public StateWrapper<BooleanState, AbstractAttribute> {
6357
6360 return false;
6361 auto *CB = cast<CallBase>(IRP.getCtxI());
6362 return CB->getOpcode() == Instruction::Call && CB->isIndirectCall() &&
6363 !CB->isMustTailCall();
6364 }
6365
6366 /// Create an abstract attribute view for the position \p IRP.
6368 Attributor &A);
6369
6370 /// Call \CB on each potential callee value and return true if all were known
6371 /// and \p CB returned true on all of them. Otherwise, return false.
6372 virtual bool foreachCallee(function_ref<bool(Function *)> CB) const = 0;
6373
6374 StringRef getName() const override { return "AAIndirectCallInfo"; }
6375
6376 const char *getIdAddr() const override { return &ID; }
6377
6378 /// This function should return true if the type of the \p AA is
6379 /// AAIndirectCallInfo
6380 /// This function should return true if the type of the \p AA is
6381 /// AADenormalFPMath.
6382 static bool classof(const AbstractAttribute *AA) {
6383 return (AA->getIdAddr() == &ID);
6384 }
6385
6386 /// Unique ID (due to the unique address)
6387 LLVM_ABI static const char ID;
6388};
6389
6390/// An abstract Attribute for specializing "dynamic" components of
6391/// denormal_fpenv to a known denormal mode.
6393 : public StateWrapper<DenormalFPMathState, AbstractAttribute> {
6395
6397
6398 /// Create an abstract attribute view for the position \p IRP.
6400 Attributor &A);
6401
6402 StringRef getName() const override { return "AADenormalFPMath"; }
6403
6404 const char *getIdAddr() const override { return &ID; }
6405
6406 /// This function should return true if the type of the \p AA is
6407 /// AADenormalFPMath.
6408 static bool classof(const AbstractAttribute *AA) {
6409 return (AA->getIdAddr() == &ID);
6410 }
6411
6412 /// Unique ID (due to the unique address)
6413 LLVM_ABI static const char ID;
6414};
6415
6416/// Run options, used by the pass manager.
6427
6428namespace AA {
6429/// Helper to avoid creating an AA for IR Attributes that might already be set.
6430template <Attribute::AttrKind AK, typename AAType = AbstractAttribute>
6432 const IRPosition &IRP, DepClassTy DepClass, bool &IsKnown,
6433 bool IgnoreSubsumingPositions = false,
6434 const AAType **AAPtr = nullptr) {
6435 IsKnown = false;
6436 switch (AK) {
6437#define CASE(ATTRNAME, AANAME, ...) \
6438 case Attribute::ATTRNAME: { \
6439 if (AANAME::isImpliedByIR(A, IRP, AK, IgnoreSubsumingPositions)) \
6440 return IsKnown = true; \
6441 if (!QueryingAA) \
6442 return false; \
6443 const auto *AA = A.getAAFor<AANAME>(*QueryingAA, IRP, DepClass); \
6444 if (AAPtr) \
6445 *AAPtr = reinterpret_cast<const AAType *>(AA); \
6446 if (!AA || !AA->isAssumed(__VA_ARGS__)) \
6447 return false; \
6448 IsKnown = AA->isKnown(__VA_ARGS__); \
6449 return true; \
6450 }
6451 CASE(NoUnwind, AANoUnwind, );
6452 CASE(WillReturn, AAWillReturn, );
6453 CASE(NoFree, AANoFree, );
6454 CASE(Captures, AANoCapture, );
6455 CASE(NoRecurse, AANoRecurse, );
6456 CASE(NoReturn, AANoReturn, );
6457 CASE(NoSync, AANoSync, );
6458 CASE(NoAlias, AANoAlias, );
6459 CASE(NonNull, AANonNull, );
6460 CASE(MustProgress, AAMustProgress, );
6461 CASE(NoUndef, AANoUndef, );
6465#undef CASE
6466 default:
6467 llvm_unreachable("hasAssumedIRAttr not available for this attribute kind");
6468 };
6469}
6470} // namespace AA
6471
6472namespace detail {
6473template <typename... AATypes> struct AAKindList {};
6474
6475/// The abstract attributes declared here, by their bit in AAKindSet.
6487
6488template <typename... AATypes>
6490 return sizeof...(AATypes);
6491}
6492
6493constexpr size_t NumAAKinds = getNumAAKinds(AAKinds());
6494static_assert(NumAAKinds <= 64, "Too many kinds for the mask");
6495
6496/// Return the bit of \p AAType in AAKindSet, or the number of kinds if it has
6497/// none. The kinds are compared by type since older compilers cannot compare
6498/// the addresses of IDs in constant expressions, and MSVC rejects the
6499/// addresses of internal IDs as template arguments.
6500template <typename AAType, typename... AATypes>
6502 constexpr bool Matches[] = {std::is_same_v<AAType, AATypes>...};
6503 for (size_t I = 0; I != sizeof...(AATypes); ++I) {
6504 if (Matches[I])
6505 return I;
6506 }
6507 return sizeof...(AATypes);
6508}
6509
6510/// Return the bit of \p AAType in the mask of AAKindSet, or 0 if it has none.
6511template <typename AAType> constexpr uint64_t getAAKindMask() {
6512 constexpr size_t Bit = getAAKindBit<AAType>(AAKinds());
6513 return Bit < NumAAKinds ? uint64_t(1) << Bit : 0;
6514}
6515
6516/// The storage of the IDs of an AAKindSet.
6517template <typename... AATypes>
6518inline constexpr const char *AAKindSetIDs[] = {&AATypes::ID...};
6519} // namespace detail
6520
6521template <typename... AATypes> constexpr AAKindSet AAKindSet::get() {
6522 return AAKindSet((detail::getAAKindMask<AATypes>() | ...),
6524}
6525
6526template <typename AAType> bool AAKindSet::contains() const {
6527 constexpr uint64_t KindMask = detail::getAAKindMask<AAType>();
6528 if constexpr (KindMask != 0)
6529 return Mask & KindMask;
6530 else
6531 return is_contained(IDs, &AAType::ID);
6532}
6533
6534} // end namespace llvm
6535
6536#endif // LLVM_TRANSFORMS_IPO_ATTRIBUTOR_H
const TargetLowering & TLI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
uint64_t 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...
#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:211
This file contains the declarations for the subclasses of Constant, which represent the different fla...
DXIL Resource Access
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
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
bool contains() const
Return true if abstract attributes of type AAType are in the set.
static constexpr AAKindSet get()
Return the set of the kinds of abstract attributes of types AATypes.
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:448
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:107
static LLVM_ABI Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
static bool isEnumAttrKind(AttrKind Kind)
Definition Attributes.h:140
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:126
@ None
No attributes have been set.
Definition Attributes.h:128
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:44
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
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:731
bool hasLocalLinkage() const
typename Sizer::Allocator Allocator
Invoke instruction.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
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:598
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:97
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
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
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:346
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 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:707
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
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
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:166
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:328
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:337
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:167
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:333
ValueScope
Flags to distinguish intra-procedural queries from potentially inter-procedural queries.
Definition Attributor.h:187
@ Intraprocedural
Definition Attributor.h:188
@ Interprocedural
Definition Attributor.h:189
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.
constexpr E & operator^=(E &LHS, E RHS)
constexpr size_t NumAAKinds
constexpr const char * AAKindSetIDs[]
The storage of the IDs of an AAKindSet.
AAKindList< AANoUnwind, AANoSync, AAMustProgress, AANonNull, AANoRecurse, AAWillReturn, AAUndefinedBehavior, AAIntraFnReachability, AANoAlias, AANoFree, AANoReturn, AAIsDead, AADereferenceable, AAAlign, AAInstanceInfo, AANoCapture, AAValueSimplify, AAHeapToStack, AAPrivatizablePtr, AAMemoryBehavior, AAMemoryLocation, AAValueConstantRange, AAPotentialConstantValues, AAPotentialValues, AANoUndef, AANoFPClass, AACallEdges, AAExecutionDomain, AAInterFnReachability, AANonConvergent, AAPointerInfo, AAAssumptionInfo, AAUnderlyingObjects, AAInvariantLoadPointer, AAAddressSpace, AANoAliasAddrSpace, AAAllocationInfo, AAGlobalValueInfo, AAIndirectCallInfo, AADenormalFPMath > AAKinds
The abstract attributes declared here, by their bit in AAKindSet.
constexpr size_t getAAKindBit(AAKindList< AATypes... >)
Return the bit of AAType in AAKindSet, or the number of kinds if it has none.
constexpr uint64_t getAAKindMask()
Return the bit of AAType in the mask of AAKindSet, or 0 if it has none.
unsigned combineHashValue(unsigned a, unsigned b)
Simplistic combination of 32-bit hash values into 32-bit hash values.
constexpr size_t getNumAAKinds(AAKindList< AATypes... >)
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
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)
LLVM_ABI bool shouldCreateAbstractAttribute()
Check the debug counter used to limit the number of AAs created.
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.
bool timeTraceProfilerEnabled()
Is the time trace profiler enabled, i.e. initialized?
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.
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
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
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
ChangeStatus
{
Definition Attributor.h:474
bool operator|=(SparseBitVector< ElementSize > &LHS, const SparseBitVector< ElementSize > *RHS)
@ OPTIONAL
The target may be valid if the source is not.
Definition Attributor.h:486
@ NONE
Do not track a dependence between source and target.
Definition Attributor.h:487
@ REQUIRED
The target cannot be valid if the source is not.
Definition Attributor.h:485
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:391
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:879
An abstract interface for address space information.
static LLVM_ABI AAAddressSpace & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
const char * getIdAddr() const override
This function should return the address of the ID of the AbstractAttribute.
static bool requiresCallersForArgOrFunction()
StringRef getName() const override
This function should return the name of the AbstractAttribute.
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)
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
An abstract interface for all align attributes.
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
This function should return the address of the ID of the AbstractAttribute.
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
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
This function should return the name of the AbstractAttribute.
static LLVM_ABI const char ID
virtual std::optional< TypeSize > getAllocatedSize() const =0
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
const char * getIdAddr() const override
This function should return the address of the ID of the AbstractAttribute.
static LLVM_ABI AAAllocationInfo & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
StringRef getName() const override
This function should return the name of the AbstractAttribute.
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.
An abstract attribute for getting assumption information.
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
This function should return the name of the AbstractAttribute.
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
This function should return the address of the ID of the AbstractAttribute.
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()
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
This function should return the name of the AbstractAttribute.
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
This function should return the address of the ID of the AbstractAttribute.
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.
An abstract Attribute for specializing "dynamic" components of denormal_fpenv to a known denormal mod...
const char * getIdAddr() const override
This function should return the address of the ID of the AbstractAttribute.
StringRef getName() const override
This function should return the name of the AbstractAttribute.
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:504
friend struct Attributor
Definition Attributor.h:525
mapped_iterator< DepSetTy::iterator, decltype(&DepGetVal)> iterator
Definition Attributor.h:511
mapped_iterator< DepSetTy::iterator, decltype(&DepGetValAA)> aaiterator
Definition Attributor.h:512
virtual ~AADepGraphNode()=default
SmallSetVector< DepTy, 2 > DepSetTy
Definition Attributor.h:496
static AADepGraphNode * DepGetVal(const DepTy &DT)
Definition Attributor.h:503
iterator child_begin()
Definition Attributor.h:517
DepSetTy Deps
Set of dependency graph nodes which should be updated if this one is updated.
Definition Attributor.h:501
friend struct AADepGraph
Definition Attributor.h:526
virtual void print(Attributor *, raw_ostream &OS) const
Definition Attributor.h:521
aaiterator begin()
Definition Attributor.h:515
PointerIntPair< AADepGraphNode *, 1 > DepTy
Definition Attributor.h:495
void print(raw_ostream &OS) const
Definition Attributor.h:520
The data structure for the dependency graph.
Definition Attributor.h:534
~AADepGraph()=default
iterator begin()
Definition Attributor.h:549
mapped_iterator< AADepGraphNode::DepSetTy::iterator, decltype(&DepGetVal)> iterator
Definition Attributor.h:540
LLVM_ABI void viewGraph()
AADepGraphNode SyntheticRoot
There is no root node for the dependency graph.
Definition Attributor.h:546
LLVM_ABI void print()
Print dependency graph.
static AADepGraphNode * DepGetVal(const DepTy &DT)
Definition Attributor.h:539
LLVM_ABI void dumpGraph(StringRef DotFileNamePrefix)
Dump graph to file.
iterator end()
Definition Attributor.h:550
AADepGraphNode * GetEntryNode()
Definition Attributor.h:547
AADepGraph()=default
AADepGraphNode::DepTy DepTy
Definition Attributor.h:538
An abstract interface for all dereferenceable attribute.
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
This function should return the name of the AbstractAttribute.
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
This function should return the address of the ID of the AbstractAttribute.
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
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
This function should return the address of the ID of the AbstractAttribute.
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
This function should return the name of the AbstractAttribute.
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)
An abstract interface for llvm::GlobalValue information interference.
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
This function should return the name of the AbstractAttribute.
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)
const char * getIdAddr() const override
This function should return the address of the ID of the AbstractAttribute.
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
This function should return the name of the AbstractAttribute.
StateWrapper< BooleanState, AbstractAttribute > Base
const char * getIdAddr() const override
This function should return the address of the ID of the AbstractAttribute.
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)
An abstract interface for indirect call information interference.
StringRef getName() const override
This function should return the name of the AbstractAttribute.
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
This function should return the address of the ID of the AbstractAttribute.
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)
An abstract interface to track if a value leaves it's defining function instance.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
StringRef getName() const override
This function should return the name of the AbstractAttribute.
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
This function should return the address of the ID of the AbstractAttribute.
An abstract Attribute for computing reachability between functions.
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
This function should return the address of the ID of the AbstractAttribute.
bool canReach(Attributor &A, const Function &Fn) const
If the function represented by this possition can reach Fn.
StringRef getName() const override
This function should return the name of the AbstractAttribute.
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
An abstract interface to determine reachability of point A to B.
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
This function should return the name of the AbstractAttribute.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
const char * getIdAddr() const override
This function should return the address of the ID of the AbstractAttribute.
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
This function should return the address of the ID of the AbstractAttribute.
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
StringRef getName() const override
This function should return the name of the AbstractAttribute.
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)
StringRef getName() const override
This function should return the name of the AbstractAttribute.
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
This function should return the address of the ID of the AbstractAttribute.
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
This function should return the name of the AbstractAttribute.
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()
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)
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
This function should return the address of the ID of the AbstractAttribute.
bool isKnownReadOnly() const
Return true if we know that the underlying value is not accessed (=written) in its respective scope.
An abstract interface for all memory location attributes (readnone/argmemonly/inaccessiblememonly/ina...
StringRef getName() const override
This function should return the name of the AbstractAttribute.
const char * getIdAddr() const override
This function should return the address of the ID of the AbstractAttribute.
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()
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()
bool isAssumedReadNone() const
Return true if we assume that the associated functions has no observable accesses.
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
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
This function should return the "summarized" assumed state as string.
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
This function should return the name of the AbstractAttribute.
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
This function should return the address of the ID of the AbstractAttribute.
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)
An abstract interface for potential address space information.
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AAAssumptionInfo.
static bool 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)
static LLVM_ABI const char ID
Unique ID (due to the unique address)
AANoAliasAddrSpace(const IRPosition &IRP, Attributor &A)
const char * getIdAddr() const override
This function should return the address of the ID of the AbstractAttribute.
StateWrapper< BooleanState, AbstractAttribute > Base
RangeMap::Allocator Allocator
StringRef getName() const override
This function should return the name of the AbstractAttribute.
An abstract interface for all noalias attributes.
static LLVM_ABI bool isImpliedByIR(Attributor &A, const IRPosition &IRP, Attribute::AttrKind ImpliedAttributeKind, bool IgnoreSubsumingPositions=false)
---------------------— NoAlias Argument Attribute ---------------------—
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AANoAlias.
StringRef getName() const override
This function should return the name of the AbstractAttribute.
static bool requiresCallersForArgOrFunction()
const char * getIdAddr() const override
This function should return the address of the ID of the AbstractAttribute.
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)
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)
@ 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
This function should return the address of the ID of the AbstractAttribute.
AANoCapture(const IRPosition &IRP, Attributor &A)
StringRef getName() const override
This function should return the name of the AbstractAttribute.
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)
--------------------— Variable Capturing ------------------------------—
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)
AANoFPClass(const IRPosition &IRP, Attributor &A)
StringRef getName() const override
This function should return the name of the AbstractAttribute.
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
This function should return the address of the ID of the AbstractAttribute.
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)
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)
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AANoFree.
StringRef getName() const override
This function should return the name of the AbstractAttribute.
const char * getIdAddr() const override
This function should return the address of the ID of the AbstractAttribute.
An abstract attribute for norecurse.
StringRef getName() const override
This function should return the name of the AbstractAttribute.
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
This function should return the address of the ID of the AbstractAttribute.
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
This function should return the name of the AbstractAttribute.
AANoReturn(const IRPosition &IRP, Attributor &A)
const char * getIdAddr() const override
This function should return the address of the ID of the AbstractAttribute.
bool isKnownNoReturn() const
Return true if the underlying object is known to never return.
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
AANoSync(const IRPosition &IRP, Attributor &A)
const char * getIdAddr() const override
This function should return the address of the ID of the AbstractAttribute.
StringRef getName() const override
This function should return the name of the AbstractAttribute.
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()
StringRef getName() const override
This function should return the name of the AbstractAttribute.
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
This function should return the address of the ID of the AbstractAttribute.
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()
static LLVM_ABI bool isImpliedByIR(Attributor &A, const IRPosition &IRP, Attribute::AttrKind ImpliedAttributeKind, bool IgnoreSubsumingPositions=false)
---------------------— NoUndef Attribute ------------------------------—
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
This function should return the name of the AbstractAttribute.
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
This function should return the address of the ID of the AbstractAttribute.
An abstract Attribute for determining the necessity of the convergent attribute.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
const char * getIdAddr() const override
This function should return the address of the ID of the AbstractAttribute.
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
This function should return the name of the AbstractAttribute.
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()
Undef is not necessarily nonnull as nonnull + noundef would cause poison.
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
static LLVM_ABI const char ID
Unique ID (due to the unique address)
const char * getIdAddr() const override
This function should return the address of the ID of the AbstractAttribute.
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
This function should return the name of the AbstractAttribute.
static LLVM_ABI bool isImpliedByIR(Attributor &A, const IRPosition &IRP, Attribute::AttrKind ImpliedAttributeKind, bool IgnoreSubsumingPositions=false)
---------------------— NonNull Argument Attribute ---------------------—
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()
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)
An abstract interface for struct information.
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
virtual bool reachesReturn() const =0
StringRef getName() const override
This function should return the name of the AbstractAttribute.
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
This function should return the address of the ID of the AbstractAttribute.
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
Return the internal abstract state for inspection.
const PotentialConstantIntValuesState & getState() const override
StateWrapper< PotentialConstantIntValuesState, AbstractAttribute, bool, unsigned > Base
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()
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.
static LLVM_ABI AAPotentialConstantValues & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
const char * getIdAddr() const override
This function should return the address of the ID of the AbstractAttribute.
LLVM_ABI AAPotentialConstantValues(const IRPosition &IRP, Attributor &A)
---------------— Potential Values Attribute ----------------------—
StringRef getName() const override
This function should return the name of the AbstractAttribute.
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
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
Return the internal abstract state for inspection.
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()
StateWrapper< PotentialLLVMValuesState, AbstractAttribute > Base
const PotentialLLVMValuesState & getState() const override
const char * getIdAddr() const override
This function should return the address of the ID of the AbstractAttribute.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
StringRef getName() const override
This function should return the name of the AbstractAttribute.
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.
An abstract interface for privatizability.
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
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
This function should return the name of the AbstractAttribute.
static bool classof(const AbstractAttribute *AA)
This function should return true if the type of the AA is AAPricatizablePtr.
static bool 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
This function should return the address of the ID of the AbstractAttribute.
StateWrapper< BooleanState, AbstractAttribute > Base
An abstract attribute for undefined behavior.
static LLVM_ABI AAUndefinedBehavior & createForPosition(const IRPosition &IRP, Attributor &A)
Create an abstract attribute view for the position IRP.
const char * getIdAddr() const override
This function should return the address of the ID of the AbstractAttribute.
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
This function should return the name of the AbstractAttribute.
virtual bool isKnownToCauseUB(Instruction *I) const =0
Return true if "undefined behavior" is known for a specific instruction.
An abstract attribute for getting all assumption underlying objects.
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
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
This function should return the address of the ID of the AbstractAttribute.
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()
StringRef getName() const override
This function should return the name of the AbstractAttribute.
An abstract interface for range value analysis.
static bool isValidIRPositionForInit(Attributor &A, const IRPosition &IRP)
StringRef getName() const override
This function should return the name of the AbstractAttribute.
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()
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
This function should return the address of the ID of the AbstractAttribute.
IntegerRangeState & getState() override
Return the internal abstract state for inspection.
const IntegerRangeState & getState() const override
An abstract interface for value simplify abstract attribute.
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
This function should return the name of the AbstractAttribute.
StateWrapper< ValueSimplifyStateType, AbstractAttribute, Type * > Base
static LLVM_ABI const char ID
Unique ID (due to the unique address)
const char * getIdAddr() const override
This function should return the address of the ID of the AbstractAttribute.
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
This function should return the address of the ID of the AbstractAttribute.
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
This function should return the name of the AbstractAttribute.
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:246
bool offsetAndSizeAreUnknown() const
Return true if offset and size are unknown, thus this is the default unknown object.
Definition Attributor.h:261
static constexpr int64_t Unknown
Definition Attributor.h:325
bool offsetOrSizeAreUnknown() const
Return true if offset or size are unknown.
Definition Attributor.h:255
static constexpr int64_t Unassigned
Constants used to represent special offsets or sizes.
Definition Attributor.h:324
RangeTy & operator&=(const RangeTy &R)
Definition Attributor.h:284
static RangeTy getUnknown()
Definition Attributor.h:252
bool isUnassigned() const
Return true if the offset and size are unassigned.
Definition Attributor.h:266
static bool LessThan(const RangeTy &L, const RangeTy &R)
Comparison for sorting ranges.
Definition Attributor.h:310
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:274
RangeTy(int64_t Offset, int64_t Size)
Definition Attributor.h:250
Value * getValue() const
Definition Attributor.h:199
std::pair< Value *, const Instruction * > Base
Definition Attributor.h:194
ValueAndContext(Value &V, const Instruction *CtxI)
Definition Attributor.h:196
const Instruction * getCtxI() const
Definition Attributor.h:200
ValueAndContext(Value &V, const Instruction &CtxI)
Definition Attributor.h:197
ValueAndContext(const Base &B)
Definition Attributor.h:195
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...
virtual bool isStateAtFixpoint() const
Return true if the state is at a fixpoint, like getState().isAtFixpoint() but with a single virtual c...
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
void invalidateAnalyses(Module &M)
Invalidates the analyses of each function in M individually, which allows preserving invariant functi...
Analysis::Result * getAnalysis(const Function &F, bool RequestCachedOnly=false)
AnalysisGetter(FunctionAnalysisManager &FAM, bool CachedOnly=false)
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.
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.
std::optional< AAKindSet > Allowed
If set, the only kinds of abstract attributes to create.
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()
const SmallSetVector< Function *, 8 > & getAttrModifiedFunctions()
Return the functions whose attributes, or whose call site attributes, were changed.
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.
bool canUseBodyFor(const IRPosition &IRP)
Return true if the body of the associated function can be used to derive information for IRP.
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)
const IPOOptions & Opts
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:431
static unsigned getHashValue(const AA::ValueAndContext &VAC)
Definition Attributor.h:427
DenseMapInfo< AA::ValueAndContext::Base > Base
Definition Attributor.h:426
static bool isEqual(const AA::ValueScope &LHS, const AA::ValueScope &RHS)
Definition Attributor.h:444
DenseMapInfo< unsigned char > Base
Definition Attributor.h:439
static unsigned getHashValue(const AA::ValueScope &S)
Definition Attributor.h:440
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
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:570
Function * getAssociatedFunction() const
Return the associated function, if any.
Definition Attributor.h:701
void setAttrList(const AttributeList &AttrList) const
Update the attributes associated with this function or call site scope.
Definition Attributor.h:836
unsigned getAttrIdx() const
Return the index in the attribute list for this position.
Definition Attributor.h:801
bool hasCallBaseContext() const
Check if the position has any call base context.
Definition Attributor.h:896
static const IRPosition callsite_returned(const CallBase &CB)
Create a position describing the returned value of CB.
Definition Attributor.h:638
static const IRPosition returned(const Function &F, const CallBaseContext *CBContext=nullptr)
Create a position describing the returned value of F.
Definition Attributor.h:620
LLVM_ABI Argument * getAssociatedArgument() const
Return the associated argument, if any.
bool isAnyCallSitePosition() const
Definition Attributor.h:863
bool operator!=(const IRPosition &RHS) const
Definition Attributor.h:679
static const IRPosition value(const Value &V, const CallBaseContext *CBContext=nullptr)
Create a position describing the value of V.
Definition Attributor.h:594
CallBase CallBaseContext
Definition Attributor.h:573
AttributeList getAttrList() const
Return the attributes associated with this function or call site scope.
Definition Attributor.h:829
int getCalleeArgNo() const
Return the callee argument number of the associated value if it is an argument or call site argument,...
Definition Attributor.h:787
static const IRPosition inst(const Instruction &I, const CallBaseContext *CBContext=nullptr)
Create a position describing the instruction I.
Definition Attributor.h:606
static const IRPosition callsite_argument(const CallBase &CB, unsigned ArgNo)
Create a position describing the argument of CB at position ArgNo.
Definition Attributor.h:643
Kind
The positions we distinguish in the IR.
Definition Attributor.h:576
@ IRP_ARGUMENT
An attribute for a function argument.
Definition Attributor.h:584
@ IRP_RETURNED
An attribute for the function return value.
Definition Attributor.h:580
@ IRP_CALL_SITE
An attribute for a call site (function scope).
Definition Attributor.h:583
@ IRP_CALL_SITE_RETURNED
An attribute for a call site return value.
Definition Attributor.h:581
@ IRP_FUNCTION
An attribute for a function (scope).
Definition Attributor.h:582
@ IRP_FLOAT
A position that is not associated with a spot suitable for attributes.
Definition Attributor.h:578
@ IRP_CALL_SITE_ARGUMENT
An attribute for a call site argument.
Definition Attributor.h:585
@ IRP_INVALID
An invalid position.
Definition Attributor.h:577
Instruction * getCtxI() const
Return the context instruction, if any.
Definition Attributor.h:754
static const IRPosition argument(const Argument &Arg, const CallBaseContext *CBContext=nullptr)
Create a position describing the argument Arg.
Definition Attributor.h:627
Type * getAssociatedType() const
Return the type this abstract attribute is associated with.
Definition Attributor.h:776
bool isFunctionScope() const
Return true if this is a function or call site position.
Definition Attributor.h:731
bool operator==(const IRPosition &RHS) const
Definition Attributor.h:676
static const IRPosition callsite_argument(AbstractCallSite ACS, unsigned ArgNo)
Create a position describing the argument of ACS at position ArgNo.
Definition Attributor.h:650
static const IRPosition function(const Function &F, const CallBaseContext *CBContext=nullptr)
Create a position describing the function scope of F.
Definition Attributor.h:613
const CallBaseContext * getCallBaseContext() const
Get the call base context from the position.
Definition Attributor.h:893
Value & getAssociatedValue() const
Return the value this abstract attribute is associated with.
Definition Attributor.h:768
Value & getAnchorValue() const
Return the value this abstract attribute is anchored with.
Definition Attributor.h:687
Value * getAttrListAnchor() const
Return the value attributes are attached to.
Definition Attributor.h:822
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:796
bool isFnInterfaceKind() const
Return true if the position refers to a function interface, that is the function scope,...
Definition Attributor.h:719
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:666
IRPosition stripCallBaseContext() const
Return the same position without the call base context.
Definition Attributor.h:886
Kind getPositionKind() const
Return the associated position kind.
Definition Attributor.h:843
bool isArgumentPosition() const
Return true if the position is an argument or call site argument.
Definition Attributor.h:875
static const IRPosition callsite_function(const CallBase &CB)
Create a position describing the function scope of CB.
Definition Attributor.h:633
IRPosition()
Default constructor available to create invalid positions implicitly.
Definition Attributor.h:591
Function * getAnchorScope() const
Return the Function surrounding the anchor value.
Definition Attributor.h:742
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.
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.
bool isOnlyUsedByAssume(const Instruction &I)
void invalidateAnalyses(Module &M)
Invalidates the cached analyses of M.
bool isExactOrInlineable(const Function &F) const
Return true if F has an exact definition or is inlineable.
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.
std::array< InstructionVectorTy *, Instruction::OtherOpsEnd > OpcodeInstMapTy
A map type from opcodes to instructions with this opcode.
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.
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 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
Return if this abstract state is fixed, thus does not need to be updated if information changes as it...
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
Return if this abstract state is in a valid state.
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
Indicate that the abstract state should converge to the pessimistic state.
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
Indicate that the abstract state should converge to the optimistic state.
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
NOTE: For now we simply pretend that the worst possible state is invalid.
virtual void handleNewAssumedValue(base_t Value)=0
Handle a new assumed value Value. Subtype dependent.
bool isAtFixpoint() const override
Return if this abstract state is fixed, thus does not need to be updated if information changes as it...
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
Indicate that the abstract state should converge to the optimistic state.
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
Indicate that the abstract state should converge to the pessimistic state.
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)
Return empty set as the best state of potential values.
PotentialValuesState & getAssumed()
Return the assumed state.
PotentialValuesState(bool IsValid, unsigned MaxPotentialValues)
bool undefIsContained() const
Returns whether this state contains an undef value or not.
bool isAtFixpoint() const override
Return if this abstract state is fixed, thus does not need to be updated if information changes as it...
void unionAssumed(const MemberTy &C)
Union assumed set with the passed value.
SmallSetVector< MemberTy, 8 > SetTy
ChangeStatus indicatePessimisticFixpoint() override
Indicate that the abstract state should converge to the pessimistic state.
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
Return if this abstract state is in a valid state.
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
Indicate that the abstract state should converge to the optimistic state.
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
Return if this abstract state is in a valid state.
bool isAtFixpoint() const override
Return if this abstract state is fixed, thus does not need to be updated if information changes as it...
const SetContents & getAssumed() const
Return the assumed state encoding.
const SetContents & getKnown() const
Return the known state encoding.
ChangeStatus indicateOptimisticFixpoint() override
Indicate that the abstract state should converge to the optimistic state.
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
Indicate that the abstract state should converge to the pessimistic state.
Helper to tie a abstract state implementation to an abstract attribute.
StateType & getState() override
StateTy StateType
Provide static access to the type of the state.
bool isStateAtFixpoint() const final
StateWrapper(const IRPosition &IRP, Ts... Args)
const StateType & getState() const override
bool isAtFixpoint() const final
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
Indicate that the abstract state should converge to the optimistic state.
ValueSimplifyStateType operator^=(const ValueSimplifyStateType &VS)
"Clamp" this state with PVS.
ChangeStatus indicatePessimisticFixpoint() override
Indicate that the abstract state should converge to the pessimistic state.
static ValueSimplifyStateType getBestState(Type *Ty)
bool isAtFixpoint() const override
Return if this abstract state is fixed, thus does not need to be updated if information changes as it...
bool isValidState() const override
Return if this abstract state is in a valid state.
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