blob: ab1ba5e2035bc6ff3bed2439d4a0dc7c9083c983 [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");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000193
194 if (UseMap.empty())
195 return;
196
197 // Copy out uses since UseMap will get touched below.
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000198 typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
199 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
200 std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
201 return L.second.second < R.second.second;
202 });
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000203 for (const auto &Pair : Uses) {
Duncan P. N. Exon Smith4a4f7852015-01-14 19:56:10 +0000204 // Check that this Ref hasn't disappeared after RAUW (when updating a
205 // previous Ref).
206 if (!UseMap.count(Pair.first))
207 continue;
208
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000209 OwnerTy Owner = Pair.second.first;
210 if (!Owner) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000211 // Update unowned tracking references directly.
212 Metadata *&Ref = *static_cast<Metadata **>(Pair.first);
213 Ref = MD;
Duncan P. N. Exon Smith121eeff2014-12-12 19:24:33 +0000214 if (MD)
215 MetadataTracking::track(Ref);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000216 UseMap.erase(Pair.first);
217 continue;
218 }
219
220 // Check for MetadataAsValue.
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000221 if (Owner.is<MetadataAsValue *>()) {
222 Owner.get<MetadataAsValue *>()->handleChangedMetadata(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000223 continue;
224 }
225
226 // There's a Metadata owner -- dispatch.
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000227 Metadata *OwnerMD = Owner.get<Metadata *>();
228 switch (OwnerMD->getMetadataID()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000229#define HANDLE_METADATA_LEAF(CLASS) \
230 case Metadata::CLASS##Kind: \
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000231 cast<CLASS>(OwnerMD)->handleChangedOperand(Pair.first, MD); \
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000232 continue;
233#include "llvm/IR/Metadata.def"
234 default:
235 llvm_unreachable("Invalid metadata subclass");
236 }
237 }
238 assert(UseMap.empty() && "Expected all uses to be replaced");
239}
240
241void ReplaceableMetadataImpl::resolveAllUses(bool ResolveUsers) {
242 if (UseMap.empty())
243 return;
244
245 if (!ResolveUsers) {
246 UseMap.clear();
247 return;
248 }
249
250 // Copy out uses since UseMap could get touched below.
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000251 typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
252 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
253 std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
254 return L.second.second < R.second.second;
255 });
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000256 UseMap.clear();
257 for (const auto &Pair : Uses) {
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000258 auto Owner = Pair.second.first;
259 if (!Owner)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000260 continue;
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000261 if (Owner.is<MetadataAsValue *>())
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000262 continue;
263
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000264 // Resolve MDNodes that point at this.
265 auto *OwnerMD = dyn_cast<MDNode>(Owner.get<Metadata *>());
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000266 if (!OwnerMD)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000267 continue;
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000268 if (OwnerMD->isResolved())
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000269 continue;
Duncan P. N. Exon Smith34c3d102015-01-12 19:43:15 +0000270 OwnerMD->decrementUnresolvedOperandCount();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000271 }
272}
273
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000274ReplaceableMetadataImpl *ReplaceableMetadataImpl::get(Metadata &MD) {
275 if (auto *N = dyn_cast<MDNode>(&MD))
276 return N->Context.getReplaceableUses();
277 return dyn_cast<ValueAsMetadata>(&MD);
278}
279
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000280static Function *getLocalFunction(Value *V) {
281 assert(V && "Expected value");
282 if (auto *A = dyn_cast<Argument>(V))
283 return A->getParent();
284 if (BasicBlock *BB = cast<Instruction>(V)->getParent())
285 return BB->getParent();
286 return nullptr;
287}
288
289ValueAsMetadata *ValueAsMetadata::get(Value *V) {
290 assert(V && "Unexpected null Value");
291
292 auto &Context = V->getContext();
293 auto *&Entry = Context.pImpl->ValuesAsMetadata[V];
294 if (!Entry) {
295 assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
296 "Expected constant or function-local value");
Owen Anderson7349ab92015-06-01 22:24:01 +0000297 assert(!V->IsUsedByMD &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000298 "Expected this to be the only metadata use");
Owen Anderson7349ab92015-06-01 22:24:01 +0000299 V->IsUsedByMD = true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000300 if (auto *C = dyn_cast<Constant>(V))
Duncan P. N. Exon Smith1c00c9f2015-01-05 20:41:25 +0000301 Entry = new ConstantAsMetadata(C);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000302 else
Duncan P. N. Exon Smith1c00c9f2015-01-05 20:41:25 +0000303 Entry = new LocalAsMetadata(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000304 }
305
306 return Entry;
307}
308
309ValueAsMetadata *ValueAsMetadata::getIfExists(Value *V) {
310 assert(V && "Unexpected null Value");
311 return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
312}
313
314void ValueAsMetadata::handleDeletion(Value *V) {
315 assert(V && "Expected valid value");
316
317 auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
318 auto I = Store.find(V);
319 if (I == Store.end())
320 return;
321
322 // Remove old entry from the map.
323 ValueAsMetadata *MD = I->second;
324 assert(MD && "Expected valid metadata");
325 assert(MD->getValue() == V && "Expected valid mapping");
326 Store.erase(I);
327
328 // Delete the metadata.
329 MD->replaceAllUsesWith(nullptr);
330 delete MD;
331}
332
333void ValueAsMetadata::handleRAUW(Value *From, Value *To) {
334 assert(From && "Expected valid value");
335 assert(To && "Expected valid value");
336 assert(From != To && "Expected changed value");
337 assert(From->getType() == To->getType() && "Unexpected type change");
338
339 LLVMContext &Context = From->getType()->getContext();
340 auto &Store = Context.pImpl->ValuesAsMetadata;
341 auto I = Store.find(From);
342 if (I == Store.end()) {
Owen Anderson7349ab92015-06-01 22:24:01 +0000343 assert(!From->IsUsedByMD &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000344 "Expected From not to be used by metadata");
345 return;
346 }
347
348 // Remove old entry from the map.
Owen Anderson7349ab92015-06-01 22:24:01 +0000349 assert(From->IsUsedByMD &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000350 "Expected From to be used by metadata");
Owen Anderson7349ab92015-06-01 22:24:01 +0000351 From->IsUsedByMD = false;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000352 ValueAsMetadata *MD = I->second;
353 assert(MD && "Expected valid metadata");
354 assert(MD->getValue() == From && "Expected valid mapping");
355 Store.erase(I);
356
357 if (isa<LocalAsMetadata>(MD)) {
358 if (auto *C = dyn_cast<Constant>(To)) {
359 // Local became a constant.
360 MD->replaceAllUsesWith(ConstantAsMetadata::get(C));
361 delete MD;
362 return;
363 }
364 if (getLocalFunction(From) && getLocalFunction(To) &&
365 getLocalFunction(From) != getLocalFunction(To)) {
366 // Function changed.
367 MD->replaceAllUsesWith(nullptr);
368 delete MD;
369 return;
370 }
371 } else if (!isa<Constant>(To)) {
372 // Changed to function-local value.
373 MD->replaceAllUsesWith(nullptr);
374 delete MD;
375 return;
376 }
377
378 auto *&Entry = Store[To];
379 if (Entry) {
380 // The target already exists.
381 MD->replaceAllUsesWith(Entry);
382 delete MD;
383 return;
384 }
385
386 // Update MD in place (and update the map entry).
Owen Anderson7349ab92015-06-01 22:24:01 +0000387 assert(!To->IsUsedByMD &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000388 "Expected this to be the only metadata use");
Owen Anderson7349ab92015-06-01 22:24:01 +0000389 To->IsUsedByMD = true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000390 MD->V = To;
391 Entry = MD;
392}
Duncan P. N. Exon Smitha69934f2014-11-14 18:42:09 +0000393
Devang Patela4f43fb2009-07-28 21:49:47 +0000394//===----------------------------------------------------------------------===//
Chris Lattnerb0c23e82009-10-19 07:10:59 +0000395// MDString implementation.
Owen Anderson0087fe62009-07-31 21:35:40 +0000396//
Chris Lattner5a409bd2009-12-28 08:30:43 +0000397
Devang Pateldcb99d32009-10-22 00:10:15 +0000398MDString *MDString::get(LLVMContext &Context, StringRef Str) {
Duncan P. N. Exon Smithf17e7402014-11-14 01:17:09 +0000399 auto &Store = Context.pImpl->MDStringCache;
400 auto I = Store.find(Str);
401 if (I != Store.end())
402 return &I->second;
403
Duncan P. N. Exon Smith56228312014-12-09 18:52:38 +0000404 auto *Entry =
405 StringMapEntry<MDString>::Create(Str, Store.getAllocator(), MDString());
Duncan P. N. Exon Smithf17e7402014-11-14 01:17:09 +0000406 bool WasInserted = Store.insert(Entry);
407 (void)WasInserted;
408 assert(WasInserted && "Expected entry to be inserted");
Duncan P. N. Exon Smithc1a664f2014-12-05 01:41:34 +0000409 Entry->second.Entry = Entry;
Duncan P. N. Exon Smithf17e7402014-11-14 01:17:09 +0000410 return &Entry->second;
411}
412
413StringRef MDString::getString() const {
Duncan P. N. Exon Smithc1a664f2014-12-05 01:41:34 +0000414 assert(Entry && "Expected to find string map entry");
415 return Entry->first();
Owen Anderson0087fe62009-07-31 21:35:40 +0000416}
417
418//===----------------------------------------------------------------------===//
Chris Lattnerb0c23e82009-10-19 07:10:59 +0000419// MDNode implementation.
Devang Patela4f43fb2009-07-28 21:49:47 +0000420//
Chris Lattner74a6ad62009-12-28 07:41:54 +0000421
James Y Knight8096d342015-06-17 01:21:20 +0000422// Assert that the MDNode types will not be unaligned by the objects
423// prepended to them.
424#define HANDLE_MDNODE_LEAF(CLASS) \
James Y Knightf27e4412015-06-17 13:53:12 +0000425 static_assert( \
426 llvm::AlignOf<uint64_t>::Alignment >= llvm::AlignOf<CLASS>::Alignment, \
427 "Alignment is insufficient after objects prepended to " #CLASS);
James Y Knight8096d342015-06-17 01:21:20 +0000428#include "llvm/IR/Metadata.def"
429
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000430void *MDNode::operator new(size_t Size, unsigned NumOps) {
James Y Knight8096d342015-06-17 01:21:20 +0000431 size_t OpSize = NumOps * sizeof(MDOperand);
432 // uint64_t is the most aligned type we need support (ensured by static_assert
433 // above)
434 OpSize = RoundUpToAlignment(OpSize, llvm::alignOf<uint64_t>());
435 void *Ptr = reinterpret_cast<char *>(::operator new(OpSize + Size)) + OpSize;
Duncan P. N. Exon Smith22600ff2014-12-09 23:56:39 +0000436 MDOperand *O = static_cast<MDOperand *>(Ptr);
James Y Knight8096d342015-06-17 01:21:20 +0000437 for (MDOperand *E = O - NumOps; O != E; --O)
438 (void)new (O - 1) MDOperand;
439 return Ptr;
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000440}
441
Naomi Musgrave21c1bc42015-08-31 21:06:08 +0000442void MDNode::operator delete(void *Mem) {
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000443 MDNode *N = static_cast<MDNode *>(Mem);
James Y Knight8096d342015-06-17 01:21:20 +0000444 size_t OpSize = N->NumOperands * sizeof(MDOperand);
445 OpSize = RoundUpToAlignment(OpSize, llvm::alignOf<uint64_t>());
446
Duncan P. N. Exon Smith22600ff2014-12-09 23:56:39 +0000447 MDOperand *O = static_cast<MDOperand *>(Mem);
448 for (MDOperand *E = O - N->NumOperands; O != E; --O)
449 (O - 1)->~MDOperand();
James Y Knight8096d342015-06-17 01:21:20 +0000450 ::operator delete(reinterpret_cast<char *>(Mem) - OpSize);
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000451}
452
Duncan P. N. Exon Smithf1340452015-01-19 18:36:18 +0000453MDNode::MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
Duncan P. N. Exon Smithfed199a2015-01-20 00:01:43 +0000454 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2)
455 : Metadata(ID, Storage), NumOperands(Ops1.size() + Ops2.size()),
456 NumUnresolved(0), Context(Context) {
457 unsigned Op = 0;
458 for (Metadata *MD : Ops1)
459 setOperand(Op++, MD);
460 for (Metadata *MD : Ops2)
461 setOperand(Op++, MD);
Duncan P. N. Exon Smith2711ca72015-01-19 19:02:06 +0000462
Duncan P. N. Exon Smitha1ae4f62015-01-19 23:15:21 +0000463 if (isDistinct())
Duncan P. N. Exon Smith5e5b8502015-01-07 22:24:46 +0000464 return;
465
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000466 if (isUniqued())
467 // Check whether any operands are unresolved, requiring re-uniquing. If
468 // not, don't support RAUW.
469 if (!countUnresolvedOperands())
Duncan P. N. Exon Smitha1ae4f62015-01-19 23:15:21 +0000470 return;
471
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000472 this->Context.makeReplaceable(make_unique<ReplaceableMetadataImpl>(Context));
Devang Patela4f43fb2009-07-28 21:49:47 +0000473}
474
Duncan P. N. Exon Smith03e05832015-01-20 02:56:57 +0000475TempMDNode MDNode::clone() const {
476 switch (getMetadataID()) {
477 default:
478 llvm_unreachable("Invalid MDNode subclass");
479#define HANDLE_MDNODE_LEAF(CLASS) \
480 case CLASS##Kind: \
481 return cast<CLASS>(this)->cloneImpl();
482#include "llvm/IR/Metadata.def"
483 }
484}
485
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000486static bool isOperandUnresolved(Metadata *Op) {
487 if (auto *N = dyn_cast_or_null<MDNode>(Op))
488 return !N->isResolved();
489 return false;
490}
491
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000492unsigned MDNode::countUnresolvedOperands() {
493 assert(NumUnresolved == 0 && "Expected unresolved ops to be uncounted");
Benjamin Kramer4c1f0972015-02-08 21:56:09 +0000494 NumUnresolved = std::count_if(op_begin(), op_end(), isOperandUnresolved);
Duncan P. N. Exon Smithc5a0e2e2015-01-19 22:18:29 +0000495 return NumUnresolved;
496}
497
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000498void MDNode::makeUniqued() {
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000499 assert(isTemporary() && "Expected this to be temporary");
500 assert(!isResolved() && "Expected this to be unresolved");
501
Duncan P. N. Exon Smithcb33d6f2015-03-31 20:50:50 +0000502 // Enable uniquing callbacks.
503 for (auto &Op : mutable_operands())
504 Op.reset(Op.get(), this);
505
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000506 // Make this 'uniqued'.
507 Storage = Uniqued;
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000508 if (!countUnresolvedOperands())
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000509 resolve();
510
511 assert(isUniqued() && "Expected this to be uniqued");
512}
513
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000514void MDNode::makeDistinct() {
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000515 assert(isTemporary() && "Expected this to be temporary");
516 assert(!isResolved() && "Expected this to be unresolved");
517
518 // Pretend to be uniqued, resolve the node, and then store in distinct table.
519 Storage = Uniqued;
520 resolve();
521 storeDistinctInContext();
522
523 assert(isDistinct() && "Expected this to be distinct");
524 assert(isResolved() && "Expected this to be resolved");
525}
526
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000527void MDNode::resolve() {
Duncan P. N. Exon Smithb8f79602015-01-19 19:26:24 +0000528 assert(isUniqued() && "Expected this to be uniqued");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000529 assert(!isResolved() && "Expected this to be unresolved");
530
531 // Move the map, so that this immediately looks resolved.
Duncan P. N. Exon Smith2711ca72015-01-19 19:02:06 +0000532 auto Uses = Context.takeReplaceableUses();
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000533 NumUnresolved = 0;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000534 assert(isResolved() && "Expected this to be resolved");
535
536 // Drop RAUW support.
537 Uses->resolveAllUses();
538}
539
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000540void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000541 assert(NumUnresolved != 0 && "Expected unresolved operands");
Duncan P. N. Exon Smith3a16d802015-01-12 19:14:15 +0000542
Duncan P. N. Exon Smith0c87d772015-01-12 19:45:44 +0000543 // Check if an operand was resolved.
Duncan P. N. Exon Smith845755c42015-01-13 00:46:34 +0000544 if (!isOperandUnresolved(Old)) {
545 if (isOperandUnresolved(New))
546 // An operand was un-resolved!
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000547 ++NumUnresolved;
Duncan P. N. Exon Smith845755c42015-01-13 00:46:34 +0000548 } else if (!isOperandUnresolved(New))
Duncan P. N. Exon Smith0c87d772015-01-12 19:45:44 +0000549 decrementUnresolvedOperandCount();
Duncan P. N. Exon Smith3a16d802015-01-12 19:14:15 +0000550}
551
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000552void MDNode::decrementUnresolvedOperandCount() {
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000553 if (!--NumUnresolved)
Duncan P. N. Exon Smith0c87d772015-01-12 19:45:44 +0000554 // Last unresolved operand has just been resolved.
Duncan P. N. Exon Smith34c3d102015-01-12 19:43:15 +0000555 resolve();
556}
557
Teresa Johnsone5a61912015-12-17 17:14:09 +0000558void MDNode::resolveCycles(bool MDMaterialized) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000559 if (isResolved())
560 return;
561
562 // Resolve this node immediately.
563 resolve();
564
565 // Resolve all operands.
566 for (const auto &Op : operands()) {
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000567 auto *N = dyn_cast_or_null<MDNode>(Op);
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000568 if (!N)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000569 continue;
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000570
Teresa Johnsone5a61912015-12-17 17:14:09 +0000571 if (N->isTemporary() && !MDMaterialized)
572 continue;
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000573 assert(!N->isTemporary() &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000574 "Expected all forward declarations to be resolved");
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000575 if (!N->isResolved())
576 N->resolveCycles();
Chris Lattner8cb6c342009-12-31 01:05:46 +0000577 }
Duncan P. N. Exon Smith50846f82014-11-18 00:37:17 +0000578}
579
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000580static bool hasSelfReference(MDNode *N) {
581 for (Metadata *MD : N->operands())
582 if (MD == N)
583 return true;
584 return false;
585}
586
587MDNode *MDNode::replaceWithPermanentImpl() {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +0000588 switch (getMetadataID()) {
589 default:
590 // If this type isn't uniquable, replace with a distinct node.
591 return replaceWithDistinctImpl();
592
593#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
594 case CLASS##Kind: \
595 break;
596#include "llvm/IR/Metadata.def"
597 }
598
599 // Even if this type is uniquable, self-references have to be distinct.
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000600 if (hasSelfReference(this))
601 return replaceWithDistinctImpl();
602 return replaceWithUniquedImpl();
603}
604
Duncan P. N. Exon Smith86475292015-01-19 23:17:09 +0000605MDNode *MDNode::replaceWithUniquedImpl() {
606 // Try to uniquify in place.
607 MDNode *UniquedNode = uniquify();
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000608
Duncan P. N. Exon Smith86475292015-01-19 23:17:09 +0000609 if (UniquedNode == this) {
610 makeUniqued();
611 return this;
612 }
613
614 // Collision, so RAUW instead.
615 replaceAllUsesWith(UniquedNode);
616 deleteAsSubclass();
617 return UniquedNode;
618}
619
620MDNode *MDNode::replaceWithDistinctImpl() {
621 makeDistinct();
622 return this;
623}
624
Duncan P. N. Exon Smith118632d2015-01-12 20:09:34 +0000625void MDTuple::recalculateHash() {
Duncan P. N. Exon Smith93e983e2015-01-19 22:53:18 +0000626 setHash(MDTupleInfo::KeyTy::calculateHash(this));
Duncan P. N. Exon Smith967629e2015-01-12 19:16:34 +0000627}
628
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000629void MDNode::dropAllReferences() {
630 for (unsigned I = 0, E = NumOperands; I != E; ++I)
631 setOperand(I, nullptr);
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000632 if (!isResolved()) {
633 Context.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);
634 (void)Context.takeReplaceableUses();
635 }
Chris Lattner8cb6c342009-12-31 01:05:46 +0000636}
637
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000638void MDNode::handleChangedOperand(void *Ref, Metadata *New) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000639 unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
640 assert(Op < getNumOperands() && "Expected valid operand");
641
Duncan P. N. Exon Smith3d580562015-01-19 19:28:28 +0000642 if (!isUniqued()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000643 // This node is not uniqued. Just set the operand and be done with it.
644 setOperand(Op, New);
645 return;
Duncan Sandsc2928c62010-05-04 12:43:36 +0000646 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000647
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000648 // This node is uniqued.
649 eraseFromStore();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000650
651 Metadata *Old = getOperand(Op);
652 setOperand(Op, New);
653
Duncan P. N. Exon Smithbcd960a2015-01-05 23:31:54 +0000654 // Drop uniquing for self-reference cycles.
655 if (New == this) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000656 if (!isResolved())
657 resolve();
Duncan P. N. Exon Smithf08b8b42015-01-19 19:25:33 +0000658 storeDistinctInContext();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000659 return;
660 }
661
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000662 // Re-unique the node.
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000663 auto *Uniqued = uniquify();
664 if (Uniqued == this) {
Duncan P. N. Exon Smith3a16d802015-01-12 19:14:15 +0000665 if (!isResolved())
666 resolveAfterOperandChange(Old, New);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000667 return;
668 }
669
670 // Collision.
671 if (!isResolved()) {
672 // Still unresolved, so RAUW.
Duncan P. N. Exon Smithd9e6eb72015-01-12 19:36:35 +0000673 //
674 // First, clear out all operands to prevent any recursion (similar to
675 // dropAllReferences(), but we still need the use-list).
676 for (unsigned O = 0, E = getNumOperands(); O != E; ++O)
677 setOperand(O, nullptr);
Duncan P. N. Exon Smith2711ca72015-01-19 19:02:06 +0000678 Context.getReplaceableUses()->replaceAllUsesWith(Uniqued);
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000679 deleteAsSubclass();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000680 return;
681 }
682
Duncan P. N. Exon Smithd9e6eb72015-01-12 19:36:35 +0000683 // Store in non-uniqued form if RAUW isn't possible.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000684 storeDistinctInContext();
Victor Hernandeze5f2af72010-01-20 04:45:57 +0000685}
686
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000687void MDNode::deleteAsSubclass() {
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000688 switch (getMetadataID()) {
689 default:
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000690 llvm_unreachable("Invalid subclass of MDNode");
691#define HANDLE_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000692 case CLASS##Kind: \
693 delete cast<CLASS>(this); \
694 break;
695#include "llvm/IR/Metadata.def"
696 }
697}
698
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000699template <class T, class InfoT>
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000700static T *uniquifyImpl(T *N, DenseSet<T *, InfoT> &Store) {
701 if (T *U = getUniqued(Store, N))
702 return U;
703
704 Store.insert(N);
705 return N;
706}
707
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000708template <class NodeTy> struct MDNode::HasCachedHash {
709 typedef char Yes[1];
710 typedef char No[2];
711 template <class U, U Val> struct SFINAE {};
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000712
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000713 template <class U>
714 static Yes &check(SFINAE<void (U::*)(unsigned), &U::setHash> *);
715 template <class U> static No &check(...);
716
717 static const bool value = sizeof(check<NodeTy>(nullptr)) == sizeof(Yes);
718};
719
720MDNode *MDNode::uniquify() {
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000721 assert(!hasSelfReference(this) && "Cannot uniquify a self-referencing node");
722
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000723 // Try to insert into uniquing store.
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000724 switch (getMetadataID()) {
725 default:
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +0000726 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
727#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000728 case CLASS##Kind: { \
729 CLASS *SubclassThis = cast<CLASS>(this); \
730 std::integral_constant<bool, HasCachedHash<CLASS>::value> \
731 ShouldRecalculateHash; \
732 dispatchRecalculateHash(SubclassThis, ShouldRecalculateHash); \
733 return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s); \
734 }
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000735#include "llvm/IR/Metadata.def"
736 }
737}
738
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000739void MDNode::eraseFromStore() {
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000740 switch (getMetadataID()) {
741 default:
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +0000742 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
743#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000744 case CLASS##Kind: \
Duncan P. N. Exon Smith6cf10d22015-01-19 22:47:08 +0000745 getContext().pImpl->CLASS##s.erase(cast<CLASS>(this)); \
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000746 break;
747#include "llvm/IR/Metadata.def"
748 }
749}
750
Duncan P. N. Exon Smithac3128d2015-01-12 20:13:56 +0000751MDTuple *MDTuple::getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
Duncan P. N. Exon Smith1b0064d2015-01-19 20:14:15 +0000752 StorageType Storage, bool ShouldCreate) {
753 unsigned Hash = 0;
754 if (Storage == Uniqued) {
755 MDTupleInfo::KeyTy Key(MDs);
Duncan P. N. Exon Smithb57f9e92015-01-19 20:16:50 +0000756 if (auto *N = getUniqued(Context.pImpl->MDTuples, Key))
757 return N;
Duncan P. N. Exon Smith1b0064d2015-01-19 20:14:15 +0000758 if (!ShouldCreate)
759 return nullptr;
Duncan P. N. Exon Smith93e983e2015-01-19 22:53:18 +0000760 Hash = Key.getHash();
Duncan P. N. Exon Smith1b0064d2015-01-19 20:14:15 +0000761 } else {
762 assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
763 }
Duncan Sands26a80f32012-03-31 08:20:11 +0000764
Duncan P. N. Exon Smith5b8c4402015-01-19 20:18:13 +0000765 return storeImpl(new (MDs.size()) MDTuple(Context, Storage, Hash, MDs),
766 Storage, Context.pImpl->MDTuples);
Duncan P. N. Exon Smith5e5b8502015-01-07 22:24:46 +0000767}
768
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000769void MDNode::deleteTemporary(MDNode *N) {
770 assert(N->isTemporary() && "Expected temporary node");
Duncan P. N. Exon Smith8d536972015-01-22 21:36:45 +0000771 N->replaceAllUsesWith(nullptr);
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000772 N->deleteAsSubclass();
Dan Gohman16a5d982010-08-20 22:02:26 +0000773}
774
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000775void MDNode::storeDistinctInContext() {
Duncan P. N. Exon Smithf08b8b42015-01-19 19:25:33 +0000776 assert(isResolved() && "Expected resolved nodes");
Duncan P. N. Exon Smithf1340452015-01-19 18:36:18 +0000777 Storage = Distinct;
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000778
779 // Reset the hash.
780 switch (getMetadataID()) {
781 default:
782 llvm_unreachable("Invalid subclass of MDNode");
783#define HANDLE_MDNODE_LEAF(CLASS) \
784 case CLASS##Kind: { \
785 std::integral_constant<bool, HasCachedHash<CLASS>::value> ShouldResetHash; \
786 dispatchResetHash(cast<CLASS>(this), ShouldResetHash); \
787 break; \
788 }
789#include "llvm/IR/Metadata.def"
790 }
791
Duncan P. N. Exon Smithde03ff52015-01-13 20:44:56 +0000792 getContext().pImpl->DistinctMDNodes.insert(this);
Devang Patel82ab3f82010-02-18 20:53:16 +0000793}
Chris Lattnerf543eff2009-12-28 09:12:35 +0000794
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000795void MDNode::replaceOperandWith(unsigned I, Metadata *New) {
796 if (getOperand(I) == New)
Devang Patelf7188322009-09-03 01:39:20 +0000797 return;
Devang Patelf7188322009-09-03 01:39:20 +0000798
Duncan P. N. Exon Smithde03a8b2015-01-19 18:45:35 +0000799 if (!isUniqued()) {
Duncan P. N. Exon Smithdaa335a2015-01-12 18:01:45 +0000800 setOperand(I, New);
Duncan P. N. Exon Smithf39c3b82014-11-17 23:28:21 +0000801 return;
802 }
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +0000803
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000804 handleChangedOperand(mutable_begin() + I, New);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000805}
Chris Lattnerc6d17e22009-12-28 09:24:53 +0000806
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000807void MDNode::setOperand(unsigned I, Metadata *New) {
808 assert(I < NumOperands);
Duncan P. N. Exon Smithefdf2852015-01-19 19:29:25 +0000809 mutable_begin()[I].reset(New, isUniqued() ? this : nullptr);
Devang Patelf7188322009-09-03 01:39:20 +0000810}
811
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000812/// \brief Get a node, or a self-reference that looks like it.
813///
814/// Special handling for finding self-references, for use by \a
815/// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
816/// when self-referencing nodes were still uniqued. If the first operand has
817/// the same operands as \c Ops, return the first operand instead.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000818static MDNode *getOrSelfReference(LLVMContext &Context,
819 ArrayRef<Metadata *> Ops) {
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000820 if (!Ops.empty())
821 if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))
822 if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
823 for (unsigned I = 1, E = Ops.size(); I != E; ++I)
824 if (Ops[I] != N->getOperand(I))
825 return MDNode::get(Context, Ops);
826 return N;
827 }
828
829 return MDNode::get(Context, Ops);
830}
831
Hal Finkel94146652014-07-24 14:25:39 +0000832MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {
833 if (!A)
834 return B;
835 if (!B)
836 return A;
837
Benjamin Kramer4c1f0972015-02-08 21:56:09 +0000838 SmallVector<Metadata *, 4> MDs;
839 MDs.reserve(A->getNumOperands() + B->getNumOperands());
840 MDs.append(A->op_begin(), A->op_end());
841 MDs.append(B->op_begin(), B->op_end());
Hal Finkel94146652014-07-24 14:25:39 +0000842
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000843 // FIXME: This preserves long-standing behaviour, but is it really the right
844 // behaviour? Or was that an unintended side-effect of node uniquing?
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000845 return getOrSelfReference(A->getContext(), MDs);
Hal Finkel94146652014-07-24 14:25:39 +0000846}
847
848MDNode *MDNode::intersect(MDNode *A, MDNode *B) {
849 if (!A || !B)
850 return nullptr;
851
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000852 SmallVector<Metadata *, 4> MDs;
Benjamin Kramer4c1f0972015-02-08 21:56:09 +0000853 for (Metadata *MD : A->operands())
854 if (std::find(B->op_begin(), B->op_end(), MD) != B->op_end())
855 MDs.push_back(MD);
Hal Finkel94146652014-07-24 14:25:39 +0000856
Duncan P. N. Exon Smithac8ee282014-12-07 19:52:06 +0000857 // FIXME: This preserves long-standing behaviour, but is it really the right
858 // behaviour? Or was that an unintended side-effect of node uniquing?
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000859 return getOrSelfReference(A->getContext(), MDs);
Hal Finkel94146652014-07-24 14:25:39 +0000860}
861
Bjorn Steinbrink5ec75222015-02-08 17:07:14 +0000862MDNode *MDNode::getMostGenericAliasScope(MDNode *A, MDNode *B) {
863 if (!A || !B)
864 return nullptr;
865
866 SmallVector<Metadata *, 4> MDs(B->op_begin(), B->op_end());
Benjamin Kramer4c1f0972015-02-08 21:56:09 +0000867 for (Metadata *MD : A->operands())
868 if (std::find(B->op_begin(), B->op_end(), MD) == B->op_end())
869 MDs.push_back(MD);
Bjorn Steinbrink5ec75222015-02-08 17:07:14 +0000870
871 // FIXME: This preserves long-standing behaviour, but is it really the right
872 // behaviour? Or was that an unintended side-effect of node uniquing?
873 return getOrSelfReference(A->getContext(), MDs);
874}
875
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000876MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
877 if (!A || !B)
Craig Topperc6207612014-04-09 06:08:46 +0000878 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000879
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000880 APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
881 APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000882 if (AVal.compare(BVal) == APFloat::cmpLessThan)
883 return A;
884 return B;
885}
886
887static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
888 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
889}
890
891static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
892 return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
893}
894
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000895static bool tryMergeRange(SmallVectorImpl<ConstantInt *> &EndPoints,
896 ConstantInt *Low, ConstantInt *High) {
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000897 ConstantRange NewRange(Low->getValue(), High->getValue());
898 unsigned Size = EndPoints.size();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000899 APInt LB = EndPoints[Size - 2]->getValue();
900 APInt LE = EndPoints[Size - 1]->getValue();
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000901 ConstantRange LastRange(LB, LE);
902 if (canBeMerged(NewRange, LastRange)) {
903 ConstantRange Union = LastRange.unionWith(NewRange);
904 Type *Ty = High->getType();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000905 EndPoints[Size - 2] =
906 cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
907 EndPoints[Size - 1] =
908 cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000909 return true;
910 }
911 return false;
912}
913
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000914static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,
915 ConstantInt *Low, ConstantInt *High) {
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000916 if (!EndPoints.empty())
917 if (tryMergeRange(EndPoints, Low, High))
918 return;
919
920 EndPoints.push_back(Low);
921 EndPoints.push_back(High);
922}
923
924MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
925 // Given two ranges, we want to compute the union of the ranges. This
926 // is slightly complitade by having to combine the intervals and merge
927 // the ones that overlap.
928
929 if (!A || !B)
Craig Topperc6207612014-04-09 06:08:46 +0000930 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000931
932 if (A == B)
933 return A;
934
935 // First, walk both lists in older of the lower boundary of each interval.
936 // 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 +0000937 SmallVector<ConstantInt *, 4> EndPoints;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000938 int AI = 0;
939 int BI = 0;
940 int AN = A->getNumOperands() / 2;
941 int BN = B->getNumOperands() / 2;
942 while (AI < AN && BI < BN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000943 ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
944 ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000945
946 if (ALow->getValue().slt(BLow->getValue())) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000947 addRange(EndPoints, ALow,
948 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000949 ++AI;
950 } else {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000951 addRange(EndPoints, BLow,
952 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000953 ++BI;
954 }
955 }
956 while (AI < AN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000957 addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
958 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000959 ++AI;
960 }
961 while (BI < BN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000962 addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
963 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000964 ++BI;
965 }
966
967 // If we have more than 2 ranges (4 endpoints) we have to try to merge
968 // the last and first ones.
969 unsigned Size = EndPoints.size();
970 if (Size > 4) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000971 ConstantInt *FB = EndPoints[0];
972 ConstantInt *FE = EndPoints[1];
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000973 if (tryMergeRange(EndPoints, FB, FE)) {
974 for (unsigned i = 0; i < Size - 2; ++i) {
975 EndPoints[i] = EndPoints[i + 2];
976 }
977 EndPoints.resize(Size - 2);
978 }
979 }
980
981 // If in the end we have a single range, it is possible that it is now the
982 // full range. Just drop the metadata in that case.
983 if (EndPoints.size() == 2) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000984 ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000985 if (Range.isFullSet())
Craig Topperc6207612014-04-09 06:08:46 +0000986 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000987 }
988
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000989 SmallVector<Metadata *, 4> MDs;
990 MDs.reserve(EndPoints.size());
991 for (auto *I : EndPoints)
992 MDs.push_back(ConstantAsMetadata::get(I));
993 return MDNode::get(A->getContext(), MDs);
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000994}
995
Artur Pilipenko5c5011d2015-11-02 17:53:51 +0000996MDNode *MDNode::getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B) {
997 if (!A || !B)
998 return nullptr;
999
1000 ConstantInt *AVal = mdconst::extract<ConstantInt>(A->getOperand(0));
1001 ConstantInt *BVal = mdconst::extract<ConstantInt>(B->getOperand(0));
1002 if (AVal->getZExtValue() < BVal->getZExtValue())
1003 return A;
1004 return B;
1005}
1006
Devang Patel05a26fb2009-07-29 00:33:07 +00001007//===----------------------------------------------------------------------===//
Chris Lattnerb0c23e82009-10-19 07:10:59 +00001008// NamedMDNode implementation.
Devang Patel05a26fb2009-07-29 00:33:07 +00001009//
Devang Patel943ddf62010-01-12 18:34:06 +00001010
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001011static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
1012 return *(SmallVector<TrackingMDRef, 4> *)Operands;
Chris Lattner1bc810b2009-12-28 08:07:14 +00001013}
1014
Dan Gohman2637cc12010-07-21 23:38:33 +00001015NamedMDNode::NamedMDNode(const Twine &N)
Duncan P. N. Exon Smithc5754a62014-11-05 18:16:03 +00001016 : Name(N.str()), Parent(nullptr),
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001017 Operands(new SmallVector<TrackingMDRef, 4>()) {}
Devang Patel5c310be2009-08-11 18:01:24 +00001018
Chris Lattner1bc810b2009-12-28 08:07:14 +00001019NamedMDNode::~NamedMDNode() {
1020 dropAllReferences();
1021 delete &getNMDOps(Operands);
1022}
1023
Chris Lattner9b493022009-12-31 01:22:29 +00001024unsigned NamedMDNode::getNumOperands() const {
Chris Lattner1bc810b2009-12-28 08:07:14 +00001025 return (unsigned)getNMDOps(Operands).size();
1026}
1027
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001028MDNode *NamedMDNode::getOperand(unsigned i) const {
Chris Lattner9b493022009-12-31 01:22:29 +00001029 assert(i < getNumOperands() && "Invalid Operand number!");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001030 auto *N = getNMDOps(Operands)[i].get();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001031 return cast_or_null<MDNode>(N);
Chris Lattner1bc810b2009-12-28 08:07:14 +00001032}
1033
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001034void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
Chris Lattner1bc810b2009-12-28 08:07:14 +00001035
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001036void NamedMDNode::setOperand(unsigned I, MDNode *New) {
1037 assert(I < getNumOperands() && "Invalid operand number");
1038 getNMDOps(Operands)[I].reset(New);
1039}
1040
Devang Patel79238d72009-08-03 06:19:01 +00001041void NamedMDNode::eraseFromParent() {
Dan Gohman2637cc12010-07-21 23:38:33 +00001042 getParent()->eraseNamedMetadata(this);
Devang Patel79238d72009-08-03 06:19:01 +00001043}
1044
Devang Patel79238d72009-08-03 06:19:01 +00001045void NamedMDNode::dropAllReferences() {
Chris Lattner1bc810b2009-12-28 08:07:14 +00001046 getNMDOps(Operands).clear();
Devang Patel79238d72009-08-03 06:19:01 +00001047}
1048
Devang Patelfcfee0f2010-01-07 19:39:36 +00001049StringRef NamedMDNode::getName() const {
1050 return StringRef(Name);
1051}
Devang Pateld5497a4b2009-09-16 18:09:00 +00001052
1053//===----------------------------------------------------------------------===//
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001054// Instruction Metadata method implementations.
1055//
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001056void MDAttachmentMap::set(unsigned ID, MDNode &MD) {
1057 for (auto &I : Attachments)
1058 if (I.first == ID) {
1059 I.second.reset(&MD);
1060 return;
1061 }
1062 Attachments.emplace_back(std::piecewise_construct, std::make_tuple(ID),
1063 std::make_tuple(&MD));
1064}
1065
1066void MDAttachmentMap::erase(unsigned ID) {
1067 if (empty())
1068 return;
1069
1070 // Common case is one/last value.
1071 if (Attachments.back().first == ID) {
1072 Attachments.pop_back();
1073 return;
1074 }
1075
1076 for (auto I = Attachments.begin(), E = std::prev(Attachments.end()); I != E;
1077 ++I)
1078 if (I->first == ID) {
1079 *I = std::move(Attachments.back());
1080 Attachments.pop_back();
1081 return;
1082 }
1083}
1084
1085MDNode *MDAttachmentMap::lookup(unsigned ID) const {
1086 for (const auto &I : Attachments)
1087 if (I.first == ID)
1088 return I.second;
1089 return nullptr;
1090}
1091
1092void MDAttachmentMap::getAll(
1093 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1094 Result.append(Attachments.begin(), Attachments.end());
1095
1096 // Sort the resulting array so it is stable.
1097 if (Result.size() > 1)
1098 array_pod_sort(Result.begin(), Result.end());
1099}
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001100
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001101void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
1102 if (!Node && !hasMetadata())
1103 return;
1104 setMetadata(getContext().getMDKindID(Kind), Node);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001105}
1106
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001107MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
Chris Lattnera0566972009-12-29 09:01:33 +00001108 return getMetadataImpl(getContext().getMDKindID(Kind));
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001109}
1110
Adrian Prantlcbdfdb72015-08-20 22:00:30 +00001111void Instruction::dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs) {
Rafael Espindolaab73c492014-01-28 16:56:46 +00001112 SmallSet<unsigned, 5> KnownSet;
1113 KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
1114
Rafael Espindolaab73c492014-01-28 16:56:46 +00001115 if (!hasMetadataHashEntry())
1116 return; // Nothing to remove!
1117
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001118 auto &InstructionMetadata = getContext().pImpl->InstructionMetadata;
Rafael Espindolaab73c492014-01-28 16:56:46 +00001119
1120 if (KnownSet.empty()) {
1121 // Just drop our entry at the store.
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001122 InstructionMetadata.erase(this);
Rafael Espindolaab73c492014-01-28 16:56:46 +00001123 setHasMetadataHashEntry(false);
1124 return;
1125 }
1126
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001127 auto &Info = InstructionMetadata[this];
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001128 Info.remove_if([&KnownSet](const std::pair<unsigned, TrackingMDNodeRef> &I) {
1129 return !KnownSet.count(I.first);
1130 });
Rafael Espindolaab73c492014-01-28 16:56:46 +00001131
Duncan P. N. Exon Smith75ef0c02015-04-24 20:23:44 +00001132 if (Info.empty()) {
Rafael Espindolaab73c492014-01-28 16:56:46 +00001133 // Drop our entry at the store.
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001134 InstructionMetadata.erase(this);
Rafael Espindolaab73c492014-01-28 16:56:46 +00001135 setHasMetadataHashEntry(false);
1136 }
1137}
1138
Sanjay Patel942b46a2015-08-24 23:18:44 +00001139/// setMetadata - Set the metadata of the specified kind to the specified
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001140/// node. This updates/replaces metadata if already present, or removes it if
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001141/// Node is null.
1142void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
1143 if (!Node && !hasMetadata())
1144 return;
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001145
Chris Lattnerc263b422010-03-30 23:03:27 +00001146 // Handle 'dbg' as a special case since it is not stored in the hash table.
1147 if (KindID == LLVMContext::MD_dbg) {
Duncan P. N. Exon Smithab659fb32015-03-30 19:40:05 +00001148 DbgLoc = DebugLoc(Node);
Chris Lattnerc263b422010-03-30 23:03:27 +00001149 return;
1150 }
1151
Chris Lattnera0566972009-12-29 09:01:33 +00001152 // Handle the case when we're adding/updating metadata on an instruction.
1153 if (Node) {
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001154 auto &Info = getContext().pImpl->InstructionMetadata[this];
Chris Lattnerc263b422010-03-30 23:03:27 +00001155 assert(!Info.empty() == hasMetadataHashEntry() &&
1156 "HasMetadata bit is wonked");
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001157 if (Info.empty())
Chris Lattnerc263b422010-03-30 23:03:27 +00001158 setHasMetadataHashEntry(true);
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001159 Info.set(KindID, *Node);
Chris Lattnera0566972009-12-29 09:01:33 +00001160 return;
1161 }
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001162
Chris Lattnera0566972009-12-29 09:01:33 +00001163 // Otherwise, we're removing metadata from an instruction.
Nick Lewycky4c131382011-12-27 01:17:40 +00001164 assert((hasMetadataHashEntry() ==
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001165 (getContext().pImpl->InstructionMetadata.count(this) > 0)) &&
Chris Lattnera0566972009-12-29 09:01:33 +00001166 "HasMetadata bit out of date!");
Nick Lewycky4c131382011-12-27 01:17:40 +00001167 if (!hasMetadataHashEntry())
1168 return; // Nothing to remove!
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001169 auto &Info = getContext().pImpl->InstructionMetadata[this];
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001170
Chris Lattnerc263b422010-03-30 23:03:27 +00001171 // Handle removal of an existing value.
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001172 Info.erase(KindID);
1173
1174 if (!Info.empty())
1175 return;
1176
1177 getContext().pImpl->InstructionMetadata.erase(this);
1178 setHasMetadataHashEntry(false);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001179}
1180
Hal Finkelcc39b672014-07-24 12:16:19 +00001181void Instruction::setAAMetadata(const AAMDNodes &N) {
1182 setMetadata(LLVMContext::MD_tbaa, N.TBAA);
Hal Finkel94146652014-07-24 14:25:39 +00001183 setMetadata(LLVMContext::MD_alias_scope, N.Scope);
1184 setMetadata(LLVMContext::MD_noalias, N.NoAlias);
Hal Finkelcc39b672014-07-24 12:16:19 +00001185}
1186
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001187MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
Chris Lattnerc263b422010-03-30 23:03:27 +00001188 // Handle 'dbg' as a special case since it is not stored in the hash table.
1189 if (KindID == LLVMContext::MD_dbg)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001190 return DbgLoc.getAsMDNode();
1191
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001192 if (!hasMetadataHashEntry())
1193 return nullptr;
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001194 auto &Info = getContext().pImpl->InstructionMetadata[this];
Chris Lattnerc263b422010-03-30 23:03:27 +00001195 assert(!Info.empty() && "bit out of sync with hash table");
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001196
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001197 return Info.lookup(KindID);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001198}
1199
Duncan P. N. Exon Smith4abd1a02014-11-01 00:26:42 +00001200void Instruction::getAllMetadataImpl(
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001201 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
Chris Lattnerc263b422010-03-30 23:03:27 +00001202 Result.clear();
1203
1204 // 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 +00001205 if (DbgLoc) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001206 Result.push_back(
1207 std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
Chris Lattnerc263b422010-03-30 23:03:27 +00001208 if (!hasMetadataHashEntry()) return;
1209 }
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001210
Chris Lattnerc263b422010-03-30 23:03:27 +00001211 assert(hasMetadataHashEntry() &&
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001212 getContext().pImpl->InstructionMetadata.count(this) &&
Chris Lattnera0566972009-12-29 09:01:33 +00001213 "Shouldn't have called this");
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001214 const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
Chris Lattnera0566972009-12-29 09:01:33 +00001215 assert(!Info.empty() && "Shouldn't have called this");
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001216 Info.getAll(Result);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001217}
1218
Duncan P. N. Exon Smith3d5a02f2014-11-03 18:13:57 +00001219void Instruction::getAllMetadataOtherThanDebugLocImpl(
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001220 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001221 Result.clear();
1222 assert(hasMetadataHashEntry() &&
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001223 getContext().pImpl->InstructionMetadata.count(this) &&
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001224 "Shouldn't have called this");
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001225 const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001226 assert(!Info.empty() && "Shouldn't have called this");
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001227 Info.getAll(Result);
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001228}
1229
Dan Gohman48a995f2010-07-20 22:25:04 +00001230/// clearMetadataHashEntries - Clear all hashtable-based metadata from
1231/// this instruction.
1232void Instruction::clearMetadataHashEntries() {
1233 assert(hasMetadataHashEntry() && "Caller should check");
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001234 getContext().pImpl->InstructionMetadata.erase(this);
Dan Gohman48a995f2010-07-20 22:25:04 +00001235 setHasMetadataHashEntry(false);
Chris Lattner68017802009-12-29 07:44:16 +00001236}
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001237
1238MDNode *Function::getMetadata(unsigned KindID) const {
1239 if (!hasMetadata())
1240 return nullptr;
1241 return getContext().pImpl->FunctionMetadata[this].lookup(KindID);
1242}
1243
1244MDNode *Function::getMetadata(StringRef Kind) const {
1245 if (!hasMetadata())
1246 return nullptr;
1247 return getMetadata(getContext().getMDKindID(Kind));
1248}
1249
1250void Function::setMetadata(unsigned KindID, MDNode *MD) {
1251 if (MD) {
1252 if (!hasMetadata())
1253 setHasMetadataHashEntry(true);
1254
1255 getContext().pImpl->FunctionMetadata[this].set(KindID, *MD);
1256 return;
1257 }
1258
1259 // Nothing to unset.
1260 if (!hasMetadata())
1261 return;
1262
1263 auto &Store = getContext().pImpl->FunctionMetadata[this];
1264 Store.erase(KindID);
1265 if (Store.empty())
1266 clearMetadata();
1267}
1268
1269void Function::setMetadata(StringRef Kind, MDNode *MD) {
1270 if (!MD && !hasMetadata())
1271 return;
1272 setMetadata(getContext().getMDKindID(Kind), MD);
1273}
1274
1275void Function::getAllMetadata(
1276 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
1277 MDs.clear();
1278
1279 if (!hasMetadata())
1280 return;
1281
1282 getContext().pImpl->FunctionMetadata[this].getAll(MDs);
1283}
1284
1285void Function::dropUnknownMetadata(ArrayRef<unsigned> KnownIDs) {
1286 if (!hasMetadata())
1287 return;
1288 if (KnownIDs.empty()) {
1289 clearMetadata();
1290 return;
1291 }
1292
1293 SmallSet<unsigned, 5> KnownSet;
1294 KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
1295
1296 auto &Store = getContext().pImpl->FunctionMetadata[this];
1297 assert(!Store.empty());
1298
1299 Store.remove_if([&KnownSet](const std::pair<unsigned, TrackingMDNodeRef> &I) {
1300 return !KnownSet.count(I.first);
1301 });
1302
1303 if (Store.empty())
1304 clearMetadata();
1305}
1306
1307void Function::clearMetadata() {
1308 if (!hasMetadata())
1309 return;
1310 getContext().pImpl->FunctionMetadata.erase(this);
1311 setHasMetadataHashEntry(false);
1312}
Duncan P. N. Exon Smithb56b5af2015-08-28 21:55:35 +00001313
1314void Function::setSubprogram(DISubprogram *SP) {
1315 setMetadata(LLVMContext::MD_dbg, SP);
1316}
1317
1318DISubprogram *Function::getSubprogram() const {
1319 return cast_or_null<DISubprogram>(getMetadata(LLVMContext::MD_dbg));
1320}