blob: 543eaac483d377ffdb59472633ee0a38c7ab1320 [file] [log] [blame]
Duncan P. N. Exon Smith71db6422015-02-02 18:20:15 +00001//===- Metadata.cpp - Implement Metadata classes --------------------------===//
Devang Patela4f43fb2009-07-28 21:49:47 +00002//
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 the Metadata classes.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carruth9fb823b2013-01-02 11:36:10 +000014#include "llvm/IR/Metadata.h"
Chris Lattner1300f452009-12-28 08:24:16 +000015#include "LLVMContextImpl.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000016#include "MetadataImpl.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "SymbolTableListTraitsImpl.h"
18#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/STLExtras.h"
Rafael Espindolaab73c492014-01-28 16:56:46 +000020#include "llvm/ADT/SmallSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/ADT/SmallString.h"
22#include "llvm/ADT/StringMap.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000023#include "llvm/IR/ConstantRange.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000024#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Instruction.h"
26#include "llvm/IR/LLVMContext.h"
27#include "llvm/IR/Module.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000028#include "llvm/IR/ValueHandle.h"
Duncan P. N. Exon Smith46d91ad2014-11-14 18:42:06 +000029
Devang Patela4f43fb2009-07-28 21:49:47 +000030using namespace llvm;
31
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +000032MetadataAsValue::MetadataAsValue(Type *Ty, Metadata *MD)
33 : Value(Ty, MetadataAsValueVal), MD(MD) {
34 track();
35}
36
37MetadataAsValue::~MetadataAsValue() {
38 getType()->getContext().pImpl->MetadataAsValues.erase(MD);
39 untrack();
40}
41
42/// \brief Canonicalize metadata arguments to intrinsics.
43///
44/// To support bitcode upgrades (and assembly semantic sugar) for \a
45/// MetadataAsValue, we need to canonicalize certain metadata.
46///
47/// - nullptr is replaced by an empty MDNode.
48/// - An MDNode with a single null operand is replaced by an empty MDNode.
49/// - An MDNode whose only operand is a \a ConstantAsMetadata gets skipped.
50///
51/// This maintains readability of bitcode from when metadata was a type of
52/// value, and these bridges were unnecessary.
53static Metadata *canonicalizeMetadataForValue(LLVMContext &Context,
54 Metadata *MD) {
55 if (!MD)
56 // !{}
57 return MDNode::get(Context, None);
58
59 // Return early if this isn't a single-operand MDNode.
60 auto *N = dyn_cast<MDNode>(MD);
61 if (!N || N->getNumOperands() != 1)
62 return MD;
63
64 if (!N->getOperand(0))
65 // !{}
66 return MDNode::get(Context, None);
67
68 if (auto *C = dyn_cast<ConstantAsMetadata>(N->getOperand(0)))
69 // Look through the MDNode.
70 return C;
71
72 return MD;
73}
74
75MetadataAsValue *MetadataAsValue::get(LLVMContext &Context, Metadata *MD) {
76 MD = canonicalizeMetadataForValue(Context, MD);
77 auto *&Entry = Context.pImpl->MetadataAsValues[MD];
78 if (!Entry)
79 Entry = new MetadataAsValue(Type::getMetadataTy(Context), MD);
80 return Entry;
81}
82
83MetadataAsValue *MetadataAsValue::getIfExists(LLVMContext &Context,
84 Metadata *MD) {
85 MD = canonicalizeMetadataForValue(Context, MD);
86 auto &Store = Context.pImpl->MetadataAsValues;
Benjamin Kramer4c1f0972015-02-08 21:56:09 +000087 return Store.lookup(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +000088}
89
90void MetadataAsValue::handleChangedMetadata(Metadata *MD) {
91 LLVMContext &Context = getContext();
92 MD = canonicalizeMetadataForValue(Context, MD);
93 auto &Store = Context.pImpl->MetadataAsValues;
94
95 // Stop tracking the old metadata.
96 Store.erase(this->MD);
97 untrack();
98 this->MD = nullptr;
99
100 // Start tracking MD, or RAUW if necessary.
101 auto *&Entry = Store[MD];
102 if (Entry) {
103 replaceAllUsesWith(Entry);
104 delete this;
105 return;
106 }
107
108 this->MD = MD;
109 track();
110 Entry = this;
111}
112
113void MetadataAsValue::track() {
114 if (MD)
115 MetadataTracking::track(&MD, *MD, *this);
116}
117
118void MetadataAsValue::untrack() {
119 if (MD)
120 MetadataTracking::untrack(MD);
121}
122
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000123bool MetadataTracking::track(void *Ref, Metadata &MD, OwnerTy Owner) {
124 assert(Ref && "Expected live reference");
125 assert((Owner || *static_cast<Metadata **>(Ref) == &MD) &&
126 "Reference without owner must be direct");
127 if (auto *R = ReplaceableMetadataImpl::get(MD)) {
128 R->addRef(Ref, Owner);
129 return true;
130 }
131 return false;
132}
133
134void MetadataTracking::untrack(void *Ref, Metadata &MD) {
135 assert(Ref && "Expected live reference");
136 if (auto *R = ReplaceableMetadataImpl::get(MD))
137 R->dropRef(Ref);
138}
139
140bool MetadataTracking::retrack(void *Ref, Metadata &MD, void *New) {
141 assert(Ref && "Expected live reference");
142 assert(New && "Expected live reference");
143 assert(Ref != New && "Expected change");
144 if (auto *R = ReplaceableMetadataImpl::get(MD)) {
145 R->moveRef(Ref, New, MD);
146 return true;
147 }
148 return false;
149}
150
151bool MetadataTracking::isReplaceable(const Metadata &MD) {
152 return ReplaceableMetadataImpl::get(const_cast<Metadata &>(MD));
153}
154
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000155void ReplaceableMetadataImpl::addRef(void *Ref, OwnerTy Owner) {
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000156 bool WasInserted =
157 UseMap.insert(std::make_pair(Ref, std::make_pair(Owner, NextIndex)))
158 .second;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000159 (void)WasInserted;
160 assert(WasInserted && "Expected to add a reference");
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000161
162 ++NextIndex;
163 assert(NextIndex != 0 && "Unexpected overflow");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000164}
165
166void ReplaceableMetadataImpl::dropRef(void *Ref) {
167 bool WasErased = UseMap.erase(Ref);
168 (void)WasErased;
169 assert(WasErased && "Expected to drop a reference");
170}
171
172void ReplaceableMetadataImpl::moveRef(void *Ref, void *New,
173 const Metadata &MD) {
174 auto I = UseMap.find(Ref);
175 assert(I != UseMap.end() && "Expected to move a reference");
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000176 auto OwnerAndIndex = I->second;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000177 UseMap.erase(I);
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000178 bool WasInserted = UseMap.insert(std::make_pair(New, OwnerAndIndex)).second;
179 (void)WasInserted;
180 assert(WasInserted && "Expected to add a reference");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000181
182 // Check that the references are direct if there's no owner.
183 (void)MD;
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000184 assert((OwnerAndIndex.first || *static_cast<Metadata **>(Ref) == &MD) &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000185 "Reference without owner must be direct");
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000186 assert((OwnerAndIndex.first || *static_cast<Metadata **>(New) == &MD) &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000187 "Reference without owner must be direct");
188}
189
190void ReplaceableMetadataImpl::replaceAllUsesWith(Metadata *MD) {
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000191 assert(!(MD && isa<MDNode>(MD) && cast<MDNode>(MD)->isTemporary()) &&
192 "Expected non-temp node");
Teresa Johnsoncc428572015-12-30 19:32:24 +0000193 assert(CanReplace &&
194 "Attempted to replace Metadata marked for no replacement");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000195
196 if (UseMap.empty())
197 return;
198
199 // Copy out uses since UseMap will get touched below.
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000200 typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
201 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
202 std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
203 return L.second.second < R.second.second;
204 });
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000205 for (const auto &Pair : Uses) {
Duncan P. N. Exon Smith4a4f7852015-01-14 19:56:10 +0000206 // Check that this Ref hasn't disappeared after RAUW (when updating a
207 // previous Ref).
208 if (!UseMap.count(Pair.first))
209 continue;
210
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000211 OwnerTy Owner = Pair.second.first;
212 if (!Owner) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000213 // Update unowned tracking references directly.
214 Metadata *&Ref = *static_cast<Metadata **>(Pair.first);
215 Ref = MD;
Duncan P. N. Exon Smith121eeff2014-12-12 19:24:33 +0000216 if (MD)
217 MetadataTracking::track(Ref);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000218 UseMap.erase(Pair.first);
219 continue;
220 }
221
222 // Check for MetadataAsValue.
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000223 if (Owner.is<MetadataAsValue *>()) {
224 Owner.get<MetadataAsValue *>()->handleChangedMetadata(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000225 continue;
226 }
227
228 // There's a Metadata owner -- dispatch.
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000229 Metadata *OwnerMD = Owner.get<Metadata *>();
230 switch (OwnerMD->getMetadataID()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000231#define HANDLE_METADATA_LEAF(CLASS) \
232 case Metadata::CLASS##Kind: \
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000233 cast<CLASS>(OwnerMD)->handleChangedOperand(Pair.first, MD); \
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000234 continue;
235#include "llvm/IR/Metadata.def"
236 default:
237 llvm_unreachable("Invalid metadata subclass");
238 }
239 }
240 assert(UseMap.empty() && "Expected all uses to be replaced");
241}
242
243void ReplaceableMetadataImpl::resolveAllUses(bool ResolveUsers) {
244 if (UseMap.empty())
245 return;
246
247 if (!ResolveUsers) {
248 UseMap.clear();
249 return;
250 }
251
252 // Copy out uses since UseMap could get touched below.
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000253 typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
254 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
255 std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
256 return L.second.second < R.second.second;
257 });
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000258 UseMap.clear();
259 for (const auto &Pair : Uses) {
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000260 auto Owner = Pair.second.first;
261 if (!Owner)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000262 continue;
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000263 if (Owner.is<MetadataAsValue *>())
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000264 continue;
265
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000266 // Resolve MDNodes that point at this.
267 auto *OwnerMD = dyn_cast<MDNode>(Owner.get<Metadata *>());
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000268 if (!OwnerMD)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000269 continue;
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000270 if (OwnerMD->isResolved())
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000271 continue;
Duncan P. N. Exon Smith34c3d102015-01-12 19:43:15 +0000272 OwnerMD->decrementUnresolvedOperandCount();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000273 }
274}
275
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000276ReplaceableMetadataImpl *ReplaceableMetadataImpl::get(Metadata &MD) {
277 if (auto *N = dyn_cast<MDNode>(&MD))
278 return N->Context.getReplaceableUses();
279 return dyn_cast<ValueAsMetadata>(&MD);
280}
281
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000282static Function *getLocalFunction(Value *V) {
283 assert(V && "Expected value");
284 if (auto *A = dyn_cast<Argument>(V))
285 return A->getParent();
286 if (BasicBlock *BB = cast<Instruction>(V)->getParent())
287 return BB->getParent();
288 return nullptr;
289}
290
291ValueAsMetadata *ValueAsMetadata::get(Value *V) {
292 assert(V && "Unexpected null Value");
293
294 auto &Context = V->getContext();
295 auto *&Entry = Context.pImpl->ValuesAsMetadata[V];
296 if (!Entry) {
297 assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
298 "Expected constant or function-local value");
Owen Anderson7349ab92015-06-01 22:24:01 +0000299 assert(!V->IsUsedByMD &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000300 "Expected this to be the only metadata use");
Owen Anderson7349ab92015-06-01 22:24:01 +0000301 V->IsUsedByMD = true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000302 if (auto *C = dyn_cast<Constant>(V))
Duncan P. N. Exon Smith1c00c9f2015-01-05 20:41:25 +0000303 Entry = new ConstantAsMetadata(C);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000304 else
Duncan P. N. Exon Smith1c00c9f2015-01-05 20:41:25 +0000305 Entry = new LocalAsMetadata(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000306 }
307
308 return Entry;
309}
310
311ValueAsMetadata *ValueAsMetadata::getIfExists(Value *V) {
312 assert(V && "Unexpected null Value");
313 return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
314}
315
316void ValueAsMetadata::handleDeletion(Value *V) {
317 assert(V && "Expected valid value");
318
319 auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
320 auto I = Store.find(V);
321 if (I == Store.end())
322 return;
323
324 // Remove old entry from the map.
325 ValueAsMetadata *MD = I->second;
326 assert(MD && "Expected valid metadata");
327 assert(MD->getValue() == V && "Expected valid mapping");
328 Store.erase(I);
329
330 // Delete the metadata.
331 MD->replaceAllUsesWith(nullptr);
332 delete MD;
333}
334
335void ValueAsMetadata::handleRAUW(Value *From, Value *To) {
336 assert(From && "Expected valid value");
337 assert(To && "Expected valid value");
338 assert(From != To && "Expected changed value");
339 assert(From->getType() == To->getType() && "Unexpected type change");
340
341 LLVMContext &Context = From->getType()->getContext();
342 auto &Store = Context.pImpl->ValuesAsMetadata;
343 auto I = Store.find(From);
344 if (I == Store.end()) {
Owen Anderson7349ab92015-06-01 22:24:01 +0000345 assert(!From->IsUsedByMD &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000346 "Expected From not to be used by metadata");
347 return;
348 }
349
350 // Remove old entry from the map.
Owen Anderson7349ab92015-06-01 22:24:01 +0000351 assert(From->IsUsedByMD &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000352 "Expected From to be used by metadata");
Owen Anderson7349ab92015-06-01 22:24:01 +0000353 From->IsUsedByMD = false;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000354 ValueAsMetadata *MD = I->second;
355 assert(MD && "Expected valid metadata");
356 assert(MD->getValue() == From && "Expected valid mapping");
357 Store.erase(I);
358
359 if (isa<LocalAsMetadata>(MD)) {
360 if (auto *C = dyn_cast<Constant>(To)) {
361 // Local became a constant.
362 MD->replaceAllUsesWith(ConstantAsMetadata::get(C));
363 delete MD;
364 return;
365 }
366 if (getLocalFunction(From) && getLocalFunction(To) &&
367 getLocalFunction(From) != getLocalFunction(To)) {
368 // Function changed.
369 MD->replaceAllUsesWith(nullptr);
370 delete MD;
371 return;
372 }
373 } else if (!isa<Constant>(To)) {
374 // Changed to function-local value.
375 MD->replaceAllUsesWith(nullptr);
376 delete MD;
377 return;
378 }
379
380 auto *&Entry = Store[To];
381 if (Entry) {
382 // The target already exists.
383 MD->replaceAllUsesWith(Entry);
384 delete MD;
385 return;
386 }
387
388 // Update MD in place (and update the map entry).
Owen Anderson7349ab92015-06-01 22:24:01 +0000389 assert(!To->IsUsedByMD &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000390 "Expected this to be the only metadata use");
Owen Anderson7349ab92015-06-01 22:24:01 +0000391 To->IsUsedByMD = true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000392 MD->V = To;
393 Entry = MD;
394}
Duncan P. N. Exon Smitha69934f2014-11-14 18:42:09 +0000395
Devang Patela4f43fb2009-07-28 21:49:47 +0000396//===----------------------------------------------------------------------===//
Chris Lattnerb0c23e82009-10-19 07:10:59 +0000397// MDString implementation.
Owen Anderson0087fe62009-07-31 21:35:40 +0000398//
Chris Lattner5a409bd2009-12-28 08:30:43 +0000399
Devang Pateldcb99d32009-10-22 00:10:15 +0000400MDString *MDString::get(LLVMContext &Context, StringRef Str) {
Duncan P. N. Exon Smithf17e7402014-11-14 01:17:09 +0000401 auto &Store = Context.pImpl->MDStringCache;
402 auto I = Store.find(Str);
403 if (I != Store.end())
404 return &I->second;
405
Duncan P. N. Exon Smith56228312014-12-09 18:52:38 +0000406 auto *Entry =
407 StringMapEntry<MDString>::Create(Str, Store.getAllocator(), MDString());
Duncan P. N. Exon Smithf17e7402014-11-14 01:17:09 +0000408 bool WasInserted = Store.insert(Entry);
409 (void)WasInserted;
410 assert(WasInserted && "Expected entry to be inserted");
Duncan P. N. Exon Smithc1a664f2014-12-05 01:41:34 +0000411 Entry->second.Entry = Entry;
Duncan P. N. Exon Smithf17e7402014-11-14 01:17:09 +0000412 return &Entry->second;
413}
414
415StringRef MDString::getString() const {
Duncan P. N. Exon Smithc1a664f2014-12-05 01:41:34 +0000416 assert(Entry && "Expected to find string map entry");
417 return Entry->first();
Owen Anderson0087fe62009-07-31 21:35:40 +0000418}
419
420//===----------------------------------------------------------------------===//
Chris Lattnerb0c23e82009-10-19 07:10:59 +0000421// MDNode implementation.
Devang Patela4f43fb2009-07-28 21:49:47 +0000422//
Chris Lattner74a6ad62009-12-28 07:41:54 +0000423
James Y Knight8096d342015-06-17 01:21:20 +0000424// Assert that the MDNode types will not be unaligned by the objects
425// prepended to them.
426#define HANDLE_MDNODE_LEAF(CLASS) \
James Y Knightf27e4412015-06-17 13:53:12 +0000427 static_assert( \
428 llvm::AlignOf<uint64_t>::Alignment >= llvm::AlignOf<CLASS>::Alignment, \
429 "Alignment is insufficient after objects prepended to " #CLASS);
James Y Knight8096d342015-06-17 01:21:20 +0000430#include "llvm/IR/Metadata.def"
431
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000432void *MDNode::operator new(size_t Size, unsigned NumOps) {
James Y Knight8096d342015-06-17 01:21:20 +0000433 size_t OpSize = NumOps * sizeof(MDOperand);
434 // uint64_t is the most aligned type we need support (ensured by static_assert
435 // above)
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000436 OpSize = alignTo(OpSize, llvm::alignOf<uint64_t>());
James Y Knight8096d342015-06-17 01:21:20 +0000437 void *Ptr = reinterpret_cast<char *>(::operator new(OpSize + Size)) + OpSize;
Duncan P. N. Exon Smith22600ff2014-12-09 23:56:39 +0000438 MDOperand *O = static_cast<MDOperand *>(Ptr);
James Y Knight8096d342015-06-17 01:21:20 +0000439 for (MDOperand *E = O - NumOps; O != E; --O)
440 (void)new (O - 1) MDOperand;
441 return Ptr;
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000442}
443
Naomi Musgrave21c1bc42015-08-31 21:06:08 +0000444void MDNode::operator delete(void *Mem) {
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000445 MDNode *N = static_cast<MDNode *>(Mem);
James Y Knight8096d342015-06-17 01:21:20 +0000446 size_t OpSize = N->NumOperands * sizeof(MDOperand);
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000447 OpSize = alignTo(OpSize, llvm::alignOf<uint64_t>());
James Y Knight8096d342015-06-17 01:21:20 +0000448
Duncan P. N. Exon Smith22600ff2014-12-09 23:56:39 +0000449 MDOperand *O = static_cast<MDOperand *>(Mem);
450 for (MDOperand *E = O - N->NumOperands; O != E; --O)
451 (O - 1)->~MDOperand();
James Y Knight8096d342015-06-17 01:21:20 +0000452 ::operator delete(reinterpret_cast<char *>(Mem) - OpSize);
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000453}
454
Duncan P. N. Exon Smithf1340452015-01-19 18:36:18 +0000455MDNode::MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
Duncan P. N. Exon Smithfed199a2015-01-20 00:01:43 +0000456 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2)
457 : Metadata(ID, Storage), NumOperands(Ops1.size() + Ops2.size()),
458 NumUnresolved(0), Context(Context) {
459 unsigned Op = 0;
460 for (Metadata *MD : Ops1)
461 setOperand(Op++, MD);
462 for (Metadata *MD : Ops2)
463 setOperand(Op++, MD);
Duncan P. N. Exon Smith2711ca72015-01-19 19:02:06 +0000464
Duncan P. N. Exon Smitha1ae4f62015-01-19 23:15:21 +0000465 if (isDistinct())
Duncan P. N. Exon Smith5e5b8502015-01-07 22:24:46 +0000466 return;
467
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000468 if (isUniqued())
469 // Check whether any operands are unresolved, requiring re-uniquing. If
470 // not, don't support RAUW.
471 if (!countUnresolvedOperands())
Duncan P. N. Exon Smitha1ae4f62015-01-19 23:15:21 +0000472 return;
473
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000474 this->Context.makeReplaceable(make_unique<ReplaceableMetadataImpl>(Context));
Devang Patela4f43fb2009-07-28 21:49:47 +0000475}
476
Duncan P. N. Exon Smith03e05832015-01-20 02:56:57 +0000477TempMDNode MDNode::clone() const {
478 switch (getMetadataID()) {
479 default:
480 llvm_unreachable("Invalid MDNode subclass");
481#define HANDLE_MDNODE_LEAF(CLASS) \
482 case CLASS##Kind: \
483 return cast<CLASS>(this)->cloneImpl();
484#include "llvm/IR/Metadata.def"
485 }
486}
487
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000488static bool isOperandUnresolved(Metadata *Op) {
489 if (auto *N = dyn_cast_or_null<MDNode>(Op))
490 return !N->isResolved();
491 return false;
492}
493
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000494unsigned MDNode::countUnresolvedOperands() {
495 assert(NumUnresolved == 0 && "Expected unresolved ops to be uncounted");
Benjamin Kramer4c1f0972015-02-08 21:56:09 +0000496 NumUnresolved = std::count_if(op_begin(), op_end(), isOperandUnresolved);
Duncan P. N. Exon Smithc5a0e2e2015-01-19 22:18:29 +0000497 return NumUnresolved;
498}
499
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000500void MDNode::makeUniqued() {
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000501 assert(isTemporary() && "Expected this to be temporary");
502 assert(!isResolved() && "Expected this to be unresolved");
503
Duncan P. N. Exon Smithcb33d6f2015-03-31 20:50:50 +0000504 // Enable uniquing callbacks.
505 for (auto &Op : mutable_operands())
506 Op.reset(Op.get(), this);
507
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000508 // Make this 'uniqued'.
509 Storage = Uniqued;
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000510 if (!countUnresolvedOperands())
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000511 resolve();
512
513 assert(isUniqued() && "Expected this to be uniqued");
514}
515
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000516void MDNode::makeDistinct() {
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000517 assert(isTemporary() && "Expected this to be temporary");
518 assert(!isResolved() && "Expected this to be unresolved");
519
520 // Pretend to be uniqued, resolve the node, and then store in distinct table.
521 Storage = Uniqued;
522 resolve();
523 storeDistinctInContext();
524
525 assert(isDistinct() && "Expected this to be distinct");
526 assert(isResolved() && "Expected this to be resolved");
527}
528
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000529void MDNode::resolve() {
Duncan P. N. Exon Smithb8f79602015-01-19 19:26:24 +0000530 assert(isUniqued() && "Expected this to be uniqued");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000531 assert(!isResolved() && "Expected this to be unresolved");
532
533 // Move the map, so that this immediately looks resolved.
Duncan P. N. Exon Smith2711ca72015-01-19 19:02:06 +0000534 auto Uses = Context.takeReplaceableUses();
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000535 NumUnresolved = 0;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000536 assert(isResolved() && "Expected this to be resolved");
537
538 // Drop RAUW support.
539 Uses->resolveAllUses();
540}
541
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000542void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000543 assert(NumUnresolved != 0 && "Expected unresolved operands");
Duncan P. N. Exon Smith3a16d802015-01-12 19:14:15 +0000544
Duncan P. N. Exon Smith0c87d772015-01-12 19:45:44 +0000545 // Check if an operand was resolved.
Duncan P. N. Exon Smith845755c42015-01-13 00:46:34 +0000546 if (!isOperandUnresolved(Old)) {
547 if (isOperandUnresolved(New))
548 // An operand was un-resolved!
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000549 ++NumUnresolved;
Duncan P. N. Exon Smith845755c42015-01-13 00:46:34 +0000550 } else if (!isOperandUnresolved(New))
Duncan P. N. Exon Smith0c87d772015-01-12 19:45:44 +0000551 decrementUnresolvedOperandCount();
Duncan P. N. Exon Smith3a16d802015-01-12 19:14:15 +0000552}
553
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000554void MDNode::decrementUnresolvedOperandCount() {
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000555 if (!--NumUnresolved)
Duncan P. N. Exon Smith0c87d772015-01-12 19:45:44 +0000556 // Last unresolved operand has just been resolved.
Duncan P. N. Exon Smith34c3d102015-01-12 19:43:15 +0000557 resolve();
558}
559
Teresa Johnsonb43257d2016-01-11 21:37:41 +0000560void MDNode::resolveRecursivelyImpl(bool AllowTemps) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000561 if (isResolved())
562 return;
563
564 // Resolve this node immediately.
565 resolve();
566
567 // Resolve all operands.
568 for (const auto &Op : operands()) {
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000569 auto *N = dyn_cast_or_null<MDNode>(Op);
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000570 if (!N)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000571 continue;
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000572
Teresa Johnson96f7f812015-12-30 21:13:55 +0000573 if (N->isTemporary() && AllowTemps)
Teresa Johnsone5a61912015-12-17 17:14:09 +0000574 continue;
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000575 assert(!N->isTemporary() &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000576 "Expected all forward declarations to be resolved");
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000577 if (!N->isResolved())
578 N->resolveCycles();
Chris Lattner8cb6c342009-12-31 01:05:46 +0000579 }
Duncan P. N. Exon Smith50846f82014-11-18 00:37:17 +0000580}
581
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000582static bool hasSelfReference(MDNode *N) {
583 for (Metadata *MD : N->operands())
584 if (MD == N)
585 return true;
586 return false;
587}
588
589MDNode *MDNode::replaceWithPermanentImpl() {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +0000590 switch (getMetadataID()) {
591 default:
592 // If this type isn't uniquable, replace with a distinct node.
593 return replaceWithDistinctImpl();
594
595#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
596 case CLASS##Kind: \
597 break;
598#include "llvm/IR/Metadata.def"
599 }
600
601 // Even if this type is uniquable, self-references have to be distinct.
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000602 if (hasSelfReference(this))
603 return replaceWithDistinctImpl();
604 return replaceWithUniquedImpl();
605}
606
Duncan P. N. Exon Smith86475292015-01-19 23:17:09 +0000607MDNode *MDNode::replaceWithUniquedImpl() {
608 // Try to uniquify in place.
609 MDNode *UniquedNode = uniquify();
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000610
Duncan P. N. Exon Smith86475292015-01-19 23:17:09 +0000611 if (UniquedNode == this) {
612 makeUniqued();
613 return this;
614 }
615
616 // Collision, so RAUW instead.
617 replaceAllUsesWith(UniquedNode);
618 deleteAsSubclass();
619 return UniquedNode;
620}
621
622MDNode *MDNode::replaceWithDistinctImpl() {
623 makeDistinct();
624 return this;
625}
626
Duncan P. N. Exon Smith118632d2015-01-12 20:09:34 +0000627void MDTuple::recalculateHash() {
Duncan P. N. Exon Smith93e983e2015-01-19 22:53:18 +0000628 setHash(MDTupleInfo::KeyTy::calculateHash(this));
Duncan P. N. Exon Smith967629e2015-01-12 19:16:34 +0000629}
630
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000631void MDNode::dropAllReferences() {
632 for (unsigned I = 0, E = NumOperands; I != E; ++I)
633 setOperand(I, nullptr);
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000634 if (!isResolved()) {
635 Context.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);
636 (void)Context.takeReplaceableUses();
637 }
Chris Lattner8cb6c342009-12-31 01:05:46 +0000638}
639
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000640void MDNode::handleChangedOperand(void *Ref, Metadata *New) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000641 unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
642 assert(Op < getNumOperands() && "Expected valid operand");
643
Duncan P. N. Exon Smith3d580562015-01-19 19:28:28 +0000644 if (!isUniqued()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000645 // This node is not uniqued. Just set the operand and be done with it.
646 setOperand(Op, New);
647 return;
Duncan Sandsc2928c62010-05-04 12:43:36 +0000648 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000649
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000650 // This node is uniqued.
651 eraseFromStore();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000652
653 Metadata *Old = getOperand(Op);
654 setOperand(Op, New);
655
Duncan P. N. Exon Smithbcd960a2015-01-05 23:31:54 +0000656 // Drop uniquing for self-reference cycles.
657 if (New == this) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000658 if (!isResolved())
659 resolve();
Duncan P. N. Exon Smithf08b8b42015-01-19 19:25:33 +0000660 storeDistinctInContext();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000661 return;
662 }
663
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000664 // Re-unique the node.
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000665 auto *Uniqued = uniquify();
666 if (Uniqued == this) {
Duncan P. N. Exon Smith3a16d802015-01-12 19:14:15 +0000667 if (!isResolved())
668 resolveAfterOperandChange(Old, New);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000669 return;
670 }
671
672 // Collision.
673 if (!isResolved()) {
674 // Still unresolved, so RAUW.
Duncan P. N. Exon Smithd9e6eb72015-01-12 19:36:35 +0000675 //
676 // First, clear out all operands to prevent any recursion (similar to
677 // dropAllReferences(), but we still need the use-list).
678 for (unsigned O = 0, E = getNumOperands(); O != E; ++O)
679 setOperand(O, nullptr);
Duncan P. N. Exon Smith2711ca72015-01-19 19:02:06 +0000680 Context.getReplaceableUses()->replaceAllUsesWith(Uniqued);
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000681 deleteAsSubclass();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000682 return;
683 }
684
Duncan P. N. Exon Smithd9e6eb72015-01-12 19:36:35 +0000685 // Store in non-uniqued form if RAUW isn't possible.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000686 storeDistinctInContext();
Victor Hernandeze5f2af72010-01-20 04:45:57 +0000687}
688
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000689void MDNode::deleteAsSubclass() {
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000690 switch (getMetadataID()) {
691 default:
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000692 llvm_unreachable("Invalid subclass of MDNode");
693#define HANDLE_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000694 case CLASS##Kind: \
695 delete cast<CLASS>(this); \
696 break;
697#include "llvm/IR/Metadata.def"
698 }
699}
700
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000701template <class T, class InfoT>
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000702static T *uniquifyImpl(T *N, DenseSet<T *, InfoT> &Store) {
703 if (T *U = getUniqued(Store, N))
704 return U;
705
706 Store.insert(N);
707 return N;
708}
709
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000710template <class NodeTy> struct MDNode::HasCachedHash {
711 typedef char Yes[1];
712 typedef char No[2];
713 template <class U, U Val> struct SFINAE {};
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000714
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000715 template <class U>
716 static Yes &check(SFINAE<void (U::*)(unsigned), &U::setHash> *);
717 template <class U> static No &check(...);
718
719 static const bool value = sizeof(check<NodeTy>(nullptr)) == sizeof(Yes);
720};
721
722MDNode *MDNode::uniquify() {
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000723 assert(!hasSelfReference(this) && "Cannot uniquify a self-referencing node");
724
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000725 // Try to insert into uniquing store.
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000726 switch (getMetadataID()) {
727 default:
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +0000728 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
729#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000730 case CLASS##Kind: { \
731 CLASS *SubclassThis = cast<CLASS>(this); \
732 std::integral_constant<bool, HasCachedHash<CLASS>::value> \
733 ShouldRecalculateHash; \
734 dispatchRecalculateHash(SubclassThis, ShouldRecalculateHash); \
735 return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s); \
736 }
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000737#include "llvm/IR/Metadata.def"
738 }
739}
740
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000741void MDNode::eraseFromStore() {
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000742 switch (getMetadataID()) {
743 default:
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +0000744 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
745#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000746 case CLASS##Kind: \
Duncan P. N. Exon Smith6cf10d22015-01-19 22:47:08 +0000747 getContext().pImpl->CLASS##s.erase(cast<CLASS>(this)); \
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000748 break;
749#include "llvm/IR/Metadata.def"
750 }
751}
752
Duncan P. N. Exon Smithac3128d2015-01-12 20:13:56 +0000753MDTuple *MDTuple::getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
Duncan P. N. Exon Smith1b0064d2015-01-19 20:14:15 +0000754 StorageType Storage, bool ShouldCreate) {
755 unsigned Hash = 0;
756 if (Storage == Uniqued) {
757 MDTupleInfo::KeyTy Key(MDs);
Duncan P. N. Exon Smithb57f9e92015-01-19 20:16:50 +0000758 if (auto *N = getUniqued(Context.pImpl->MDTuples, Key))
759 return N;
Duncan P. N. Exon Smith1b0064d2015-01-19 20:14:15 +0000760 if (!ShouldCreate)
761 return nullptr;
Duncan P. N. Exon Smith93e983e2015-01-19 22:53:18 +0000762 Hash = Key.getHash();
Duncan P. N. Exon Smith1b0064d2015-01-19 20:14:15 +0000763 } else {
764 assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
765 }
Duncan Sands26a80f32012-03-31 08:20:11 +0000766
Duncan P. N. Exon Smith5b8c4402015-01-19 20:18:13 +0000767 return storeImpl(new (MDs.size()) MDTuple(Context, Storage, Hash, MDs),
768 Storage, Context.pImpl->MDTuples);
Duncan P. N. Exon Smith5e5b8502015-01-07 22:24:46 +0000769}
770
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000771void MDNode::deleteTemporary(MDNode *N) {
772 assert(N->isTemporary() && "Expected temporary node");
Duncan P. N. Exon Smith8d536972015-01-22 21:36:45 +0000773 N->replaceAllUsesWith(nullptr);
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000774 N->deleteAsSubclass();
Dan Gohman16a5d982010-08-20 22:02:26 +0000775}
776
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000777void MDNode::storeDistinctInContext() {
Duncan P. N. Exon Smithf08b8b42015-01-19 19:25:33 +0000778 assert(isResolved() && "Expected resolved nodes");
Duncan P. N. Exon Smithf1340452015-01-19 18:36:18 +0000779 Storage = Distinct;
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000780
781 // Reset the hash.
782 switch (getMetadataID()) {
783 default:
784 llvm_unreachable("Invalid subclass of MDNode");
785#define HANDLE_MDNODE_LEAF(CLASS) \
786 case CLASS##Kind: { \
787 std::integral_constant<bool, HasCachedHash<CLASS>::value> ShouldResetHash; \
788 dispatchResetHash(cast<CLASS>(this), ShouldResetHash); \
789 break; \
790 }
791#include "llvm/IR/Metadata.def"
792 }
793
Duncan P. N. Exon Smithde03ff52015-01-13 20:44:56 +0000794 getContext().pImpl->DistinctMDNodes.insert(this);
Devang Patel82ab3f82010-02-18 20:53:16 +0000795}
Chris Lattnerf543eff2009-12-28 09:12:35 +0000796
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000797void MDNode::replaceOperandWith(unsigned I, Metadata *New) {
798 if (getOperand(I) == New)
Devang Patelf7188322009-09-03 01:39:20 +0000799 return;
Devang Patelf7188322009-09-03 01:39:20 +0000800
Duncan P. N. Exon Smithde03a8b2015-01-19 18:45:35 +0000801 if (!isUniqued()) {
Duncan P. N. Exon Smithdaa335a2015-01-12 18:01:45 +0000802 setOperand(I, New);
Duncan P. N. Exon Smithf39c3b82014-11-17 23:28:21 +0000803 return;
804 }
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +0000805
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000806 handleChangedOperand(mutable_begin() + I, New);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000807}
Chris Lattnerc6d17e22009-12-28 09:24:53 +0000808
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000809void MDNode::setOperand(unsigned I, Metadata *New) {
810 assert(I < NumOperands);
Duncan P. N. Exon Smithefdf2852015-01-19 19:29:25 +0000811 mutable_begin()[I].reset(New, isUniqued() ? this : nullptr);
Devang Patelf7188322009-09-03 01:39:20 +0000812}
813
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000814/// \brief Get a node, or a self-reference that looks like it.
815///
816/// Special handling for finding self-references, for use by \a
817/// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
818/// when self-referencing nodes were still uniqued. If the first operand has
819/// the same operands as \c Ops, return the first operand instead.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000820static MDNode *getOrSelfReference(LLVMContext &Context,
821 ArrayRef<Metadata *> Ops) {
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000822 if (!Ops.empty())
823 if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))
824 if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
825 for (unsigned I = 1, E = Ops.size(); I != E; ++I)
826 if (Ops[I] != N->getOperand(I))
827 return MDNode::get(Context, Ops);
828 return N;
829 }
830
831 return MDNode::get(Context, Ops);
832}
833
Hal Finkel94146652014-07-24 14:25:39 +0000834MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {
835 if (!A)
836 return B;
837 if (!B)
838 return A;
839
Benjamin Kramer4c1f0972015-02-08 21:56:09 +0000840 SmallVector<Metadata *, 4> MDs;
841 MDs.reserve(A->getNumOperands() + B->getNumOperands());
842 MDs.append(A->op_begin(), A->op_end());
843 MDs.append(B->op_begin(), B->op_end());
Hal Finkel94146652014-07-24 14:25:39 +0000844
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000845 // FIXME: This preserves long-standing behaviour, but is it really the right
846 // behaviour? Or was that an unintended side-effect of node uniquing?
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000847 return getOrSelfReference(A->getContext(), MDs);
Hal Finkel94146652014-07-24 14:25:39 +0000848}
849
850MDNode *MDNode::intersect(MDNode *A, MDNode *B) {
851 if (!A || !B)
852 return nullptr;
853
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000854 SmallVector<Metadata *, 4> MDs;
Benjamin Kramer4c1f0972015-02-08 21:56:09 +0000855 for (Metadata *MD : A->operands())
856 if (std::find(B->op_begin(), B->op_end(), MD) != B->op_end())
857 MDs.push_back(MD);
Hal Finkel94146652014-07-24 14:25:39 +0000858
Duncan P. N. Exon Smithac8ee282014-12-07 19:52:06 +0000859 // FIXME: This preserves long-standing behaviour, but is it really the right
860 // behaviour? Or was that an unintended side-effect of node uniquing?
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000861 return getOrSelfReference(A->getContext(), MDs);
Hal Finkel94146652014-07-24 14:25:39 +0000862}
863
Bjorn Steinbrink5ec75222015-02-08 17:07:14 +0000864MDNode *MDNode::getMostGenericAliasScope(MDNode *A, MDNode *B) {
865 if (!A || !B)
866 return nullptr;
867
868 SmallVector<Metadata *, 4> MDs(B->op_begin(), B->op_end());
Benjamin Kramer4c1f0972015-02-08 21:56:09 +0000869 for (Metadata *MD : A->operands())
870 if (std::find(B->op_begin(), B->op_end(), MD) == B->op_end())
871 MDs.push_back(MD);
Bjorn Steinbrink5ec75222015-02-08 17:07:14 +0000872
873 // FIXME: This preserves long-standing behaviour, but is it really the right
874 // behaviour? Or was that an unintended side-effect of node uniquing?
875 return getOrSelfReference(A->getContext(), MDs);
876}
877
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000878MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
879 if (!A || !B)
Craig Topperc6207612014-04-09 06:08:46 +0000880 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000881
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000882 APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
883 APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000884 if (AVal.compare(BVal) == APFloat::cmpLessThan)
885 return A;
886 return B;
887}
888
889static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
890 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
891}
892
893static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
894 return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
895}
896
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000897static bool tryMergeRange(SmallVectorImpl<ConstantInt *> &EndPoints,
898 ConstantInt *Low, ConstantInt *High) {
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000899 ConstantRange NewRange(Low->getValue(), High->getValue());
900 unsigned Size = EndPoints.size();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000901 APInt LB = EndPoints[Size - 2]->getValue();
902 APInt LE = EndPoints[Size - 1]->getValue();
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000903 ConstantRange LastRange(LB, LE);
904 if (canBeMerged(NewRange, LastRange)) {
905 ConstantRange Union = LastRange.unionWith(NewRange);
906 Type *Ty = High->getType();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000907 EndPoints[Size - 2] =
908 cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
909 EndPoints[Size - 1] =
910 cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000911 return true;
912 }
913 return false;
914}
915
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000916static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,
917 ConstantInt *Low, ConstantInt *High) {
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000918 if (!EndPoints.empty())
919 if (tryMergeRange(EndPoints, Low, High))
920 return;
921
922 EndPoints.push_back(Low);
923 EndPoints.push_back(High);
924}
925
926MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
927 // Given two ranges, we want to compute the union of the ranges. This
928 // is slightly complitade by having to combine the intervals and merge
929 // the ones that overlap.
930
931 if (!A || !B)
Craig Topperc6207612014-04-09 06:08:46 +0000932 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000933
934 if (A == B)
935 return A;
936
937 // First, walk both lists in older of the lower boundary of each interval.
938 // At each step, try to merge the new interval to the last one we adedd.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000939 SmallVector<ConstantInt *, 4> EndPoints;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000940 int AI = 0;
941 int BI = 0;
942 int AN = A->getNumOperands() / 2;
943 int BN = B->getNumOperands() / 2;
944 while (AI < AN && BI < BN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000945 ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
946 ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000947
948 if (ALow->getValue().slt(BLow->getValue())) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000949 addRange(EndPoints, ALow,
950 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000951 ++AI;
952 } else {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000953 addRange(EndPoints, BLow,
954 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000955 ++BI;
956 }
957 }
958 while (AI < AN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000959 addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
960 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000961 ++AI;
962 }
963 while (BI < BN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000964 addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
965 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000966 ++BI;
967 }
968
969 // If we have more than 2 ranges (4 endpoints) we have to try to merge
970 // the last and first ones.
971 unsigned Size = EndPoints.size();
972 if (Size > 4) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000973 ConstantInt *FB = EndPoints[0];
974 ConstantInt *FE = EndPoints[1];
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000975 if (tryMergeRange(EndPoints, FB, FE)) {
976 for (unsigned i = 0; i < Size - 2; ++i) {
977 EndPoints[i] = EndPoints[i + 2];
978 }
979 EndPoints.resize(Size - 2);
980 }
981 }
982
983 // If in the end we have a single range, it is possible that it is now the
984 // full range. Just drop the metadata in that case.
985 if (EndPoints.size() == 2) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000986 ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000987 if (Range.isFullSet())
Craig Topperc6207612014-04-09 06:08:46 +0000988 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000989 }
990
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000991 SmallVector<Metadata *, 4> MDs;
992 MDs.reserve(EndPoints.size());
993 for (auto *I : EndPoints)
994 MDs.push_back(ConstantAsMetadata::get(I));
995 return MDNode::get(A->getContext(), MDs);
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000996}
997
Artur Pilipenko5c5011d2015-11-02 17:53:51 +0000998MDNode *MDNode::getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B) {
999 if (!A || !B)
1000 return nullptr;
1001
1002 ConstantInt *AVal = mdconst::extract<ConstantInt>(A->getOperand(0));
1003 ConstantInt *BVal = mdconst::extract<ConstantInt>(B->getOperand(0));
1004 if (AVal->getZExtValue() < BVal->getZExtValue())
1005 return A;
1006 return B;
1007}
1008
Devang Patel05a26fb2009-07-29 00:33:07 +00001009//===----------------------------------------------------------------------===//
Chris Lattnerb0c23e82009-10-19 07:10:59 +00001010// NamedMDNode implementation.
Devang Patel05a26fb2009-07-29 00:33:07 +00001011//
Devang Patel943ddf62010-01-12 18:34:06 +00001012
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001013static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
1014 return *(SmallVector<TrackingMDRef, 4> *)Operands;
Chris Lattner1bc810b2009-12-28 08:07:14 +00001015}
1016
Dan Gohman2637cc12010-07-21 23:38:33 +00001017NamedMDNode::NamedMDNode(const Twine &N)
Duncan P. N. Exon Smithc5754a62014-11-05 18:16:03 +00001018 : Name(N.str()), Parent(nullptr),
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001019 Operands(new SmallVector<TrackingMDRef, 4>()) {}
Devang Patel5c310be2009-08-11 18:01:24 +00001020
Chris Lattner1bc810b2009-12-28 08:07:14 +00001021NamedMDNode::~NamedMDNode() {
1022 dropAllReferences();
1023 delete &getNMDOps(Operands);
1024}
1025
Chris Lattner9b493022009-12-31 01:22:29 +00001026unsigned NamedMDNode::getNumOperands() const {
Chris Lattner1bc810b2009-12-28 08:07:14 +00001027 return (unsigned)getNMDOps(Operands).size();
1028}
1029
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001030MDNode *NamedMDNode::getOperand(unsigned i) const {
Chris Lattner9b493022009-12-31 01:22:29 +00001031 assert(i < getNumOperands() && "Invalid Operand number!");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001032 auto *N = getNMDOps(Operands)[i].get();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001033 return cast_or_null<MDNode>(N);
Chris Lattner1bc810b2009-12-28 08:07:14 +00001034}
1035
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001036void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
Chris Lattner1bc810b2009-12-28 08:07:14 +00001037
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001038void NamedMDNode::setOperand(unsigned I, MDNode *New) {
1039 assert(I < getNumOperands() && "Invalid operand number");
1040 getNMDOps(Operands)[I].reset(New);
1041}
1042
Devang Patel79238d72009-08-03 06:19:01 +00001043void NamedMDNode::eraseFromParent() {
Dan Gohman2637cc12010-07-21 23:38:33 +00001044 getParent()->eraseNamedMetadata(this);
Devang Patel79238d72009-08-03 06:19:01 +00001045}
1046
Devang Patel79238d72009-08-03 06:19:01 +00001047void NamedMDNode::dropAllReferences() {
Chris Lattner1bc810b2009-12-28 08:07:14 +00001048 getNMDOps(Operands).clear();
Devang Patel79238d72009-08-03 06:19:01 +00001049}
1050
Devang Patelfcfee0f2010-01-07 19:39:36 +00001051StringRef NamedMDNode::getName() const {
1052 return StringRef(Name);
1053}
Devang Pateld5497a4b2009-09-16 18:09:00 +00001054
1055//===----------------------------------------------------------------------===//
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001056// Instruction Metadata method implementations.
1057//
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001058void MDAttachmentMap::set(unsigned ID, MDNode &MD) {
1059 for (auto &I : Attachments)
1060 if (I.first == ID) {
1061 I.second.reset(&MD);
1062 return;
1063 }
1064 Attachments.emplace_back(std::piecewise_construct, std::make_tuple(ID),
1065 std::make_tuple(&MD));
1066}
1067
1068void MDAttachmentMap::erase(unsigned ID) {
1069 if (empty())
1070 return;
1071
1072 // Common case is one/last value.
1073 if (Attachments.back().first == ID) {
1074 Attachments.pop_back();
1075 return;
1076 }
1077
1078 for (auto I = Attachments.begin(), E = std::prev(Attachments.end()); I != E;
1079 ++I)
1080 if (I->first == ID) {
1081 *I = std::move(Attachments.back());
1082 Attachments.pop_back();
1083 return;
1084 }
1085}
1086
1087MDNode *MDAttachmentMap::lookup(unsigned ID) const {
1088 for (const auto &I : Attachments)
1089 if (I.first == ID)
1090 return I.second;
1091 return nullptr;
1092}
1093
1094void MDAttachmentMap::getAll(
1095 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1096 Result.append(Attachments.begin(), Attachments.end());
1097
1098 // Sort the resulting array so it is stable.
1099 if (Result.size() > 1)
1100 array_pod_sort(Result.begin(), Result.end());
1101}
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001102
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001103void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
1104 if (!Node && !hasMetadata())
1105 return;
1106 setMetadata(getContext().getMDKindID(Kind), Node);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001107}
1108
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001109MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
Chris Lattnera0566972009-12-29 09:01:33 +00001110 return getMetadataImpl(getContext().getMDKindID(Kind));
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001111}
1112
Adrian Prantlcbdfdb72015-08-20 22:00:30 +00001113void Instruction::dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs) {
Rafael Espindolaab73c492014-01-28 16:56:46 +00001114 SmallSet<unsigned, 5> KnownSet;
1115 KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
1116
Rafael Espindolaab73c492014-01-28 16:56:46 +00001117 if (!hasMetadataHashEntry())
1118 return; // Nothing to remove!
1119
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001120 auto &InstructionMetadata = getContext().pImpl->InstructionMetadata;
Rafael Espindolaab73c492014-01-28 16:56:46 +00001121
1122 if (KnownSet.empty()) {
1123 // Just drop our entry at the store.
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001124 InstructionMetadata.erase(this);
Rafael Espindolaab73c492014-01-28 16:56:46 +00001125 setHasMetadataHashEntry(false);
1126 return;
1127 }
1128
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001129 auto &Info = InstructionMetadata[this];
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001130 Info.remove_if([&KnownSet](const std::pair<unsigned, TrackingMDNodeRef> &I) {
1131 return !KnownSet.count(I.first);
1132 });
Rafael Espindolaab73c492014-01-28 16:56:46 +00001133
Duncan P. N. Exon Smith75ef0c02015-04-24 20:23:44 +00001134 if (Info.empty()) {
Rafael Espindolaab73c492014-01-28 16:56:46 +00001135 // Drop our entry at the store.
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001136 InstructionMetadata.erase(this);
Rafael Espindolaab73c492014-01-28 16:56:46 +00001137 setHasMetadataHashEntry(false);
1138 }
1139}
1140
Sanjay Patel942b46a2015-08-24 23:18:44 +00001141/// setMetadata - Set the metadata of the specified kind to the specified
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001142/// node. This updates/replaces metadata if already present, or removes it if
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001143/// Node is null.
1144void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
1145 if (!Node && !hasMetadata())
1146 return;
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001147
Chris Lattnerc263b422010-03-30 23:03:27 +00001148 // Handle 'dbg' as a special case since it is not stored in the hash table.
1149 if (KindID == LLVMContext::MD_dbg) {
Duncan P. N. Exon Smithab659fb32015-03-30 19:40:05 +00001150 DbgLoc = DebugLoc(Node);
Chris Lattnerc263b422010-03-30 23:03:27 +00001151 return;
1152 }
1153
Chris Lattnera0566972009-12-29 09:01:33 +00001154 // Handle the case when we're adding/updating metadata on an instruction.
1155 if (Node) {
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001156 auto &Info = getContext().pImpl->InstructionMetadata[this];
Chris Lattnerc263b422010-03-30 23:03:27 +00001157 assert(!Info.empty() == hasMetadataHashEntry() &&
1158 "HasMetadata bit is wonked");
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001159 if (Info.empty())
Chris Lattnerc263b422010-03-30 23:03:27 +00001160 setHasMetadataHashEntry(true);
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001161 Info.set(KindID, *Node);
Chris Lattnera0566972009-12-29 09:01:33 +00001162 return;
1163 }
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001164
Chris Lattnera0566972009-12-29 09:01:33 +00001165 // Otherwise, we're removing metadata from an instruction.
Nick Lewycky4c131382011-12-27 01:17:40 +00001166 assert((hasMetadataHashEntry() ==
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001167 (getContext().pImpl->InstructionMetadata.count(this) > 0)) &&
Chris Lattnera0566972009-12-29 09:01:33 +00001168 "HasMetadata bit out of date!");
Nick Lewycky4c131382011-12-27 01:17:40 +00001169 if (!hasMetadataHashEntry())
1170 return; // Nothing to remove!
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001171 auto &Info = getContext().pImpl->InstructionMetadata[this];
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001172
Chris Lattnerc263b422010-03-30 23:03:27 +00001173 // Handle removal of an existing value.
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001174 Info.erase(KindID);
1175
1176 if (!Info.empty())
1177 return;
1178
1179 getContext().pImpl->InstructionMetadata.erase(this);
1180 setHasMetadataHashEntry(false);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001181}
1182
Hal Finkelcc39b672014-07-24 12:16:19 +00001183void Instruction::setAAMetadata(const AAMDNodes &N) {
1184 setMetadata(LLVMContext::MD_tbaa, N.TBAA);
Hal Finkel94146652014-07-24 14:25:39 +00001185 setMetadata(LLVMContext::MD_alias_scope, N.Scope);
1186 setMetadata(LLVMContext::MD_noalias, N.NoAlias);
Hal Finkelcc39b672014-07-24 12:16:19 +00001187}
1188
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001189MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
Chris Lattnerc263b422010-03-30 23:03:27 +00001190 // Handle 'dbg' as a special case since it is not stored in the hash table.
1191 if (KindID == LLVMContext::MD_dbg)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001192 return DbgLoc.getAsMDNode();
1193
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001194 if (!hasMetadataHashEntry())
1195 return nullptr;
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001196 auto &Info = getContext().pImpl->InstructionMetadata[this];
Chris Lattnerc263b422010-03-30 23:03:27 +00001197 assert(!Info.empty() && "bit out of sync with hash table");
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001198
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001199 return Info.lookup(KindID);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001200}
1201
Duncan P. N. Exon Smith4abd1a02014-11-01 00:26:42 +00001202void Instruction::getAllMetadataImpl(
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001203 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
Chris Lattnerc263b422010-03-30 23:03:27 +00001204 Result.clear();
1205
1206 // Handle 'dbg' as a special case since it is not stored in the hash table.
Duncan P. N. Exon Smithab659fb32015-03-30 19:40:05 +00001207 if (DbgLoc) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001208 Result.push_back(
1209 std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
Chris Lattnerc263b422010-03-30 23:03:27 +00001210 if (!hasMetadataHashEntry()) return;
1211 }
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001212
Chris Lattnerc263b422010-03-30 23:03:27 +00001213 assert(hasMetadataHashEntry() &&
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001214 getContext().pImpl->InstructionMetadata.count(this) &&
Chris Lattnera0566972009-12-29 09:01:33 +00001215 "Shouldn't have called this");
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001216 const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
Chris Lattnera0566972009-12-29 09:01:33 +00001217 assert(!Info.empty() && "Shouldn't have called this");
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001218 Info.getAll(Result);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001219}
1220
Duncan P. N. Exon Smith3d5a02f2014-11-03 18:13:57 +00001221void Instruction::getAllMetadataOtherThanDebugLocImpl(
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001222 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001223 Result.clear();
1224 assert(hasMetadataHashEntry() &&
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001225 getContext().pImpl->InstructionMetadata.count(this) &&
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001226 "Shouldn't have called this");
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001227 const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001228 assert(!Info.empty() && "Shouldn't have called this");
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001229 Info.getAll(Result);
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001230}
1231
Dan Gohman48a995f2010-07-20 22:25:04 +00001232/// clearMetadataHashEntries - Clear all hashtable-based metadata from
1233/// this instruction.
1234void Instruction::clearMetadataHashEntries() {
1235 assert(hasMetadataHashEntry() && "Caller should check");
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001236 getContext().pImpl->InstructionMetadata.erase(this);
Dan Gohman48a995f2010-07-20 22:25:04 +00001237 setHasMetadataHashEntry(false);
Chris Lattner68017802009-12-29 07:44:16 +00001238}
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001239
1240MDNode *Function::getMetadata(unsigned KindID) const {
1241 if (!hasMetadata())
1242 return nullptr;
1243 return getContext().pImpl->FunctionMetadata[this].lookup(KindID);
1244}
1245
1246MDNode *Function::getMetadata(StringRef Kind) const {
1247 if (!hasMetadata())
1248 return nullptr;
1249 return getMetadata(getContext().getMDKindID(Kind));
1250}
1251
1252void Function::setMetadata(unsigned KindID, MDNode *MD) {
1253 if (MD) {
1254 if (!hasMetadata())
1255 setHasMetadataHashEntry(true);
1256
1257 getContext().pImpl->FunctionMetadata[this].set(KindID, *MD);
1258 return;
1259 }
1260
1261 // Nothing to unset.
1262 if (!hasMetadata())
1263 return;
1264
1265 auto &Store = getContext().pImpl->FunctionMetadata[this];
1266 Store.erase(KindID);
1267 if (Store.empty())
1268 clearMetadata();
1269}
1270
1271void Function::setMetadata(StringRef Kind, MDNode *MD) {
1272 if (!MD && !hasMetadata())
1273 return;
1274 setMetadata(getContext().getMDKindID(Kind), MD);
1275}
1276
1277void Function::getAllMetadata(
1278 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
1279 MDs.clear();
1280
1281 if (!hasMetadata())
1282 return;
1283
1284 getContext().pImpl->FunctionMetadata[this].getAll(MDs);
1285}
1286
1287void Function::dropUnknownMetadata(ArrayRef<unsigned> KnownIDs) {
1288 if (!hasMetadata())
1289 return;
1290 if (KnownIDs.empty()) {
1291 clearMetadata();
1292 return;
1293 }
1294
1295 SmallSet<unsigned, 5> KnownSet;
1296 KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
1297
1298 auto &Store = getContext().pImpl->FunctionMetadata[this];
1299 assert(!Store.empty());
1300
1301 Store.remove_if([&KnownSet](const std::pair<unsigned, TrackingMDNodeRef> &I) {
1302 return !KnownSet.count(I.first);
1303 });
1304
1305 if (Store.empty())
1306 clearMetadata();
1307}
1308
1309void Function::clearMetadata() {
1310 if (!hasMetadata())
1311 return;
1312 getContext().pImpl->FunctionMetadata.erase(this);
1313 setHasMetadataHashEntry(false);
1314}
Duncan P. N. Exon Smithb56b5af2015-08-28 21:55:35 +00001315
1316void Function::setSubprogram(DISubprogram *SP) {
1317 setMetadata(LLVMContext::MD_dbg, SP);
1318}
1319
1320DISubprogram *Function::getSubprogram() const {
1321 return cast_or_null<DISubprogram>(getMetadata(LLVMContext::MD_dbg));
1322}