1 //===- MetadataTracking.cpp - Implement metadata tracking -----------------===//
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 // This file implements Metadata tracking.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/IR/MetadataTracking.h"
15 #include "llvm/IR/Metadata.h"
16 
17 using namespace llvm;
18 
get(Metadata & MD)19 ReplaceableMetadataImpl *ReplaceableMetadataImpl::get(Metadata &MD) {
20   if (auto *N = dyn_cast<MDNode>(&MD))
21     return N->Context.getReplaceableUses();
22   return dyn_cast<ValueAsMetadata>(&MD);
23 }
24 
track(void * Ref,Metadata & MD,OwnerTy Owner)25 bool MetadataTracking::track(void *Ref, Metadata &MD, OwnerTy Owner) {
26   assert(Ref && "Expected live reference");
27   assert((Owner || *static_cast<Metadata **>(Ref) == &MD) &&
28          "Reference without owner must be direct");
29   if (auto *R = ReplaceableMetadataImpl::get(MD)) {
30     R->addRef(Ref, Owner);
31     return true;
32   }
33   return false;
34 }
35 
untrack(void * Ref,Metadata & MD)36 void MetadataTracking::untrack(void *Ref, Metadata &MD) {
37   assert(Ref && "Expected live reference");
38   if (auto *R = ReplaceableMetadataImpl::get(MD))
39     R->dropRef(Ref);
40 }
41 
retrack(void * Ref,Metadata & MD,void * New)42 bool MetadataTracking::retrack(void *Ref, Metadata &MD, void *New) {
43   assert(Ref && "Expected live reference");
44   assert(New && "Expected live reference");
45   assert(Ref != New && "Expected change");
46   if (auto *R = ReplaceableMetadataImpl::get(MD)) {
47     R->moveRef(Ref, New, MD);
48     return true;
49   }
50   return false;
51 }
52 
isReplaceable(const Metadata & MD)53 bool MetadataTracking::isReplaceable(const Metadata &MD) {
54   return ReplaceableMetadataImpl::get(const_cast<Metadata &>(MD));
55 }
56