LLVM 22.0.0git
Metadata.h
Go to the documentation of this file.
1//===- llvm/IR/Metadata.h - Metadata definitions ----------------*- 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/// @file
10/// This file contains the declarations for metadata subclasses.
11/// They represent the different flavors of metadata that live in LLVM.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_IR_METADATA_H
16#define LLVM_IR_METADATA_H
17
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/DenseMap.h"
23#include "llvm/ADT/StringRef.h"
24#include "llvm/ADT/ilist_node.h"
26#include "llvm/IR/Constant.h"
27#include "llvm/IR/LLVMContext.h"
28#include "llvm/IR/Value.h"
33#include <cassert>
34#include <cstddef>
35#include <cstdint>
36#include <iterator>
37#include <memory>
38#include <string>
39#include <type_traits>
40#include <utility>
41
42namespace llvm {
43
44class Module;
45class ModuleSlotTracker;
46class raw_ostream;
47class DbgVariableRecord;
48template <typename T> class StringMapEntry;
49template <typename ValueTy> class StringMapEntryStorage;
50class Type;
51
53 DEBUG_METADATA_VERSION = 3 // Current debug info version number.
54};
55
56/// Magic number in the value profile metadata showing a target has been
57/// promoted for the instruction and shouldn't be promoted again.
59
60/// Root of the metadata hierarchy.
61///
62/// This is a root class for typeless data in the IR.
63class Metadata {
65
66 /// RTTI.
67 const unsigned char SubclassID;
68
69protected:
70 /// Active type of storage.
72
73 /// Storage flag for non-uniqued, otherwise unowned, metadata.
74 unsigned char Storage : 7;
75
76 unsigned char SubclassData1 : 1;
77 unsigned short SubclassData16 = 0;
78 unsigned SubclassData32 = 0;
79
80public:
82#define HANDLE_METADATA_LEAF(CLASS) CLASS##Kind,
83#include "llvm/IR/Metadata.def"
84 };
85
86protected:
88 : SubclassID(ID), Storage(Storage), SubclassData1(false) {
89 static_assert(sizeof(*this) == 8, "Metadata fields poorly packed");
90 }
91
92 ~Metadata() = default;
93
94 /// Default handling of a changed operand, which asserts.
95 ///
96 /// If subclasses pass themselves in as owners to a tracking node reference,
97 /// they must provide an implementation of this method.
99 llvm_unreachable("Unimplemented in Metadata subclass");
100 }
101
102public:
103 unsigned getMetadataID() const { return SubclassID; }
104
105 /// User-friendly dump.
106 ///
107 /// If \c M is provided, metadata nodes will be numbered canonically;
108 /// otherwise, pointer addresses are substituted.
109 ///
110 /// Note: this uses an explicit overload instead of default arguments so that
111 /// the nullptr version is easy to call from a debugger.
112 ///
113 /// @{
114 LLVM_ABI void dump() const;
115 LLVM_ABI void dump(const Module *M) const;
116 /// @}
117
118 /// Print.
119 ///
120 /// Prints definition of \c this.
121 ///
122 /// If \c M is provided, metadata nodes will be numbered canonically;
123 /// otherwise, pointer addresses are substituted.
124 /// @{
125 LLVM_ABI void print(raw_ostream &OS, const Module *M = nullptr,
126 bool IsForDebug = false) const;
128 const Module *M = nullptr, bool IsForDebug = false) const;
129 /// @}
130
131 /// Print as operand.
132 ///
133 /// Prints reference of \c this.
134 ///
135 /// If \c M is provided, metadata nodes will be numbered canonically;
136 /// otherwise, pointer addresses are substituted.
137 /// @{
139 const Module *M = nullptr) const;
141 const Module *M = nullptr) const;
142 /// @}
143
144 /// Metadata IDs that may generate poison.
145 constexpr static const unsigned PoisonGeneratingIDs[] = {
146 LLVMContext::MD_range, LLVMContext::MD_nonnull, LLVMContext::MD_align};
147};
148
149// Create wrappers for C Binding types (see CBindingWrapping.h).
151
152// Specialized opaque metadata conversions.
154 return reinterpret_cast<Metadata**>(MDs);
155}
156
157#define HANDLE_METADATA(CLASS) class CLASS;
158#include "llvm/IR/Metadata.def"
159
160// Provide specializations of isa so that we don't need definitions of
161// subclasses to see if the metadata is a subclass.
162#define HANDLE_METADATA_LEAF(CLASS) \
163 template <> struct isa_impl<CLASS, Metadata> { \
164 static inline bool doit(const Metadata &MD) { \
165 return MD.getMetadataID() == Metadata::CLASS##Kind; \
166 } \
167 };
168#include "llvm/IR/Metadata.def"
169
171 MD.print(OS);
172 return OS;
173}
174
175/// Metadata wrapper in the Value hierarchy.
176///
177/// A member of the \a Value hierarchy to represent a reference to metadata.
178/// This allows, e.g., intrinsics to have metadata as operands.
179///
180/// Notably, this is the only thing in either hierarchy that is allowed to
181/// reference \a LocalAsMetadata.
182class MetadataAsValue : public Value {
184 friend class LLVMContextImpl;
185
186 Metadata *MD;
187
188 MetadataAsValue(Type *Ty, Metadata *MD);
189
190 /// Drop use of metadata (during teardown).
191 void dropUse() { MD = nullptr; }
192
193public:
195
196 LLVM_ABI static MetadataAsValue *get(LLVMContext &Context, Metadata *MD);
198 Metadata *MD);
199
200 Metadata *getMetadata() const { return MD; }
201
202 static bool classof(const Value *V) {
203 return V->getValueID() == MetadataAsValueVal;
204 }
205
206private:
207 void handleChangedMetadata(Metadata *MD);
208 void track();
209 void untrack();
210};
211
212/// Base class for tracking ValueAsMetadata/DIArgLists with user lookups and
213/// Owner callbacks outside of ValueAsMetadata.
214///
215/// Currently only inherited by DbgVariableRecord; if other classes need to use
216/// it, then a SubclassID will need to be added (either as a new field or by
217/// making DebugValue into a PointerIntUnion) to discriminate between the
218/// subclasses in lookup and callback handling.
220protected:
221 // Capacity to store 3 debug values.
222 // TODO: Not all DebugValueUser instances need all 3 elements, if we
223 // restructure the DbgVariableRecord class then we can template parameterize
224 // this array size.
225 std::array<Metadata *, 3> DebugValues;
226
228
229public:
231 LLVM_ABI const DbgVariableRecord *getUser() const;
232 /// To be called by ReplaceableMetadataImpl::replaceAllUsesWith, where `Old`
233 /// is a pointer to one of the pointers in `DebugValues` (so should be type
234 /// Metadata**), and `NewDebugValue` is the new Metadata* that is replacing
235 /// *Old.
236 /// For manually replacing elements of DebugValues,
237 /// `resetDebugValue(Idx, NewDebugValue)` should be used instead.
238 LLVM_ABI void handleChangedValue(void *Old, Metadata *NewDebugValue);
239 DebugValueUser() = default;
240 explicit DebugValueUser(std::array<Metadata *, 3> DebugValues)
242 trackDebugValues();
243 }
245 DebugValues = X.DebugValues;
246 retrackDebugValues(X);
247 }
249 DebugValues = X.DebugValues;
250 trackDebugValues();
251 }
252
254 if (&X == this)
255 return *this;
256
257 untrackDebugValues();
258 DebugValues = X.DebugValues;
259 retrackDebugValues(X);
260 return *this;
261 }
262
264 if (&X == this)
265 return *this;
266
267 untrackDebugValues();
268 DebugValues = X.DebugValues;
269 trackDebugValues();
270 return *this;
271 }
272
273 ~DebugValueUser() { untrackDebugValues(); }
274
276 untrackDebugValues();
277 DebugValues.fill(nullptr);
278 }
279
280 void resetDebugValue(size_t Idx, Metadata *DebugValue) {
281 assert(Idx < 3 && "Invalid debug value index.");
282 untrackDebugValue(Idx);
283 DebugValues[Idx] = DebugValue;
284 trackDebugValue(Idx);
285 }
286
287 bool operator==(const DebugValueUser &X) const {
288 return DebugValues == X.DebugValues;
289 }
290 bool operator!=(const DebugValueUser &X) const {
291 return DebugValues != X.DebugValues;
292 }
293
294private:
295 LLVM_ABI void trackDebugValue(size_t Idx);
296 LLVM_ABI void trackDebugValues();
297
298 LLVM_ABI void untrackDebugValue(size_t Idx);
299 LLVM_ABI void untrackDebugValues();
300
301 LLVM_ABI void retrackDebugValues(DebugValueUser &X);
302};
303
304/// API for tracking metadata references through RAUW and deletion.
305///
306/// Shared API for updating \a Metadata pointers in subclasses that support
307/// RAUW.
308///
309/// This API is not meant to be used directly. See \a TrackingMDRef for a
310/// user-friendly tracking reference.
312public:
313 /// Track the reference to metadata.
314 ///
315 /// Register \c MD with \c *MD, if the subclass supports tracking. If \c *MD
316 /// gets RAUW'ed, \c MD will be updated to the new address. If \c *MD gets
317 /// deleted, \c MD will be set to \c nullptr.
318 ///
319 /// If tracking isn't supported, \c *MD will not change.
320 ///
321 /// \return true iff tracking is supported by \c MD.
322 static bool track(Metadata *&MD) {
323 return track(&MD, *MD, static_cast<Metadata *>(nullptr));
324 }
325
326 /// Track the reference to metadata for \a Metadata.
327 ///
328 /// As \a track(Metadata*&), but with support for calling back to \c Owner to
329 /// tell it that its operand changed. This could trigger \c Owner being
330 /// re-uniqued.
331 static bool track(void *Ref, Metadata &MD, Metadata &Owner) {
332 return track(Ref, MD, &Owner);
333 }
334
335 /// Track the reference to metadata for \a MetadataAsValue.
336 ///
337 /// As \a track(Metadata*&), but with support for calling back to \c Owner to
338 /// tell it that its operand changed. This could trigger \c Owner being
339 /// re-uniqued.
340 static bool track(void *Ref, Metadata &MD, MetadataAsValue &Owner) {
341 return track(Ref, MD, &Owner);
342 }
343
344 /// Track the reference to metadata for \a DebugValueUser.
345 ///
346 /// As \a track(Metadata*&), but with support for calling back to \c Owner to
347 /// tell it that its operand changed. This could trigger \c Owner being
348 /// re-uniqued.
349 static bool track(void *Ref, Metadata &MD, DebugValueUser &Owner) {
350 return track(Ref, MD, &Owner);
351 }
352
353 /// Stop tracking a reference to metadata.
354 ///
355 /// Stops \c *MD from tracking \c MD.
356 static void untrack(Metadata *&MD) { untrack(&MD, *MD); }
357 LLVM_ABI static void untrack(void *Ref, Metadata &MD);
358
359 /// Move tracking from one reference to another.
360 ///
361 /// Semantically equivalent to \c untrack(MD) followed by \c track(New),
362 /// except that ownership callbacks are maintained.
363 ///
364 /// Note: it is an error if \c *MD does not equal \c New.
365 ///
366 /// \return true iff tracking is supported by \c MD.
367 static bool retrack(Metadata *&MD, Metadata *&New) {
368 return retrack(&MD, *MD, &New);
369 }
370 LLVM_ABI static bool retrack(void *Ref, Metadata &MD, void *New);
371
372 /// Check whether metadata is replaceable.
373 LLVM_ABI static bool isReplaceable(const Metadata &MD);
374
376
377private:
378 /// Track a reference to metadata for an owner.
379 ///
380 /// Generalized version of tracking.
381 LLVM_ABI static bool track(void *Ref, Metadata &MD, OwnerTy Owner);
382};
383
384/// Shared implementation of use-lists for replaceable metadata.
385///
386/// Most metadata cannot be RAUW'ed. This is a shared implementation of
387/// use-lists and associated API for the three that support it (
388/// \a ValueAsMetadata, \a TempMDNode, and \a DIArgList).
390 friend class MetadataTracking;
391
392public:
394
395private:
396 LLVMContext &Context;
397 uint64_t NextIndex = 0;
399
400public:
402
404 assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
405 }
406
407 LLVMContext &getContext() const { return Context; }
408
409 /// Replace all uses of this with MD.
410 ///
411 /// Replace all uses of this with \c MD, which is allowed to be null.
413 /// Replace all uses of the constant with Undef in debug info metadata
414 LLVM_ABI static void SalvageDebugInfo(const Constant &C);
415 /// Returns the list of all DIArgList users of this.
417 /// Returns the list of all DbgVariableRecord users of this.
419
420 /// Resolve all uses of this.
421 ///
422 /// Resolve all uses of this, turning off RAUW permanently. If \c
423 /// ResolveUsers, call \a MDNode::resolve() on any users whose last operand
424 /// is resolved.
425 LLVM_ABI void resolveAllUses(bool ResolveUsers = true);
426
427 unsigned getNumUses() const { return UseMap.size(); }
428
429private:
430 void addRef(void *Ref, OwnerTy Owner);
431 void dropRef(void *Ref);
432 void moveRef(void *Ref, void *New, const Metadata &MD);
433
434 /// Lazily construct RAUW support on MD.
435 ///
436 /// If this is an unresolved MDNode, RAUW support will be created on-demand.
437 /// ValueAsMetadata always has RAUW support.
438 static ReplaceableMetadataImpl *getOrCreate(Metadata &MD);
439
440 /// Get RAUW support on MD, if it exists.
441 static ReplaceableMetadataImpl *getIfExists(Metadata &MD);
442
443 /// Check whether this node will support RAUW.
444 ///
445 /// Returns \c true unless getOrCreate() would return null.
446 static bool isReplaceable(const Metadata &MD);
447};
448
449/// Value wrapper in the Metadata hierarchy.
450///
451/// This is a custom value handle that allows other metadata to refer to
452/// classes in the Value hierarchy.
453///
454/// Because of full uniquing support, each value is only wrapped by a single \a
455/// ValueAsMetadata object, so the lookup maps are far more efficient than
456/// those using ValueHandleBase.
459 friend class LLVMContextImpl;
460
461 Value *V;
462
463 /// Drop users without RAUW (during teardown).
464 void dropUsers() {
465 ReplaceableMetadataImpl::resolveAllUses(/* ResolveUsers */ false);
466 }
467
468protected:
471 assert(V && "Expected valid value");
472 }
473
474 ~ValueAsMetadata() = default;
475
476public:
477 LLVM_ABI static ValueAsMetadata *get(Value *V);
478
480 return cast<ConstantAsMetadata>(get(C));
481 }
482
484 return cast<LocalAsMetadata>(get(Local));
485 }
486
488
490 return cast_or_null<ConstantAsMetadata>(getIfExists(C));
491 }
492
494 return cast_or_null<LocalAsMetadata>(getIfExists(Local));
495 }
496
497 Value *getValue() const { return V; }
498 Type *getType() const { return V->getType(); }
499 LLVMContext &getContext() const { return V->getContext(); }
500
503 }
506 }
507
508 LLVM_ABI static void handleDeletion(Value *V);
509 LLVM_ABI static void handleRAUW(Value *From, Value *To);
510
511protected:
512 /// Handle collisions after \a Value::replaceAllUsesWith().
513 ///
514 /// RAUW isn't supported directly for \a ValueAsMetadata, but if the wrapped
515 /// \a Value gets RAUW'ed and the target already exists, this is used to
516 /// merge the two metadata nodes.
519 }
520
521public:
522 static bool classof(const Metadata *MD) {
523 return MD->getMetadataID() == LocalAsMetadataKind ||
524 MD->getMetadataID() == ConstantAsMetadataKind;
525 }
526};
527
529 friend class ValueAsMetadata;
530
532 : ValueAsMetadata(ConstantAsMetadataKind, C) {}
533
534public:
537 }
538
541 }
542
544 return cast<Constant>(ValueAsMetadata::getValue());
545 }
546
547 static bool classof(const Metadata *MD) {
548 return MD->getMetadataID() == ConstantAsMetadataKind;
549 }
550};
551
553 friend class ValueAsMetadata;
554
556 : ValueAsMetadata(LocalAsMetadataKind, Local) {
557 assert(!isa<Constant>(Local) && "Expected local value");
558 }
559
560public:
563 }
564
567 }
568
569 static bool classof(const Metadata *MD) {
570 return MD->getMetadataID() == LocalAsMetadataKind;
571 }
572};
573
574/// Transitional API for extracting constants from Metadata.
575///
576/// This namespace contains transitional functions for metadata that points to
577/// \a Constants.
578///
579/// In prehistory -- when metadata was a subclass of \a Value -- \a MDNode
580/// operands could refer to any \a Value. There's was a lot of code like this:
581///
582/// \code
583/// MDNode *N = ...;
584/// auto *CI = dyn_cast<ConstantInt>(N->getOperand(2));
585/// \endcode
586///
587/// Now that \a Value and \a Metadata are in separate hierarchies, maintaining
588/// the semantics for \a isa(), \a cast(), \a dyn_cast() (etc.) requires three
589/// steps: cast in the \a Metadata hierarchy, extraction of the \a Value, and
590/// cast in the \a Value hierarchy. Besides creating boiler-plate, this
591/// requires subtle control flow changes.
592///
593/// The end-goal is to create a new type of metadata, called (e.g.) \a MDInt,
594/// so that metadata can refer to numbers without traversing a bridge to the \a
595/// Value hierarchy. In this final state, the code above would look like this:
596///
597/// \code
598/// MDNode *N = ...;
599/// auto *MI = dyn_cast<MDInt>(N->getOperand(2));
600/// \endcode
601///
602/// The API in this namespace supports the transition. \a MDInt doesn't exist
603/// yet, and even once it does, changing each metadata schema to use it is its
604/// own mini-project. In the meantime this API prevents us from introducing
605/// complex and bug-prone control flow that will disappear in the end. In
606/// particular, the above code looks like this:
607///
608/// \code
609/// MDNode *N = ...;
610/// auto *CI = mdconst::dyn_extract<ConstantInt>(N->getOperand(2));
611/// \endcode
612///
613/// The full set of provided functions includes:
614///
615/// mdconst::hasa <=> isa
616/// mdconst::extract <=> cast
617/// mdconst::extract_or_null <=> cast_or_null
618/// mdconst::dyn_extract <=> dyn_cast
619/// mdconst::dyn_extract_or_null <=> dyn_cast_or_null
620///
621/// The target of the cast must be a subclass of \a Constant.
622namespace mdconst {
623
624namespace detail {
625template <typename U, typename V>
626using check_has_dereference = decltype(static_cast<V>(*std::declval<U &>()));
627
628template <typename U, typename V>
629static constexpr bool HasDereference =
631
632template <class V, class M> struct IsValidPointer {
633 static const bool value = std::is_base_of<Constant, V>::value &&
634 HasDereference<M, const Metadata &>;
635};
636template <class V, class M> struct IsValidReference {
637 static const bool value = std::is_base_of<Constant, V>::value &&
638 std::is_convertible<M, const Metadata &>::value;
639};
640
641} // end namespace detail
642
643/// Check whether Metadata has a Value.
644///
645/// As an analogue to \a isa(), check whether \c MD has an \a Value inside of
646/// type \c X.
647template <class X, class Y>
648inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, bool>
649hasa(Y &&MD) {
650 assert(MD && "Null pointer sent into hasa");
651 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
652 return isa<X>(V->getValue());
653 return false;
654}
655template <class X, class Y>
656inline std::enable_if_t<detail::IsValidReference<X, Y &>::value, bool>
657hasa(Y &MD) {
658 return hasa(&MD);
659}
660
661/// Extract a Value from Metadata.
662///
663/// As an analogue to \a cast(), extract the \a Value subclass \c X from \c MD.
664template <class X, class Y>
665inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, X *>
666extract(Y &&MD) {
667 return cast<X>(cast<ConstantAsMetadata>(MD)->getValue());
668}
669template <class X, class Y>
670inline std::enable_if_t<detail::IsValidReference<X, Y &>::value, X *>
671extract(Y &MD) {
672 return extract(&MD);
673}
674
675/// Extract a Value from Metadata, allowing null.
676///
677/// As an analogue to \a cast_or_null(), extract the \a Value subclass \c X
678/// from \c MD, allowing \c MD to be null.
679template <class X, class Y>
680inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, X *>
682 if (auto *V = cast_or_null<ConstantAsMetadata>(MD))
683 return cast<X>(V->getValue());
684 return nullptr;
685}
686
687/// Extract a Value from Metadata, if any.
688///
689/// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
690/// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
691/// Value it does contain is of the wrong subclass.
692template <class X, class Y>
693inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, X *>
695 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
696 return dyn_cast<X>(V->getValue());
697 return nullptr;
698}
699
700/// Extract a Value from Metadata, if any, allowing null.
701///
702/// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
703/// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
704/// Value it does contain is of the wrong subclass, allowing \c MD to be null.
705template <class X, class Y>
706inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, X *>
708 if (auto *V = dyn_cast_or_null<ConstantAsMetadata>(MD))
709 return dyn_cast<X>(V->getValue());
710 return nullptr;
711}
712
713} // end namespace mdconst
714
715//===----------------------------------------------------------------------===//
716/// A single uniqued string.
717///
718/// These are used to efficiently contain a byte sequence for metadata.
719/// MDString is always unnamed.
720class MDString : public Metadata {
721 friend class StringMapEntryStorage<MDString>;
722
723 StringMapEntry<MDString> *Entry = nullptr;
724
725 MDString() : Metadata(MDStringKind, Uniqued) {}
726
727public:
728 MDString(const MDString &) = delete;
730 MDString &operator=(const MDString &) = delete;
731
732 LLVM_ABI static MDString *get(LLVMContext &Context, StringRef Str);
733 static MDString *get(LLVMContext &Context, const char *Str) {
734 return get(Context, Str ? StringRef(Str) : StringRef());
735 }
736
738
739 unsigned getLength() const { return (unsigned)getString().size(); }
740
742
743 /// Pointer to the first byte of the string.
744 iterator begin() const { return getString().begin(); }
745
746 /// Pointer to one byte past the end of the string.
747 iterator end() const { return getString().end(); }
748
749 const unsigned char *bytes_begin() const { return getString().bytes_begin(); }
750 const unsigned char *bytes_end() const { return getString().bytes_end(); }
751
752 /// Methods for support type inquiry through isa, cast, and dyn_cast.
753 static bool classof(const Metadata *MD) {
754 return MD->getMetadataID() == MDStringKind;
755 }
756};
757
758/// A collection of metadata nodes that might be associated with a
759/// memory access used by the alias-analysis infrastructure.
760struct AAMDNodes {
761 explicit AAMDNodes() = default;
762 explicit AAMDNodes(MDNode *T, MDNode *TS, MDNode *S, MDNode *N, MDNode *NAS)
763 : TBAA(T), TBAAStruct(TS), Scope(S), NoAlias(N), NoAliasAddrSpace(NAS) {}
764
765 bool operator==(const AAMDNodes &A) const {
766 return TBAA == A.TBAA && TBAAStruct == A.TBAAStruct && Scope == A.Scope &&
767 NoAlias == A.NoAlias && NoAliasAddrSpace == A.NoAliasAddrSpace;
768 }
769
770 bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
771
772 explicit operator bool() const {
773 return TBAA || TBAAStruct || Scope || NoAlias || NoAliasAddrSpace;
774 }
775
776 /// The tag for type-based alias analysis.
777 MDNode *TBAA = nullptr;
778
779 /// The tag for type-based alias analysis (tbaa struct).
780 MDNode *TBAAStruct = nullptr;
781
782 /// The tag for alias scope specification (used with noalias).
783 MDNode *Scope = nullptr;
784
785 /// The tag specifying the noalias scope.
786 MDNode *NoAlias = nullptr;
787
788 /// The tag specifying the noalias address spaces.
790
791 // Shift tbaa Metadata node to start off bytes later
792 LLVM_ABI static MDNode *shiftTBAA(MDNode *M, size_t off);
793
794 // Shift tbaa.struct Metadata node to start off bytes later
795 LLVM_ABI static MDNode *shiftTBAAStruct(MDNode *M, size_t off);
796
797 // Extend tbaa Metadata node to apply to a series of bytes of length len.
798 // A size of -1 denotes an unknown size.
799 LLVM_ABI static MDNode *extendToTBAA(MDNode *TBAA, ssize_t len);
800
801 /// Given two sets of AAMDNodes that apply to the same pointer,
802 /// give the best AAMDNodes that are compatible with both (i.e. a set of
803 /// nodes whose allowable aliasing conclusions are a subset of those
804 /// allowable by both of the inputs). However, for efficiency
805 /// reasons, do not create any new MDNodes.
807 AAMDNodes Result;
808 Result.TBAA = Other.TBAA == TBAA ? TBAA : nullptr;
809 Result.TBAAStruct = Other.TBAAStruct == TBAAStruct ? TBAAStruct : nullptr;
810 Result.Scope = Other.Scope == Scope ? Scope : nullptr;
811 Result.NoAlias = Other.NoAlias == NoAlias ? NoAlias : nullptr;
812 Result.NoAliasAddrSpace =
813 Other.NoAliasAddrSpace == NoAliasAddrSpace ? NoAliasAddrSpace : nullptr;
814 return Result;
815 }
816
817 /// Create a new AAMDNode that describes this AAMDNode after applying a
818 /// constant offset to the start of the pointer.
819 AAMDNodes shift(size_t Offset) const {
820 AAMDNodes Result;
821 Result.TBAA = TBAA ? shiftTBAA(TBAA, Offset) : nullptr;
822 Result.TBAAStruct =
824 Result.Scope = Scope;
825 Result.NoAlias = NoAlias;
826 Result.NoAliasAddrSpace = NoAliasAddrSpace;
827 return Result;
828 }
829
830 /// Create a new AAMDNode that describes this AAMDNode after extending it to
831 /// apply to a series of bytes of length Len. A size of -1 denotes an unknown
832 /// size.
833 AAMDNodes extendTo(ssize_t Len) const {
834 AAMDNodes Result;
835 Result.TBAA = TBAA ? extendToTBAA(TBAA, Len) : nullptr;
836 // tbaa.struct contains (offset, size, type) triples. Extending the length
837 // of the tbaa.struct doesn't require changing this (though more information
838 // could be provided by adding more triples at subsequent lengths).
839 Result.TBAAStruct = TBAAStruct;
840 Result.Scope = Scope;
841 Result.NoAlias = NoAlias;
842 Result.NoAliasAddrSpace = NoAliasAddrSpace;
843 return Result;
844 }
845
846 /// Given two sets of AAMDNodes applying to potentially different locations,
847 /// determine the best AAMDNodes that apply to both.
848 LLVM_ABI AAMDNodes merge(const AAMDNodes &Other) const;
849
850 /// Determine the best AAMDNodes after concatenating two different locations
851 /// together. Different from `merge`, where different locations should
852 /// overlap each other, `concat` puts non-overlapping locations together.
854
855 /// Create a new AAMDNode for accessing \p AccessSize bytes of this AAMDNode.
856 /// If this AAMDNode has !tbaa.struct and \p AccessSize matches the size of
857 /// the field at offset 0, get the TBAA tag describing the accessed field.
858 /// If such an AAMDNode already embeds !tbaa, the existing one is retrieved.
859 /// Finally, !tbaa.struct is zeroed out.
860 LLVM_ABI AAMDNodes adjustForAccess(unsigned AccessSize);
861 LLVM_ABI AAMDNodes adjustForAccess(size_t Offset, Type *AccessTy,
862 const DataLayout &DL);
863 LLVM_ABI AAMDNodes adjustForAccess(size_t Offset, unsigned AccessSize);
864};
865
866// Specialize DenseMapInfo for AAMDNodes.
867template<>
869 static inline AAMDNodes getEmptyKey() {
870 return AAMDNodes(DenseMapInfo<MDNode *>::getEmptyKey(), nullptr, nullptr,
871 nullptr, nullptr);
872 }
873
874 static inline AAMDNodes getTombstoneKey() {
876 nullptr, nullptr, nullptr);
877 }
878
879 static unsigned getHashValue(const AAMDNodes &Val) {
885 }
886
887 static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS) {
888 return LHS == RHS;
889 }
890};
891
892/// Tracking metadata reference owned by Metadata.
893///
894/// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
895/// of \a Metadata, which has the option of registering itself for callbacks to
896/// re-unique itself.
897///
898/// In particular, this is used by \a MDNode.
900 Metadata *MD = nullptr;
901
902public:
903 MDOperand() = default;
904 MDOperand(const MDOperand &) = delete;
906 MD = Op.MD;
907 if (MD)
908 (void)MetadataTracking::retrack(Op.MD, MD);
909 Op.MD = nullptr;
910 }
911 MDOperand &operator=(const MDOperand &) = delete;
913 MD = Op.MD;
914 if (MD)
915 (void)MetadataTracking::retrack(Op.MD, MD);
916 Op.MD = nullptr;
917 return *this;
918 }
919
920 // Check if MDOperand is of type MDString and equals `Str`.
921 bool equalsStr(StringRef Str) const {
922 return isa<MDString>(this->get()) &&
923 cast<MDString>(this->get())->getString() == Str;
924 }
925
926 ~MDOperand() { untrack(); }
927
928 Metadata *get() const { return MD; }
929 operator Metadata *() const { return get(); }
930 Metadata *operator->() const { return get(); }
931 Metadata &operator*() const { return *get(); }
932
933 void reset() {
934 untrack();
935 MD = nullptr;
936 }
937 void reset(Metadata *MD, Metadata *Owner) {
938 untrack();
939 this->MD = MD;
940 track(Owner);
941 }
942
943private:
944 void track(Metadata *Owner) {
945 if (MD) {
946 if (Owner)
947 MetadataTracking::track(this, *MD, *Owner);
948 else
950 }
951 }
952
953 void untrack() {
954 assert(static_cast<void *>(this) == &MD && "Expected same address");
955 if (MD)
957 }
958};
959
960template <> struct simplify_type<MDOperand> {
962
963 static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
964};
965
966template <> struct simplify_type<const MDOperand> {
968
969 static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
970};
971
972/// Pointer to the context, with optional RAUW support.
973///
974/// Either a raw (non-null) pointer to the \a LLVMContext, or an owned pointer
975/// to \a ReplaceableMetadataImpl (which has a reference to \a LLVMContext).
978
979public:
982 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses)
983 : Ptr(ReplaceableUses.release()) {
984 assert(getReplaceableUses() && "Expected non-null replaceable uses");
985 }
993
994 operator LLVMContext &() { return getContext(); }
995
996 /// Whether this contains RAUW support.
997 bool hasReplaceableUses() const {
998 return isa<ReplaceableMetadataImpl *>(Ptr);
999 }
1000
1002 if (hasReplaceableUses())
1003 return getReplaceableUses()->getContext();
1004 return *cast<LLVMContext *>(Ptr);
1005 }
1006
1008 if (hasReplaceableUses())
1009 return cast<ReplaceableMetadataImpl *>(Ptr);
1010 return nullptr;
1011 }
1012
1013 /// Ensure that this has RAUW support, and then return it.
1015 if (!hasReplaceableUses())
1016 makeReplaceable(std::make_unique<ReplaceableMetadataImpl>(getContext()));
1017 return getReplaceableUses();
1018 }
1019
1020 /// Assign RAUW support to this.
1021 ///
1022 /// Make this replaceable, taking ownership of \c ReplaceableUses (which must
1023 /// not be null).
1024 void
1025 makeReplaceable(std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses) {
1026 assert(ReplaceableUses && "Expected non-null replaceable uses");
1027 assert(&ReplaceableUses->getContext() == &getContext() &&
1028 "Expected same context");
1029 delete getReplaceableUses();
1030 Ptr = ReplaceableUses.release();
1031 }
1032
1033 /// Drop RAUW support.
1034 ///
1035 /// Cede ownership of RAUW support, returning it.
1036 std::unique_ptr<ReplaceableMetadataImpl> takeReplaceableUses() {
1037 assert(hasReplaceableUses() && "Expected to own replaceable uses");
1038 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses(
1040 Ptr = &ReplaceableUses->getContext();
1041 return ReplaceableUses;
1042 }
1043};
1044
1046 inline void operator()(MDNode *Node) const;
1047};
1048
1049#define HANDLE_MDNODE_LEAF(CLASS) \
1050 using Temp##CLASS = std::unique_ptr<CLASS, TempMDNodeDeleter>;
1051#define HANDLE_MDNODE_BRANCH(CLASS) HANDLE_MDNODE_LEAF(CLASS)
1052#include "llvm/IR/Metadata.def"
1053
1054/// Metadata node.
1055///
1056/// Metadata nodes can be uniqued, like constants, or distinct. Temporary
1057/// metadata nodes (with full support for RAUW) can be used to delay uniquing
1058/// until forward references are known. The basic metadata node is an \a
1059/// MDTuple.
1060///
1061/// There is limited support for RAUW at construction time. At construction
1062/// time, if any operand is a temporary node (or an unresolved uniqued node,
1063/// which indicates a transitive temporary operand), the node itself will be
1064/// unresolved. As soon as all operands become resolved, it will drop RAUW
1065/// support permanently.
1066///
1067/// If an unresolved node is part of a cycle, \a resolveCycles() needs
1068/// to be called on some member of the cycle once all temporary nodes have been
1069/// replaced.
1070///
1071/// MDNodes can be large or small, as well as resizable or non-resizable.
1072/// Large MDNodes' operands are allocated in a separate storage vector,
1073/// whereas small MDNodes' operands are co-allocated. Distinct and temporary
1074/// MDnodes are resizable, but only MDTuples support this capability.
1075///
1076/// Clients can add operands to resizable MDNodes using push_back().
1077class MDNode : public Metadata {
1079 friend class LLVMContextImpl;
1080 friend class DIAssignID;
1081
1082 /// The header that is coallocated with an MDNode along with its "small"
1083 /// operands. It is located immediately before the main body of the node.
1084 /// The operands are in turn located immediately before the header.
1085 /// For resizable MDNodes, the space for the storage vector is also allocated
1086 /// immediately before the header, overlapping with the operands.
1087 /// Explicity set alignment because bitfields by default have an
1088 /// alignment of 1 on z/OS.
1089 struct alignas(alignof(size_t)) Header {
1090 size_t IsResizable : 1;
1091 size_t IsLarge : 1;
1092 size_t SmallSize : 4;
1093 size_t SmallNumOps : 4;
1094 size_t : sizeof(size_t) * CHAR_BIT - 10;
1095
1096 unsigned NumUnresolved = 0;
1097 using LargeStorageVector = SmallVector<MDOperand, 0>;
1098
1099 static constexpr size_t NumOpsFitInVector =
1100 sizeof(LargeStorageVector) / sizeof(MDOperand);
1101 static_assert(
1102 NumOpsFitInVector * sizeof(MDOperand) == sizeof(LargeStorageVector),
1103 "sizeof(LargeStorageVector) must be a multiple of sizeof(MDOperand)");
1104
1105 static constexpr size_t MaxSmallSize = 15;
1106
1107 static constexpr size_t getOpSize(unsigned NumOps) {
1108 return sizeof(MDOperand) * NumOps;
1109 }
1110 /// Returns the number of operands the node has space for based on its
1111 /// allocation characteristics.
1112 static size_t getSmallSize(size_t NumOps, bool IsResizable, bool IsLarge) {
1113 return IsLarge ? NumOpsFitInVector
1114 : std::max(NumOps, NumOpsFitInVector * IsResizable);
1115 }
1116 /// Returns the number of bytes allocated for operands and header.
1117 static size_t getAllocSize(StorageType Storage, size_t NumOps) {
1118 return getOpSize(
1119 getSmallSize(NumOps, isResizable(Storage), isLarge(NumOps))) +
1120 sizeof(Header);
1121 }
1122
1123 /// Only temporary and distinct nodes are resizable.
1124 static bool isResizable(StorageType Storage) { return Storage != Uniqued; }
1125 static bool isLarge(size_t NumOps) { return NumOps > MaxSmallSize; }
1126
1127 size_t getAllocSize() const {
1128 return getOpSize(SmallSize) + sizeof(Header);
1129 }
1130 void *getAllocation() {
1131 return reinterpret_cast<char *>(this + 1) -
1132 alignTo(getAllocSize(), alignof(uint64_t));
1133 }
1134
1135 void *getLargePtr() const {
1136 static_assert(alignof(LargeStorageVector) <= alignof(Header),
1137 "LargeStorageVector too strongly aligned");
1138 return reinterpret_cast<char *>(const_cast<Header *>(this)) -
1139 sizeof(LargeStorageVector);
1140 }
1141
1142 LLVM_ABI void *getSmallPtr();
1143
1144 LargeStorageVector &getLarge() {
1145 assert(IsLarge);
1146 return *reinterpret_cast<LargeStorageVector *>(getLargePtr());
1147 }
1148
1149 const LargeStorageVector &getLarge() const {
1150 assert(IsLarge);
1151 return *reinterpret_cast<const LargeStorageVector *>(getLargePtr());
1152 }
1153
1154 LLVM_ABI void resizeSmall(size_t NumOps);
1155 LLVM_ABI void resizeSmallToLarge(size_t NumOps);
1156 LLVM_ABI void resize(size_t NumOps);
1157
1158 LLVM_ABI explicit Header(size_t NumOps, StorageType Storage);
1159 LLVM_ABI ~Header();
1160
1161 MutableArrayRef<MDOperand> operands() {
1162 if (IsLarge)
1163 return getLarge();
1164 return MutableArrayRef(
1165 reinterpret_cast<MDOperand *>(this) - SmallSize, SmallNumOps);
1166 }
1167
1168 ArrayRef<MDOperand> operands() const {
1169 if (IsLarge)
1170 return getLarge();
1171 return ArrayRef(reinterpret_cast<const MDOperand *>(this) - SmallSize,
1172 SmallNumOps);
1173 }
1174
1175 unsigned getNumOperands() const {
1176 if (!IsLarge)
1177 return SmallNumOps;
1178 return getLarge().size();
1179 }
1180 };
1181
1182 Header &getHeader() { return *(reinterpret_cast<Header *>(this) - 1); }
1183
1184 const Header &getHeader() const {
1185 return *(reinterpret_cast<const Header *>(this) - 1);
1186 }
1187
1188 ContextAndReplaceableUses Context;
1189
1190protected:
1191 LLVM_ABI MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
1192 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = {});
1193 ~MDNode() = default;
1194
1195 LLVM_ABI void *operator new(size_t Size, size_t NumOps, StorageType Storage);
1196 LLVM_ABI void operator delete(void *Mem);
1197
1198 /// Required by std, but never called.
1199 void operator delete(void *, unsigned) {
1200 llvm_unreachable("Constructor throws?");
1201 }
1202
1203 /// Required by std, but never called.
1204 void operator delete(void *, unsigned, bool) {
1205 llvm_unreachable("Constructor throws?");
1206 }
1207
1209
1210 MDOperand *mutable_begin() { return getHeader().operands().begin(); }
1211 MDOperand *mutable_end() { return getHeader().operands().end(); }
1212
1214
1217 }
1218
1219public:
1220 MDNode(const MDNode &) = delete;
1221 void operator=(const MDNode &) = delete;
1222 void *operator new(size_t) = delete;
1223
1224 static inline MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs);
1225 static inline MDTuple *getIfExists(LLVMContext &Context,
1227 static inline MDTuple *getDistinct(LLVMContext &Context,
1229 static inline TempMDTuple getTemporary(LLVMContext &Context,
1231
1232 /// Create a (temporary) clone of this.
1233 LLVM_ABI TempMDNode clone() const;
1234
1235 /// Deallocate a node created by getTemporary.
1236 ///
1237 /// Calls \c replaceAllUsesWith(nullptr) before deleting, so any remaining
1238 /// references will be reset.
1239 LLVM_ABI static void deleteTemporary(MDNode *N);
1240
1241 LLVMContext &getContext() const { return Context.getContext(); }
1242
1243 /// Replace a specific operand.
1244 LLVM_ABI void replaceOperandWith(unsigned I, Metadata *New);
1245
1246 /// Check if node is fully resolved.
1247 ///
1248 /// If \a isTemporary(), this always returns \c false; if \a isDistinct(),
1249 /// this always returns \c true.
1250 ///
1251 /// If \a isUniqued(), returns \c true if this has already dropped RAUW
1252 /// support (because all operands are resolved).
1253 ///
1254 /// As forward declarations are resolved, their containers should get
1255 /// resolved automatically. However, if this (or one of its operands) is
1256 /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
1257 bool isResolved() const { return !isTemporary() && !getNumUnresolved(); }
1258
1259 bool isUniqued() const { return Storage == Uniqued; }
1260 bool isDistinct() const { return Storage == Distinct; }
1261 bool isTemporary() const { return Storage == Temporary; }
1262
1263 bool isReplaceable() const { return isTemporary() || isAlwaysReplaceable(); }
1264 bool isAlwaysReplaceable() const { return getMetadataID() == DIAssignIDKind; }
1265
1266 /// Check if this is a valid generalized type metadata node.
1268 if (getNumOperands() < 2 || !isa<MDString>(getOperand(1)))
1269 return false;
1270 return cast<MDString>(getOperand(1))->getString().ends_with(".generalized");
1271 }
1272
1273 unsigned getNumTemporaryUses() const {
1274 assert(isTemporary() && "Only for temporaries");
1275 return Context.getReplaceableUses()->getNumUses();
1276 }
1277
1278 /// RAUW a temporary.
1279 ///
1280 /// \pre \a isTemporary() must be \c true.
1282 assert(isReplaceable() && "Expected temporary/replaceable node");
1283 if (Context.hasReplaceableUses())
1284 Context.getReplaceableUses()->replaceAllUsesWith(MD);
1285 }
1286
1287 /// Resolve cycles.
1288 ///
1289 /// Once all forward declarations have been resolved, force cycles to be
1290 /// resolved.
1291 ///
1292 /// \pre No operands (or operands' operands, etc.) have \a isTemporary().
1293 LLVM_ABI void resolveCycles();
1294
1295 /// Resolve a unique, unresolved node.
1296 LLVM_ABI void resolve();
1297
1298 /// Replace a temporary node with a permanent one.
1299 ///
1300 /// Try to create a uniqued version of \c N -- in place, if possible -- and
1301 /// return it. If \c N cannot be uniqued, return a distinct node instead.
1302 template <class T>
1303 static std::enable_if_t<std::is_base_of<MDNode, T>::value, T *>
1304 replaceWithPermanent(std::unique_ptr<T, TempMDNodeDeleter> N) {
1305 return cast<T>(N.release()->replaceWithPermanentImpl());
1306 }
1307
1308 /// Replace a temporary node with a uniqued one.
1309 ///
1310 /// Create a uniqued version of \c N -- in place, if possible -- and return
1311 /// it. Takes ownership of the temporary node.
1312 ///
1313 /// \pre N does not self-reference.
1314 template <class T>
1315 static std::enable_if_t<std::is_base_of<MDNode, T>::value, T *>
1316 replaceWithUniqued(std::unique_ptr<T, TempMDNodeDeleter> N) {
1317 return cast<T>(N.release()->replaceWithUniquedImpl());
1318 }
1319
1320 /// Replace a temporary node with a distinct one.
1321 ///
1322 /// Create a distinct version of \c N -- in place, if possible -- and return
1323 /// it. Takes ownership of the temporary node.
1324 template <class T>
1325 static std::enable_if_t<std::is_base_of<MDNode, T>::value, T *>
1326 replaceWithDistinct(std::unique_ptr<T, TempMDNodeDeleter> N) {
1327 return cast<T>(N.release()->replaceWithDistinctImpl());
1328 }
1329
1330 /// Print in tree shape.
1331 ///
1332 /// Prints definition of \c this in tree shape.
1333 ///
1334 /// If \c M is provided, metadata nodes will be numbered canonically;
1335 /// otherwise, pointer addresses are substituted.
1336 /// @{
1337 LLVM_ABI void printTree(raw_ostream &OS, const Module *M = nullptr) const;
1339 const Module *M = nullptr) const;
1340 /// @}
1341
1342 /// User-friendly dump in tree shape.
1343 ///
1344 /// If \c M is provided, metadata nodes will be numbered canonically;
1345 /// otherwise, pointer addresses are substituted.
1346 ///
1347 /// Note: this uses an explicit overload instead of default arguments so that
1348 /// the nullptr version is easy to call from a debugger.
1349 ///
1350 /// @{
1351 LLVM_ABI void dumpTree() const;
1352 LLVM_ABI void dumpTree(const Module *M) const;
1353 /// @}
1354
1355private:
1356 LLVM_ABI MDNode *replaceWithPermanentImpl();
1357 LLVM_ABI MDNode *replaceWithUniquedImpl();
1358 LLVM_ABI MDNode *replaceWithDistinctImpl();
1359
1360protected:
1361 /// Set an operand.
1362 ///
1363 /// Sets the operand directly, without worrying about uniquing.
1364 LLVM_ABI void setOperand(unsigned I, Metadata *New);
1365
1366 unsigned getNumUnresolved() const { return getHeader().NumUnresolved; }
1367
1368 void setNumUnresolved(unsigned N) { getHeader().NumUnresolved = N; }
1370 template <class T, class StoreT>
1371 static T *storeImpl(T *N, StorageType Storage, StoreT &Store);
1372 template <class T> static T *storeImpl(T *N, StorageType Storage);
1373
1374 /// Resize the node to hold \a NumOps operands.
1375 ///
1376 /// \pre \a isTemporary() or \a isDistinct()
1377 /// \pre MetadataID == MDTupleKind
1378 void resize(size_t NumOps) {
1379 assert(!isUniqued() && "Resizing is not supported for uniqued nodes");
1380 assert(getMetadataID() == MDTupleKind &&
1381 "Resizing is not supported for this node kind");
1382 getHeader().resize(NumOps);
1383 }
1384
1385private:
1386 void handleChangedOperand(void *Ref, Metadata *New);
1387
1388 /// Drop RAUW support, if any.
1389 void dropReplaceableUses();
1390
1391 void resolveAfterOperandChange(Metadata *Old, Metadata *New);
1392 void decrementUnresolvedOperandCount();
1393 void countUnresolvedOperands();
1394
1395 /// Mutate this to be "uniqued".
1396 ///
1397 /// Mutate this so that \a isUniqued().
1398 /// \pre \a isTemporary().
1399 /// \pre already added to uniquing set.
1400 void makeUniqued();
1401
1402 /// Mutate this to be "distinct".
1403 ///
1404 /// Mutate this so that \a isDistinct().
1405 /// \pre \a isTemporary().
1406 void makeDistinct();
1407
1408 void deleteAsSubclass();
1409 MDNode *uniquify();
1410 void eraseFromStore();
1411
1412 template <class NodeTy> struct HasCachedHash;
1413 template <class NodeTy>
1414 static void dispatchRecalculateHash(NodeTy *N, std::true_type) {
1415 N->recalculateHash();
1416 }
1417 template <class NodeTy>
1418 static void dispatchRecalculateHash(NodeTy *, std::false_type) {}
1419 template <class NodeTy>
1420 static void dispatchResetHash(NodeTy *N, std::true_type) {
1421 N->setHash(0);
1422 }
1423 template <class NodeTy>
1424 static void dispatchResetHash(NodeTy *, std::false_type) {}
1425
1426 /// Merge branch weights from two direct callsites.
1427 static MDNode *mergeDirectCallProfMetadata(MDNode *A, MDNode *B,
1428 const Instruction *AInstr,
1429 const Instruction *BInstr);
1430
1431public:
1432 using op_iterator = const MDOperand *;
1434
1436 return const_cast<MDNode *>(this)->mutable_begin();
1437 }
1438
1440 return const_cast<MDNode *>(this)->mutable_end();
1441 }
1442
1443 ArrayRef<MDOperand> operands() const { return getHeader().operands(); }
1444
1445 const MDOperand &getOperand(unsigned I) const {
1446 assert(I < getNumOperands() && "Out of range");
1447 return getHeader().operands()[I];
1448 }
1449
1450 /// Return number of MDNode operands.
1451 unsigned getNumOperands() const { return getHeader().getNumOperands(); }
1452
1453 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1454 static bool classof(const Metadata *MD) {
1455 switch (MD->getMetadataID()) {
1456 default:
1457 return false;
1458#define HANDLE_MDNODE_LEAF(CLASS) \
1459 case CLASS##Kind: \
1460 return true;
1461#include "llvm/IR/Metadata.def"
1462 }
1463 }
1464
1465 /// Check whether MDNode is a vtable access.
1466 LLVM_ABI bool isTBAAVtableAccess() const;
1467
1468 /// Methods for metadata merging.
1470 LLVM_ABI static MDNode *intersect(MDNode *A, MDNode *B);
1477 MDNode *B);
1478 /// Merge !prof metadata from two instructions.
1479 /// Currently only implemented with direct callsites with branch weights.
1481 const Instruction *AInstr,
1482 const Instruction *BInstr);
1486 const MDNode *B);
1487};
1488
1489/// Tuple of metadata.
1490///
1491/// This is the simple \a MDNode arbitrary tuple. Nodes are uniqued by
1492/// default based on their operands.
1493class MDTuple : public MDNode {
1494 friend class LLVMContextImpl;
1495 friend class MDNode;
1496
1497 MDTuple(LLVMContext &C, StorageType Storage, unsigned Hash,
1499 : MDNode(C, MDTupleKind, Storage, Vals) {
1500 setHash(Hash);
1501 }
1502
1504
1505 void setHash(unsigned Hash) { SubclassData32 = Hash; }
1506 void recalculateHash();
1507
1508 LLVM_ABI static MDTuple *getImpl(LLVMContext &Context,
1509 ArrayRef<Metadata *> MDs,
1511 bool ShouldCreate = true);
1512
1513 TempMDTuple cloneImpl() const {
1514 ArrayRef<MDOperand> Operands = operands();
1515 return getTemporary(getContext(), SmallVector<Metadata *, 4>(Operands));
1516 }
1517
1518public:
1519 /// Get the hash, if any.
1520 unsigned getHash() const { return SubclassData32; }
1521
1523 return getImpl(Context, MDs, Uniqued);
1524 }
1525
1527 return getImpl(Context, MDs, Uniqued, /* ShouldCreate */ false);
1528 }
1529
1530 /// Return a distinct node.
1531 ///
1532 /// Return a distinct node -- i.e., a node that is not uniqued.
1534 return getImpl(Context, MDs, Distinct);
1535 }
1536
1537 /// Return a temporary node.
1538 ///
1539 /// For use in constructing cyclic MDNode structures. A temporary MDNode is
1540 /// not uniqued, may be RAUW'd, and must be manually deleted with
1541 /// deleteTemporary.
1542 static TempMDTuple getTemporary(LLVMContext &Context,
1544 return TempMDTuple(getImpl(Context, MDs, Temporary));
1545 }
1546
1547 /// Return a (temporary) clone of this.
1548 TempMDTuple clone() const { return cloneImpl(); }
1549
1550 /// Append an element to the tuple. This will resize the node.
1552 size_t NumOps = getNumOperands();
1553 resize(NumOps + 1);
1554 setOperand(NumOps, MD);
1555 }
1556
1557 /// Shrink the operands by 1.
1558 void pop_back() { resize(getNumOperands() - 1); }
1559
1560 static bool classof(const Metadata *MD) {
1561 return MD->getMetadataID() == MDTupleKind;
1562 }
1563};
1564
1566 return MDTuple::get(Context, MDs);
1567}
1568
1570 return MDTuple::getIfExists(Context, MDs);
1571}
1572
1574 return MDTuple::getDistinct(Context, MDs);
1575}
1576
1579 return MDTuple::getTemporary(Context, MDs);
1580}
1581
1584}
1585
1586/// This is a simple wrapper around an MDNode which provides a higher-level
1587/// interface by hiding the details of how alias analysis information is encoded
1588/// in its operands.
1590 const MDNode *Node = nullptr;
1591
1592public:
1593 AliasScopeNode() = default;
1594 explicit AliasScopeNode(const MDNode *N) : Node(N) {}
1595
1596 /// Get the MDNode for this AliasScopeNode.
1597 const MDNode *getNode() const { return Node; }
1598
1599 /// Get the MDNode for this AliasScopeNode's domain.
1600 const MDNode *getDomain() const {
1601 if (Node->getNumOperands() < 2)
1602 return nullptr;
1603 return dyn_cast_or_null<MDNode>(Node->getOperand(1));
1604 }
1606 if (Node->getNumOperands() > 2)
1607 if (MDString *N = dyn_cast_or_null<MDString>(Node->getOperand(2)))
1608 return N->getString();
1609 return StringRef();
1610 }
1611};
1612
1613/// Typed iterator through MDNode operands.
1614///
1615/// An iterator that transforms an \a MDNode::iterator into an iterator over a
1616/// particular Metadata subclass.
1617template <class T> class TypedMDOperandIterator {
1618 MDNode::op_iterator I = nullptr;
1619
1620public:
1621 using iterator_category = std::input_iterator_tag;
1622 using value_type = T *;
1623 using difference_type = std::ptrdiff_t;
1624 using pointer = void;
1625 using reference = T *;
1626
1629
1630 T *operator*() const { return cast_or_null<T>(*I); }
1631
1633 ++I;
1634 return *this;
1635 }
1636
1638 TypedMDOperandIterator Temp(*this);
1639 ++I;
1640 return Temp;
1641 }
1642
1643 bool operator==(const TypedMDOperandIterator &X) const { return I == X.I; }
1644 bool operator!=(const TypedMDOperandIterator &X) const { return I != X.I; }
1645};
1646
1647/// Typed, array-like tuple of metadata.
1648///
1649/// This is a wrapper for \a MDTuple that makes it act like an array holding a
1650/// particular type of metadata.
1651template <class T> class MDTupleTypedArrayWrapper {
1652 const MDTuple *N = nullptr;
1653
1654public:
1657
1658 template <class U>
1661 std::enable_if_t<std::is_convertible<U *, T *>::value> * = nullptr)
1662 : N(Other.get()) {}
1663
1664 template <class U>
1667 std::enable_if_t<!std::is_convertible<U *, T *>::value> * = nullptr)
1668 : N(Other.get()) {}
1669
1670 explicit operator bool() const { return get(); }
1671 explicit operator MDTuple *() const { return get(); }
1672
1673 MDTuple *get() const { return const_cast<MDTuple *>(N); }
1674 MDTuple *operator->() const { return get(); }
1675 MDTuple &operator*() const { return *get(); }
1676
1677 // FIXME: Fix callers and remove condition on N.
1678 unsigned size() const { return N ? N->getNumOperands() : 0u; }
1679 bool empty() const { return N ? N->getNumOperands() == 0 : true; }
1680 T *operator[](unsigned I) const { return cast_or_null<T>(N->getOperand(I)); }
1681
1682 // FIXME: Fix callers and remove condition on N.
1684
1685 iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
1686 iterator end() const { return N ? iterator(N->op_end()) : iterator(); }
1687};
1688
1689#define HANDLE_METADATA(CLASS) \
1690 using CLASS##Array = MDTupleTypedArrayWrapper<CLASS>;
1691#include "llvm/IR/Metadata.def"
1692
1693/// Placeholder metadata for operands of distinct MDNodes.
1694///
1695/// This is a lightweight placeholder for an operand of a distinct node. It's
1696/// purpose is to help track forward references when creating a distinct node.
1697/// This allows distinct nodes involved in a cycle to be constructed before
1698/// their operands without requiring a heavyweight temporary node with
1699/// full-blown RAUW support.
1700///
1701/// Each placeholder supports only a single MDNode user. Clients should pass
1702/// an ID, retrieved via \a getID(), to indicate the "real" operand that this
1703/// should be replaced with.
1704///
1705/// While it would be possible to implement move operators, they would be
1706/// fairly expensive. Leave them unimplemented to discourage their use
1707/// (clients can use std::deque, std::list, BumpPtrAllocator, etc.).
1709 friend class MetadataTracking;
1710
1711 Metadata **Use = nullptr;
1712
1713public:
1715 : Metadata(DistinctMDOperandPlaceholderKind, Distinct) {
1717 }
1718
1722
1724 if (Use)
1725 *Use = nullptr;
1726 }
1727
1728 unsigned getID() const { return SubclassData32; }
1729
1730 /// Replace the use of this with MD.
1732 if (!Use)
1733 return;
1734 *Use = MD;
1735
1736 if (*Use)
1738
1739 Metadata *T = cast<Metadata>(this);
1741 assert(!Use && "Use is still being tracked despite being untracked!");
1742 }
1743};
1744
1745//===----------------------------------------------------------------------===//
1746/// A tuple of MDNodes.
1747///
1748/// Despite its name, a NamedMDNode isn't itself an MDNode.
1749///
1750/// NamedMDNodes are named module-level entities that contain lists of MDNodes.
1751///
1752/// It is illegal for a NamedMDNode to appear as an operand of an MDNode.
1753class NamedMDNode : public ilist_node<NamedMDNode> {
1754 friend class LLVMContextImpl;
1755 friend class Module;
1756
1757 std::string Name;
1758 Module *Parent = nullptr;
1759 void *Operands; // SmallVector<TrackingMDRef, 4>
1760
1761 void setParent(Module *M) { Parent = M; }
1762
1763 explicit NamedMDNode(const Twine &N);
1764
1765 template <class T1> class op_iterator_impl {
1766 friend class NamedMDNode;
1767
1768 const NamedMDNode *Node = nullptr;
1769 unsigned Idx = 0;
1770
1771 op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) {}
1772
1773 public:
1774 using iterator_category = std::bidirectional_iterator_tag;
1775 using value_type = T1;
1776 using difference_type = std::ptrdiff_t;
1777 using pointer = value_type *;
1778 using reference = value_type;
1779
1780 op_iterator_impl() = default;
1781
1782 bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
1783 bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
1784
1785 op_iterator_impl &operator++() {
1786 ++Idx;
1787 return *this;
1788 }
1789
1790 op_iterator_impl operator++(int) {
1791 op_iterator_impl tmp(*this);
1792 operator++();
1793 return tmp;
1794 }
1795
1796 op_iterator_impl &operator--() {
1797 --Idx;
1798 return *this;
1799 }
1800
1801 op_iterator_impl operator--(int) {
1802 op_iterator_impl tmp(*this);
1803 operator--();
1804 return tmp;
1805 }
1806
1807 T1 operator*() const { return Node->getOperand(Idx); }
1808 };
1809
1810public:
1811 NamedMDNode(const NamedMDNode &) = delete;
1813
1814 /// Drop all references and remove the node from parent module.
1816
1817 /// Remove all uses and clear node vector.
1819 /// Drop all references to this node's operands.
1820 LLVM_ABI void clearOperands();
1821
1822 /// Get the module that holds this named metadata collection.
1823 inline Module *getParent() { return Parent; }
1824 inline const Module *getParent() const { return Parent; }
1825
1826 LLVM_ABI MDNode *getOperand(unsigned i) const;
1827 LLVM_ABI unsigned getNumOperands() const;
1828 LLVM_ABI void addOperand(MDNode *M);
1829 LLVM_ABI void setOperand(unsigned I, MDNode *New);
1830 LLVM_ABI StringRef getName() const;
1831 LLVM_ABI void print(raw_ostream &ROS, bool IsForDebug = false) const;
1833 bool IsForDebug = false) const;
1834 LLVM_ABI void dump() const;
1835
1836 // ---------------------------------------------------------------------------
1837 // Operand Iterator interface...
1838 //
1839 using op_iterator = op_iterator_impl<MDNode *>;
1840
1841 op_iterator op_begin() { return op_iterator(this, 0); }
1843
1844 using const_op_iterator = op_iterator_impl<const MDNode *>;
1845
1846 const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
1848
1850 return make_range(op_begin(), op_end());
1851 }
1853 return make_range(op_begin(), op_end());
1854 }
1855};
1856
1857// Create wrappers for C Binding types (see CBindingWrapping.h).
1859
1860} // end namespace llvm
1861
1862#endif // LLVM_IR_METADATA_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
always inline
BlockVerifier::State From
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define DEFINE_ISA_CONVERSION_FUNCTIONS(ty, ref)
RelocType Type
Definition: COFFYAML.cpp:410
#define LLVM_ABI
Definition: Compiler.h:213
dxil translate DXIL Translate Metadata
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
This file defines DenseMapInfo traits for DenseMap.
This file defines the DenseMap class.
std::string Name
uint64_t Size
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
loop extract
#define I(x, y, z)
Definition: MD5.cpp:58
mir Rename Register Operands
Machine Check Debug Module
#define T1
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
This file defines the PointerUnion class, which is a discriminated union of pointer types.
raw_pwrite_stream & OS
This file defines the SmallVector class.
Value * RHS
Value * LHS
This is a simple wrapper around an MDNode which provides a higher-level interface by hiding the detai...
Definition: Metadata.h:1589
AliasScopeNode()=default
AliasScopeNode(const MDNode *N)
Definition: Metadata.h:1594
const MDNode * getNode() const
Get the MDNode for this AliasScopeNode.
Definition: Metadata.h:1597
const MDNode * getDomain() const
Get the MDNode for this AliasScopeNode's domain.
Definition: Metadata.h:1600
StringRef getName() const
Definition: Metadata.h:1605
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
static ConstantAsMetadata * get(Constant *C)
Definition: Metadata.h:535
Constant * getValue() const
Definition: Metadata.h:543
static ConstantAsMetadata * getIfExists(Constant *C)
Definition: Metadata.h:539
static bool classof(const Metadata *MD)
Definition: Metadata.h:547
This is an important base class in LLVM.
Definition: Constant.h:43
Pointer to the context, with optional RAUW support.
Definition: Metadata.h:976
ContextAndReplaceableUses & operator=(const ContextAndReplaceableUses &)=delete
ReplaceableMetadataImpl * getReplaceableUses() const
Definition: Metadata.h:1007
std::unique_ptr< ReplaceableMetadataImpl > takeReplaceableUses()
Drop RAUW support.
Definition: Metadata.h:1036
ContextAndReplaceableUses & operator=(ContextAndReplaceableUses &&)=delete
ReplaceableMetadataImpl * getOrCreateReplaceableUses()
Ensure that this has RAUW support, and then return it.
Definition: Metadata.h:1014
void makeReplaceable(std::unique_ptr< ReplaceableMetadataImpl > ReplaceableUses)
Assign RAUW support to this.
Definition: Metadata.h:1025
ContextAndReplaceableUses(ContextAndReplaceableUses &&)=delete
ContextAndReplaceableUses(const ContextAndReplaceableUses &)=delete
LLVMContext & getContext() const
Definition: Metadata.h:1001
bool hasReplaceableUses() const
Whether this contains RAUW support.
Definition: Metadata.h:997
ContextAndReplaceableUses(LLVMContext &Context)
Definition: Metadata.h:980
ContextAndReplaceableUses(std::unique_ptr< ReplaceableMetadataImpl > ReplaceableUses)
Definition: Metadata.h:981
Assignment ID.
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:63
Record of a variable value-assignment, aka a non instruction representation of the dbg....
Base class for tracking ValueAsMetadata/DIArgLists with user lookups and Owner callbacks outside of V...
Definition: Metadata.h:219
DebugValueUser(const DebugValueUser &X)
Definition: Metadata.h:248
DebugValueUser & operator=(DebugValueUser &&X)
Definition: Metadata.h:253
DebugValueUser()=default
LLVM_ABI void handleChangedValue(void *Old, Metadata *NewDebugValue)
To be called by ReplaceableMetadataImpl::replaceAllUsesWith, where Old is a pointer to one of the poi...
Definition: Metadata.cpp:158
bool operator!=(const DebugValueUser &X) const
Definition: Metadata.h:290
DebugValueUser(std::array< Metadata *, 3 > DebugValues)
Definition: Metadata.h:240
bool operator==(const DebugValueUser &X) const
Definition: Metadata.h:287
void resetDebugValues()
Definition: Metadata.h:275
ArrayRef< Metadata * > getDebugValues() const
Definition: Metadata.h:227
DebugValueUser & operator=(const DebugValueUser &X)
Definition: Metadata.h:263
std::array< Metadata *, 3 > DebugValues
Definition: Metadata.h:225
void resetDebugValue(size_t Idx, Metadata *DebugValue)
Definition: Metadata.h:280
LLVM_ABI DbgVariableRecord * getUser()
Definition: Metadata.cpp:151
DebugValueUser(DebugValueUser &&X)
Definition: Metadata.h:244
unsigned size() const
Definition: DenseMap.h:120
bool empty() const
Definition: DenseMap.h:119
Placeholder metadata for operands of distinct MDNodes.
Definition: Metadata.h:1708
void replaceUseWith(Metadata *MD)
Replace the use of this with MD.
Definition: Metadata.h:1731
DistinctMDOperandPlaceholder(const DistinctMDOperandPlaceholder &)=delete
DistinctMDOperandPlaceholder(unsigned ID)
Definition: Metadata.h:1714
DistinctMDOperandPlaceholder(DistinctMDOperandPlaceholder &&)=delete
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
static LocalAsMetadata * getIfExists(Value *Local)
Definition: Metadata.h:565
static LocalAsMetadata * get(Value *Local)
Definition: Metadata.h:561
static bool classof(const Metadata *MD)
Definition: Metadata.h:569
Metadata node.
Definition: Metadata.h:1077
static LLVM_ABI MDNode * getMostGenericAliasScope(MDNode *A, MDNode *B)
Definition: Metadata.cpp:1142
static LLVM_ABI MDNode * getMergedCallsiteMetadata(MDNode *A, MDNode *B)
LLVM_ABI void printTree(raw_ostream &OS, const Module *M=nullptr) const
Print in tree shape.
Definition: AsmWriter.cpp:5432
LLVM_ABI void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
Definition: Metadata.cpp:1078
iterator_range< MDOperand * > mutable_op_range
Definition: Metadata.h:1213
LLVM_ABI void resolveCycles()
Resolve cycles.
Definition: Metadata.cpp:842
LLVM_ABI bool isTBAAVtableAccess() const
Check whether MDNode is a vtable access.
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1573
mutable_op_range mutable_operands()
Definition: Metadata.h:1215
static LLVM_ABI MDNode * getMergedCalleeTypeMetadata(const MDNode *A, const MDNode *B)
Definition: Metadata.cpp:1306
void replaceAllUsesWith(Metadata *MD)
RAUW a temporary.
Definition: Metadata.h:1281
static LLVM_ABI MDNode * concatenate(MDNode *A, MDNode *B)
Methods for metadata merging.
Definition: Metadata.cpp:1115
static LLVM_ABI void deleteTemporary(MDNode *N)
Deallocate a node created by getTemporary.
Definition: Metadata.cpp:1050
LLVM_ABI void resolve()
Resolve a unique, unresolved node.
Definition: Metadata.cpp:796
static LLVM_ABI MDNode * getMostGenericTBAA(MDNode *A, MDNode *B)
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1445
static LLVM_ABI MDNode * getMostGenericNoaliasAddrspace(MDNode *A, MDNode *B)
Definition: Metadata.cpp:1397
LLVM_ABI void storeDistinctInContext()
Definition: Metadata.cpp:1056
bool isTemporary() const
Definition: Metadata.h:1261
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1577
ArrayRef< MDOperand > operands() const
Definition: Metadata.h:1443
op_iterator op_end() const
Definition: Metadata.h:1439
bool hasGeneralizedMDString()
Check if this is a valid generalized type metadata node.
Definition: Metadata.h:1267
MDNode(const MDNode &)=delete
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1565
static std::enable_if_t< std::is_base_of< MDNode, T >::value, T * > replaceWithDistinct(std::unique_ptr< T, TempMDNodeDeleter > N)
Replace a temporary node with a distinct one.
Definition: Metadata.h:1326
static LLVM_ABI MDNode * getMergedProfMetadata(MDNode *A, MDNode *B, const Instruction *AInstr, const Instruction *BInstr)
Merge !prof metadata from two instructions.
Definition: Metadata.cpp:1224
static bool classof(const Metadata *MD)
Methods for support type inquiry through isa, cast, and dyn_cast:
Definition: Metadata.h:1454
bool isUniqued() const
Definition: Metadata.h:1259
static LLVM_ABI MDNode * getMostGenericFPMath(MDNode *A, MDNode *B)
Definition: Metadata.cpp:1174
void setNumUnresolved(unsigned N)
Definition: Metadata.h:1368
void resize(size_t NumOps)
Resize the node to hold NumOps operands.
Definition: Metadata.h:1378
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1451
MDOperand * mutable_begin()
Definition: Metadata.h:1210
LLVM_ABI MDNode(LLVMContext &Context, unsigned ID, StorageType Storage, ArrayRef< Metadata * > Ops1, ArrayRef< Metadata * > Ops2={})
Definition: Metadata.cpp:651
LLVM_ABI TempMDNode clone() const
Create a (temporary) clone of this.
Definition: Metadata.cpp:668
static LLVM_ABI MDNode * getMostGenericRange(MDNode *A, MDNode *B)
Definition: Metadata.cpp:1324
bool isDistinct() const
Definition: Metadata.h:1260
unsigned getNumTemporaryUses() const
Definition: Metadata.h:1273
static LLVM_ABI MDNode * getMergedMemProfMetadata(MDNode *A, MDNode *B)
bool isReplaceable() const
Definition: Metadata.h:1263
LLVM_ABI void setOperand(unsigned I, Metadata *New)
Set an operand.
Definition: Metadata.cpp:1090
bool isResolved() const
Check if node is fully resolved.
Definition: Metadata.h:1257
op_iterator op_begin() const
Definition: Metadata.h:1435
static LLVM_ABI MDNode * intersect(MDNode *A, MDNode *B)
Definition: Metadata.cpp:1129
static T * storeImpl(T *N, StorageType Storage, StoreT &Store)
Definition: MetadataImpl.h:42
LLVMContext & getContext() const
Definition: Metadata.h:1241
MDOperand * mutable_end()
Definition: Metadata.h:1211
~MDNode()=default
static MDTuple * getIfExists(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1569
static std::enable_if_t< std::is_base_of< MDNode, T >::value, T * > replaceWithPermanent(std::unique_ptr< T, TempMDNodeDeleter > N)
Replace a temporary node with a permanent one.
Definition: Metadata.h:1304
LLVM_ABI void dropAllReferences()
Definition: Metadata.cpp:908
void operator=(const MDNode &)=delete
static std::enable_if_t< std::is_base_of< MDNode, T >::value, T * > replaceWithUniqued(std::unique_ptr< T, TempMDNodeDeleter > N)
Replace a temporary node with a uniqued one.
Definition: Metadata.h:1316
LLVM_ABI void dumpTree() const
User-friendly dump in tree shape.
Definition: AsmWriter.cpp:5507
static LLVM_ABI MDNode * getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B)
Definition: Metadata.cpp:1434
unsigned getNumUnresolved() const
Definition: Metadata.h:1366
bool isAlwaysReplaceable() const
Definition: Metadata.h:1264
Tracking metadata reference owned by Metadata.
Definition: Metadata.h:899
MDOperand()=default
bool equalsStr(StringRef Str) const
Definition: Metadata.h:921
void reset(Metadata *MD, Metadata *Owner)
Definition: Metadata.h:937
Metadata * operator->() const
Definition: Metadata.h:930
MDOperand & operator=(const MDOperand &)=delete
Metadata & operator*() const
Definition: Metadata.h:931
Metadata * get() const
Definition: Metadata.h:928
MDOperand(const MDOperand &)=delete
void reset()
Definition: Metadata.h:933
MDOperand & operator=(MDOperand &&Op)
Definition: Metadata.h:912
MDOperand(MDOperand &&Op)
Definition: Metadata.h:905
A single uniqued string.
Definition: Metadata.h:720
unsigned getLength() const
Definition: Metadata.h:739
const unsigned char * bytes_begin() const
Definition: Metadata.h:749
MDString(const MDString &)=delete
static MDString * get(LLVMContext &Context, const char *Str)
Definition: Metadata.h:733
MDString & operator=(MDString &&)=delete
static bool classof(const Metadata *MD)
Methods for support type inquiry through isa, cast, and dyn_cast.
Definition: Metadata.h:753
const unsigned char * bytes_end() const
Definition: Metadata.h:750
iterator begin() const
Pointer to the first byte of the string.
Definition: Metadata.h:744
MDString & operator=(const MDString &)=delete
LLVM_ABI StringRef getString() const
Definition: Metadata.cpp:617
iterator end() const
Pointer to one byte past the end of the string.
Definition: Metadata.h:747
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition: Metadata.cpp:607
Typed, array-like tuple of metadata.
Definition: Metadata.h:1651
MDTupleTypedArrayWrapper(const MDTupleTypedArrayWrapper< U > &Other, std::enable_if_t<!std::is_convertible< U *, T * >::value > *=nullptr)
Definition: Metadata.h:1665
MDTupleTypedArrayWrapper(const MDTuple *N)
Definition: Metadata.h:1656
T * operator[](unsigned I) const
Definition: Metadata.h:1680
MDTuple * operator->() const
Definition: Metadata.h:1674
MDTuple & operator*() const
Definition: Metadata.h:1675
MDTupleTypedArrayWrapper(const MDTupleTypedArrayWrapper< U > &Other, std::enable_if_t< std::is_convertible< U *, T * >::value > *=nullptr)
Definition: Metadata.h:1659
TypedMDOperandIterator< T > iterator
Definition: Metadata.h:1683
Tuple of metadata.
Definition: Metadata.h:1493
TempMDTuple clone() const
Return a (temporary) clone of this.
Definition: Metadata.h:1548
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
Definition: Metadata.h:1533
static bool classof(const Metadata *MD)
Definition: Metadata.h:1560
void push_back(Metadata *MD)
Append an element to the tuple. This will resize the node.
Definition: Metadata.h:1551
unsigned getHash() const
Get the hash, if any.
Definition: Metadata.h:1520
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1522
static MDTuple * getIfExists(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1526
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
Definition: Metadata.h:1542
void pop_back()
Shrink the operands by 1.
Definition: Metadata.h:1558
Metadata wrapper in the Value hierarchy.
Definition: Metadata.h:182
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition: Metadata.cpp:103
static LLVM_ABI MetadataAsValue * getIfExists(LLVMContext &Context, Metadata *MD)
Definition: Metadata.cpp:111
LLVM_ABI ~MetadataAsValue()
Definition: Metadata.cpp:65
static bool classof(const Value *V)
Definition: Metadata.h:202
Metadata * getMetadata() const
Definition: Metadata.h:200
API for tracking metadata references through RAUW and deletion.
Definition: Metadata.h:311
static LLVM_ABI bool isReplaceable(const Metadata &MD)
Check whether metadata is replaceable.
Definition: Metadata.cpp:246
static bool track(void *Ref, Metadata &MD, MetadataAsValue &Owner)
Track the reference to metadata for MetadataAsValue.
Definition: Metadata.h:340
static void untrack(Metadata *&MD)
Stop tracking a reference to metadata.
Definition: Metadata.h:356
PointerUnion< MetadataAsValue *, Metadata *, DebugValueUser * > OwnerTy
Definition: Metadata.h:375
static bool retrack(Metadata *&MD, Metadata *&New)
Move tracking from one reference to another.
Definition: Metadata.h:367
static bool track(Metadata *&MD)
Track the reference to metadata.
Definition: Metadata.h:322
static bool track(void *Ref, Metadata &MD, Metadata &Owner)
Track the reference to metadata for Metadata.
Definition: Metadata.h:331
static bool track(void *Ref, Metadata &MD, DebugValueUser &Owner)
Track the reference to metadata for DebugValueUser.
Definition: Metadata.h:349
Root of the metadata hierarchy.
Definition: Metadata.h:63
void handleChangedOperand(void *, Metadata *)
Default handling of a changed operand, which asserts.
Definition: Metadata.h:98
StorageType
Active type of storage.
Definition: Metadata.h:71
LLVM_ABI void print(raw_ostream &OS, const Module *M=nullptr, bool IsForDebug=false) const
Print.
Definition: AsmWriter.cpp:5421
static constexpr const unsigned PoisonGeneratingIDs[]
Metadata IDs that may generate poison.
Definition: Metadata.h:145
unsigned short SubclassData16
Definition: Metadata.h:77
unsigned SubclassData32
Definition: Metadata.h:78
~Metadata()=default
unsigned char Storage
Storage flag for non-uniqued, otherwise unowned, metadata.
Definition: Metadata.h:74
unsigned getMetadataID() const
Definition: Metadata.h:103
unsigned char SubclassData1
Definition: Metadata.h:76
LLVM_ABI void printAsOperand(raw_ostream &OS, const Module *M=nullptr) const
Print as operand.
Definition: AsmWriter.cpp:5411
Metadata(unsigned ID, StorageType Storage)
Definition: Metadata.h:87
LLVM_ABI void dump() const
User-friendly dump.
Definition: AsmWriter.cpp:5498
Manage lifetime of a slot tracker for printing IR.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:67
A tuple of MDNodes.
Definition: Metadata.h:1753
const_op_iterator op_begin() const
Definition: Metadata.h:1846
NamedMDNode(const NamedMDNode &)=delete
op_iterator_impl< const MDNode * > const_op_iterator
Definition: Metadata.h:1844
LLVM_ABI void dump() const
Definition: AsmWriter.cpp:5495
LLVM_ABI void setOperand(unsigned I, MDNode *New)
Definition: Metadata.cpp:1473
LLVM_ABI ~NamedMDNode()
Definition: Metadata.cpp:1456
LLVM_ABI StringRef getName() const
Definition: Metadata.cpp:1482
void dropAllReferences()
Remove all uses and clear node vector.
Definition: Metadata.h:1818
LLVM_ABI void print(raw_ostream &ROS, bool IsForDebug=false) const
Definition: AsmWriter.cpp:5082
LLVM_ABI void eraseFromParent()
Drop all references and remove the node from parent module.
Definition: Metadata.cpp:1478
const_op_iterator op_end() const
Definition: Metadata.h:1847
iterator_range< const_op_iterator > operands() const
Definition: Metadata.h:1852
op_iterator op_end()
Definition: Metadata.h:1842
LLVM_ABI MDNode * getOperand(unsigned i) const
Definition: Metadata.cpp:1465
op_iterator op_begin()
Definition: Metadata.h:1841
op_iterator_impl< MDNode * > op_iterator
Definition: Metadata.h:1839
LLVM_ABI unsigned getNumOperands() const
Definition: Metadata.cpp:1461
const Module * getParent() const
Definition: Metadata.h:1824
LLVM_ABI void clearOperands()
Drop all references to this node's operands.
Definition: Metadata.cpp:1480
iterator_range< op_iterator > operands()
Definition: Metadata.h:1849
Module * getParent()
Get the module that holds this named metadata collection.
Definition: Metadata.h:1823
LLVM_ABI void addOperand(MDNode *M)
Definition: Metadata.cpp:1471
A discriminated union of two or more pointer types, with the discriminator in the low bit of the poin...
Definition: PointerUnion.h:118
Shared implementation of use-lists for replaceable metadata.
Definition: Metadata.h:389
static LLVM_ABI void SalvageDebugInfo(const Constant &C)
Replace all uses of the constant with Undef in debug info metadata.
Definition: Metadata.cpp:331
LLVM_ABI void replaceAllUsesWith(Metadata *MD)
Replace all uses of this with MD.
Definition: Metadata.cpp:368
LLVM_ABI SmallVector< DbgVariableRecord * > getAllDbgVariableRecordUsers()
Returns the list of all DbgVariableRecord users of this.
Definition: Metadata.cpp:272
ReplaceableMetadataImpl(LLVMContext &Context)
Definition: Metadata.h:401
LLVMContext & getContext() const
Definition: Metadata.h:407
unsigned getNumUses() const
Definition: Metadata.h:427
LLVM_ABI void resolveAllUses(bool ResolveUsers=true)
Resolve all uses of this.
Definition: Metadata.cpp:421
LLVM_ABI SmallVector< Metadata * > getAllArgListUsers()
Returns the list of all DIArgList users of this.
Definition: Metadata.cpp:250
MetadataTracking::OwnerTy OwnerTy
Definition: Metadata.h:393
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
StringMapEntryStorage - Holds the value in a StringMapEntry.
StringMapEntry - This is used to represent one value that is inserted into a StringMap.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
const char * iterator
Definition: StringRef.h:59
const unsigned char * bytes_end() const
Definition: StringRef.h:135
iterator begin() const
Definition: StringRef.h:120
constexpr size_t size() const
size - Get the string size.
Definition: StringRef.h:154
iterator end() const
Definition: StringRef.h:122
const unsigned char * bytes_begin() const
Definition: StringRef.h:132
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
Typed iterator through MDNode operands.
Definition: Metadata.h:1617
TypedMDOperandIterator operator++(int)
Definition: Metadata.h:1637
std::ptrdiff_t difference_type
Definition: Metadata.h:1623
std::input_iterator_tag iterator_category
Definition: Metadata.h:1621
bool operator==(const TypedMDOperandIterator &X) const
Definition: Metadata.h:1643
TypedMDOperandIterator & operator++()
Definition: Metadata.h:1632
TypedMDOperandIterator(MDNode::op_iterator I)
Definition: Metadata.h:1628
bool operator!=(const TypedMDOperandIterator &X) const
Definition: Metadata.h:1644
A Use represents the edge between a Value definition and its users.
Definition: Use.h:35
Value wrapper in the Metadata hierarchy.
Definition: Metadata.h:457
Type * getType() const
Definition: Metadata.h:498
static LocalAsMetadata * getLocalIfExists(Value *Local)
Definition: Metadata.h:493
void replaceAllUsesWith(Metadata *MD)
Handle collisions after Value::replaceAllUsesWith().
Definition: Metadata.h:517
SmallVector< DbgVariableRecord * > getAllDbgVariableRecordUsers()
Definition: Metadata.h:504
LLVMContext & getContext() const
Definition: Metadata.h:499
static LLVM_ABI void handleDeletion(Value *V)
Definition: Metadata.cpp:526
static LocalAsMetadata * getLocal(Value *Local)
Definition: Metadata.h:483
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition: Metadata.cpp:502
static ConstantAsMetadata * getConstantIfExists(Value *C)
Definition: Metadata.h:489
static ConstantAsMetadata * getConstant(Value *C)
Definition: Metadata.h:479
static LLVM_ABI ValueAsMetadata * getIfExists(Value *V)
Definition: Metadata.cpp:521
static LLVM_ABI void handleRAUW(Value *From, Value *To)
Definition: Metadata.cpp:545
static bool classof(const Metadata *MD)
Definition: Metadata.h:522
SmallVector< Metadata * > getAllArgListUsers()
Definition: Metadata.h:501
ValueAsMetadata(unsigned ID, Value *V)
Definition: Metadata.h:469
Value * getValue() const
Definition: Metadata.h:497
~ValueAsMetadata()=default
LLVM Value Representation.
Definition: Value.h:75
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
struct LLVMOpaqueNamedMDNode * LLVMNamedMDNodeRef
Represents an LLVM Named Metadata Node.
Definition: Types.h:96
struct LLVMOpaqueMetadata * LLVMMetadataRef
Represents an LLVM Metadata.
Definition: Types.h:89
This file defines the ilist_node class template, which is a convenient base class for creating classe...
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
ArchKind & operator--(ArchKind &Kind)
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
decltype(static_cast< V >(*std::declval< U & >())) check_has_dereference
Definition: Metadata.h:626
static constexpr bool HasDereference
Definition: Metadata.h:629
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract_or_null(Y &&MD)
Extract a Value from Metadata, if any, allowing null.
Definition: Metadata.h:707
std::enable_if_t< detail::IsValidPointer< X, Y >::value, bool > hasa(Y &&MD)
Check whether Metadata has a Value.
Definition: Metadata.h:649
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract_or_null(Y &&MD)
Extract a Value from Metadata, allowing null.
Definition: Metadata.h:681
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
Definition: Metadata.h:694
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:477
APInt operator*(APInt a, uint64_t RHS)
Definition: APInt.h:2235
bool operator!=(uint64_t V1, const APInt &V2)
Definition: APInt.h:2113
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
typename detail::detector< void, Op, Args... >::value_t is_detected
Detects if a given trait holds for some set of arguments 'Args'.
Definition: STLExtras.h:79
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
@ Ref
The access may reference the value stored in memory.
@ Other
Any other memory.
Attribute unwrap(LLVMAttributeRef Attr)
Definition: Attributes.h:351
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:155
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
Definition: APFixedPoint.h:312
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI std::optional< APInt > getAllocSize(const CallBase *CB, const TargetLibraryInfo *TLI, function_ref< const Value *(const Value *)> Mapper=[](const Value *V) { return V;})
Return the size of the requested allocation.
const uint64_t NOMORE_ICP_MAGICNUM
Magic number in the value profile metadata showing a target has been promoted for the instruction and...
Definition: Metadata.h:58
LLVMConstants
Definition: Metadata.h:52
@ DEBUG_METADATA_VERSION
Definition: Metadata.h:53
#define N
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition: Metadata.h:760
LLVM_ABI AAMDNodes concat(const AAMDNodes &Other) const
Determine the best AAMDNodes after concatenating two different locations together.
static LLVM_ABI MDNode * shiftTBAAStruct(MDNode *M, size_t off)
bool operator!=(const AAMDNodes &A) const
Definition: Metadata.h:770
MDNode * NoAliasAddrSpace
The tag specifying the noalias address spaces.
Definition: Metadata.h:789
MDNode * TBAAStruct
The tag for type-based alias analysis (tbaa struct).
Definition: Metadata.h:780
MDNode * Scope
The tag for alias scope specification (used with noalias).
Definition: Metadata.h:783
static LLVM_ABI MDNode * extendToTBAA(MDNode *TBAA, ssize_t len)
MDNode * TBAA
The tag for type-based alias analysis.
Definition: Metadata.h:777
AAMDNodes shift(size_t Offset) const
Create a new AAMDNode that describes this AAMDNode after applying a constant offset to the start of t...
Definition: Metadata.h:819
LLVM_ABI AAMDNodes merge(const AAMDNodes &Other) const
Given two sets of AAMDNodes applying to potentially different locations, determine the best AAMDNodes...
MDNode * NoAlias
The tag specifying the noalias scope.
Definition: Metadata.h:786
AAMDNodes intersect(const AAMDNodes &Other) const
Given two sets of AAMDNodes that apply to the same pointer, give the best AAMDNodes that are compatib...
Definition: Metadata.h:806
LLVM_ABI AAMDNodes adjustForAccess(unsigned AccessSize)
Create a new AAMDNode for accessing AccessSize bytes of this AAMDNode.
AAMDNodes(MDNode *T, MDNode *TS, MDNode *S, MDNode *N, MDNode *NAS)
Definition: Metadata.h:762
AAMDNodes extendTo(ssize_t Len) const
Create a new AAMDNode that describes this AAMDNode after extending it to apply to a series of bytes o...
Definition: Metadata.h:833
bool operator==(const AAMDNodes &A) const
Definition: Metadata.h:765
AAMDNodes()=default
static LLVM_ABI MDNode * shiftTBAA(MDNode *M, size_t off)
static AAMDNodes getEmptyKey()
Definition: Metadata.h:869
static unsigned getHashValue(const AAMDNodes &Val)
Definition: Metadata.h:879
static AAMDNodes getTombstoneKey()
Definition: Metadata.h:874
static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS)
Definition: Metadata.h:887
An information struct used to provide DenseMap with the various necessary components for a given valu...
Definition: DenseMapInfo.h:54
void operator()(MDNode *Node) const
Definition: Metadata.h:1582
static SimpleType getSimplifiedValue(MDOperand &MD)
Definition: Metadata.h:963
static SimpleType getSimplifiedValue(const MDOperand &MD)
Definition: Metadata.h:969
Define a template that can be specialized by smart pointers to reflect the fact that they are automat...
Definition: Casting.h:34