1 //===-- llvm/Metadata.h - Metadata definitions ------------------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// @file
11 /// This file contains the declarations for metadata subclasses.
12 /// They represent the different flavors of metadata that live in LLVM.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_IR_METADATA_H
17 #define LLVM_IR_METADATA_H
18
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/ilist_node.h"
22 #include "llvm/ADT/iterator_range.h"
23 #include "llvm/IR/Constant.h"
24 #include "llvm/IR/MetadataTracking.h"
25 #include "llvm/IR/Value.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include <type_traits>
28
29 namespace llvm {
30 class LLVMContext;
31 class Module;
32 template<typename ValueSubClass, typename ItemParentClass>
33 class SymbolTableListTraits;
34
35
36 enum LLVMConstants : uint32_t {
37 DEBUG_METADATA_VERSION = 2 // Current debug info version number.
38 };
39
40 /// \brief Root of the metadata hierarchy.
41 ///
42 /// This is a root class for typeless data in the IR.
43 class Metadata {
44 friend class ReplaceableMetadataImpl;
45
46 /// \brief RTTI.
47 const unsigned char SubclassID;
48
49 protected:
50 /// \brief Storage flag for non-uniqued, otherwise unowned, metadata.
51 bool IsDistinctInContext : 1;
52 // TODO: expose remaining bits to subclasses.
53
54 unsigned short SubclassData16;
55 unsigned SubclassData32;
56
57 public:
58 enum MetadataKind {
59 MDTupleKind,
60 MDLocationKind,
61 MDNodeFwdDeclKind,
62 ConstantAsMetadataKind,
63 LocalAsMetadataKind,
64 MDStringKind
65 };
66
67 protected:
Metadata(unsigned ID)68 Metadata(unsigned ID)
69 : SubclassID(ID), IsDistinctInContext(false), SubclassData16(0),
70 SubclassData32(0) {}
~Metadata()71 ~Metadata() {}
72
73 /// \brief Store this in a big non-uniqued untyped bucket.
isStoredDistinctInContext()74 bool isStoredDistinctInContext() const { return IsDistinctInContext; }
75
76 /// \brief Default handling of a changed operand, which asserts.
77 ///
78 /// If subclasses pass themselves in as owners to a tracking node reference,
79 /// they must provide an implementation of this method.
handleChangedOperand(void *,Metadata *)80 void handleChangedOperand(void *, Metadata *) {
81 llvm_unreachable("Unimplemented in Metadata subclass");
82 }
83
84 public:
getMetadataID()85 unsigned getMetadataID() const { return SubclassID; }
86
87 /// \brief User-friendly dump.
88 void dump() const;
89 void print(raw_ostream &OS) const;
90 void printAsOperand(raw_ostream &OS, bool PrintType = true,
91 const Module *M = nullptr) const;
92 };
93
94 #define HANDLE_METADATA(CLASS) class CLASS;
95 #include "llvm/IR/Metadata.def"
96
97 inline raw_ostream &operator<<(raw_ostream &OS, const Metadata &MD) {
98 MD.print(OS);
99 return OS;
100 }
101
102 /// \brief Metadata wrapper in the Value hierarchy.
103 ///
104 /// A member of the \a Value hierarchy to represent a reference to metadata.
105 /// This allows, e.g., instrinsics to have metadata as operands.
106 ///
107 /// Notably, this is the only thing in either hierarchy that is allowed to
108 /// reference \a LocalAsMetadata.
109 class MetadataAsValue : public Value {
110 friend class ReplaceableMetadataImpl;
111 friend class LLVMContextImpl;
112
113 Metadata *MD;
114
115 MetadataAsValue(Type *Ty, Metadata *MD);
116 ~MetadataAsValue();
117
118 /// \brief Drop use of metadata (during teardown).
dropUse()119 void dropUse() { MD = nullptr; }
120
121 public:
122 static MetadataAsValue *get(LLVMContext &Context, Metadata *MD);
123 static MetadataAsValue *getIfExists(LLVMContext &Context, Metadata *MD);
getMetadata()124 Metadata *getMetadata() const { return MD; }
125
classof(const Value * V)126 static bool classof(const Value *V) {
127 return V->getValueID() == MetadataAsValueVal;
128 }
129
130 private:
131 void handleChangedMetadata(Metadata *MD);
132 void track();
133 void untrack();
134 };
135
136 /// \brief Shared implementation of use-lists for replaceable metadata.
137 ///
138 /// Most metadata cannot be RAUW'ed. This is a shared implementation of
139 /// use-lists and associated API for the two that support it (\a ValueAsMetadata
140 /// and \a TempMDNode).
141 class ReplaceableMetadataImpl {
142 friend class MetadataTracking;
143
144 public:
145 typedef MetadataTracking::OwnerTy OwnerTy;
146
147 private:
148 uint64_t NextIndex;
149 SmallDenseMap<void *, std::pair<OwnerTy, uint64_t>, 4> UseMap;
150
151 public:
ReplaceableMetadataImpl()152 ReplaceableMetadataImpl() : NextIndex(0) {}
~ReplaceableMetadataImpl()153 ~ReplaceableMetadataImpl() {
154 assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
155 }
156
157 /// \brief Replace all uses of this with MD.
158 ///
159 /// Replace all uses of this with \c MD, which is allowed to be null.
160 void replaceAllUsesWith(Metadata *MD);
161
162 /// \brief Resolve all uses of this.
163 ///
164 /// Resolve all uses of this, turning off RAUW permanently. If \c
165 /// ResolveUsers, call \a UniquableMDNode::resolve() on any users whose last
166 /// operand is resolved.
167 void resolveAllUses(bool ResolveUsers = true);
168
169 private:
170 void addRef(void *Ref, OwnerTy Owner);
171 void dropRef(void *Ref);
172 void moveRef(void *Ref, void *New, const Metadata &MD);
173
174 static ReplaceableMetadataImpl *get(Metadata &MD);
175 };
176
177 /// \brief Value wrapper in the Metadata hierarchy.
178 ///
179 /// This is a custom value handle that allows other metadata to refer to
180 /// classes in the Value hierarchy.
181 ///
182 /// Because of full uniquing support, each value is only wrapped by a single \a
183 /// ValueAsMetadata object, so the lookup maps are far more efficient than
184 /// those using ValueHandleBase.
185 class ValueAsMetadata : public Metadata, ReplaceableMetadataImpl {
186 friend class ReplaceableMetadataImpl;
187 friend class LLVMContextImpl;
188
189 Value *V;
190
191 /// \brief Drop users without RAUW (during teardown).
dropUsers()192 void dropUsers() {
193 ReplaceableMetadataImpl::resolveAllUses(/* ResolveUsers */ false);
194 }
195
196 protected:
ValueAsMetadata(unsigned ID,Value * V)197 ValueAsMetadata(unsigned ID, Value *V)
198 : Metadata(ID), V(V) {
199 assert(V && "Expected valid value");
200 }
~ValueAsMetadata()201 ~ValueAsMetadata() {}
202
203 public:
204 static ValueAsMetadata *get(Value *V);
getConstant(Value * C)205 static ConstantAsMetadata *getConstant(Value *C) {
206 return cast<ConstantAsMetadata>(get(C));
207 }
getLocal(Value * Local)208 static LocalAsMetadata *getLocal(Value *Local) {
209 return cast<LocalAsMetadata>(get(Local));
210 }
211
212 static ValueAsMetadata *getIfExists(Value *V);
getConstantIfExists(Value * C)213 static ConstantAsMetadata *getConstantIfExists(Value *C) {
214 return cast_or_null<ConstantAsMetadata>(getIfExists(C));
215 }
getLocalIfExists(Value * Local)216 static LocalAsMetadata *getLocalIfExists(Value *Local) {
217 return cast_or_null<LocalAsMetadata>(getIfExists(Local));
218 }
219
getValue()220 Value *getValue() const { return V; }
getType()221 Type *getType() const { return V->getType(); }
getContext()222 LLVMContext &getContext() const { return V->getContext(); }
223
224 static void handleDeletion(Value *V);
225 static void handleRAUW(Value *From, Value *To);
226
227 protected:
228 /// \brief Handle collisions after \a Value::replaceAllUsesWith().
229 ///
230 /// RAUW isn't supported directly for \a ValueAsMetadata, but if the wrapped
231 /// \a Value gets RAUW'ed and the target already exists, this is used to
232 /// merge the two metadata nodes.
replaceAllUsesWith(Metadata * MD)233 void replaceAllUsesWith(Metadata *MD) {
234 ReplaceableMetadataImpl::replaceAllUsesWith(MD);
235 }
236
237 public:
classof(const Metadata * MD)238 static bool classof(const Metadata *MD) {
239 return MD->getMetadataID() == LocalAsMetadataKind ||
240 MD->getMetadataID() == ConstantAsMetadataKind;
241 }
242 };
243
244 class ConstantAsMetadata : public ValueAsMetadata {
245 friend class ValueAsMetadata;
246
ConstantAsMetadata(Constant * C)247 ConstantAsMetadata(Constant *C)
248 : ValueAsMetadata(ConstantAsMetadataKind, C) {}
249
250 public:
get(Constant * C)251 static ConstantAsMetadata *get(Constant *C) {
252 return ValueAsMetadata::getConstant(C);
253 }
getIfExists(Constant * C)254 static ConstantAsMetadata *getIfExists(Constant *C) {
255 return ValueAsMetadata::getConstantIfExists(C);
256 }
257
getValue()258 Constant *getValue() const {
259 return cast<Constant>(ValueAsMetadata::getValue());
260 }
261
classof(const Metadata * MD)262 static bool classof(const Metadata *MD) {
263 return MD->getMetadataID() == ConstantAsMetadataKind;
264 }
265 };
266
267 class LocalAsMetadata : public ValueAsMetadata {
268 friend class ValueAsMetadata;
269
LocalAsMetadata(Value * Local)270 LocalAsMetadata(Value *Local)
271 : ValueAsMetadata(LocalAsMetadataKind, Local) {
272 assert(!isa<Constant>(Local) && "Expected local value");
273 }
274
275 public:
get(Value * Local)276 static LocalAsMetadata *get(Value *Local) {
277 return ValueAsMetadata::getLocal(Local);
278 }
getIfExists(Value * Local)279 static LocalAsMetadata *getIfExists(Value *Local) {
280 return ValueAsMetadata::getLocalIfExists(Local);
281 }
282
classof(const Metadata * MD)283 static bool classof(const Metadata *MD) {
284 return MD->getMetadataID() == LocalAsMetadataKind;
285 }
286 };
287
288 /// \brief Transitional API for extracting constants from Metadata.
289 ///
290 /// This namespace contains transitional functions for metadata that points to
291 /// \a Constants.
292 ///
293 /// In prehistory -- when metadata was a subclass of \a Value -- \a MDNode
294 /// operands could refer to any \a Value. There's was a lot of code like this:
295 ///
296 /// \code
297 /// MDNode *N = ...;
298 /// auto *CI = dyn_cast<ConstantInt>(N->getOperand(2));
299 /// \endcode
300 ///
301 /// Now that \a Value and \a Metadata are in separate hierarchies, maintaining
302 /// the semantics for \a isa(), \a cast(), \a dyn_cast() (etc.) requires three
303 /// steps: cast in the \a Metadata hierarchy, extraction of the \a Value, and
304 /// cast in the \a Value hierarchy. Besides creating boiler-plate, this
305 /// requires subtle control flow changes.
306 ///
307 /// The end-goal is to create a new type of metadata, called (e.g.) \a MDInt,
308 /// so that metadata can refer to numbers without traversing a bridge to the \a
309 /// Value hierarchy. In this final state, the code above would look like this:
310 ///
311 /// \code
312 /// MDNode *N = ...;
313 /// auto *MI = dyn_cast<MDInt>(N->getOperand(2));
314 /// \endcode
315 ///
316 /// The API in this namespace supports the transition. \a MDInt doesn't exist
317 /// yet, and even once it does, changing each metadata schema to use it is its
318 /// own mini-project. In the meantime this API prevents us from introducing
319 /// complex and bug-prone control flow that will disappear in the end. In
320 /// particular, the above code looks like this:
321 ///
322 /// \code
323 /// MDNode *N = ...;
324 /// auto *CI = mdconst::dyn_extract<ConstantInt>(N->getOperand(2));
325 /// \endcode
326 ///
327 /// The full set of provided functions includes:
328 ///
329 /// mdconst::hasa <=> isa
330 /// mdconst::extract <=> cast
331 /// mdconst::extract_or_null <=> cast_or_null
332 /// mdconst::dyn_extract <=> dyn_cast
333 /// mdconst::dyn_extract_or_null <=> dyn_cast_or_null
334 ///
335 /// The target of the cast must be a subclass of \a Constant.
336 namespace mdconst {
337
338 namespace detail {
339 template <class T> T &make();
340 template <class T, class Result> struct HasDereference {
341 typedef char Yes[1];
342 typedef char No[2];
343 template <size_t N> struct SFINAE {};
344
345 template <class U, class V>
346 static Yes &hasDereference(SFINAE<sizeof(static_cast<V>(*make<U>()))> * = 0);
347 template <class U, class V> static No &hasDereference(...);
348
349 static const bool value =
350 sizeof(hasDereference<T, Result>(nullptr)) == sizeof(Yes);
351 };
352 template <class V, class M> struct IsValidPointer {
353 static const bool value = std::is_base_of<Constant, V>::value &&
354 HasDereference<M, const Metadata &>::value;
355 };
356 template <class V, class M> struct IsValidReference {
357 static const bool value = std::is_base_of<Constant, V>::value &&
358 std::is_convertible<M, const Metadata &>::value;
359 };
360 } // end namespace detail
361
362 /// \brief Check whether Metadata has a Value.
363 ///
364 /// As an analogue to \a isa(), check whether \c MD has an \a Value inside of
365 /// type \c X.
366 template <class X, class Y>
367 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, bool>::type
hasa(Y && MD)368 hasa(Y &&MD) {
369 assert(MD && "Null pointer sent into hasa");
370 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
371 return isa<X>(V->getValue());
372 return false;
373 }
374 template <class X, class Y>
375 inline
376 typename std::enable_if<detail::IsValidReference<X, Y &>::value, bool>::type
hasa(Y & MD)377 hasa(Y &MD) {
378 return hasa(&MD);
379 }
380
381 /// \brief Extract a Value from Metadata.
382 ///
383 /// As an analogue to \a cast(), extract the \a Value subclass \c X from \c MD.
384 template <class X, class Y>
385 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
extract(Y && MD)386 extract(Y &&MD) {
387 return cast<X>(cast<ConstantAsMetadata>(MD)->getValue());
388 }
389 template <class X, class Y>
390 inline
391 typename std::enable_if<detail::IsValidReference<X, Y &>::value, X *>::type
extract(Y & MD)392 extract(Y &MD) {
393 return extract(&MD);
394 }
395
396 /// \brief Extract a Value from Metadata, allowing null.
397 ///
398 /// As an analogue to \a cast_or_null(), extract the \a Value subclass \c X
399 /// from \c MD, allowing \c MD to be null.
400 template <class X, class Y>
401 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
extract_or_null(Y && MD)402 extract_or_null(Y &&MD) {
403 if (auto *V = cast_or_null<ConstantAsMetadata>(MD))
404 return cast<X>(V->getValue());
405 return nullptr;
406 }
407
408 /// \brief Extract a Value from Metadata, if any.
409 ///
410 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
411 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
412 /// Value it does contain is of the wrong subclass.
413 template <class X, class Y>
414 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
dyn_extract(Y && MD)415 dyn_extract(Y &&MD) {
416 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
417 return dyn_cast<X>(V->getValue());
418 return nullptr;
419 }
420
421 /// \brief Extract a Value from Metadata, if any, allowing null.
422 ///
423 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
424 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
425 /// Value it does contain is of the wrong subclass, allowing \c MD to be null.
426 template <class X, class Y>
427 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
dyn_extract_or_null(Y && MD)428 dyn_extract_or_null(Y &&MD) {
429 if (auto *V = dyn_cast_or_null<ConstantAsMetadata>(MD))
430 return dyn_cast<X>(V->getValue());
431 return nullptr;
432 }
433
434 } // end namespace mdconst
435
436 //===----------------------------------------------------------------------===//
437 /// \brief A single uniqued string.
438 ///
439 /// These are used to efficiently contain a byte sequence for metadata.
440 /// MDString is always unnamed.
441 class MDString : public Metadata {
442 friend class StringMapEntry<MDString>;
443
444 MDString(const MDString &) LLVM_DELETED_FUNCTION;
445 MDString &operator=(MDString &&) LLVM_DELETED_FUNCTION;
446 MDString &operator=(const MDString &) LLVM_DELETED_FUNCTION;
447
448 StringMapEntry<MDString> *Entry;
MDString()449 MDString() : Metadata(MDStringKind), Entry(nullptr) {}
MDString(MDString &&)450 MDString(MDString &&) : Metadata(MDStringKind) {}
451
452 public:
453 static MDString *get(LLVMContext &Context, StringRef Str);
get(LLVMContext & Context,const char * Str)454 static MDString *get(LLVMContext &Context, const char *Str) {
455 return get(Context, Str ? StringRef(Str) : StringRef());
456 }
457
458 StringRef getString() const;
459
getLength()460 unsigned getLength() const { return (unsigned)getString().size(); }
461
462 typedef StringRef::iterator iterator;
463
464 /// \brief Pointer to the first byte of the string.
begin()465 iterator begin() const { return getString().begin(); }
466
467 /// \brief Pointer to one byte past the end of the string.
end()468 iterator end() const { return getString().end(); }
469
bytes_begin()470 const unsigned char *bytes_begin() const { return getString().bytes_begin(); }
bytes_end()471 const unsigned char *bytes_end() const { return getString().bytes_end(); }
472
473 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
classof(const Metadata * MD)474 static bool classof(const Metadata *MD) {
475 return MD->getMetadataID() == MDStringKind;
476 }
477 };
478
479 /// \brief A collection of metadata nodes that might be associated with a
480 /// memory access used by the alias-analysis infrastructure.
481 struct AAMDNodes {
482 explicit AAMDNodes(MDNode *T = nullptr, MDNode *S = nullptr,
483 MDNode *N = nullptr)
TBAAAAMDNodes484 : TBAA(T), Scope(S), NoAlias(N) {}
485
486 bool operator==(const AAMDNodes &A) const {
487 return TBAA == A.TBAA && Scope == A.Scope && NoAlias == A.NoAlias;
488 }
489
490 bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
491
492 LLVM_EXPLICIT operator bool() const { return TBAA || Scope || NoAlias; }
493
494 /// \brief The tag for type-based alias analysis.
495 MDNode *TBAA;
496
497 /// \brief The tag for alias scope specification (used with noalias).
498 MDNode *Scope;
499
500 /// \brief The tag specifying the noalias scope.
501 MDNode *NoAlias;
502 };
503
504 // Specialize DenseMapInfo for AAMDNodes.
505 template<>
506 struct DenseMapInfo<AAMDNodes> {
507 static inline AAMDNodes getEmptyKey() {
508 return AAMDNodes(DenseMapInfo<MDNode *>::getEmptyKey(), 0, 0);
509 }
510 static inline AAMDNodes getTombstoneKey() {
511 return AAMDNodes(DenseMapInfo<MDNode *>::getTombstoneKey(), 0, 0);
512 }
513 static unsigned getHashValue(const AAMDNodes &Val) {
514 return DenseMapInfo<MDNode *>::getHashValue(Val.TBAA) ^
515 DenseMapInfo<MDNode *>::getHashValue(Val.Scope) ^
516 DenseMapInfo<MDNode *>::getHashValue(Val.NoAlias);
517 }
518 static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS) {
519 return LHS == RHS;
520 }
521 };
522
523 /// \brief Tracking metadata reference owned by Metadata.
524 ///
525 /// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
526 /// of \a Metadata, which has the option of registering itself for callbacks to
527 /// re-unique itself.
528 ///
529 /// In particular, this is used by \a MDNode.
530 class MDOperand {
531 MDOperand(MDOperand &&) LLVM_DELETED_FUNCTION;
532 MDOperand(const MDOperand &) LLVM_DELETED_FUNCTION;
533 MDOperand &operator=(MDOperand &&) LLVM_DELETED_FUNCTION;
534 MDOperand &operator=(const MDOperand &) LLVM_DELETED_FUNCTION;
535
536 Metadata *MD;
537
538 public:
539 MDOperand() : MD(nullptr) {}
540 ~MDOperand() { untrack(); }
541
542 Metadata *get() const { return MD; }
543 operator Metadata *() const { return get(); }
544 Metadata *operator->() const { return get(); }
545 Metadata &operator*() const { return *get(); }
546
547 void reset() {
548 untrack();
549 MD = nullptr;
550 }
551 void reset(Metadata *MD, Metadata *Owner) {
552 untrack();
553 this->MD = MD;
554 track(Owner);
555 }
556
557 private:
558 void track(Metadata *Owner) {
559 if (MD) {
560 if (Owner)
561 MetadataTracking::track(this, *MD, *Owner);
562 else
563 MetadataTracking::track(MD);
564 }
565 }
566 void untrack() {
567 assert(static_cast<void *>(this) == &MD && "Expected same address");
568 if (MD)
569 MetadataTracking::untrack(MD);
570 }
571 };
572
573 template <> struct simplify_type<MDOperand> {
574 typedef Metadata *SimpleType;
575 static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
576 };
577
578 template <> struct simplify_type<const MDOperand> {
579 typedef Metadata *SimpleType;
580 static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
581 };
582
583 //===----------------------------------------------------------------------===//
584 /// \brief Tuple of metadata.
585 class MDNode : public Metadata {
586 MDNode(const MDNode &) LLVM_DELETED_FUNCTION;
587 void operator=(const MDNode &) LLVM_DELETED_FUNCTION;
588 void *operator new(size_t) LLVM_DELETED_FUNCTION;
589
590 LLVMContext &Context;
591 unsigned NumOperands;
592
593 protected:
594 unsigned MDNodeSubclassData;
595
596 void *operator new(size_t Size, unsigned NumOps);
597 void operator delete(void *Mem);
598
599 /// \brief Required by std, but never called.
600 void operator delete(void *, unsigned) {
601 llvm_unreachable("Constructor throws?");
602 }
603
604 /// \brief Required by std, but never called.
605 void operator delete(void *, unsigned, bool) {
606 llvm_unreachable("Constructor throws?");
607 }
608
609 MDNode(LLVMContext &Context, unsigned ID, ArrayRef<Metadata *> MDs);
610 ~MDNode() {}
611
612 void dropAllReferences();
613
614 MDOperand *mutable_begin() { return mutable_end() - NumOperands; }
615 MDOperand *mutable_end() { return reinterpret_cast<MDOperand *>(this); }
616
617 public:
618 static inline MDNode *get(LLVMContext &Context, ArrayRef<Metadata *> MDs);
619 static inline MDNode *getIfExists(LLVMContext &Context,
620 ArrayRef<Metadata *> MDs);
621 static inline MDNode *getDistinct(LLVMContext &Context,
622 ArrayRef<Metadata *> MDs);
623
624 /// \brief Return a temporary MDNode
625 ///
626 /// For use in constructing cyclic MDNode structures. A temporary MDNode is
627 /// not uniqued, may be RAUW'd, and must be manually deleted with
628 /// deleteTemporary.
629 static MDNodeFwdDecl *getTemporary(LLVMContext &Context,
630 ArrayRef<Metadata *> MDs);
631
632 /// \brief Deallocate a node created by getTemporary.
633 ///
634 /// The node must not have any users.
635 static void deleteTemporary(MDNode *N);
636
637 LLVMContext &getContext() const { return Context; }
638
639 /// \brief Replace a specific operand.
640 void replaceOperandWith(unsigned I, Metadata *New);
641
642 /// \brief Check if node is fully resolved.
643 bool isResolved() const;
644
645 /// \brief Check if node is distinct.
646 ///
647 /// Distinct nodes are not uniqued, and will not be returned by \a
648 /// MDNode::get().
649 bool isDistinct() const {
650 return isStoredDistinctInContext() || isa<MDNodeFwdDecl>(this);
651 }
652
653 protected:
654 /// \brief Set an operand.
655 ///
656 /// Sets the operand directly, without worrying about uniquing.
657 void setOperand(unsigned I, Metadata *New);
658
659 public:
660 typedef const MDOperand *op_iterator;
661 typedef iterator_range<op_iterator> op_range;
662
663 op_iterator op_begin() const {
664 return const_cast<MDNode *>(this)->mutable_begin();
665 }
666 op_iterator op_end() const {
667 return const_cast<MDNode *>(this)->mutable_end();
668 }
669 op_range operands() const { return op_range(op_begin(), op_end()); }
670
671 const MDOperand &getOperand(unsigned I) const {
672 assert(I < NumOperands && "Out of range");
673 return op_begin()[I];
674 }
675
676 /// \brief Return number of MDNode operands.
677 unsigned getNumOperands() const { return NumOperands; }
678
679 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
680 static bool classof(const Metadata *MD) {
681 return MD->getMetadataID() == MDTupleKind ||
682 MD->getMetadataID() == MDLocationKind ||
683 MD->getMetadataID() == MDNodeFwdDeclKind;
684 }
685
686 /// \brief Check whether MDNode is a vtable access.
687 bool isTBAAVtableAccess() const;
688
689 /// \brief Methods for metadata merging.
690 static MDNode *concatenate(MDNode *A, MDNode *B);
691 static MDNode *intersect(MDNode *A, MDNode *B);
692 static MDNode *getMostGenericTBAA(MDNode *A, MDNode *B);
693 static AAMDNodes getMostGenericAA(const AAMDNodes &A, const AAMDNodes &B);
694 static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B);
695 static MDNode *getMostGenericRange(MDNode *A, MDNode *B);
696 static MDNode *getMostGenericAliasScope(MDNode *A, MDNode *B);
697 };
698
699 /// \brief Uniquable metadata node.
700 ///
701 /// A uniquable metadata node. This contains the basic functionality
702 /// for implementing sub-types of \a MDNode that can be uniqued like
703 /// constants.
704 ///
705 /// There is limited support for RAUW at construction time. At
706 /// construction time, if any operands are an instance of \a
707 /// MDNodeFwdDecl (or another unresolved \a UniquableMDNode, which
708 /// indicates an \a MDNodeFwdDecl in its path), the node itself will be
709 /// unresolved. As soon as all operands become resolved, it will drop
710 /// RAUW support permanently.
711 ///
712 /// If an unresolved node is part of a cycle, \a resolveCycles() needs
713 /// to be called on some member of the cycle when each \a MDNodeFwdDecl
714 /// has been removed.
715 class UniquableMDNode : public MDNode {
716 friend class ReplaceableMetadataImpl;
717 friend class MDNode;
718 friend class LLVMContextImpl;
719
720 /// \brief Support RAUW as long as one of its arguments is replaceable.
721 ///
722 /// FIXME: Save memory by storing this in a pointer union with the
723 /// LLVMContext, and adding an LLVMContext reference to RMI.
724 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses;
725
726 protected:
727 /// \brief Create a new node.
728 ///
729 /// If \c AllowRAUW, then if any operands are unresolved support RAUW. RAUW
730 /// will be dropped once all operands have been resolved (or if \a
731 /// resolveCycles() is called).
732 UniquableMDNode(LLVMContext &C, unsigned ID, ArrayRef<Metadata *> Vals,
733 bool AllowRAUW);
734 ~UniquableMDNode() {}
735
736 void storeDistinctInContext();
737
738 public:
739 static bool classof(const Metadata *MD) {
740 return MD->getMetadataID() == MDTupleKind ||
741 MD->getMetadataID() == MDLocationKind;
742 }
743
744 /// \brief Check whether any operands are forward declarations.
745 ///
746 /// Returns \c true as long as any operands (or their operands, etc.) are \a
747 /// MDNodeFwdDecl.
748 ///
749 /// As forward declarations are resolved, their containers should get
750 /// resolved automatically. However, if this (or one of its operands) is
751 /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
752 bool isResolved() const { return !ReplaceableUses; }
753
754 /// \brief Resolve cycles.
755 ///
756 /// Once all forward declarations have been resolved, force cycles to be
757 /// resolved.
758 ///
759 /// \pre No operands (or operands' operands, etc.) are \a MDNodeFwdDecl.
760 void resolveCycles();
761
762 private:
763 void handleChangedOperand(void *Ref, Metadata *New);
764
765 void resolve();
766 void resolveAfterOperandChange(Metadata *Old, Metadata *New);
767 void decrementUnresolvedOperandCount();
768
769 void deleteAsSubclass();
770 UniquableMDNode *uniquify();
771 void eraseFromStore();
772 };
773
774 /// \brief Tuple of metadata.
775 ///
776 /// This is the simple \a MDNode arbitrary tuple. Nodes are uniqued by
777 /// default based on their operands.
778 class MDTuple : public UniquableMDNode {
779 friend class LLVMContextImpl;
780 friend class UniquableMDNode;
781
782 MDTuple(LLVMContext &C, ArrayRef<Metadata *> Vals, bool AllowRAUW)
783 : UniquableMDNode(C, MDTupleKind, Vals, AllowRAUW) {}
784 ~MDTuple() { dropAllReferences(); }
785
786 void setHash(unsigned Hash) { MDNodeSubclassData = Hash; }
787 void recalculateHash();
788
789 static MDTuple *getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
790 bool ShouldCreate);
791
792 public:
793 /// \brief Get the hash, if any.
794 unsigned getHash() const { return MDNodeSubclassData; }
795
796 static MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
797 return getImpl(Context, MDs, /* ShouldCreate */ true);
798 }
799 static MDTuple *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
800 return getImpl(Context, MDs, /* ShouldCreate */ false);
801 }
802
803 /// \brief Return a distinct node.
804 ///
805 /// Return a distinct node -- i.e., a node that is not uniqued.
806 static MDTuple *getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs);
807
808 static bool classof(const Metadata *MD) {
809 return MD->getMetadataID() == MDTupleKind;
810 }
811
812 private:
813 MDTuple *uniquifyImpl();
814 void eraseFromStoreImpl();
815 };
816
817 MDNode *MDNode::get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
818 return MDTuple::get(Context, MDs);
819 }
820 MDNode *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
821 return MDTuple::getIfExists(Context, MDs);
822 }
823 MDNode *MDNode::getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
824 return MDTuple::getDistinct(Context, MDs);
825 }
826
827 /// \brief Debug location.
828 ///
829 /// A debug location in source code, used for debug info and otherwise.
830 class MDLocation : public UniquableMDNode {
831 friend class LLVMContextImpl;
832 friend class UniquableMDNode;
833
834 MDLocation(LLVMContext &C, unsigned Line, unsigned Column,
835 ArrayRef<Metadata *> MDs, bool AllowRAUW);
836 ~MDLocation() { dropAllReferences(); }
837
838 static MDLocation *constructHelper(LLVMContext &Context, unsigned Line,
839 unsigned Column, Metadata *Scope,
840 Metadata *InlinedAt, bool AllowRAUW);
841
842 static MDLocation *getImpl(LLVMContext &Context, unsigned Line,
843 unsigned Column, Metadata *Scope,
844 Metadata *InlinedAt, bool ShouldCreate);
845
846 // Disallow replacing operands.
847 void replaceOperandWith(unsigned I, Metadata *New) LLVM_DELETED_FUNCTION;
848
849 public:
850 static MDLocation *get(LLVMContext &Context, unsigned Line, unsigned Column,
851 Metadata *Scope, Metadata *InlinedAt = nullptr) {
852 return getImpl(Context, Line, Column, Scope, InlinedAt,
853 /* ShouldCreate */ true);
854 }
855 static MDLocation *getIfExists(LLVMContext &Context, unsigned Line,
856 unsigned Column, Metadata *Scope,
857 Metadata *InlinedAt = nullptr) {
858 return getImpl(Context, Line, Column, Scope, InlinedAt,
859 /* ShouldCreate */ false);
860 }
861 static MDLocation *getDistinct(LLVMContext &Context, unsigned Line,
862 unsigned Column, Metadata *Scope,
863 Metadata *InlinedAt = nullptr);
864
865 unsigned getLine() const { return MDNodeSubclassData; }
866 unsigned getColumn() const { return SubclassData16; }
867 Metadata *getScope() const { return getOperand(0); }
868 Metadata *getInlinedAt() const {
869 if (getNumOperands() == 2)
870 return getOperand(1);
871 return nullptr;
872 }
873
874 static bool classof(const Metadata *MD) {
875 return MD->getMetadataID() == MDLocationKind;
876 }
877
878 private:
879 MDLocation *uniquifyImpl();
880 void eraseFromStoreImpl();
881 };
882
883 /// \brief Forward declaration of metadata.
884 ///
885 /// Forward declaration of metadata, in the form of a basic tuple. Unlike \a
886 /// MDTuple, this class has full support for RAUW, is not owned, is not
887 /// uniqued, and is suitable for forward references.
888 class MDNodeFwdDecl : public MDNode, ReplaceableMetadataImpl {
889 friend class Metadata;
890 friend class ReplaceableMetadataImpl;
891
892 MDNodeFwdDecl(LLVMContext &C, ArrayRef<Metadata *> Vals)
893 : MDNode(C, MDNodeFwdDeclKind, Vals) {}
894
895 public:
896 ~MDNodeFwdDecl() { dropAllReferences(); }
897
898 // MSVC doesn't see the alternative: "using MDNode::operator delete".
899 void operator delete(void *Mem) { MDNode::operator delete(Mem); }
900
901 static MDNodeFwdDecl *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
902 return new (MDs.size()) MDNodeFwdDecl(Context, MDs);
903 }
904
905 static bool classof(const Metadata *MD) {
906 return MD->getMetadataID() == MDNodeFwdDeclKind;
907 }
908
909 using ReplaceableMetadataImpl::replaceAllUsesWith;
910 };
911
912 //===----------------------------------------------------------------------===//
913 /// \brief A tuple of MDNodes.
914 ///
915 /// Despite its name, a NamedMDNode isn't itself an MDNode. NamedMDNodes belong
916 /// to modules, have names, and contain lists of MDNodes.
917 ///
918 /// TODO: Inherit from Metadata.
919 class NamedMDNode : public ilist_node<NamedMDNode> {
920 friend class SymbolTableListTraits<NamedMDNode, Module>;
921 friend struct ilist_traits<NamedMDNode>;
922 friend class LLVMContextImpl;
923 friend class Module;
924 NamedMDNode(const NamedMDNode &) LLVM_DELETED_FUNCTION;
925
926 std::string Name;
927 Module *Parent;
928 void *Operands; // SmallVector<TrackingMDRef, 4>
929
930 void setParent(Module *M) { Parent = M; }
931
932 explicit NamedMDNode(const Twine &N);
933
934 template<class T1, class T2>
935 class op_iterator_impl :
936 public std::iterator<std::bidirectional_iterator_tag, T2> {
937 const NamedMDNode *Node;
938 unsigned Idx;
939 op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) { }
940
941 friend class NamedMDNode;
942
943 public:
944 op_iterator_impl() : Node(nullptr), Idx(0) { }
945
946 bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
947 bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
948 op_iterator_impl &operator++() {
949 ++Idx;
950 return *this;
951 }
952 op_iterator_impl operator++(int) {
953 op_iterator_impl tmp(*this);
954 operator++();
955 return tmp;
956 }
957 op_iterator_impl &operator--() {
958 --Idx;
959 return *this;
960 }
961 op_iterator_impl operator--(int) {
962 op_iterator_impl tmp(*this);
963 operator--();
964 return tmp;
965 }
966
967 T1 operator*() const { return Node->getOperand(Idx); }
968 };
969
970 public:
971 /// \brief Drop all references and remove the node from parent module.
972 void eraseFromParent();
973
974 /// \brief Remove all uses and clear node vector.
975 void dropAllReferences();
976
977 ~NamedMDNode();
978
979 /// \brief Get the module that holds this named metadata collection.
980 inline Module *getParent() { return Parent; }
981 inline const Module *getParent() const { return Parent; }
982
983 MDNode *getOperand(unsigned i) const;
984 unsigned getNumOperands() const;
985 void addOperand(MDNode *M);
986 void setOperand(unsigned I, MDNode *New);
987 StringRef getName() const;
988 void print(raw_ostream &ROS) const;
989 void dump() const;
990
991 // ---------------------------------------------------------------------------
992 // Operand Iterator interface...
993 //
994 typedef op_iterator_impl<MDNode *, MDNode> op_iterator;
995 op_iterator op_begin() { return op_iterator(this, 0); }
996 op_iterator op_end() { return op_iterator(this, getNumOperands()); }
997
998 typedef op_iterator_impl<const MDNode *, MDNode> const_op_iterator;
999 const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
1000 const_op_iterator op_end() const { return const_op_iterator(this, getNumOperands()); }
1001
1002 inline iterator_range<op_iterator> operands() {
1003 return iterator_range<op_iterator>(op_begin(), op_end());
1004 }
1005 inline iterator_range<const_op_iterator> operands() const {
1006 return iterator_range<const_op_iterator>(op_begin(), op_end());
1007 }
1008 };
1009
1010 } // end llvm namespace
1011
1012 #endif
1013