blob: e753dbc05cacdf716e92cf2021644cb46ce84983 [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"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/STLExtras.h"
Rafael Espindolaab73c492014-01-28 16:56:46 +000019#include "llvm/ADT/SmallSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/ADT/StringMap.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000021#include "llvm/IR/ConstantRange.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000022#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Instruction.h"
24#include "llvm/IR/LLVMContext.h"
25#include "llvm/IR/Module.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000026#include "llvm/IR/ValueHandle.h"
Duncan P. N. Exon Smith46d91ad2014-11-14 18:42:06 +000027
Devang Patela4f43fb2009-07-28 21:49:47 +000028using namespace llvm;
29
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +000030MetadataAsValue::MetadataAsValue(Type *Ty, Metadata *MD)
31 : Value(Ty, MetadataAsValueVal), MD(MD) {
32 track();
33}
34
35MetadataAsValue::~MetadataAsValue() {
36 getType()->getContext().pImpl->MetadataAsValues.erase(MD);
37 untrack();
38}
39
Sanjay Patel9da9c762016-03-12 20:44:58 +000040/// Canonicalize metadata arguments to intrinsics.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +000041///
42/// To support bitcode upgrades (and assembly semantic sugar) for \a
43/// MetadataAsValue, we need to canonicalize certain metadata.
44///
45/// - nullptr is replaced by an empty MDNode.
46/// - An MDNode with a single null operand is replaced by an empty MDNode.
47/// - An MDNode whose only operand is a \a ConstantAsMetadata gets skipped.
48///
49/// This maintains readability of bitcode from when metadata was a type of
50/// value, and these bridges were unnecessary.
51static Metadata *canonicalizeMetadataForValue(LLVMContext &Context,
52 Metadata *MD) {
53 if (!MD)
54 // !{}
55 return MDNode::get(Context, None);
56
57 // Return early if this isn't a single-operand MDNode.
58 auto *N = dyn_cast<MDNode>(MD);
59 if (!N || N->getNumOperands() != 1)
60 return MD;
61
62 if (!N->getOperand(0))
63 // !{}
64 return MDNode::get(Context, None);
65
66 if (auto *C = dyn_cast<ConstantAsMetadata>(N->getOperand(0)))
67 // Look through the MDNode.
68 return C;
69
70 return MD;
71}
72
73MetadataAsValue *MetadataAsValue::get(LLVMContext &Context, Metadata *MD) {
74 MD = canonicalizeMetadataForValue(Context, MD);
75 auto *&Entry = Context.pImpl->MetadataAsValues[MD];
76 if (!Entry)
77 Entry = new MetadataAsValue(Type::getMetadataTy(Context), MD);
78 return Entry;
79}
80
81MetadataAsValue *MetadataAsValue::getIfExists(LLVMContext &Context,
82 Metadata *MD) {
83 MD = canonicalizeMetadataForValue(Context, MD);
84 auto &Store = Context.pImpl->MetadataAsValues;
Benjamin Kramer4c1f0972015-02-08 21:56:09 +000085 return Store.lookup(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +000086}
87
88void MetadataAsValue::handleChangedMetadata(Metadata *MD) {
89 LLVMContext &Context = getContext();
90 MD = canonicalizeMetadataForValue(Context, MD);
91 auto &Store = Context.pImpl->MetadataAsValues;
92
93 // Stop tracking the old metadata.
94 Store.erase(this->MD);
95 untrack();
96 this->MD = nullptr;
97
98 // Start tracking MD, or RAUW if necessary.
99 auto *&Entry = Store[MD];
100 if (Entry) {
101 replaceAllUsesWith(Entry);
102 delete this;
103 return;
104 }
105
106 this->MD = MD;
107 track();
108 Entry = this;
109}
110
111void MetadataAsValue::track() {
112 if (MD)
113 MetadataTracking::track(&MD, *MD, *this);
114}
115
116void MetadataAsValue::untrack() {
117 if (MD)
118 MetadataTracking::untrack(MD);
119}
120
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000121bool MetadataTracking::track(void *Ref, Metadata &MD, OwnerTy Owner) {
122 assert(Ref && "Expected live reference");
123 assert((Owner || *static_cast<Metadata **>(Ref) == &MD) &&
124 "Reference without owner must be direct");
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000125 if (auto *R = ReplaceableMetadataImpl::getOrCreate(MD)) {
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000126 R->addRef(Ref, Owner);
127 return true;
128 }
129 return false;
130}
131
132void MetadataTracking::untrack(void *Ref, Metadata &MD) {
133 assert(Ref && "Expected live reference");
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000134 if (auto *R = ReplaceableMetadataImpl::getIfExists(MD))
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000135 R->dropRef(Ref);
136}
137
138bool MetadataTracking::retrack(void *Ref, Metadata &MD, void *New) {
139 assert(Ref && "Expected live reference");
140 assert(New && "Expected live reference");
141 assert(Ref != New && "Expected change");
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000142 if (auto *R = ReplaceableMetadataImpl::getIfExists(MD)) {
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000143 R->moveRef(Ref, New, MD);
144 return true;
145 }
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000146 assert(!isReplaceable(MD) &&
147 "Expected un-replaceable metadata, since we didn't move a reference");
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000148 return false;
149}
150
151bool MetadataTracking::isReplaceable(const Metadata &MD) {
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000152 return ReplaceableMetadataImpl::isReplaceable(MD);
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000153}
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 Smith5bf8fef2014-12-09 18:38:53 +0000191 if (UseMap.empty())
192 return;
193
194 // Copy out uses since UseMap will get touched below.
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000195 typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
196 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
197 std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
198 return L.second.second < R.second.second;
199 });
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000200 for (const auto &Pair : Uses) {
Duncan P. N. Exon Smith4a4f7852015-01-14 19:56:10 +0000201 // Check that this Ref hasn't disappeared after RAUW (when updating a
202 // previous Ref).
203 if (!UseMap.count(Pair.first))
204 continue;
205
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000206 OwnerTy Owner = Pair.second.first;
207 if (!Owner) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000208 // Update unowned tracking references directly.
209 Metadata *&Ref = *static_cast<Metadata **>(Pair.first);
210 Ref = MD;
Duncan P. N. Exon Smith121eeff2014-12-12 19:24:33 +0000211 if (MD)
212 MetadataTracking::track(Ref);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000213 UseMap.erase(Pair.first);
214 continue;
215 }
216
217 // Check for MetadataAsValue.
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000218 if (Owner.is<MetadataAsValue *>()) {
219 Owner.get<MetadataAsValue *>()->handleChangedMetadata(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000220 continue;
221 }
222
223 // There's a Metadata owner -- dispatch.
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000224 Metadata *OwnerMD = Owner.get<Metadata *>();
225 switch (OwnerMD->getMetadataID()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000226#define HANDLE_METADATA_LEAF(CLASS) \
227 case Metadata::CLASS##Kind: \
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000228 cast<CLASS>(OwnerMD)->handleChangedOperand(Pair.first, MD); \
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000229 continue;
230#include "llvm/IR/Metadata.def"
231 default:
232 llvm_unreachable("Invalid metadata subclass");
233 }
234 }
235 assert(UseMap.empty() && "Expected all uses to be replaced");
236}
237
238void ReplaceableMetadataImpl::resolveAllUses(bool ResolveUsers) {
239 if (UseMap.empty())
240 return;
241
242 if (!ResolveUsers) {
243 UseMap.clear();
244 return;
245 }
246
247 // Copy out uses since UseMap could get touched below.
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000248 typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
249 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
250 std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
251 return L.second.second < R.second.second;
252 });
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000253 UseMap.clear();
254 for (const auto &Pair : Uses) {
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000255 auto Owner = Pair.second.first;
256 if (!Owner)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000257 continue;
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000258 if (Owner.is<MetadataAsValue *>())
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000259 continue;
260
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000261 // Resolve MDNodes that point at this.
262 auto *OwnerMD = dyn_cast<MDNode>(Owner.get<Metadata *>());
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000263 if (!OwnerMD)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000264 continue;
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000265 if (OwnerMD->isResolved())
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000266 continue;
Duncan P. N. Exon Smith34c3d102015-01-12 19:43:15 +0000267 OwnerMD->decrementUnresolvedOperandCount();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000268 }
269}
270
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000271ReplaceableMetadataImpl *ReplaceableMetadataImpl::getOrCreate(Metadata &MD) {
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000272 if (auto *N = dyn_cast<MDNode>(&MD))
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000273 return N->isResolved() ? nullptr : N->Context.getOrCreateReplaceableUses();
274 return dyn_cast<ValueAsMetadata>(&MD);
275}
276
277ReplaceableMetadataImpl *ReplaceableMetadataImpl::getIfExists(Metadata &MD) {
278 if (auto *N = dyn_cast<MDNode>(&MD))
279 return N->isResolved() ? nullptr : N->Context.getReplaceableUses();
280 return dyn_cast<ValueAsMetadata>(&MD);
281}
282
283bool ReplaceableMetadataImpl::isReplaceable(const Metadata &MD) {
284 if (auto *N = dyn_cast<MDNode>(&MD))
285 return !N->isResolved();
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000286 return dyn_cast<ValueAsMetadata>(&MD);
287}
288
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000289static Function *getLocalFunction(Value *V) {
290 assert(V && "Expected value");
291 if (auto *A = dyn_cast<Argument>(V))
292 return A->getParent();
293 if (BasicBlock *BB = cast<Instruction>(V)->getParent())
294 return BB->getParent();
295 return nullptr;
296}
297
298ValueAsMetadata *ValueAsMetadata::get(Value *V) {
299 assert(V && "Unexpected null Value");
300
301 auto &Context = V->getContext();
302 auto *&Entry = Context.pImpl->ValuesAsMetadata[V];
303 if (!Entry) {
304 assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
305 "Expected constant or function-local value");
Owen Anderson7349ab92015-06-01 22:24:01 +0000306 assert(!V->IsUsedByMD &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000307 "Expected this to be the only metadata use");
Owen Anderson7349ab92015-06-01 22:24:01 +0000308 V->IsUsedByMD = true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000309 if (auto *C = dyn_cast<Constant>(V))
Duncan P. N. Exon Smith1c00c9f2015-01-05 20:41:25 +0000310 Entry = new ConstantAsMetadata(C);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000311 else
Duncan P. N. Exon Smith1c00c9f2015-01-05 20:41:25 +0000312 Entry = new LocalAsMetadata(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000313 }
314
315 return Entry;
316}
317
318ValueAsMetadata *ValueAsMetadata::getIfExists(Value *V) {
319 assert(V && "Unexpected null Value");
320 return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
321}
322
323void ValueAsMetadata::handleDeletion(Value *V) {
324 assert(V && "Expected valid value");
325
326 auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
327 auto I = Store.find(V);
328 if (I == Store.end())
329 return;
330
331 // Remove old entry from the map.
332 ValueAsMetadata *MD = I->second;
333 assert(MD && "Expected valid metadata");
334 assert(MD->getValue() == V && "Expected valid mapping");
335 Store.erase(I);
336
337 // Delete the metadata.
338 MD->replaceAllUsesWith(nullptr);
339 delete MD;
340}
341
342void ValueAsMetadata::handleRAUW(Value *From, Value *To) {
343 assert(From && "Expected valid value");
344 assert(To && "Expected valid value");
345 assert(From != To && "Expected changed value");
346 assert(From->getType() == To->getType() && "Unexpected type change");
347
348 LLVMContext &Context = From->getType()->getContext();
349 auto &Store = Context.pImpl->ValuesAsMetadata;
350 auto I = Store.find(From);
351 if (I == Store.end()) {
Owen Anderson7349ab92015-06-01 22:24:01 +0000352 assert(!From->IsUsedByMD &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000353 "Expected From not to be used by metadata");
354 return;
355 }
356
357 // Remove old entry from the map.
Owen Anderson7349ab92015-06-01 22:24:01 +0000358 assert(From->IsUsedByMD &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000359 "Expected From to be used by metadata");
Owen Anderson7349ab92015-06-01 22:24:01 +0000360 From->IsUsedByMD = false;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000361 ValueAsMetadata *MD = I->second;
362 assert(MD && "Expected valid metadata");
363 assert(MD->getValue() == From && "Expected valid mapping");
364 Store.erase(I);
365
366 if (isa<LocalAsMetadata>(MD)) {
367 if (auto *C = dyn_cast<Constant>(To)) {
368 // Local became a constant.
369 MD->replaceAllUsesWith(ConstantAsMetadata::get(C));
370 delete MD;
371 return;
372 }
373 if (getLocalFunction(From) && getLocalFunction(To) &&
374 getLocalFunction(From) != getLocalFunction(To)) {
375 // Function changed.
376 MD->replaceAllUsesWith(nullptr);
377 delete MD;
378 return;
379 }
380 } else if (!isa<Constant>(To)) {
381 // Changed to function-local value.
382 MD->replaceAllUsesWith(nullptr);
383 delete MD;
384 return;
385 }
386
387 auto *&Entry = Store[To];
388 if (Entry) {
389 // The target already exists.
390 MD->replaceAllUsesWith(Entry);
391 delete MD;
392 return;
393 }
394
395 // Update MD in place (and update the map entry).
Owen Anderson7349ab92015-06-01 22:24:01 +0000396 assert(!To->IsUsedByMD &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000397 "Expected this to be the only metadata use");
Owen Anderson7349ab92015-06-01 22:24:01 +0000398 To->IsUsedByMD = true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000399 MD->V = To;
400 Entry = MD;
401}
Duncan P. N. Exon Smitha69934f2014-11-14 18:42:09 +0000402
Devang Patela4f43fb2009-07-28 21:49:47 +0000403//===----------------------------------------------------------------------===//
Chris Lattnerb0c23e82009-10-19 07:10:59 +0000404// MDString implementation.
Owen Anderson0087fe62009-07-31 21:35:40 +0000405//
Chris Lattner5a409bd2009-12-28 08:30:43 +0000406
Devang Pateldcb99d32009-10-22 00:10:15 +0000407MDString *MDString::get(LLVMContext &Context, StringRef Str) {
Duncan P. N. Exon Smithf17e7402014-11-14 01:17:09 +0000408 auto &Store = Context.pImpl->MDStringCache;
Mehdi Aminicb708b22016-03-25 05:58:04 +0000409 auto I = Store.emplace_second(Str);
410 auto &MapEntry = I.first->getValue();
411 if (!I.second)
412 return &MapEntry;
413 MapEntry.Entry = &*I.first;
414 return &MapEntry;
Duncan P. N. Exon Smithf17e7402014-11-14 01:17:09 +0000415}
416
417StringRef MDString::getString() const {
Duncan P. N. Exon Smithc1a664f2014-12-05 01:41:34 +0000418 assert(Entry && "Expected to find string map entry");
419 return Entry->first();
Owen Anderson0087fe62009-07-31 21:35:40 +0000420}
421
422//===----------------------------------------------------------------------===//
Chris Lattnerb0c23e82009-10-19 07:10:59 +0000423// MDNode implementation.
Devang Patela4f43fb2009-07-28 21:49:47 +0000424//
Chris Lattner74a6ad62009-12-28 07:41:54 +0000425
James Y Knight8096d342015-06-17 01:21:20 +0000426// Assert that the MDNode types will not be unaligned by the objects
427// prepended to them.
428#define HANDLE_MDNODE_LEAF(CLASS) \
James Y Knightf27e4412015-06-17 13:53:12 +0000429 static_assert( \
430 llvm::AlignOf<uint64_t>::Alignment >= llvm::AlignOf<CLASS>::Alignment, \
431 "Alignment is insufficient after objects prepended to " #CLASS);
James Y Knight8096d342015-06-17 01:21:20 +0000432#include "llvm/IR/Metadata.def"
433
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000434void *MDNode::operator new(size_t Size, unsigned NumOps) {
James Y Knight8096d342015-06-17 01:21:20 +0000435 size_t OpSize = NumOps * sizeof(MDOperand);
436 // uint64_t is the most aligned type we need support (ensured by static_assert
437 // above)
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000438 OpSize = alignTo(OpSize, llvm::alignOf<uint64_t>());
James Y Knight8096d342015-06-17 01:21:20 +0000439 void *Ptr = reinterpret_cast<char *>(::operator new(OpSize + Size)) + OpSize;
Duncan P. N. Exon Smith22600ff2014-12-09 23:56:39 +0000440 MDOperand *O = static_cast<MDOperand *>(Ptr);
James Y Knight8096d342015-06-17 01:21:20 +0000441 for (MDOperand *E = O - NumOps; O != E; --O)
442 (void)new (O - 1) MDOperand;
443 return Ptr;
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000444}
445
Naomi Musgrave21c1bc42015-08-31 21:06:08 +0000446void MDNode::operator delete(void *Mem) {
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000447 MDNode *N = static_cast<MDNode *>(Mem);
James Y Knight8096d342015-06-17 01:21:20 +0000448 size_t OpSize = N->NumOperands * sizeof(MDOperand);
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000449 OpSize = alignTo(OpSize, llvm::alignOf<uint64_t>());
James Y Knight8096d342015-06-17 01:21:20 +0000450
Duncan P. N. Exon Smith22600ff2014-12-09 23:56:39 +0000451 MDOperand *O = static_cast<MDOperand *>(Mem);
452 for (MDOperand *E = O - N->NumOperands; O != E; --O)
453 (O - 1)->~MDOperand();
James Y Knight8096d342015-06-17 01:21:20 +0000454 ::operator delete(reinterpret_cast<char *>(Mem) - OpSize);
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000455}
456
Duncan P. N. Exon Smithf1340452015-01-19 18:36:18 +0000457MDNode::MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
Duncan P. N. Exon Smithfed199a2015-01-20 00:01:43 +0000458 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2)
459 : Metadata(ID, Storage), NumOperands(Ops1.size() + Ops2.size()),
460 NumUnresolved(0), Context(Context) {
461 unsigned Op = 0;
462 for (Metadata *MD : Ops1)
463 setOperand(Op++, MD);
464 for (Metadata *MD : Ops2)
465 setOperand(Op++, MD);
Duncan P. N. Exon Smith2711ca72015-01-19 19:02:06 +0000466
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000467 if (!isUniqued())
Duncan P. N. Exon Smith5e5b8502015-01-07 22:24:46 +0000468 return;
469
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000470 // Count the unresolved operands. If there are any, RAUW support will be
471 // added lazily on first reference.
472 countUnresolvedOperands();
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 Smithfef609f2016-04-03 21:23:52 +0000492void MDNode::countUnresolvedOperands() {
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000493 assert(NumUnresolved == 0 && "Expected unresolved ops to be uncounted");
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000494 assert(isUniqued() && "Expected this to be uniqued");
Benjamin Kramer4c1f0972015-02-08 21:56:09 +0000495 NumUnresolved = std::count_if(op_begin(), op_end(), isOperandUnresolved);
Duncan P. N. Exon Smithc5a0e2e2015-01-19 22:18:29 +0000496}
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 Smithfef609f2016-04-03 21:23:52 +0000508 countUnresolvedOperands();
509 if (!NumUnresolved) {
510 dropReplaceableUses();
511 assert(isResolved() && "Expected this to be resolved");
512 }
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000513
514 assert(isUniqued() && "Expected this to be uniqued");
515}
516
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000517void MDNode::makeDistinct() {
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000518 assert(isTemporary() && "Expected this to be temporary");
519 assert(!isResolved() && "Expected this to be unresolved");
520
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000521 // Drop RAUW support and store as a distinct node.
522 dropReplaceableUses();
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000523 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
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000533 NumUnresolved = 0;
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000534 dropReplaceableUses();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000535
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000536 assert(isResolved() && "Expected this to be resolved");
537}
538
539void MDNode::dropReplaceableUses() {
540 assert(!NumUnresolved && "Unexpected unresolved operand");
541
542 // Drop any RAUW support.
543 if (Context.hasReplaceableUses())
544 Context.takeReplaceableUses()->resolveAllUses();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000545}
546
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000547void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000548 assert(isUniqued() && "Expected this to be uniqued");
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000549 assert(NumUnresolved != 0 && "Expected unresolved operands");
Duncan P. N. Exon Smith3a16d802015-01-12 19:14:15 +0000550
Duncan P. N. Exon Smith0c87d772015-01-12 19:45:44 +0000551 // Check if an operand was resolved.
Duncan P. N. Exon Smith845755c42015-01-13 00:46:34 +0000552 if (!isOperandUnresolved(Old)) {
553 if (isOperandUnresolved(New))
554 // An operand was un-resolved!
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000555 ++NumUnresolved;
Duncan P. N. Exon Smith845755c42015-01-13 00:46:34 +0000556 } else if (!isOperandUnresolved(New))
Duncan P. N. Exon Smith0c87d772015-01-12 19:45:44 +0000557 decrementUnresolvedOperandCount();
Duncan P. N. Exon Smith3a16d802015-01-12 19:14:15 +0000558}
559
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000560void MDNode::decrementUnresolvedOperandCount() {
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000561 assert(!isResolved() && "Expected this to be unresolved");
562 if (isTemporary())
563 return;
564
565 assert(isUniqued() && "Expected this to be uniqued");
566 if (--NumUnresolved)
567 return;
568
569 // Last unresolved operand has just been resolved.
570 dropReplaceableUses();
571 assert(isResolved() && "Expected this to become resolved");
Duncan P. N. Exon Smith34c3d102015-01-12 19:43:15 +0000572}
573
Teresa Johnsonb703c772016-03-29 18:24:19 +0000574void MDNode::resolveCycles() {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000575 if (isResolved())
576 return;
577
578 // Resolve this node immediately.
579 resolve();
580
581 // Resolve all operands.
582 for (const auto &Op : operands()) {
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000583 auto *N = dyn_cast_or_null<MDNode>(Op);
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000584 if (!N)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000585 continue;
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000586
587 assert(!N->isTemporary() &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000588 "Expected all forward declarations to be resolved");
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000589 if (!N->isResolved())
590 N->resolveCycles();
Chris Lattner8cb6c342009-12-31 01:05:46 +0000591 }
Duncan P. N. Exon Smith50846f82014-11-18 00:37:17 +0000592}
593
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000594static bool hasSelfReference(MDNode *N) {
595 for (Metadata *MD : N->operands())
596 if (MD == N)
597 return true;
598 return false;
599}
600
601MDNode *MDNode::replaceWithPermanentImpl() {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +0000602 switch (getMetadataID()) {
603 default:
604 // If this type isn't uniquable, replace with a distinct node.
605 return replaceWithDistinctImpl();
606
607#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
608 case CLASS##Kind: \
609 break;
610#include "llvm/IR/Metadata.def"
611 }
612
613 // Even if this type is uniquable, self-references have to be distinct.
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000614 if (hasSelfReference(this))
615 return replaceWithDistinctImpl();
616 return replaceWithUniquedImpl();
617}
618
Duncan P. N. Exon Smith86475292015-01-19 23:17:09 +0000619MDNode *MDNode::replaceWithUniquedImpl() {
620 // Try to uniquify in place.
621 MDNode *UniquedNode = uniquify();
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000622
Duncan P. N. Exon Smith86475292015-01-19 23:17:09 +0000623 if (UniquedNode == this) {
624 makeUniqued();
625 return this;
626 }
627
628 // Collision, so RAUW instead.
629 replaceAllUsesWith(UniquedNode);
630 deleteAsSubclass();
631 return UniquedNode;
632}
633
634MDNode *MDNode::replaceWithDistinctImpl() {
635 makeDistinct();
636 return this;
637}
638
Duncan P. N. Exon Smith118632d2015-01-12 20:09:34 +0000639void MDTuple::recalculateHash() {
Duncan P. N. Exon Smith93e983e2015-01-19 22:53:18 +0000640 setHash(MDTupleInfo::KeyTy::calculateHash(this));
Duncan P. N. Exon Smith967629e2015-01-12 19:16:34 +0000641}
642
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000643void MDNode::dropAllReferences() {
644 for (unsigned I = 0, E = NumOperands; I != E; ++I)
645 setOperand(I, nullptr);
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000646 if (Context.hasReplaceableUses()) {
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000647 Context.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);
648 (void)Context.takeReplaceableUses();
649 }
Chris Lattner8cb6c342009-12-31 01:05:46 +0000650}
651
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000652void MDNode::handleChangedOperand(void *Ref, Metadata *New) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000653 unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
654 assert(Op < getNumOperands() && "Expected valid operand");
655
Duncan P. N. Exon Smith3d580562015-01-19 19:28:28 +0000656 if (!isUniqued()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000657 // This node is not uniqued. Just set the operand and be done with it.
658 setOperand(Op, New);
659 return;
Duncan Sandsc2928c62010-05-04 12:43:36 +0000660 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000661
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000662 // This node is uniqued.
663 eraseFromStore();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000664
665 Metadata *Old = getOperand(Op);
666 setOperand(Op, New);
667
Duncan P. N. Exon Smithbcd960a2015-01-05 23:31:54 +0000668 // Drop uniquing for self-reference cycles.
669 if (New == this) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000670 if (!isResolved())
671 resolve();
Duncan P. N. Exon Smithf08b8b42015-01-19 19:25:33 +0000672 storeDistinctInContext();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000673 return;
674 }
675
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000676 // Re-unique the node.
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000677 auto *Uniqued = uniquify();
678 if (Uniqued == this) {
Duncan P. N. Exon Smith3a16d802015-01-12 19:14:15 +0000679 if (!isResolved())
680 resolveAfterOperandChange(Old, New);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000681 return;
682 }
683
684 // Collision.
685 if (!isResolved()) {
686 // Still unresolved, so RAUW.
Duncan P. N. Exon Smithd9e6eb72015-01-12 19:36:35 +0000687 //
688 // First, clear out all operands to prevent any recursion (similar to
689 // dropAllReferences(), but we still need the use-list).
690 for (unsigned O = 0, E = getNumOperands(); O != E; ++O)
691 setOperand(O, nullptr);
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000692 if (Context.hasReplaceableUses())
693 Context.getReplaceableUses()->replaceAllUsesWith(Uniqued);
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000694 deleteAsSubclass();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000695 return;
696 }
697
Duncan P. N. Exon Smithd9e6eb72015-01-12 19:36:35 +0000698 // Store in non-uniqued form if RAUW isn't possible.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000699 storeDistinctInContext();
Victor Hernandeze5f2af72010-01-20 04:45:57 +0000700}
701
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000702void MDNode::deleteAsSubclass() {
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000703 switch (getMetadataID()) {
704 default:
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000705 llvm_unreachable("Invalid subclass of MDNode");
706#define HANDLE_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000707 case CLASS##Kind: \
708 delete cast<CLASS>(this); \
709 break;
710#include "llvm/IR/Metadata.def"
711 }
712}
713
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000714template <class T, class InfoT>
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000715static T *uniquifyImpl(T *N, DenseSet<T *, InfoT> &Store) {
716 if (T *U = getUniqued(Store, N))
717 return U;
718
719 Store.insert(N);
720 return N;
721}
722
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000723template <class NodeTy> struct MDNode::HasCachedHash {
724 typedef char Yes[1];
725 typedef char No[2];
726 template <class U, U Val> struct SFINAE {};
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000727
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000728 template <class U>
729 static Yes &check(SFINAE<void (U::*)(unsigned), &U::setHash> *);
730 template <class U> static No &check(...);
731
732 static const bool value = sizeof(check<NodeTy>(nullptr)) == sizeof(Yes);
733};
734
735MDNode *MDNode::uniquify() {
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000736 assert(!hasSelfReference(this) && "Cannot uniquify a self-referencing node");
737
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000738 // Try to insert into uniquing store.
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000739 switch (getMetadataID()) {
740 default:
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +0000741 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
742#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000743 case CLASS##Kind: { \
744 CLASS *SubclassThis = cast<CLASS>(this); \
745 std::integral_constant<bool, HasCachedHash<CLASS>::value> \
746 ShouldRecalculateHash; \
747 dispatchRecalculateHash(SubclassThis, ShouldRecalculateHash); \
748 return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s); \
749 }
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000750#include "llvm/IR/Metadata.def"
751 }
752}
753
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000754void MDNode::eraseFromStore() {
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000755 switch (getMetadataID()) {
756 default:
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +0000757 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
758#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000759 case CLASS##Kind: \
Duncan P. N. Exon Smith6cf10d22015-01-19 22:47:08 +0000760 getContext().pImpl->CLASS##s.erase(cast<CLASS>(this)); \
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000761 break;
762#include "llvm/IR/Metadata.def"
763 }
764}
765
Duncan P. N. Exon Smithac3128d2015-01-12 20:13:56 +0000766MDTuple *MDTuple::getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
Duncan P. N. Exon Smith1b0064d2015-01-19 20:14:15 +0000767 StorageType Storage, bool ShouldCreate) {
768 unsigned Hash = 0;
769 if (Storage == Uniqued) {
770 MDTupleInfo::KeyTy Key(MDs);
Duncan P. N. Exon Smithb57f9e92015-01-19 20:16:50 +0000771 if (auto *N = getUniqued(Context.pImpl->MDTuples, Key))
772 return N;
Duncan P. N. Exon Smith1b0064d2015-01-19 20:14:15 +0000773 if (!ShouldCreate)
774 return nullptr;
Duncan P. N. Exon Smith93e983e2015-01-19 22:53:18 +0000775 Hash = Key.getHash();
Duncan P. N. Exon Smith1b0064d2015-01-19 20:14:15 +0000776 } else {
777 assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
778 }
Duncan Sands26a80f32012-03-31 08:20:11 +0000779
Duncan P. N. Exon Smith5b8c4402015-01-19 20:18:13 +0000780 return storeImpl(new (MDs.size()) MDTuple(Context, Storage, Hash, MDs),
781 Storage, Context.pImpl->MDTuples);
Duncan P. N. Exon Smith5e5b8502015-01-07 22:24:46 +0000782}
783
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000784void MDNode::deleteTemporary(MDNode *N) {
785 assert(N->isTemporary() && "Expected temporary node");
Duncan P. N. Exon Smith8d536972015-01-22 21:36:45 +0000786 N->replaceAllUsesWith(nullptr);
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000787 N->deleteAsSubclass();
Dan Gohman16a5d982010-08-20 22:02:26 +0000788}
789
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000790void MDNode::storeDistinctInContext() {
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000791 assert(!Context.hasReplaceableUses() && "Unexpected replaceable uses");
792 assert(!NumUnresolved && "Unexpected unresolved nodes");
Duncan P. N. Exon Smithf1340452015-01-19 18:36:18 +0000793 Storage = Distinct;
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000794 assert(isResolved() && "Expected this to be resolved");
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000795
796 // Reset the hash.
797 switch (getMetadataID()) {
798 default:
799 llvm_unreachable("Invalid subclass of MDNode");
800#define HANDLE_MDNODE_LEAF(CLASS) \
801 case CLASS##Kind: { \
802 std::integral_constant<bool, HasCachedHash<CLASS>::value> ShouldResetHash; \
803 dispatchResetHash(cast<CLASS>(this), ShouldResetHash); \
804 break; \
805 }
806#include "llvm/IR/Metadata.def"
807 }
808
Duncan P. N. Exon Smith3eef9d12016-04-19 23:59:13 +0000809 getContext().pImpl->DistinctMDNodes.push_back(this);
Devang Patel82ab3f82010-02-18 20:53:16 +0000810}
Chris Lattnerf543eff2009-12-28 09:12:35 +0000811
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000812void MDNode::replaceOperandWith(unsigned I, Metadata *New) {
813 if (getOperand(I) == New)
Devang Patelf7188322009-09-03 01:39:20 +0000814 return;
Devang Patelf7188322009-09-03 01:39:20 +0000815
Duncan P. N. Exon Smithde03a8b2015-01-19 18:45:35 +0000816 if (!isUniqued()) {
Duncan P. N. Exon Smithdaa335a2015-01-12 18:01:45 +0000817 setOperand(I, New);
Duncan P. N. Exon Smithf39c3b82014-11-17 23:28:21 +0000818 return;
819 }
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +0000820
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000821 handleChangedOperand(mutable_begin() + I, New);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000822}
Chris Lattnerc6d17e22009-12-28 09:24:53 +0000823
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000824void MDNode::setOperand(unsigned I, Metadata *New) {
825 assert(I < NumOperands);
Duncan P. N. Exon Smithefdf2852015-01-19 19:29:25 +0000826 mutable_begin()[I].reset(New, isUniqued() ? this : nullptr);
Devang Patelf7188322009-09-03 01:39:20 +0000827}
828
Sanjay Patel9da9c762016-03-12 20:44:58 +0000829/// Get a node or a self-reference that looks like it.
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000830///
831/// Special handling for finding self-references, for use by \a
832/// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
833/// when self-referencing nodes were still uniqued. If the first operand has
834/// the same operands as \c Ops, return the first operand instead.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000835static MDNode *getOrSelfReference(LLVMContext &Context,
836 ArrayRef<Metadata *> Ops) {
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000837 if (!Ops.empty())
838 if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))
839 if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
840 for (unsigned I = 1, E = Ops.size(); I != E; ++I)
841 if (Ops[I] != N->getOperand(I))
842 return MDNode::get(Context, Ops);
843 return N;
844 }
845
846 return MDNode::get(Context, Ops);
847}
848
Hal Finkel94146652014-07-24 14:25:39 +0000849MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {
850 if (!A)
851 return B;
852 if (!B)
853 return A;
854
Benjamin Kramer4c1f0972015-02-08 21:56:09 +0000855 SmallVector<Metadata *, 4> MDs;
856 MDs.reserve(A->getNumOperands() + B->getNumOperands());
857 MDs.append(A->op_begin(), A->op_end());
858 MDs.append(B->op_begin(), B->op_end());
Hal Finkel94146652014-07-24 14:25:39 +0000859
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000860 // FIXME: This preserves long-standing behaviour, but is it really the right
861 // behaviour? Or was that an unintended side-effect of node uniquing?
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000862 return getOrSelfReference(A->getContext(), MDs);
Hal Finkel94146652014-07-24 14:25:39 +0000863}
864
865MDNode *MDNode::intersect(MDNode *A, MDNode *B) {
866 if (!A || !B)
867 return nullptr;
868
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000869 SmallVector<Metadata *, 4> MDs;
Benjamin Kramer4c1f0972015-02-08 21:56:09 +0000870 for (Metadata *MD : A->operands())
871 if (std::find(B->op_begin(), B->op_end(), MD) != B->op_end())
872 MDs.push_back(MD);
Hal Finkel94146652014-07-24 14:25:39 +0000873
Duncan P. N. Exon Smithac8ee282014-12-07 19:52:06 +0000874 // FIXME: This preserves long-standing behaviour, but is it really the right
875 // behaviour? Or was that an unintended side-effect of node uniquing?
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000876 return getOrSelfReference(A->getContext(), MDs);
Hal Finkel94146652014-07-24 14:25:39 +0000877}
878
Bjorn Steinbrink5ec75222015-02-08 17:07:14 +0000879MDNode *MDNode::getMostGenericAliasScope(MDNode *A, MDNode *B) {
880 if (!A || !B)
881 return nullptr;
882
883 SmallVector<Metadata *, 4> MDs(B->op_begin(), B->op_end());
Benjamin Kramer4c1f0972015-02-08 21:56:09 +0000884 for (Metadata *MD : A->operands())
885 if (std::find(B->op_begin(), B->op_end(), MD) == B->op_end())
886 MDs.push_back(MD);
Bjorn Steinbrink5ec75222015-02-08 17:07:14 +0000887
888 // FIXME: This preserves long-standing behaviour, but is it really the right
889 // behaviour? Or was that an unintended side-effect of node uniquing?
890 return getOrSelfReference(A->getContext(), MDs);
891}
892
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000893MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
894 if (!A || !B)
Craig Topperc6207612014-04-09 06:08:46 +0000895 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000896
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000897 APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
898 APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000899 if (AVal.compare(BVal) == APFloat::cmpLessThan)
900 return A;
901 return B;
902}
903
904static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
905 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
906}
907
908static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
909 return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
910}
911
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000912static bool tryMergeRange(SmallVectorImpl<ConstantInt *> &EndPoints,
913 ConstantInt *Low, ConstantInt *High) {
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000914 ConstantRange NewRange(Low->getValue(), High->getValue());
915 unsigned Size = EndPoints.size();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000916 APInt LB = EndPoints[Size - 2]->getValue();
917 APInt LE = EndPoints[Size - 1]->getValue();
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000918 ConstantRange LastRange(LB, LE);
919 if (canBeMerged(NewRange, LastRange)) {
920 ConstantRange Union = LastRange.unionWith(NewRange);
921 Type *Ty = High->getType();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000922 EndPoints[Size - 2] =
923 cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
924 EndPoints[Size - 1] =
925 cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000926 return true;
927 }
928 return false;
929}
930
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000931static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,
932 ConstantInt *Low, ConstantInt *High) {
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000933 if (!EndPoints.empty())
934 if (tryMergeRange(EndPoints, Low, High))
935 return;
936
937 EndPoints.push_back(Low);
938 EndPoints.push_back(High);
939}
940
941MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
942 // Given two ranges, we want to compute the union of the ranges. This
943 // is slightly complitade by having to combine the intervals and merge
944 // the ones that overlap.
945
946 if (!A || !B)
Craig Topperc6207612014-04-09 06:08:46 +0000947 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000948
949 if (A == B)
950 return A;
951
952 // First, walk both lists in older of the lower boundary of each interval.
953 // 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 +0000954 SmallVector<ConstantInt *, 4> EndPoints;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000955 int AI = 0;
956 int BI = 0;
957 int AN = A->getNumOperands() / 2;
958 int BN = B->getNumOperands() / 2;
959 while (AI < AN && BI < BN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000960 ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
961 ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000962
963 if (ALow->getValue().slt(BLow->getValue())) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000964 addRange(EndPoints, ALow,
965 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000966 ++AI;
967 } else {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000968 addRange(EndPoints, BLow,
969 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000970 ++BI;
971 }
972 }
973 while (AI < AN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000974 addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
975 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000976 ++AI;
977 }
978 while (BI < BN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000979 addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
980 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000981 ++BI;
982 }
983
984 // If we have more than 2 ranges (4 endpoints) we have to try to merge
985 // the last and first ones.
986 unsigned Size = EndPoints.size();
987 if (Size > 4) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000988 ConstantInt *FB = EndPoints[0];
989 ConstantInt *FE = EndPoints[1];
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000990 if (tryMergeRange(EndPoints, FB, FE)) {
991 for (unsigned i = 0; i < Size - 2; ++i) {
992 EndPoints[i] = EndPoints[i + 2];
993 }
994 EndPoints.resize(Size - 2);
995 }
996 }
997
998 // If in the end we have a single range, it is possible that it is now the
999 // full range. Just drop the metadata in that case.
1000 if (EndPoints.size() == 2) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001001 ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
Hal Finkel16ddd4b2012-06-16 20:33:37 +00001002 if (Range.isFullSet())
Craig Topperc6207612014-04-09 06:08:46 +00001003 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +00001004 }
1005
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001006 SmallVector<Metadata *, 4> MDs;
1007 MDs.reserve(EndPoints.size());
1008 for (auto *I : EndPoints)
1009 MDs.push_back(ConstantAsMetadata::get(I));
1010 return MDNode::get(A->getContext(), MDs);
Hal Finkel16ddd4b2012-06-16 20:33:37 +00001011}
1012
Artur Pilipenko5c5011d2015-11-02 17:53:51 +00001013MDNode *MDNode::getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B) {
1014 if (!A || !B)
1015 return nullptr;
1016
1017 ConstantInt *AVal = mdconst::extract<ConstantInt>(A->getOperand(0));
1018 ConstantInt *BVal = mdconst::extract<ConstantInt>(B->getOperand(0));
1019 if (AVal->getZExtValue() < BVal->getZExtValue())
1020 return A;
1021 return B;
1022}
1023
Devang Patel05a26fb2009-07-29 00:33:07 +00001024//===----------------------------------------------------------------------===//
Chris Lattnerb0c23e82009-10-19 07:10:59 +00001025// NamedMDNode implementation.
Devang Patel05a26fb2009-07-29 00:33:07 +00001026//
Devang Patel943ddf62010-01-12 18:34:06 +00001027
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001028static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
1029 return *(SmallVector<TrackingMDRef, 4> *)Operands;
Chris Lattner1bc810b2009-12-28 08:07:14 +00001030}
1031
Dan Gohman2637cc12010-07-21 23:38:33 +00001032NamedMDNode::NamedMDNode(const Twine &N)
Duncan P. N. Exon Smithc5754a62014-11-05 18:16:03 +00001033 : Name(N.str()), Parent(nullptr),
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001034 Operands(new SmallVector<TrackingMDRef, 4>()) {}
Devang Patel5c310be2009-08-11 18:01:24 +00001035
Chris Lattner1bc810b2009-12-28 08:07:14 +00001036NamedMDNode::~NamedMDNode() {
1037 dropAllReferences();
1038 delete &getNMDOps(Operands);
1039}
1040
Chris Lattner9b493022009-12-31 01:22:29 +00001041unsigned NamedMDNode::getNumOperands() const {
Chris Lattner1bc810b2009-12-28 08:07:14 +00001042 return (unsigned)getNMDOps(Operands).size();
1043}
1044
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001045MDNode *NamedMDNode::getOperand(unsigned i) const {
Chris Lattner9b493022009-12-31 01:22:29 +00001046 assert(i < getNumOperands() && "Invalid Operand number!");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001047 auto *N = getNMDOps(Operands)[i].get();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001048 return cast_or_null<MDNode>(N);
Chris Lattner1bc810b2009-12-28 08:07:14 +00001049}
1050
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001051void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
Chris Lattner1bc810b2009-12-28 08:07:14 +00001052
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001053void NamedMDNode::setOperand(unsigned I, MDNode *New) {
1054 assert(I < getNumOperands() && "Invalid operand number");
1055 getNMDOps(Operands)[I].reset(New);
1056}
1057
Devang Patel79238d72009-08-03 06:19:01 +00001058void NamedMDNode::eraseFromParent() {
Dan Gohman2637cc12010-07-21 23:38:33 +00001059 getParent()->eraseNamedMetadata(this);
Devang Patel79238d72009-08-03 06:19:01 +00001060}
1061
Devang Patel79238d72009-08-03 06:19:01 +00001062void NamedMDNode::dropAllReferences() {
Chris Lattner1bc810b2009-12-28 08:07:14 +00001063 getNMDOps(Operands).clear();
Devang Patel79238d72009-08-03 06:19:01 +00001064}
1065
Devang Patelfcfee0f2010-01-07 19:39:36 +00001066StringRef NamedMDNode::getName() const {
1067 return StringRef(Name);
1068}
Devang Pateld5497a4b2009-09-16 18:09:00 +00001069
1070//===----------------------------------------------------------------------===//
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001071// Instruction Metadata method implementations.
1072//
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001073void MDAttachmentMap::set(unsigned ID, MDNode &MD) {
1074 for (auto &I : Attachments)
1075 if (I.first == ID) {
1076 I.second.reset(&MD);
1077 return;
1078 }
1079 Attachments.emplace_back(std::piecewise_construct, std::make_tuple(ID),
1080 std::make_tuple(&MD));
1081}
1082
1083void MDAttachmentMap::erase(unsigned ID) {
1084 if (empty())
1085 return;
1086
1087 // Common case is one/last value.
1088 if (Attachments.back().first == ID) {
1089 Attachments.pop_back();
1090 return;
1091 }
1092
1093 for (auto I = Attachments.begin(), E = std::prev(Attachments.end()); I != E;
1094 ++I)
1095 if (I->first == ID) {
1096 *I = std::move(Attachments.back());
1097 Attachments.pop_back();
1098 return;
1099 }
1100}
1101
1102MDNode *MDAttachmentMap::lookup(unsigned ID) const {
1103 for (const auto &I : Attachments)
1104 if (I.first == ID)
1105 return I.second;
1106 return nullptr;
1107}
1108
1109void MDAttachmentMap::getAll(
1110 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1111 Result.append(Attachments.begin(), Attachments.end());
1112
1113 // Sort the resulting array so it is stable.
1114 if (Result.size() > 1)
1115 array_pod_sort(Result.begin(), Result.end());
1116}
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001117
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001118void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
1119 if (!Node && !hasMetadata())
1120 return;
1121 setMetadata(getContext().getMDKindID(Kind), Node);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001122}
1123
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001124MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
Chris Lattnera0566972009-12-29 09:01:33 +00001125 return getMetadataImpl(getContext().getMDKindID(Kind));
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001126}
1127
Adrian Prantlcbdfdb72015-08-20 22:00:30 +00001128void Instruction::dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs) {
Rafael Espindolaab73c492014-01-28 16:56:46 +00001129 SmallSet<unsigned, 5> KnownSet;
1130 KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
1131
Rafael Espindolaab73c492014-01-28 16:56:46 +00001132 if (!hasMetadataHashEntry())
1133 return; // Nothing to remove!
1134
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001135 auto &InstructionMetadata = getContext().pImpl->InstructionMetadata;
Rafael Espindolaab73c492014-01-28 16:56:46 +00001136
1137 if (KnownSet.empty()) {
1138 // Just drop our entry at the store.
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001139 InstructionMetadata.erase(this);
Rafael Espindolaab73c492014-01-28 16:56:46 +00001140 setHasMetadataHashEntry(false);
1141 return;
1142 }
1143
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001144 auto &Info = InstructionMetadata[this];
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001145 Info.remove_if([&KnownSet](const std::pair<unsigned, TrackingMDNodeRef> &I) {
1146 return !KnownSet.count(I.first);
1147 });
Rafael Espindolaab73c492014-01-28 16:56:46 +00001148
Duncan P. N. Exon Smith75ef0c02015-04-24 20:23:44 +00001149 if (Info.empty()) {
Rafael Espindolaab73c492014-01-28 16:56:46 +00001150 // Drop our entry at the store.
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001151 InstructionMetadata.erase(this);
Rafael Espindolaab73c492014-01-28 16:56:46 +00001152 setHasMetadataHashEntry(false);
1153 }
1154}
1155
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001156void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
1157 if (!Node && !hasMetadata())
1158 return;
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001159
Chris Lattnerc263b422010-03-30 23:03:27 +00001160 // Handle 'dbg' as a special case since it is not stored in the hash table.
1161 if (KindID == LLVMContext::MD_dbg) {
Duncan P. N. Exon Smithab659fb32015-03-30 19:40:05 +00001162 DbgLoc = DebugLoc(Node);
Chris Lattnerc263b422010-03-30 23:03:27 +00001163 return;
1164 }
1165
Chris Lattnera0566972009-12-29 09:01:33 +00001166 // Handle the case when we're adding/updating metadata on an instruction.
1167 if (Node) {
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001168 auto &Info = getContext().pImpl->InstructionMetadata[this];
Chris Lattnerc263b422010-03-30 23:03:27 +00001169 assert(!Info.empty() == hasMetadataHashEntry() &&
1170 "HasMetadata bit is wonked");
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001171 if (Info.empty())
Chris Lattnerc263b422010-03-30 23:03:27 +00001172 setHasMetadataHashEntry(true);
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001173 Info.set(KindID, *Node);
Chris Lattnera0566972009-12-29 09:01:33 +00001174 return;
1175 }
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001176
Chris Lattnera0566972009-12-29 09:01:33 +00001177 // Otherwise, we're removing metadata from an instruction.
Nick Lewycky4c131382011-12-27 01:17:40 +00001178 assert((hasMetadataHashEntry() ==
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001179 (getContext().pImpl->InstructionMetadata.count(this) > 0)) &&
Chris Lattnera0566972009-12-29 09:01:33 +00001180 "HasMetadata bit out of date!");
Nick Lewycky4c131382011-12-27 01:17:40 +00001181 if (!hasMetadataHashEntry())
1182 return; // Nothing to remove!
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001183 auto &Info = getContext().pImpl->InstructionMetadata[this];
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001184
Chris Lattnerc263b422010-03-30 23:03:27 +00001185 // Handle removal of an existing value.
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001186 Info.erase(KindID);
1187
1188 if (!Info.empty())
1189 return;
1190
1191 getContext().pImpl->InstructionMetadata.erase(this);
1192 setHasMetadataHashEntry(false);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001193}
1194
Hal Finkelcc39b672014-07-24 12:16:19 +00001195void Instruction::setAAMetadata(const AAMDNodes &N) {
1196 setMetadata(LLVMContext::MD_tbaa, N.TBAA);
Hal Finkel94146652014-07-24 14:25:39 +00001197 setMetadata(LLVMContext::MD_alias_scope, N.Scope);
1198 setMetadata(LLVMContext::MD_noalias, N.NoAlias);
Hal Finkelcc39b672014-07-24 12:16:19 +00001199}
1200
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001201MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
Chris Lattnerc263b422010-03-30 23:03:27 +00001202 // Handle 'dbg' as a special case since it is not stored in the hash table.
1203 if (KindID == LLVMContext::MD_dbg)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001204 return DbgLoc.getAsMDNode();
1205
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001206 if (!hasMetadataHashEntry())
1207 return nullptr;
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001208 auto &Info = getContext().pImpl->InstructionMetadata[this];
Chris Lattnerc263b422010-03-30 23:03:27 +00001209 assert(!Info.empty() && "bit out of sync with hash table");
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001210
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001211 return Info.lookup(KindID);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001212}
1213
Duncan P. N. Exon Smith4abd1a02014-11-01 00:26:42 +00001214void Instruction::getAllMetadataImpl(
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001215 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
Chris Lattnerc263b422010-03-30 23:03:27 +00001216 Result.clear();
1217
1218 // 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 +00001219 if (DbgLoc) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001220 Result.push_back(
1221 std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
Chris Lattnerc263b422010-03-30 23:03:27 +00001222 if (!hasMetadataHashEntry()) return;
1223 }
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001224
Chris Lattnerc263b422010-03-30 23:03:27 +00001225 assert(hasMetadataHashEntry() &&
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001226 getContext().pImpl->InstructionMetadata.count(this) &&
Chris Lattnera0566972009-12-29 09:01:33 +00001227 "Shouldn't have called this");
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001228 const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
Chris Lattnera0566972009-12-29 09:01:33 +00001229 assert(!Info.empty() && "Shouldn't have called this");
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001230 Info.getAll(Result);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001231}
1232
Duncan P. N. Exon Smith3d5a02f2014-11-03 18:13:57 +00001233void Instruction::getAllMetadataOtherThanDebugLocImpl(
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001234 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001235 Result.clear();
1236 assert(hasMetadataHashEntry() &&
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001237 getContext().pImpl->InstructionMetadata.count(this) &&
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001238 "Shouldn't have called this");
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001239 const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001240 assert(!Info.empty() && "Shouldn't have called this");
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001241 Info.getAll(Result);
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001242}
1243
Dan Gohman48a995f2010-07-20 22:25:04 +00001244void Instruction::clearMetadataHashEntries() {
1245 assert(hasMetadataHashEntry() && "Caller should check");
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001246 getContext().pImpl->InstructionMetadata.erase(this);
Dan Gohman48a995f2010-07-20 22:25:04 +00001247 setHasMetadataHashEntry(false);
Chris Lattner68017802009-12-29 07:44:16 +00001248}
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001249
1250MDNode *Function::getMetadata(unsigned KindID) const {
1251 if (!hasMetadata())
1252 return nullptr;
1253 return getContext().pImpl->FunctionMetadata[this].lookup(KindID);
1254}
1255
1256MDNode *Function::getMetadata(StringRef Kind) const {
1257 if (!hasMetadata())
1258 return nullptr;
1259 return getMetadata(getContext().getMDKindID(Kind));
1260}
1261
1262void Function::setMetadata(unsigned KindID, MDNode *MD) {
1263 if (MD) {
1264 if (!hasMetadata())
1265 setHasMetadataHashEntry(true);
1266
1267 getContext().pImpl->FunctionMetadata[this].set(KindID, *MD);
1268 return;
1269 }
1270
1271 // Nothing to unset.
1272 if (!hasMetadata())
1273 return;
1274
1275 auto &Store = getContext().pImpl->FunctionMetadata[this];
1276 Store.erase(KindID);
1277 if (Store.empty())
1278 clearMetadata();
1279}
1280
1281void Function::setMetadata(StringRef Kind, MDNode *MD) {
1282 if (!MD && !hasMetadata())
1283 return;
1284 setMetadata(getContext().getMDKindID(Kind), MD);
1285}
1286
1287void Function::getAllMetadata(
1288 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
1289 MDs.clear();
1290
1291 if (!hasMetadata())
1292 return;
1293
1294 getContext().pImpl->FunctionMetadata[this].getAll(MDs);
1295}
1296
1297void Function::dropUnknownMetadata(ArrayRef<unsigned> KnownIDs) {
1298 if (!hasMetadata())
1299 return;
1300 if (KnownIDs.empty()) {
1301 clearMetadata();
1302 return;
1303 }
1304
1305 SmallSet<unsigned, 5> KnownSet;
1306 KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
1307
1308 auto &Store = getContext().pImpl->FunctionMetadata[this];
1309 assert(!Store.empty());
1310
1311 Store.remove_if([&KnownSet](const std::pair<unsigned, TrackingMDNodeRef> &I) {
1312 return !KnownSet.count(I.first);
1313 });
1314
1315 if (Store.empty())
1316 clearMetadata();
1317}
1318
1319void Function::clearMetadata() {
1320 if (!hasMetadata())
1321 return;
1322 getContext().pImpl->FunctionMetadata.erase(this);
1323 setHasMetadataHashEntry(false);
1324}
Duncan P. N. Exon Smithb56b5af2015-08-28 21:55:35 +00001325
1326void Function::setSubprogram(DISubprogram *SP) {
1327 setMetadata(LLVMContext::MD_dbg, SP);
1328}
1329
1330DISubprogram *Function::getSubprogram() const {
1331 return cast_or_null<DISubprogram>(getMetadata(LLVMContext::MD_dbg));
1332}