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"
20 #include "llvm/ADT/DenseMapInfo.h"
21 #include "llvm/ADT/PointerUnion.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/ilist_node.h"
25 #include "llvm/ADT/iterator_range.h"
26 #include "llvm/IR/Constant.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/Value.h"
29 #include "llvm/Support/CBindingWrapping.h"
30 #include "llvm/Support/Casting.h"
31 #include "llvm/Support/Compiler.h"
32 #include "llvm/Support/ErrorHandling.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
42 namespace llvm {
43
44 class Module;
45 class ModuleSlotTracker;
46 class raw_ostream;
47 class DbgVariableRecord;
48 template <typename T> class StringMapEntry;
49 template <typename ValueTy> class StringMapEntryStorage;
50 class Type;
51
52 enum LLVMConstants : uint32_t {
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.
58 const uint64_t NOMORE_ICP_MAGICNUM = -1;
59
60 /// Root of the metadata hierarchy.
61 ///
62 /// This is a root class for typeless data in the IR.
63 class Metadata {
64 friend class ReplaceableMetadataImpl;
65
66 /// RTTI.
67 const unsigned char SubclassID;
68
69 protected:
70 /// Active type of storage.
71 enum StorageType { Uniqued, Distinct, Temporary };
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
80 public:
81 enum MetadataKind {
82 #define HANDLE_METADATA_LEAF(CLASS) CLASS##Kind,
83 #include "llvm/IR/Metadata.def"
84 };
85
86 protected:
Metadata(unsigned ID,StorageType Storage)87 Metadata(unsigned ID, StorageType Storage)
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.
handleChangedOperand(void *,Metadata *)98 void handleChangedOperand(void *, Metadata *) {
99 llvm_unreachable("Unimplemented in Metadata subclass");
100 }
101
102 public:
getMetadataID()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;
127 LLVM_ABI void print(raw_ostream &OS, ModuleSlotTracker &MST,
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 /// @{
138 LLVM_ABI void printAsOperand(raw_ostream &OS,
139 const Module *M = nullptr) const;
140 LLVM_ABI void printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
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).
DEFINE_ISA_CONVERSION_FUNCTIONS(Metadata,LLVMMetadataRef)150 DEFINE_ISA_CONVERSION_FUNCTIONS(Metadata, LLVMMetadataRef)
151
152 // Specialized opaque metadata conversions.
153 inline Metadata **unwrap(LLVMMetadataRef *MDs) {
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
170 inline raw_ostream &operator<<(raw_ostream &OS, const Metadata &MD) {
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.
182 class MetadataAsValue : public Value {
183 friend class ReplaceableMetadataImpl;
184 friend class LLVMContextImpl;
185
186 Metadata *MD;
187
188 MetadataAsValue(Type *Ty, Metadata *MD);
189
190 /// Drop use of metadata (during teardown).
dropUse()191 void dropUse() { MD = nullptr; }
192
193 public:
194 LLVM_ABI ~MetadataAsValue();
195
196 LLVM_ABI static MetadataAsValue *get(LLVMContext &Context, Metadata *MD);
197 LLVM_ABI static MetadataAsValue *getIfExists(LLVMContext &Context,
198 Metadata *MD);
199
getMetadata()200 Metadata *getMetadata() const { return MD; }
201
classof(const Value * V)202 static bool classof(const Value *V) {
203 return V->getValueID() == MetadataAsValueVal;
204 }
205
206 private:
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.
219 class DebugValueUser {
220 protected:
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
getDebugValues()227 ArrayRef<Metadata *> getDebugValues() const { return DebugValues; }
228
229 public:
230 LLVM_ABI DbgVariableRecord *getUser();
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;
DebugValueUser(std::array<Metadata *,3> DebugValues)240 explicit DebugValueUser(std::array<Metadata *, 3> DebugValues)
241 : DebugValues(DebugValues) {
242 trackDebugValues();
243 }
DebugValueUser(DebugValueUser && X)244 DebugValueUser(DebugValueUser &&X) {
245 DebugValues = X.DebugValues;
246 retrackDebugValues(X);
247 }
DebugValueUser(const DebugValueUser & X)248 DebugValueUser(const DebugValueUser &X) {
249 DebugValues = X.DebugValues;
250 trackDebugValues();
251 }
252
253 DebugValueUser &operator=(DebugValueUser &&X) {
254 if (&X == this)
255 return *this;
256
257 untrackDebugValues();
258 DebugValues = X.DebugValues;
259 retrackDebugValues(X);
260 return *this;
261 }
262
263 DebugValueUser &operator=(const DebugValueUser &X) {
264 if (&X == this)
265 return *this;
266
267 untrackDebugValues();
268 DebugValues = X.DebugValues;
269 trackDebugValues();
270 return *this;
271 }
272
~DebugValueUser()273 ~DebugValueUser() { untrackDebugValues(); }
274
resetDebugValues()275 void resetDebugValues() {
276 untrackDebugValues();
277 DebugValues.fill(nullptr);
278 }
279
resetDebugValue(size_t Idx,Metadata * DebugValue)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
294 private:
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.
311 class MetadataTracking {
312 public:
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.
track(Metadata * & 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.
track(void * Ref,Metadata & MD,Metadata & Owner)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.
track(void * Ref,Metadata & MD,MetadataAsValue & Owner)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.
track(void * Ref,Metadata & MD,DebugValueUser & Owner)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.
untrack(Metadata * & 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.
retrack(Metadata * & MD,Metadata * & New)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
375 using OwnerTy = PointerUnion<MetadataAsValue *, Metadata *, DebugValueUser *>;
376
377 private:
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).
389 class ReplaceableMetadataImpl {
390 friend class MetadataTracking;
391
392 public:
393 using OwnerTy = MetadataTracking::OwnerTy;
394
395 private:
396 LLVMContext &Context;
397 uint64_t NextIndex = 0;
398 SmallDenseMap<void *, std::pair<OwnerTy, uint64_t>, 4> UseMap;
399
400 public:
ReplaceableMetadataImpl(LLVMContext & Context)401 ReplaceableMetadataImpl(LLVMContext &Context) : Context(Context) {}
402
~ReplaceableMetadataImpl()403 ~ReplaceableMetadataImpl() {
404 assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
405 }
406
getContext()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.
412 LLVM_ABI void replaceAllUsesWith(Metadata *MD);
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.
416 LLVM_ABI SmallVector<Metadata *> getAllArgListUsers();
417 /// Returns the list of all DbgVariableRecord users of this.
418 LLVM_ABI SmallVector<DbgVariableRecord *> getAllDbgVariableRecordUsers();
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
getNumUses()427 unsigned getNumUses() const { return UseMap.size(); }
428
429 private:
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.
457 class ValueAsMetadata : public Metadata, ReplaceableMetadataImpl {
458 friend class ReplaceableMetadataImpl;
459 friend class LLVMContextImpl;
460
461 Value *V;
462
463 /// Drop users without RAUW (during teardown).
dropUsers()464 void dropUsers() {
465 ReplaceableMetadataImpl::resolveAllUses(/* ResolveUsers */ false);
466 }
467
468 protected:
ValueAsMetadata(unsigned ID,Value * V)469 ValueAsMetadata(unsigned ID, Value *V)
470 : Metadata(ID, Uniqued), ReplaceableMetadataImpl(V->getContext()), V(V) {
471 assert(V && "Expected valid value");
472 }
473
474 ~ValueAsMetadata() = default;
475
476 public:
477 LLVM_ABI static ValueAsMetadata *get(Value *V);
478
getConstant(Value * C)479 static ConstantAsMetadata *getConstant(Value *C) {
480 return cast<ConstantAsMetadata>(get(C));
481 }
482
getLocal(Value * Local)483 static LocalAsMetadata *getLocal(Value *Local) {
484 return cast<LocalAsMetadata>(get(Local));
485 }
486
487 LLVM_ABI static ValueAsMetadata *getIfExists(Value *V);
488
getConstantIfExists(Value * C)489 static ConstantAsMetadata *getConstantIfExists(Value *C) {
490 return cast_or_null<ConstantAsMetadata>(getIfExists(C));
491 }
492
getLocalIfExists(Value * Local)493 static LocalAsMetadata *getLocalIfExists(Value *Local) {
494 return cast_or_null<LocalAsMetadata>(getIfExists(Local));
495 }
496
getValue()497 Value *getValue() const { return V; }
getType()498 Type *getType() const { return V->getType(); }
getContext()499 LLVMContext &getContext() const { return V->getContext(); }
500
getAllArgListUsers()501 SmallVector<Metadata *> getAllArgListUsers() {
502 return ReplaceableMetadataImpl::getAllArgListUsers();
503 }
getAllDbgVariableRecordUsers()504 SmallVector<DbgVariableRecord *> getAllDbgVariableRecordUsers() {
505 return ReplaceableMetadataImpl::getAllDbgVariableRecordUsers();
506 }
507
508 LLVM_ABI static void handleDeletion(Value *V);
509 LLVM_ABI static void handleRAUW(Value *From, Value *To);
510
511 protected:
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.
replaceAllUsesWith(Metadata * MD)517 void replaceAllUsesWith(Metadata *MD) {
518 ReplaceableMetadataImpl::replaceAllUsesWith(MD);
519 }
520
521 public:
classof(const Metadata * MD)522 static bool classof(const Metadata *MD) {
523 return MD->getMetadataID() == LocalAsMetadataKind ||
524 MD->getMetadataID() == ConstantAsMetadataKind;
525 }
526 };
527
528 class ConstantAsMetadata : public ValueAsMetadata {
529 friend class ValueAsMetadata;
530
ConstantAsMetadata(Constant * C)531 ConstantAsMetadata(Constant *C)
532 : ValueAsMetadata(ConstantAsMetadataKind, C) {}
533
534 public:
get(Constant * C)535 static ConstantAsMetadata *get(Constant *C) {
536 return ValueAsMetadata::getConstant(C);
537 }
538
getIfExists(Constant * C)539 static ConstantAsMetadata *getIfExists(Constant *C) {
540 return ValueAsMetadata::getConstantIfExists(C);
541 }
542
getValue()543 Constant *getValue() const {
544 return cast<Constant>(ValueAsMetadata::getValue());
545 }
546
classof(const Metadata * MD)547 static bool classof(const Metadata *MD) {
548 return MD->getMetadataID() == ConstantAsMetadataKind;
549 }
550 };
551
552 class LocalAsMetadata : public ValueAsMetadata {
553 friend class ValueAsMetadata;
554
LocalAsMetadata(Value * Local)555 LocalAsMetadata(Value *Local)
556 : ValueAsMetadata(LocalAsMetadataKind, Local) {
557 assert(!isa<Constant>(Local) && "Expected local value");
558 }
559
560 public:
get(Value * Local)561 static LocalAsMetadata *get(Value *Local) {
562 return ValueAsMetadata::getLocal(Local);
563 }
564
getIfExists(Value * Local)565 static LocalAsMetadata *getIfExists(Value *Local) {
566 return ValueAsMetadata::getLocalIfExists(Local);
567 }
568
classof(const Metadata * MD)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.
622 namespace mdconst {
623
624 namespace detail {
625 template <typename U, typename V>
626 using check_has_dereference = decltype(static_cast<V>(*std::declval<U &>()));
627
628 template <typename U, typename V>
629 static constexpr bool HasDereference =
630 is_detected<check_has_dereference, U, V>::value;
631
632 template <class V, class M> struct IsValidPointer {
633 static const bool value = std::is_base_of<Constant, V>::value &&
634 HasDereference<M, const Metadata &>;
635 };
636 template <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.
647 template <class X, class Y>
648 inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, bool>
hasa(Y && MD)649 hasa(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 }
655 template <class X, class Y>
656 inline std::enable_if_t<detail::IsValidReference<X, Y &>::value, bool>
hasa(Y & MD)657 hasa(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.
664 template <class X, class Y>
665 inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, X *>
extract(Y && MD)666 extract(Y &&MD) {
667 return cast<X>(cast<ConstantAsMetadata>(MD)->getValue());
668 }
669 template <class X, class Y>
670 inline std::enable_if_t<detail::IsValidReference<X, Y &>::value, X *>
extract(Y & MD)671 extract(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.
679 template <class X, class Y>
680 inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, X *>
extract_or_null(Y && MD)681 extract_or_null(Y &&MD) {
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.
692 template <class X, class Y>
693 inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, X *>
dyn_extract(Y && MD)694 dyn_extract(Y &&MD) {
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.
705 template <class X, class Y>
706 inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, X *>
dyn_extract_or_null(Y && MD)707 dyn_extract_or_null(Y &&MD) {
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.
720 class MDString : public Metadata {
721 friend class StringMapEntryStorage<MDString>;
722
723 StringMapEntry<MDString> *Entry = nullptr;
724
MDString()725 MDString() : Metadata(MDStringKind, Uniqued) {}
726
727 public:
728 MDString(const MDString &) = delete;
729 MDString &operator=(MDString &&) = delete;
730 MDString &operator=(const MDString &) = delete;
731
732 LLVM_ABI static MDString *get(LLVMContext &Context, StringRef Str);
get(LLVMContext & Context,const char * Str)733 static MDString *get(LLVMContext &Context, const char *Str) {
734 return get(Context, Str ? StringRef(Str) : StringRef());
735 }
736
737 LLVM_ABI StringRef getString() const;
738
getLength()739 unsigned getLength() const { return (unsigned)getString().size(); }
740
741 using iterator = StringRef::iterator;
742
743 /// Pointer to the first byte of the string.
begin()744 iterator begin() const { return getString().begin(); }
745
746 /// Pointer to one byte past the end of the string.
end()747 iterator end() const { return getString().end(); }
748
bytes_begin()749 const unsigned char *bytes_begin() const { return getString().bytes_begin(); }
bytes_end()750 const unsigned char *bytes_end() const { return getString().bytes_end(); }
751
752 /// Methods for support type inquiry through isa, cast, and dyn_cast.
classof(const Metadata * MD)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.
760 struct AAMDNodes {
761 explicit AAMDNodes() = default;
AAMDNodesAAMDNodes762 explicit AAMDNodes(MDNode *T, MDNode *TS, MDNode *S, MDNode *N)
763 : TBAA(T), TBAAStruct(TS), Scope(S), NoAlias(N) {}
764
765 bool operator==(const AAMDNodes &A) const {
766 return TBAA == A.TBAA && TBAAStruct == A.TBAAStruct && Scope == A.Scope &&
767 NoAlias == A.NoAlias;
768 }
769
770 bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
771
772 explicit operator bool() const {
773 return TBAA || TBAAStruct || Scope || NoAlias;
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 // Shift tbaa Metadata node to start off bytes later
789 LLVM_ABI static MDNode *shiftTBAA(MDNode *M, size_t off);
790
791 // Shift tbaa.struct Metadata node to start off bytes later
792 LLVM_ABI static MDNode *shiftTBAAStruct(MDNode *M, size_t off);
793
794 // Extend tbaa Metadata node to apply to a series of bytes of length len.
795 // A size of -1 denotes an unknown size.
796 LLVM_ABI static MDNode *extendToTBAA(MDNode *TBAA, ssize_t len);
797
798 /// Given two sets of AAMDNodes that apply to the same pointer,
799 /// give the best AAMDNodes that are compatible with both (i.e. a set of
800 /// nodes whose allowable aliasing conclusions are a subset of those
801 /// allowable by both of the inputs). However, for efficiency
802 /// reasons, do not create any new MDNodes.
intersectAAMDNodes803 AAMDNodes intersect(const AAMDNodes &Other) const {
804 AAMDNodes Result;
805 Result.TBAA = Other.TBAA == TBAA ? TBAA : nullptr;
806 Result.TBAAStruct = Other.TBAAStruct == TBAAStruct ? TBAAStruct : nullptr;
807 Result.Scope = Other.Scope == Scope ? Scope : nullptr;
808 Result.NoAlias = Other.NoAlias == NoAlias ? NoAlias : nullptr;
809 return Result;
810 }
811
812 /// Create a new AAMDNode that describes this AAMDNode after applying a
813 /// constant offset to the start of the pointer.
shiftAAMDNodes814 AAMDNodes shift(size_t Offset) const {
815 AAMDNodes Result;
816 Result.TBAA = TBAA ? shiftTBAA(TBAA, Offset) : nullptr;
817 Result.TBAAStruct =
818 TBAAStruct ? shiftTBAAStruct(TBAAStruct, Offset) : nullptr;
819 Result.Scope = Scope;
820 Result.NoAlias = NoAlias;
821 return Result;
822 }
823
824 /// Create a new AAMDNode that describes this AAMDNode after extending it to
825 /// apply to a series of bytes of length Len. A size of -1 denotes an unknown
826 /// size.
extendToAAMDNodes827 AAMDNodes extendTo(ssize_t Len) const {
828 AAMDNodes Result;
829 Result.TBAA = TBAA ? extendToTBAA(TBAA, Len) : nullptr;
830 // tbaa.struct contains (offset, size, type) triples. Extending the length
831 // of the tbaa.struct doesn't require changing this (though more information
832 // could be provided by adding more triples at subsequent lengths).
833 Result.TBAAStruct = TBAAStruct;
834 Result.Scope = Scope;
835 Result.NoAlias = NoAlias;
836 return Result;
837 }
838
839 /// Given two sets of AAMDNodes applying to potentially different locations,
840 /// determine the best AAMDNodes that apply to both.
841 LLVM_ABI AAMDNodes merge(const AAMDNodes &Other) const;
842
843 /// Determine the best AAMDNodes after concatenating two different locations
844 /// together. Different from `merge`, where different locations should
845 /// overlap each other, `concat` puts non-overlapping locations together.
846 LLVM_ABI AAMDNodes concat(const AAMDNodes &Other) const;
847
848 /// Create a new AAMDNode for accessing \p AccessSize bytes of this AAMDNode.
849 /// If this AAMDNode has !tbaa.struct and \p AccessSize matches the size of
850 /// the field at offset 0, get the TBAA tag describing the accessed field.
851 /// If such an AAMDNode already embeds !tbaa, the existing one is retrieved.
852 /// Finally, !tbaa.struct is zeroed out.
853 LLVM_ABI AAMDNodes adjustForAccess(unsigned AccessSize);
854 LLVM_ABI AAMDNodes adjustForAccess(size_t Offset, Type *AccessTy,
855 const DataLayout &DL);
856 LLVM_ABI AAMDNodes adjustForAccess(size_t Offset, unsigned AccessSize);
857 };
858
859 // Specialize DenseMapInfo for AAMDNodes.
860 template<>
861 struct DenseMapInfo<AAMDNodes> {
862 static inline AAMDNodes getEmptyKey() {
863 return AAMDNodes(DenseMapInfo<MDNode *>::getEmptyKey(),
864 nullptr, nullptr, nullptr);
865 }
866
867 static inline AAMDNodes getTombstoneKey() {
868 return AAMDNodes(DenseMapInfo<MDNode *>::getTombstoneKey(),
869 nullptr, nullptr, nullptr);
870 }
871
872 static unsigned getHashValue(const AAMDNodes &Val) {
873 return DenseMapInfo<MDNode *>::getHashValue(Val.TBAA) ^
874 DenseMapInfo<MDNode *>::getHashValue(Val.TBAAStruct) ^
875 DenseMapInfo<MDNode *>::getHashValue(Val.Scope) ^
876 DenseMapInfo<MDNode *>::getHashValue(Val.NoAlias);
877 }
878
879 static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS) {
880 return LHS == RHS;
881 }
882 };
883
884 /// Tracking metadata reference owned by Metadata.
885 ///
886 /// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
887 /// of \a Metadata, which has the option of registering itself for callbacks to
888 /// re-unique itself.
889 ///
890 /// In particular, this is used by \a MDNode.
891 class MDOperand {
892 Metadata *MD = nullptr;
893
894 public:
895 MDOperand() = default;
896 MDOperand(const MDOperand &) = delete;
897 MDOperand(MDOperand &&Op) {
898 MD = Op.MD;
899 if (MD)
900 (void)MetadataTracking::retrack(Op.MD, MD);
901 Op.MD = nullptr;
902 }
903 MDOperand &operator=(const MDOperand &) = delete;
904 MDOperand &operator=(MDOperand &&Op) {
905 MD = Op.MD;
906 if (MD)
907 (void)MetadataTracking::retrack(Op.MD, MD);
908 Op.MD = nullptr;
909 return *this;
910 }
911
912 // Check if MDOperand is of type MDString and equals `Str`.
913 bool equalsStr(StringRef Str) const {
914 return isa<MDString>(this->get()) &&
915 cast<MDString>(this->get())->getString() == Str;
916 }
917
918 ~MDOperand() { untrack(); }
919
920 Metadata *get() const { return MD; }
921 operator Metadata *() const { return get(); }
922 Metadata *operator->() const { return get(); }
923 Metadata &operator*() const { return *get(); }
924
925 void reset() {
926 untrack();
927 MD = nullptr;
928 }
929 void reset(Metadata *MD, Metadata *Owner) {
930 untrack();
931 this->MD = MD;
932 track(Owner);
933 }
934
935 private:
936 void track(Metadata *Owner) {
937 if (MD) {
938 if (Owner)
939 MetadataTracking::track(this, *MD, *Owner);
940 else
941 MetadataTracking::track(MD);
942 }
943 }
944
945 void untrack() {
946 assert(static_cast<void *>(this) == &MD && "Expected same address");
947 if (MD)
948 MetadataTracking::untrack(MD);
949 }
950 };
951
952 template <> struct simplify_type<MDOperand> {
953 using SimpleType = Metadata *;
954
955 static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
956 };
957
958 template <> struct simplify_type<const MDOperand> {
959 using SimpleType = Metadata *;
960
961 static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
962 };
963
964 /// Pointer to the context, with optional RAUW support.
965 ///
966 /// Either a raw (non-null) pointer to the \a LLVMContext, or an owned pointer
967 /// to \a ReplaceableMetadataImpl (which has a reference to \a LLVMContext).
968 class ContextAndReplaceableUses {
969 PointerUnion<LLVMContext *, ReplaceableMetadataImpl *> Ptr;
970
971 public:
972 ContextAndReplaceableUses(LLVMContext &Context) : Ptr(&Context) {}
973 ContextAndReplaceableUses(
974 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses)
975 : Ptr(ReplaceableUses.release()) {
976 assert(getReplaceableUses() && "Expected non-null replaceable uses");
977 }
978 ContextAndReplaceableUses() = delete;
979 ContextAndReplaceableUses(ContextAndReplaceableUses &&) = delete;
980 ContextAndReplaceableUses(const ContextAndReplaceableUses &) = delete;
981 ContextAndReplaceableUses &operator=(ContextAndReplaceableUses &&) = delete;
982 ContextAndReplaceableUses &
983 operator=(const ContextAndReplaceableUses &) = delete;
984 ~ContextAndReplaceableUses() { delete getReplaceableUses(); }
985
986 operator LLVMContext &() { return getContext(); }
987
988 /// Whether this contains RAUW support.
989 bool hasReplaceableUses() const {
990 return isa<ReplaceableMetadataImpl *>(Ptr);
991 }
992
993 LLVMContext &getContext() const {
994 if (hasReplaceableUses())
995 return getReplaceableUses()->getContext();
996 return *cast<LLVMContext *>(Ptr);
997 }
998
999 ReplaceableMetadataImpl *getReplaceableUses() const {
1000 if (hasReplaceableUses())
1001 return cast<ReplaceableMetadataImpl *>(Ptr);
1002 return nullptr;
1003 }
1004
1005 /// Ensure that this has RAUW support, and then return it.
1006 ReplaceableMetadataImpl *getOrCreateReplaceableUses() {
1007 if (!hasReplaceableUses())
1008 makeReplaceable(std::make_unique<ReplaceableMetadataImpl>(getContext()));
1009 return getReplaceableUses();
1010 }
1011
1012 /// Assign RAUW support to this.
1013 ///
1014 /// Make this replaceable, taking ownership of \c ReplaceableUses (which must
1015 /// not be null).
1016 void
1017 makeReplaceable(std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses) {
1018 assert(ReplaceableUses && "Expected non-null replaceable uses");
1019 assert(&ReplaceableUses->getContext() == &getContext() &&
1020 "Expected same context");
1021 delete getReplaceableUses();
1022 Ptr = ReplaceableUses.release();
1023 }
1024
1025 /// Drop RAUW support.
1026 ///
1027 /// Cede ownership of RAUW support, returning it.
1028 std::unique_ptr<ReplaceableMetadataImpl> takeReplaceableUses() {
1029 assert(hasReplaceableUses() && "Expected to own replaceable uses");
1030 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses(
1031 getReplaceableUses());
1032 Ptr = &ReplaceableUses->getContext();
1033 return ReplaceableUses;
1034 }
1035 };
1036
1037 struct TempMDNodeDeleter {
1038 inline void operator()(MDNode *Node) const;
1039 };
1040
1041 #define HANDLE_MDNODE_LEAF(CLASS) \
1042 using Temp##CLASS = std::unique_ptr<CLASS, TempMDNodeDeleter>;
1043 #define HANDLE_MDNODE_BRANCH(CLASS) HANDLE_MDNODE_LEAF(CLASS)
1044 #include "llvm/IR/Metadata.def"
1045
1046 /// Metadata node.
1047 ///
1048 /// Metadata nodes can be uniqued, like constants, or distinct. Temporary
1049 /// metadata nodes (with full support for RAUW) can be used to delay uniquing
1050 /// until forward references are known. The basic metadata node is an \a
1051 /// MDTuple.
1052 ///
1053 /// There is limited support for RAUW at construction time. At construction
1054 /// time, if any operand is a temporary node (or an unresolved uniqued node,
1055 /// which indicates a transitive temporary operand), the node itself will be
1056 /// unresolved. As soon as all operands become resolved, it will drop RAUW
1057 /// support permanently.
1058 ///
1059 /// If an unresolved node is part of a cycle, \a resolveCycles() needs
1060 /// to be called on some member of the cycle once all temporary nodes have been
1061 /// replaced.
1062 ///
1063 /// MDNodes can be large or small, as well as resizable or non-resizable.
1064 /// Large MDNodes' operands are allocated in a separate storage vector,
1065 /// whereas small MDNodes' operands are co-allocated. Distinct and temporary
1066 /// MDnodes are resizable, but only MDTuples support this capability.
1067 ///
1068 /// Clients can add operands to resizable MDNodes using push_back().
1069 class MDNode : public Metadata {
1070 friend class ReplaceableMetadataImpl;
1071 friend class LLVMContextImpl;
1072 friend class DIAssignID;
1073
1074 /// The header that is coallocated with an MDNode along with its "small"
1075 /// operands. It is located immediately before the main body of the node.
1076 /// The operands are in turn located immediately before the header.
1077 /// For resizable MDNodes, the space for the storage vector is also allocated
1078 /// immediately before the header, overlapping with the operands.
1079 /// Explicity set alignment because bitfields by default have an
1080 /// alignment of 1 on z/OS.
1081 struct alignas(alignof(size_t)) Header {
1082 size_t IsResizable : 1;
1083 size_t IsLarge : 1;
1084 size_t SmallSize : 4;
1085 size_t SmallNumOps : 4;
1086 size_t : sizeof(size_t) * CHAR_BIT - 10;
1087
1088 unsigned NumUnresolved = 0;
1089 using LargeStorageVector = SmallVector<MDOperand, 0>;
1090
1091 static constexpr size_t NumOpsFitInVector =
1092 sizeof(LargeStorageVector) / sizeof(MDOperand);
1093 static_assert(
1094 NumOpsFitInVector * sizeof(MDOperand) == sizeof(LargeStorageVector),
1095 "sizeof(LargeStorageVector) must be a multiple of sizeof(MDOperand)");
1096
1097 static constexpr size_t MaxSmallSize = 15;
1098
1099 static constexpr size_t getOpSize(unsigned NumOps) {
1100 return sizeof(MDOperand) * NumOps;
1101 }
1102 /// Returns the number of operands the node has space for based on its
1103 /// allocation characteristics.
1104 static size_t getSmallSize(size_t NumOps, bool IsResizable, bool IsLarge) {
1105 return IsLarge ? NumOpsFitInVector
1106 : std::max(NumOps, NumOpsFitInVector * IsResizable);
1107 }
1108 /// Returns the number of bytes allocated for operands and header.
1109 static size_t getAllocSize(StorageType Storage, size_t NumOps) {
1110 return getOpSize(
1111 getSmallSize(NumOps, isResizable(Storage), isLarge(NumOps))) +
1112 sizeof(Header);
1113 }
1114
1115 /// Only temporary and distinct nodes are resizable.
1116 static bool isResizable(StorageType Storage) { return Storage != Uniqued; }
1117 static bool isLarge(size_t NumOps) { return NumOps > MaxSmallSize; }
1118
1119 size_t getAllocSize() const {
1120 return getOpSize(SmallSize) + sizeof(Header);
1121 }
1122 void *getAllocation() {
1123 return reinterpret_cast<char *>(this + 1) -
1124 alignTo(getAllocSize(), alignof(uint64_t));
1125 }
1126
1127 void *getLargePtr() const {
1128 static_assert(alignof(LargeStorageVector) <= alignof(Header),
1129 "LargeStorageVector too strongly aligned");
1130 return reinterpret_cast<char *>(const_cast<Header *>(this)) -
1131 sizeof(LargeStorageVector);
1132 }
1133
1134 LLVM_ABI void *getSmallPtr();
1135
1136 LargeStorageVector &getLarge() {
1137 assert(IsLarge);
1138 return *reinterpret_cast<LargeStorageVector *>(getLargePtr());
1139 }
1140
1141 const LargeStorageVector &getLarge() const {
1142 assert(IsLarge);
1143 return *reinterpret_cast<const LargeStorageVector *>(getLargePtr());
1144 }
1145
1146 LLVM_ABI void resizeSmall(size_t NumOps);
1147 LLVM_ABI void resizeSmallToLarge(size_t NumOps);
1148 LLVM_ABI void resize(size_t NumOps);
1149
1150 LLVM_ABI explicit Header(size_t NumOps, StorageType Storage);
1151 LLVM_ABI ~Header();
1152
1153 MutableArrayRef<MDOperand> operands() {
1154 if (IsLarge)
1155 return getLarge();
1156 return MutableArrayRef(
1157 reinterpret_cast<MDOperand *>(this) - SmallSize, SmallNumOps);
1158 }
1159
1160 ArrayRef<MDOperand> operands() const {
1161 if (IsLarge)
1162 return getLarge();
1163 return ArrayRef(reinterpret_cast<const MDOperand *>(this) - SmallSize,
1164 SmallNumOps);
1165 }
1166
1167 unsigned getNumOperands() const {
1168 if (!IsLarge)
1169 return SmallNumOps;
1170 return getLarge().size();
1171 }
1172 };
1173
1174 Header &getHeader() { return *(reinterpret_cast<Header *>(this) - 1); }
1175
1176 const Header &getHeader() const {
1177 return *(reinterpret_cast<const Header *>(this) - 1);
1178 }
1179
1180 ContextAndReplaceableUses Context;
1181
1182 protected:
1183 LLVM_ABI MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
1184 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = {});
1185 ~MDNode() = default;
1186
1187 LLVM_ABI void *operator new(size_t Size, size_t NumOps, StorageType Storage);
1188 LLVM_ABI void operator delete(void *Mem);
1189
1190 /// Required by std, but never called.
1191 void operator delete(void *, unsigned) {
1192 llvm_unreachable("Constructor throws?");
1193 }
1194
1195 /// Required by std, but never called.
1196 void operator delete(void *, unsigned, bool) {
1197 llvm_unreachable("Constructor throws?");
1198 }
1199
1200 LLVM_ABI void dropAllReferences();
1201
1202 MDOperand *mutable_begin() { return getHeader().operands().begin(); }
1203 MDOperand *mutable_end() { return getHeader().operands().end(); }
1204
1205 using mutable_op_range = iterator_range<MDOperand *>;
1206
1207 mutable_op_range mutable_operands() {
1208 return mutable_op_range(mutable_begin(), mutable_end());
1209 }
1210
1211 public:
1212 MDNode(const MDNode &) = delete;
1213 void operator=(const MDNode &) = delete;
1214 void *operator new(size_t) = delete;
1215
1216 static inline MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs);
1217 static inline MDTuple *getIfExists(LLVMContext &Context,
1218 ArrayRef<Metadata *> MDs);
1219 static inline MDTuple *getDistinct(LLVMContext &Context,
1220 ArrayRef<Metadata *> MDs);
1221 static inline TempMDTuple getTemporary(LLVMContext &Context,
1222 ArrayRef<Metadata *> MDs);
1223
1224 /// Create a (temporary) clone of this.
1225 LLVM_ABI TempMDNode clone() const;
1226
1227 /// Deallocate a node created by getTemporary.
1228 ///
1229 /// Calls \c replaceAllUsesWith(nullptr) before deleting, so any remaining
1230 /// references will be reset.
1231 LLVM_ABI static void deleteTemporary(MDNode *N);
1232
1233 LLVMContext &getContext() const { return Context.getContext(); }
1234
1235 /// Replace a specific operand.
1236 LLVM_ABI void replaceOperandWith(unsigned I, Metadata *New);
1237
1238 /// Check if node is fully resolved.
1239 ///
1240 /// If \a isTemporary(), this always returns \c false; if \a isDistinct(),
1241 /// this always returns \c true.
1242 ///
1243 /// If \a isUniqued(), returns \c true if this has already dropped RAUW
1244 /// support (because all operands are resolved).
1245 ///
1246 /// As forward declarations are resolved, their containers should get
1247 /// resolved automatically. However, if this (or one of its operands) is
1248 /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
1249 bool isResolved() const { return !isTemporary() && !getNumUnresolved(); }
1250
1251 bool isUniqued() const { return Storage == Uniqued; }
1252 bool isDistinct() const { return Storage == Distinct; }
1253 bool isTemporary() const { return Storage == Temporary; }
1254
1255 bool isReplaceable() const { return isTemporary() || isAlwaysReplaceable(); }
1256 bool isAlwaysReplaceable() const { return getMetadataID() == DIAssignIDKind; }
1257
1258 unsigned getNumTemporaryUses() const {
1259 assert(isTemporary() && "Only for temporaries");
1260 return Context.getReplaceableUses()->getNumUses();
1261 }
1262
1263 /// RAUW a temporary.
1264 ///
1265 /// \pre \a isTemporary() must be \c true.
1266 void replaceAllUsesWith(Metadata *MD) {
1267 assert(isReplaceable() && "Expected temporary/replaceable node");
1268 if (Context.hasReplaceableUses())
1269 Context.getReplaceableUses()->replaceAllUsesWith(MD);
1270 }
1271
1272 /// Resolve cycles.
1273 ///
1274 /// Once all forward declarations have been resolved, force cycles to be
1275 /// resolved.
1276 ///
1277 /// \pre No operands (or operands' operands, etc.) have \a isTemporary().
1278 LLVM_ABI void resolveCycles();
1279
1280 /// Resolve a unique, unresolved node.
1281 LLVM_ABI void resolve();
1282
1283 /// Replace a temporary node with a permanent one.
1284 ///
1285 /// Try to create a uniqued version of \c N -- in place, if possible -- and
1286 /// return it. If \c N cannot be uniqued, return a distinct node instead.
1287 template <class T>
1288 static std::enable_if_t<std::is_base_of<MDNode, T>::value, T *>
1289 replaceWithPermanent(std::unique_ptr<T, TempMDNodeDeleter> N) {
1290 return cast<T>(N.release()->replaceWithPermanentImpl());
1291 }
1292
1293 /// Replace a temporary node with a uniqued one.
1294 ///
1295 /// Create a uniqued version of \c N -- in place, if possible -- and return
1296 /// it. Takes ownership of the temporary node.
1297 ///
1298 /// \pre N does not self-reference.
1299 template <class T>
1300 static std::enable_if_t<std::is_base_of<MDNode, T>::value, T *>
1301 replaceWithUniqued(std::unique_ptr<T, TempMDNodeDeleter> N) {
1302 return cast<T>(N.release()->replaceWithUniquedImpl());
1303 }
1304
1305 /// Replace a temporary node with a distinct one.
1306 ///
1307 /// Create a distinct version of \c N -- in place, if possible -- and return
1308 /// it. Takes ownership of the temporary node.
1309 template <class T>
1310 static std::enable_if_t<std::is_base_of<MDNode, T>::value, T *>
1311 replaceWithDistinct(std::unique_ptr<T, TempMDNodeDeleter> N) {
1312 return cast<T>(N.release()->replaceWithDistinctImpl());
1313 }
1314
1315 /// Print in tree shape.
1316 ///
1317 /// Prints definition of \c this in tree shape.
1318 ///
1319 /// If \c M is provided, metadata nodes will be numbered canonically;
1320 /// otherwise, pointer addresses are substituted.
1321 /// @{
1322 LLVM_ABI void printTree(raw_ostream &OS, const Module *M = nullptr) const;
1323 LLVM_ABI void printTree(raw_ostream &OS, ModuleSlotTracker &MST,
1324 const Module *M = nullptr) const;
1325 /// @}
1326
1327 /// User-friendly dump in tree shape.
1328 ///
1329 /// If \c M is provided, metadata nodes will be numbered canonically;
1330 /// otherwise, pointer addresses are substituted.
1331 ///
1332 /// Note: this uses an explicit overload instead of default arguments so that
1333 /// the nullptr version is easy to call from a debugger.
1334 ///
1335 /// @{
1336 LLVM_ABI void dumpTree() const;
1337 LLVM_ABI void dumpTree(const Module *M) const;
1338 /// @}
1339
1340 private:
1341 LLVM_ABI MDNode *replaceWithPermanentImpl();
1342 LLVM_ABI MDNode *replaceWithUniquedImpl();
1343 LLVM_ABI MDNode *replaceWithDistinctImpl();
1344
1345 protected:
1346 /// Set an operand.
1347 ///
1348 /// Sets the operand directly, without worrying about uniquing.
1349 LLVM_ABI void setOperand(unsigned I, Metadata *New);
1350
1351 unsigned getNumUnresolved() const { return getHeader().NumUnresolved; }
1352
1353 void setNumUnresolved(unsigned N) { getHeader().NumUnresolved = N; }
1354 LLVM_ABI void storeDistinctInContext();
1355 template <class T, class StoreT>
1356 static T *storeImpl(T *N, StorageType Storage, StoreT &Store);
1357 template <class T> static T *storeImpl(T *N, StorageType Storage);
1358
1359 /// Resize the node to hold \a NumOps operands.
1360 ///
1361 /// \pre \a isTemporary() or \a isDistinct()
1362 /// \pre MetadataID == MDTupleKind
1363 void resize(size_t NumOps) {
1364 assert(!isUniqued() && "Resizing is not supported for uniqued nodes");
1365 assert(getMetadataID() == MDTupleKind &&
1366 "Resizing is not supported for this node kind");
1367 getHeader().resize(NumOps);
1368 }
1369
1370 private:
1371 void handleChangedOperand(void *Ref, Metadata *New);
1372
1373 /// Drop RAUW support, if any.
1374 void dropReplaceableUses();
1375
1376 void resolveAfterOperandChange(Metadata *Old, Metadata *New);
1377 void decrementUnresolvedOperandCount();
1378 void countUnresolvedOperands();
1379
1380 /// Mutate this to be "uniqued".
1381 ///
1382 /// Mutate this so that \a isUniqued().
1383 /// \pre \a isTemporary().
1384 /// \pre already added to uniquing set.
1385 void makeUniqued();
1386
1387 /// Mutate this to be "distinct".
1388 ///
1389 /// Mutate this so that \a isDistinct().
1390 /// \pre \a isTemporary().
1391 void makeDistinct();
1392
1393 void deleteAsSubclass();
1394 MDNode *uniquify();
1395 void eraseFromStore();
1396
1397 template <class NodeTy> struct HasCachedHash;
1398 template <class NodeTy>
1399 static void dispatchRecalculateHash(NodeTy *N, std::true_type) {
1400 N->recalculateHash();
1401 }
1402 template <class NodeTy>
1403 static void dispatchRecalculateHash(NodeTy *, std::false_type) {}
1404 template <class NodeTy>
1405 static void dispatchResetHash(NodeTy *N, std::true_type) {
1406 N->setHash(0);
1407 }
1408 template <class NodeTy>
1409 static void dispatchResetHash(NodeTy *, std::false_type) {}
1410
1411 /// Merge branch weights from two direct callsites.
1412 static MDNode *mergeDirectCallProfMetadata(MDNode *A, MDNode *B,
1413 const Instruction *AInstr,
1414 const Instruction *BInstr);
1415
1416 public:
1417 using op_iterator = const MDOperand *;
1418 using op_range = iterator_range<op_iterator>;
1419
1420 op_iterator op_begin() const {
1421 return const_cast<MDNode *>(this)->mutable_begin();
1422 }
1423
1424 op_iterator op_end() const {
1425 return const_cast<MDNode *>(this)->mutable_end();
1426 }
1427
1428 ArrayRef<MDOperand> operands() const { return getHeader().operands(); }
1429
1430 const MDOperand &getOperand(unsigned I) const {
1431 assert(I < getNumOperands() && "Out of range");
1432 return getHeader().operands()[I];
1433 }
1434
1435 /// Return number of MDNode operands.
1436 unsigned getNumOperands() const { return getHeader().getNumOperands(); }
1437
1438 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1439 static bool classof(const Metadata *MD) {
1440 switch (MD->getMetadataID()) {
1441 default:
1442 return false;
1443 #define HANDLE_MDNODE_LEAF(CLASS) \
1444 case CLASS##Kind: \
1445 return true;
1446 #include "llvm/IR/Metadata.def"
1447 }
1448 }
1449
1450 /// Check whether MDNode is a vtable access.
1451 LLVM_ABI bool isTBAAVtableAccess() const;
1452
1453 /// Methods for metadata merging.
1454 LLVM_ABI static MDNode *concatenate(MDNode *A, MDNode *B);
1455 LLVM_ABI static MDNode *intersect(MDNode *A, MDNode *B);
1456 LLVM_ABI static MDNode *getMostGenericTBAA(MDNode *A, MDNode *B);
1457 LLVM_ABI static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B);
1458 LLVM_ABI static MDNode *getMostGenericRange(MDNode *A, MDNode *B);
1459 LLVM_ABI static MDNode *getMostGenericNoaliasAddrspace(MDNode *A, MDNode *B);
1460 LLVM_ABI static MDNode *getMostGenericAliasScope(MDNode *A, MDNode *B);
1461 LLVM_ABI static MDNode *getMostGenericAlignmentOrDereferenceable(MDNode *A,
1462 MDNode *B);
1463 /// Merge !prof metadata from two instructions.
1464 /// Currently only implemented with direct callsites with branch weights.
1465 LLVM_ABI static MDNode *getMergedProfMetadata(MDNode *A, MDNode *B,
1466 const Instruction *AInstr,
1467 const Instruction *BInstr);
1468 LLVM_ABI static MDNode *getMergedMemProfMetadata(MDNode *A, MDNode *B);
1469 LLVM_ABI static MDNode *getMergedCallsiteMetadata(MDNode *A, MDNode *B);
1470 };
1471
1472 /// Tuple of metadata.
1473 ///
1474 /// This is the simple \a MDNode arbitrary tuple. Nodes are uniqued by
1475 /// default based on their operands.
1476 class MDTuple : public MDNode {
1477 friend class LLVMContextImpl;
1478 friend class MDNode;
1479
1480 MDTuple(LLVMContext &C, StorageType Storage, unsigned Hash,
1481 ArrayRef<Metadata *> Vals)
1482 : MDNode(C, MDTupleKind, Storage, Vals) {
1483 setHash(Hash);
1484 }
1485
1486 ~MDTuple() { dropAllReferences(); }
1487
1488 void setHash(unsigned Hash) { SubclassData32 = Hash; }
1489 void recalculateHash();
1490
1491 LLVM_ABI static MDTuple *getImpl(LLVMContext &Context,
1492 ArrayRef<Metadata *> MDs,
1493 StorageType Storage,
1494 bool ShouldCreate = true);
1495
1496 TempMDTuple cloneImpl() const {
1497 ArrayRef<MDOperand> Operands = operands();
1498 return getTemporary(getContext(), SmallVector<Metadata *, 4>(Operands));
1499 }
1500
1501 public:
1502 /// Get the hash, if any.
1503 unsigned getHash() const { return SubclassData32; }
1504
1505 static MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1506 return getImpl(Context, MDs, Uniqued);
1507 }
1508
1509 static MDTuple *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1510 return getImpl(Context, MDs, Uniqued, /* ShouldCreate */ false);
1511 }
1512
1513 /// Return a distinct node.
1514 ///
1515 /// Return a distinct node -- i.e., a node that is not uniqued.
1516 static MDTuple *getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1517 return getImpl(Context, MDs, Distinct);
1518 }
1519
1520 /// Return a temporary node.
1521 ///
1522 /// For use in constructing cyclic MDNode structures. A temporary MDNode is
1523 /// not uniqued, may be RAUW'd, and must be manually deleted with
1524 /// deleteTemporary.
1525 static TempMDTuple getTemporary(LLVMContext &Context,
1526 ArrayRef<Metadata *> MDs) {
1527 return TempMDTuple(getImpl(Context, MDs, Temporary));
1528 }
1529
1530 /// Return a (temporary) clone of this.
1531 TempMDTuple clone() const { return cloneImpl(); }
1532
1533 /// Append an element to the tuple. This will resize the node.
1534 void push_back(Metadata *MD) {
1535 size_t NumOps = getNumOperands();
1536 resize(NumOps + 1);
1537 setOperand(NumOps, MD);
1538 }
1539
1540 /// Shrink the operands by 1.
1541 void pop_back() { resize(getNumOperands() - 1); }
1542
1543 static bool classof(const Metadata *MD) {
1544 return MD->getMetadataID() == MDTupleKind;
1545 }
1546 };
1547
1548 MDTuple *MDNode::get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1549 return MDTuple::get(Context, MDs);
1550 }
1551
1552 MDTuple *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1553 return MDTuple::getIfExists(Context, MDs);
1554 }
1555
1556 MDTuple *MDNode::getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1557 return MDTuple::getDistinct(Context, MDs);
1558 }
1559
1560 TempMDTuple MDNode::getTemporary(LLVMContext &Context,
1561 ArrayRef<Metadata *> MDs) {
1562 return MDTuple::getTemporary(Context, MDs);
1563 }
1564
1565 void TempMDNodeDeleter::operator()(MDNode *Node) const {
1566 MDNode::deleteTemporary(Node);
1567 }
1568
1569 /// This is a simple wrapper around an MDNode which provides a higher-level
1570 /// interface by hiding the details of how alias analysis information is encoded
1571 /// in its operands.
1572 class AliasScopeNode {
1573 const MDNode *Node = nullptr;
1574
1575 public:
1576 AliasScopeNode() = default;
1577 explicit AliasScopeNode(const MDNode *N) : Node(N) {}
1578
1579 /// Get the MDNode for this AliasScopeNode.
1580 const MDNode *getNode() const { return Node; }
1581
1582 /// Get the MDNode for this AliasScopeNode's domain.
1583 const MDNode *getDomain() const {
1584 if (Node->getNumOperands() < 2)
1585 return nullptr;
1586 return dyn_cast_or_null<MDNode>(Node->getOperand(1));
1587 }
1588 StringRef getName() const {
1589 if (Node->getNumOperands() > 2)
1590 if (MDString *N = dyn_cast_or_null<MDString>(Node->getOperand(2)))
1591 return N->getString();
1592 return StringRef();
1593 }
1594 };
1595
1596 /// Typed iterator through MDNode operands.
1597 ///
1598 /// An iterator that transforms an \a MDNode::iterator into an iterator over a
1599 /// particular Metadata subclass.
1600 template <class T> class TypedMDOperandIterator {
1601 MDNode::op_iterator I = nullptr;
1602
1603 public:
1604 using iterator_category = std::input_iterator_tag;
1605 using value_type = T *;
1606 using difference_type = std::ptrdiff_t;
1607 using pointer = void;
1608 using reference = T *;
1609
1610 TypedMDOperandIterator() = default;
1611 explicit TypedMDOperandIterator(MDNode::op_iterator I) : I(I) {}
1612
1613 T *operator*() const { return cast_or_null<T>(*I); }
1614
1615 TypedMDOperandIterator &operator++() {
1616 ++I;
1617 return *this;
1618 }
1619
1620 TypedMDOperandIterator operator++(int) {
1621 TypedMDOperandIterator Temp(*this);
1622 ++I;
1623 return Temp;
1624 }
1625
1626 bool operator==(const TypedMDOperandIterator &X) const { return I == X.I; }
1627 bool operator!=(const TypedMDOperandIterator &X) const { return I != X.I; }
1628 };
1629
1630 /// Typed, array-like tuple of metadata.
1631 ///
1632 /// This is a wrapper for \a MDTuple that makes it act like an array holding a
1633 /// particular type of metadata.
1634 template <class T> class MDTupleTypedArrayWrapper {
1635 const MDTuple *N = nullptr;
1636
1637 public:
1638 MDTupleTypedArrayWrapper() = default;
1639 MDTupleTypedArrayWrapper(const MDTuple *N) : N(N) {}
1640
1641 template <class U>
1642 MDTupleTypedArrayWrapper(
1643 const MDTupleTypedArrayWrapper<U> &Other,
1644 std::enable_if_t<std::is_convertible<U *, T *>::value> * = nullptr)
1645 : N(Other.get()) {}
1646
1647 template <class U>
1648 explicit MDTupleTypedArrayWrapper(
1649 const MDTupleTypedArrayWrapper<U> &Other,
1650 std::enable_if_t<!std::is_convertible<U *, T *>::value> * = nullptr)
1651 : N(Other.get()) {}
1652
1653 explicit operator bool() const { return get(); }
1654 explicit operator MDTuple *() const { return get(); }
1655
1656 MDTuple *get() const { return const_cast<MDTuple *>(N); }
1657 MDTuple *operator->() const { return get(); }
1658 MDTuple &operator*() const { return *get(); }
1659
1660 // FIXME: Fix callers and remove condition on N.
1661 unsigned size() const { return N ? N->getNumOperands() : 0u; }
1662 bool empty() const { return N ? N->getNumOperands() == 0 : true; }
1663 T *operator[](unsigned I) const { return cast_or_null<T>(N->getOperand(I)); }
1664
1665 // FIXME: Fix callers and remove condition on N.
1666 using iterator = TypedMDOperandIterator<T>;
1667
1668 iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
1669 iterator end() const { return N ? iterator(N->op_end()) : iterator(); }
1670 };
1671
1672 #define HANDLE_METADATA(CLASS) \
1673 using CLASS##Array = MDTupleTypedArrayWrapper<CLASS>;
1674 #include "llvm/IR/Metadata.def"
1675
1676 /// Placeholder metadata for operands of distinct MDNodes.
1677 ///
1678 /// This is a lightweight placeholder for an operand of a distinct node. It's
1679 /// purpose is to help track forward references when creating a distinct node.
1680 /// This allows distinct nodes involved in a cycle to be constructed before
1681 /// their operands without requiring a heavyweight temporary node with
1682 /// full-blown RAUW support.
1683 ///
1684 /// Each placeholder supports only a single MDNode user. Clients should pass
1685 /// an ID, retrieved via \a getID(), to indicate the "real" operand that this
1686 /// should be replaced with.
1687 ///
1688 /// While it would be possible to implement move operators, they would be
1689 /// fairly expensive. Leave them unimplemented to discourage their use
1690 /// (clients can use std::deque, std::list, BumpPtrAllocator, etc.).
1691 class DistinctMDOperandPlaceholder : public Metadata {
1692 friend class MetadataTracking;
1693
1694 Metadata **Use = nullptr;
1695
1696 public:
1697 explicit DistinctMDOperandPlaceholder(unsigned ID)
1698 : Metadata(DistinctMDOperandPlaceholderKind, Distinct) {
1699 SubclassData32 = ID;
1700 }
1701
1702 DistinctMDOperandPlaceholder() = delete;
1703 DistinctMDOperandPlaceholder(DistinctMDOperandPlaceholder &&) = delete;
1704 DistinctMDOperandPlaceholder(const DistinctMDOperandPlaceholder &) = delete;
1705
1706 ~DistinctMDOperandPlaceholder() {
1707 if (Use)
1708 *Use = nullptr;
1709 }
1710
1711 unsigned getID() const { return SubclassData32; }
1712
1713 /// Replace the use of this with MD.
1714 void replaceUseWith(Metadata *MD) {
1715 if (!Use)
1716 return;
1717 *Use = MD;
1718
1719 if (*Use)
1720 MetadataTracking::track(*Use);
1721
1722 Metadata *T = cast<Metadata>(this);
1723 MetadataTracking::untrack(T);
1724 assert(!Use && "Use is still being tracked despite being untracked!");
1725 }
1726 };
1727
1728 //===----------------------------------------------------------------------===//
1729 /// A tuple of MDNodes.
1730 ///
1731 /// Despite its name, a NamedMDNode isn't itself an MDNode.
1732 ///
1733 /// NamedMDNodes are named module-level entities that contain lists of MDNodes.
1734 ///
1735 /// It is illegal for a NamedMDNode to appear as an operand of an MDNode.
1736 class NamedMDNode : public ilist_node<NamedMDNode> {
1737 friend class LLVMContextImpl;
1738 friend class Module;
1739
1740 std::string Name;
1741 Module *Parent = nullptr;
1742 void *Operands; // SmallVector<TrackingMDRef, 4>
1743
1744 void setParent(Module *M) { Parent = M; }
1745
1746 explicit NamedMDNode(const Twine &N);
1747
1748 template <class T1> class op_iterator_impl {
1749 friend class NamedMDNode;
1750
1751 const NamedMDNode *Node = nullptr;
1752 unsigned Idx = 0;
1753
1754 op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) {}
1755
1756 public:
1757 using iterator_category = std::bidirectional_iterator_tag;
1758 using value_type = T1;
1759 using difference_type = std::ptrdiff_t;
1760 using pointer = value_type *;
1761 using reference = value_type;
1762
1763 op_iterator_impl() = default;
1764
1765 bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
1766 bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
1767
1768 op_iterator_impl &operator++() {
1769 ++Idx;
1770 return *this;
1771 }
1772
1773 op_iterator_impl operator++(int) {
1774 op_iterator_impl tmp(*this);
1775 operator++();
1776 return tmp;
1777 }
1778
1779 op_iterator_impl &operator--() {
1780 --Idx;
1781 return *this;
1782 }
1783
1784 op_iterator_impl operator--(int) {
1785 op_iterator_impl tmp(*this);
1786 operator--();
1787 return tmp;
1788 }
1789
1790 T1 operator*() const { return Node->getOperand(Idx); }
1791 };
1792
1793 public:
1794 NamedMDNode(const NamedMDNode &) = delete;
1795 LLVM_ABI ~NamedMDNode();
1796
1797 /// Drop all references and remove the node from parent module.
1798 LLVM_ABI void eraseFromParent();
1799
1800 /// Remove all uses and clear node vector.
1801 void dropAllReferences() { clearOperands(); }
1802 /// Drop all references to this node's operands.
1803 LLVM_ABI void clearOperands();
1804
1805 /// Get the module that holds this named metadata collection.
1806 inline Module *getParent() { return Parent; }
1807 inline const Module *getParent() const { return Parent; }
1808
1809 LLVM_ABI MDNode *getOperand(unsigned i) const;
1810 LLVM_ABI unsigned getNumOperands() const;
1811 LLVM_ABI void addOperand(MDNode *M);
1812 LLVM_ABI void setOperand(unsigned I, MDNode *New);
1813 LLVM_ABI StringRef getName() const;
1814 LLVM_ABI void print(raw_ostream &ROS, bool IsForDebug = false) const;
1815 LLVM_ABI void print(raw_ostream &ROS, ModuleSlotTracker &MST,
1816 bool IsForDebug = false) const;
1817 LLVM_ABI void dump() const;
1818
1819 // ---------------------------------------------------------------------------
1820 // Operand Iterator interface...
1821 //
1822 using op_iterator = op_iterator_impl<MDNode *>;
1823
1824 op_iterator op_begin() { return op_iterator(this, 0); }
1825 op_iterator op_end() { return op_iterator(this, getNumOperands()); }
1826
1827 using const_op_iterator = op_iterator_impl<const MDNode *>;
1828
1829 const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
1830 const_op_iterator op_end() const { return const_op_iterator(this, getNumOperands()); }
1831
1832 inline iterator_range<op_iterator> operands() {
1833 return make_range(op_begin(), op_end());
1834 }
1835 inline iterator_range<const_op_iterator> operands() const {
1836 return make_range(op_begin(), op_end());
1837 }
1838 };
1839
1840 // Create wrappers for C Binding types (see CBindingWrapping.h).
1841 DEFINE_ISA_CONVERSION_FUNCTIONS(NamedMDNode, LLVMNamedMDNodeRef)
1842
1843 } // end namespace llvm
1844
1845 #endif // LLVM_IR_METADATA_H
1846