blob: cd5edd216c3c90857d1cdd2e542db911d9deaae3 [file] [log] [blame]
Devang Patela4f43fb2009-07-28 21:49:47 +00001//===-- Metadata.cpp - Implement Metadata classes -------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements 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"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "SymbolTableListTraitsImpl.h"
17#include "llvm/ADT/DenseMap.h"
18#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/SmallString.h"
21#include "llvm/ADT/StringMap.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000022#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Instruction.h"
24#include "llvm/IR/LLVMContext.h"
Chandler Carruth4b6845c2014-03-04 12:46:06 +000025#include "llvm/IR/LeakDetector.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Module.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000027#include "llvm/IR/ValueHandle.h"
Duncan P. N. Exon Smith46d91ad2014-11-14 18:42:06 +000028
Devang Patela4f43fb2009-07-28 21:49:47 +000029using namespace llvm;
30
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +000031MetadataAsValue::MetadataAsValue(Type *Ty, Metadata *MD)
32 : Value(Ty, MetadataAsValueVal), MD(MD) {
33 track();
34}
35
36MetadataAsValue::~MetadataAsValue() {
37 getType()->getContext().pImpl->MetadataAsValues.erase(MD);
38 untrack();
39}
40
41/// \brief Canonicalize metadata arguments to intrinsics.
42///
43/// To support bitcode upgrades (and assembly semantic sugar) for \a
44/// MetadataAsValue, we need to canonicalize certain metadata.
45///
46/// - nullptr is replaced by an empty MDNode.
47/// - An MDNode with a single null operand is replaced by an empty MDNode.
48/// - An MDNode whose only operand is a \a ConstantAsMetadata gets skipped.
49///
50/// This maintains readability of bitcode from when metadata was a type of
51/// value, and these bridges were unnecessary.
52static Metadata *canonicalizeMetadataForValue(LLVMContext &Context,
53 Metadata *MD) {
54 if (!MD)
55 // !{}
56 return MDNode::get(Context, None);
57
58 // Return early if this isn't a single-operand MDNode.
59 auto *N = dyn_cast<MDNode>(MD);
60 if (!N || N->getNumOperands() != 1)
61 return MD;
62
63 if (!N->getOperand(0))
64 // !{}
65 return MDNode::get(Context, None);
66
67 if (auto *C = dyn_cast<ConstantAsMetadata>(N->getOperand(0)))
68 // Look through the MDNode.
69 return C;
70
71 return MD;
72}
73
74MetadataAsValue *MetadataAsValue::get(LLVMContext &Context, Metadata *MD) {
75 MD = canonicalizeMetadataForValue(Context, MD);
76 auto *&Entry = Context.pImpl->MetadataAsValues[MD];
77 if (!Entry)
78 Entry = new MetadataAsValue(Type::getMetadataTy(Context), MD);
79 return Entry;
80}
81
82MetadataAsValue *MetadataAsValue::getIfExists(LLVMContext &Context,
83 Metadata *MD) {
84 MD = canonicalizeMetadataForValue(Context, MD);
85 auto &Store = Context.pImpl->MetadataAsValues;
86 auto I = Store.find(MD);
87 return I == Store.end() ? nullptr : I->second;
88}
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
123void ReplaceableMetadataImpl::addRef(void *Ref, OwnerTy Owner) {
124 bool WasInserted = UseMap.insert(std::make_pair(Ref, Owner)).second;
125 (void)WasInserted;
126 assert(WasInserted && "Expected to add a reference");
127}
128
129void ReplaceableMetadataImpl::dropRef(void *Ref) {
130 bool WasErased = UseMap.erase(Ref);
131 (void)WasErased;
132 assert(WasErased && "Expected to drop a reference");
133}
134
135void ReplaceableMetadataImpl::moveRef(void *Ref, void *New,
136 const Metadata &MD) {
137 auto I = UseMap.find(Ref);
138 assert(I != UseMap.end() && "Expected to move a reference");
139 OwnerTy Owner = I->second;
140 UseMap.erase(I);
141 addRef(New, Owner);
142
143 // Check that the references are direct if there's no owner.
144 (void)MD;
145 assert((Owner || *static_cast<Metadata **>(Ref) == &MD) &&
146 "Reference without owner must be direct");
147 assert((Owner || *static_cast<Metadata **>(New) == &MD) &&
148 "Reference without owner must be direct");
149}
150
151void ReplaceableMetadataImpl::replaceAllUsesWith(Metadata *MD) {
152 assert(!(MD && isa<MDNodeFwdDecl>(MD)) && "Expected non-temp node");
153
154 if (UseMap.empty())
155 return;
156
157 // Copy out uses since UseMap will get touched below.
158 SmallVector<std::pair<void *, OwnerTy>, 8> Uses(UseMap.begin(), UseMap.end());
159 for (const auto &Pair : Uses) {
160 if (!Pair.second) {
161 // Update unowned tracking references directly.
162 Metadata *&Ref = *static_cast<Metadata **>(Pair.first);
163 Ref = MD;
164 MetadataTracking::track(Ref);
165 UseMap.erase(Pair.first);
166 continue;
167 }
168
169 // Check for MetadataAsValue.
170 if (Pair.second.is<MetadataAsValue *>()) {
171 Pair.second.get<MetadataAsValue *>()->handleChangedMetadata(MD);
172 continue;
173 }
174
175 // There's a Metadata owner -- dispatch.
176 Metadata *Owner = Pair.second.get<Metadata *>();
177 switch (Owner->getMetadataID()) {
178#define HANDLE_METADATA_LEAF(CLASS) \
179 case Metadata::CLASS##Kind: \
180 cast<CLASS>(Owner)->handleChangedOperand(Pair.first, MD); \
181 continue;
182#include "llvm/IR/Metadata.def"
183 default:
184 llvm_unreachable("Invalid metadata subclass");
185 }
186 }
187 assert(UseMap.empty() && "Expected all uses to be replaced");
188}
189
190void ReplaceableMetadataImpl::resolveAllUses(bool ResolveUsers) {
191 if (UseMap.empty())
192 return;
193
194 if (!ResolveUsers) {
195 UseMap.clear();
196 return;
197 }
198
199 // Copy out uses since UseMap could get touched below.
200 SmallVector<std::pair<void *, OwnerTy>, 8> Uses(UseMap.begin(), UseMap.end());
201 UseMap.clear();
202 for (const auto &Pair : Uses) {
203 if (!Pair.second)
204 continue;
205 if (Pair.second.is<MetadataAsValue *>())
206 continue;
207
208 // Resolve GenericMDNodes that point at this.
209 auto *Owner = dyn_cast<GenericMDNode>(Pair.second.get<Metadata *>());
210 if (!Owner)
211 continue;
212 if (Owner->isResolved())
213 continue;
214 Owner->decrementUnresolvedOperands();
215 if (!Owner->hasUnresolvedOperands())
216 Owner->resolve();
217 }
218}
219
220static Function *getLocalFunction(Value *V) {
221 assert(V && "Expected value");
222 if (auto *A = dyn_cast<Argument>(V))
223 return A->getParent();
224 if (BasicBlock *BB = cast<Instruction>(V)->getParent())
225 return BB->getParent();
226 return nullptr;
227}
228
229ValueAsMetadata *ValueAsMetadata::get(Value *V) {
230 assert(V && "Unexpected null Value");
231
232 auto &Context = V->getContext();
233 auto *&Entry = Context.pImpl->ValuesAsMetadata[V];
234 if (!Entry) {
235 assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
236 "Expected constant or function-local value");
237 assert(!V->NameAndIsUsedByMD.getInt() &&
238 "Expected this to be the only metadata use");
239 V->NameAndIsUsedByMD.setInt(true);
240 if (auto *C = dyn_cast<Constant>(V))
241 Entry = new ConstantAsMetadata(Context, C);
242 else
243 Entry = new LocalAsMetadata(Context, V);
244 }
245
246 return Entry;
247}
248
249ValueAsMetadata *ValueAsMetadata::getIfExists(Value *V) {
250 assert(V && "Unexpected null Value");
251 return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
252}
253
254void ValueAsMetadata::handleDeletion(Value *V) {
255 assert(V && "Expected valid value");
256
257 auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
258 auto I = Store.find(V);
259 if (I == Store.end())
260 return;
261
262 // Remove old entry from the map.
263 ValueAsMetadata *MD = I->second;
264 assert(MD && "Expected valid metadata");
265 assert(MD->getValue() == V && "Expected valid mapping");
266 Store.erase(I);
267
268 // Delete the metadata.
269 MD->replaceAllUsesWith(nullptr);
270 delete MD;
271}
272
273void ValueAsMetadata::handleRAUW(Value *From, Value *To) {
274 assert(From && "Expected valid value");
275 assert(To && "Expected valid value");
276 assert(From != To && "Expected changed value");
277 assert(From->getType() == To->getType() && "Unexpected type change");
278
279 LLVMContext &Context = From->getType()->getContext();
280 auto &Store = Context.pImpl->ValuesAsMetadata;
281 auto I = Store.find(From);
282 if (I == Store.end()) {
283 assert(!From->NameAndIsUsedByMD.getInt() &&
284 "Expected From not to be used by metadata");
285 return;
286 }
287
288 // Remove old entry from the map.
289 assert(From->NameAndIsUsedByMD.getInt() &&
290 "Expected From to be used by metadata");
291 From->NameAndIsUsedByMD.setInt(false);
292 ValueAsMetadata *MD = I->second;
293 assert(MD && "Expected valid metadata");
294 assert(MD->getValue() == From && "Expected valid mapping");
295 Store.erase(I);
296
297 if (isa<LocalAsMetadata>(MD)) {
298 if (auto *C = dyn_cast<Constant>(To)) {
299 // Local became a constant.
300 MD->replaceAllUsesWith(ConstantAsMetadata::get(C));
301 delete MD;
302 return;
303 }
304 if (getLocalFunction(From) && getLocalFunction(To) &&
305 getLocalFunction(From) != getLocalFunction(To)) {
306 // Function changed.
307 MD->replaceAllUsesWith(nullptr);
308 delete MD;
309 return;
310 }
311 } else if (!isa<Constant>(To)) {
312 // Changed to function-local value.
313 MD->replaceAllUsesWith(nullptr);
314 delete MD;
315 return;
316 }
317
318 auto *&Entry = Store[To];
319 if (Entry) {
320 // The target already exists.
321 MD->replaceAllUsesWith(Entry);
322 delete MD;
323 return;
324 }
325
326 // Update MD in place (and update the map entry).
327 assert(!To->NameAndIsUsedByMD.getInt() &&
328 "Expected this to be the only metadata use");
329 To->NameAndIsUsedByMD.setInt(true);
330 MD->V = To;
331 Entry = MD;
332}
Duncan P. N. Exon Smitha69934f2014-11-14 18:42:09 +0000333
Devang Patela4f43fb2009-07-28 21:49:47 +0000334//===----------------------------------------------------------------------===//
Chris Lattnerb0c23e82009-10-19 07:10:59 +0000335// MDString implementation.
Owen Anderson0087fe62009-07-31 21:35:40 +0000336//
Chris Lattner5a409bd2009-12-28 08:30:43 +0000337
Devang Pateldcb99d32009-10-22 00:10:15 +0000338MDString *MDString::get(LLVMContext &Context, StringRef Str) {
Duncan P. N. Exon Smithf17e7402014-11-14 01:17:09 +0000339 auto &Store = Context.pImpl->MDStringCache;
340 auto I = Store.find(Str);
341 if (I != Store.end())
342 return &I->second;
343
Duncan P. N. Exon Smith56228312014-12-09 18:52:38 +0000344 auto *Entry =
345 StringMapEntry<MDString>::Create(Str, Store.getAllocator(), MDString());
Duncan P. N. Exon Smithf17e7402014-11-14 01:17:09 +0000346 bool WasInserted = Store.insert(Entry);
347 (void)WasInserted;
348 assert(WasInserted && "Expected entry to be inserted");
Duncan P. N. Exon Smithc1a664f2014-12-05 01:41:34 +0000349 Entry->second.Entry = Entry;
Duncan P. N. Exon Smithf17e7402014-11-14 01:17:09 +0000350 return &Entry->second;
351}
352
353StringRef MDString::getString() const {
Duncan P. N. Exon Smithc1a664f2014-12-05 01:41:34 +0000354 assert(Entry && "Expected to find string map entry");
355 return Entry->first();
Owen Anderson0087fe62009-07-31 21:35:40 +0000356}
357
358//===----------------------------------------------------------------------===//
Chris Lattnerb0c23e82009-10-19 07:10:59 +0000359// MDNode implementation.
Devang Patela4f43fb2009-07-28 21:49:47 +0000360//
Chris Lattner74a6ad62009-12-28 07:41:54 +0000361
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000362void *MDNode::operator new(size_t Size, unsigned NumOps) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000363 void *Ptr = ::operator new(Size + NumOps * sizeof(MDOperand));
364 MDOperand *First = new (Ptr) MDOperand[NumOps];
365 return First + NumOps;
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000366}
367
368void MDNode::operator delete(void *Mem) {
369 MDNode *N = static_cast<MDNode *>(Mem);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000370 MDOperand *Last = static_cast<MDOperand *>(Mem);
371 ::operator delete(Last - N->NumOperands);
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000372}
373
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000374MDNode::MDNode(LLVMContext &Context, unsigned ID, ArrayRef<Metadata *> MDs)
375 : Metadata(ID), Context(Context), NumOperands(MDs.size()),
376 MDNodeSubclassData(0) {
377 for (unsigned I = 0, E = MDs.size(); I != E; ++I)
378 setOperand(I, MDs[I]);
379}
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +0000380
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000381bool MDNode::isResolved() const {
382 if (isa<MDNodeFwdDecl>(this))
383 return false;
384 return cast<GenericMDNode>(this)->isResolved();
385}
Chris Lattner8cb6c342009-12-31 01:05:46 +0000386
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000387static bool isOperandUnresolved(Metadata *Op) {
388 if (auto *N = dyn_cast_or_null<MDNode>(Op))
389 return !N->isResolved();
390 return false;
391}
392
393GenericMDNode::GenericMDNode(LLVMContext &C, ArrayRef<Metadata *> Vals)
394 : MDNode(C, GenericMDNodeKind, Vals) {
395 // Check whether any operands are unresolved, requiring re-uniquing.
396 for (const auto &Op : operands())
397 if (isOperandUnresolved(Op))
398 incrementUnresolvedOperands();
399
400 if (hasUnresolvedOperands())
401 ReplaceableUses.reset(new ReplaceableMetadataImpl);
Devang Patela4f43fb2009-07-28 21:49:47 +0000402}
403
Duncan P. N. Exon Smith50846f82014-11-18 00:37:17 +0000404GenericMDNode::~GenericMDNode() {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000405 LLVMContextImpl *pImpl = getContext().pImpl;
406 if (isStoredDistinctInContext())
Jeffrey Yasskin2cc24762010-03-13 01:26:15 +0000407 pImpl->NonUniquedMDNodes.erase(this);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000408 else
Duncan P. N. Exon Smithf39c3b82014-11-17 23:28:21 +0000409 pImpl->MDNodeSet.erase(this);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000410}
411
412void GenericMDNode::resolve() {
413 assert(!isResolved() && "Expected this to be unresolved");
414
415 // Move the map, so that this immediately looks resolved.
416 auto Uses = std::move(ReplaceableUses);
417 SubclassData32 = 0;
418 assert(isResolved() && "Expected this to be resolved");
419
420 // Drop RAUW support.
421 Uses->resolveAllUses();
422}
423
424void GenericMDNode::resolveCycles() {
425 if (isResolved())
426 return;
427
428 // Resolve this node immediately.
429 resolve();
430
431 // Resolve all operands.
432 for (const auto &Op : operands()) {
433 if (!Op)
434 continue;
435 assert(!isa<MDNodeFwdDecl>(Op) &&
436 "Expected all forward declarations to be resolved");
437 if (auto *N = dyn_cast<GenericMDNode>(Op))
438 if (!N->isResolved())
439 N->resolveCycles();
Chris Lattner8cb6c342009-12-31 01:05:46 +0000440 }
Duncan P. N. Exon Smith50846f82014-11-18 00:37:17 +0000441}
442
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000443void MDNode::dropAllReferences() {
444 for (unsigned I = 0, E = NumOperands; I != E; ++I)
445 setOperand(I, nullptr);
446 if (auto *G = dyn_cast<GenericMDNode>(this))
447 if (!G->isResolved()) {
448 G->ReplaceableUses->resolveAllUses(/* ResolveUsers */ false);
449 G->ReplaceableUses.reset();
450 }
Chris Lattner8cb6c342009-12-31 01:05:46 +0000451}
452
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000453namespace llvm {
454/// \brief Make MDOperand transparent for hashing.
455///
456/// This overload of an implementation detail of the hashing library makes
457/// MDOperand hash to the same value as a \a Metadata pointer.
458///
459/// Note that overloading \a hash_value() as follows:
460///
461/// \code
462/// size_t hash_value(const MDOperand &X) { return hash_value(X.get()); }
463/// \endcode
464///
465/// does not cause MDOperand to be transparent. In particular, a bare pointer
466/// doesn't get hashed before it's combined, whereas \a MDOperand would.
467static const Metadata *get_hashable_data(const MDOperand &X) { return X.get(); }
468}
469
470void GenericMDNode::handleChangedOperand(void *Ref, Metadata *New) {
471 unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
472 assert(Op < getNumOperands() && "Expected valid operand");
473
474 if (isStoredDistinctInContext()) {
475 assert(isResolved() && "Expected distinct node to be resolved");
476
477 // This node is not uniqued. Just set the operand and be done with it.
478 setOperand(Op, New);
479 return;
Duncan Sandsc2928c62010-05-04 12:43:36 +0000480 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000481
482 auto &Store = getContext().pImpl->MDNodeSet;
483 Store.erase(this);
484
485 Metadata *Old = getOperand(Op);
486 setOperand(Op, New);
487
488 // Drop uniquing for self-reference cycles or if an operand drops to null.
489 //
490 // FIXME: Stop dropping uniquing when an operand drops to null. The original
491 // motivation was to prevent madness during teardown of LLVMContextImpl, but
492 // dropAllReferences() fixes that problem in a better way. (It's just here
493 // now for better staging of semantic changes.)
494 if (New == this || !New) {
495 storeDistinctInContext();
496 setHash(0);
497 if (!isResolved())
498 resolve();
499 return;
500 }
501
502 // Re-calculate the hash.
503 setHash(hash_combine_range(op_begin(), op_end()));
504#ifndef NDEBUG
505 {
506 SmallVector<Metadata *, 8> MDs(op_begin(), op_end());
507 unsigned RawHash = hash_combine_range(MDs.begin(), MDs.end());
508 assert(getHash() == RawHash &&
509 "Expected hash of MDOperand to equal hash of Metadata*");
510 }
511#endif
512
513 // Re-unique the node.
514 GenericMDNodeInfo::KeyTy Key(this);
515 auto I = Store.find_as(Key);
516 if (I == Store.end()) {
517 Store.insert(this);
518
519 if (!isResolved()) {
520 // Check if the last unresolved operand has just been resolved; if so,
521 // resolve this as well.
522 if (isOperandUnresolved(Old))
523 decrementUnresolvedOperands();
524 if (isOperandUnresolved(New))
525 incrementUnresolvedOperands();
526 if (!hasUnresolvedOperands())
527 resolve();
528 }
529
530 return;
531 }
532
533 // Collision.
534 if (!isResolved()) {
535 // Still unresolved, so RAUW.
536 ReplaceableUses->replaceAllUsesWith(*I);
537 delete this;
538 return;
539 }
540
541 // Store in non-uniqued form if this node has already been resolved.
542 setHash(0);
543 storeDistinctInContext();
Victor Hernandeze5f2af72010-01-20 04:45:57 +0000544}
545
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000546MDNode *MDNode::getMDNode(LLVMContext &Context, ArrayRef<Metadata *> MDs,
547 bool Insert) {
Duncan P. N. Exon Smithf39c3b82014-11-17 23:28:21 +0000548 auto &Store = Context.pImpl->MDNodeSet;
Dan Gohman01579b22010-08-24 23:21:12 +0000549
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000550 GenericMDNodeInfo::KeyTy Key(MDs);
Duncan P. N. Exon Smithf39c3b82014-11-17 23:28:21 +0000551 auto I = Store.find_as(Key);
552 if (I != Store.end())
553 return *I;
554 if (!Insert)
555 return nullptr;
Duncan Sands26a80f32012-03-31 08:20:11 +0000556
Victor Hernandez7e8ce9a2010-01-26 02:36:35 +0000557 // Coallocate space for the node and Operands together, then placement new.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000558 GenericMDNode *N = new (MDs.size()) GenericMDNode(Context, MDs);
559 N->setHash(Key.Hash);
Duncan P. N. Exon Smithf39c3b82014-11-17 23:28:21 +0000560 Store.insert(N);
Devang Patelf7188322009-09-03 01:39:20 +0000561 return N;
Owen Anderson0087fe62009-07-31 21:35:40 +0000562}
563
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000564MDNodeFwdDecl *MDNode::getTemporary(LLVMContext &Context,
565 ArrayRef<Metadata *> MDs) {
566 MDNodeFwdDecl *N = new (MDs.size()) MDNodeFwdDecl(Context, MDs);
Dan Gohman16a5d982010-08-20 22:02:26 +0000567 LeakDetector::addGarbageObject(N);
568 return N;
569}
570
571void MDNode::deleteTemporary(MDNode *N) {
Duncan P. N. Exon Smith50846f82014-11-18 00:37:17 +0000572 assert(isa<MDNodeFwdDecl>(N) && "Expected forward declaration");
Dan Gohman16a5d982010-08-20 22:02:26 +0000573 LeakDetector::removeGarbageObject(N);
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000574 delete cast<MDNodeFwdDecl>(N);
Dan Gohman16a5d982010-08-20 22:02:26 +0000575}
576
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000577void MDNode::storeDistinctInContext() {
578 assert(!IsDistinctInContext && "Expected newly distinct metadata");
579 IsDistinctInContext = true;
Duncan P. N. Exon Smith50846f82014-11-18 00:37:17 +0000580 auto *G = cast<GenericMDNode>(this);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000581 G->setHash(0);
582 getContext().pImpl->NonUniquedMDNodes.insert(G);
Devang Patel82ab3f82010-02-18 20:53:16 +0000583}
Chris Lattnerf543eff2009-12-28 09:12:35 +0000584
Chris Lattner9b493022009-12-31 01:22:29 +0000585// Replace value from this node's operand list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000586void MDNode::replaceOperandWith(unsigned I, Metadata *New) {
587 if (getOperand(I) == New)
Devang Patelf7188322009-09-03 01:39:20 +0000588 return;
Devang Patelf7188322009-09-03 01:39:20 +0000589
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000590 if (auto *N = dyn_cast<GenericMDNode>(this)) {
591 N->handleChangedOperand(mutable_begin() + I, New);
Duncan P. N. Exon Smithf39c3b82014-11-17 23:28:21 +0000592 return;
593 }
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +0000594
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000595 assert(isa<MDNodeFwdDecl>(this) && "Expected an MDNode");
596 setOperand(I, New);
597}
Chris Lattnerc6d17e22009-12-28 09:24:53 +0000598
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000599void MDNode::setOperand(unsigned I, Metadata *New) {
600 assert(I < NumOperands);
601 if (isStoredDistinctInContext() || isa<MDNodeFwdDecl>(this))
602 // No need for a callback, this isn't uniqued.
603 mutable_begin()[I].reset(New, nullptr);
604 else
605 mutable_begin()[I].reset(New, this);
Devang Patelf7188322009-09-03 01:39:20 +0000606}
607
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000608/// \brief Get a node, or a self-reference that looks like it.
609///
610/// Special handling for finding self-references, for use by \a
611/// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
612/// when self-referencing nodes were still uniqued. If the first operand has
613/// the same operands as \c Ops, return the first operand instead.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000614static MDNode *getOrSelfReference(LLVMContext &Context,
615 ArrayRef<Metadata *> Ops) {
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000616 if (!Ops.empty())
617 if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))
618 if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
619 for (unsigned I = 1, E = Ops.size(); I != E; ++I)
620 if (Ops[I] != N->getOperand(I))
621 return MDNode::get(Context, Ops);
622 return N;
623 }
624
625 return MDNode::get(Context, Ops);
626}
627
Hal Finkel94146652014-07-24 14:25:39 +0000628MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {
629 if (!A)
630 return B;
631 if (!B)
632 return A;
633
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000634 SmallVector<Metadata *, 4> MDs(A->getNumOperands() + B->getNumOperands());
Hal Finkel94146652014-07-24 14:25:39 +0000635
636 unsigned j = 0;
637 for (unsigned i = 0, ie = A->getNumOperands(); i != ie; ++i)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000638 MDs[j++] = A->getOperand(i);
Hal Finkel94146652014-07-24 14:25:39 +0000639 for (unsigned i = 0, ie = B->getNumOperands(); i != ie; ++i)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000640 MDs[j++] = B->getOperand(i);
Hal Finkel94146652014-07-24 14:25:39 +0000641
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000642 // FIXME: This preserves long-standing behaviour, but is it really the right
643 // behaviour? Or was that an unintended side-effect of node uniquing?
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000644 return getOrSelfReference(A->getContext(), MDs);
Hal Finkel94146652014-07-24 14:25:39 +0000645}
646
647MDNode *MDNode::intersect(MDNode *A, MDNode *B) {
648 if (!A || !B)
649 return nullptr;
650
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000651 SmallVector<Metadata *, 4> MDs;
Hal Finkel94146652014-07-24 14:25:39 +0000652 for (unsigned i = 0, ie = A->getNumOperands(); i != ie; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000653 Metadata *MD = A->getOperand(i);
Hal Finkel94146652014-07-24 14:25:39 +0000654 for (unsigned j = 0, je = B->getNumOperands(); j != je; ++j)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000655 if (MD == B->getOperand(j)) {
656 MDs.push_back(MD);
Hal Finkel94146652014-07-24 14:25:39 +0000657 break;
658 }
659 }
660
Duncan P. N. Exon Smithac8ee282014-12-07 19:52:06 +0000661 // FIXME: This preserves long-standing behaviour, but is it really the right
662 // behaviour? Or was that an unintended side-effect of node uniquing?
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000663 return getOrSelfReference(A->getContext(), MDs);
Hal Finkel94146652014-07-24 14:25:39 +0000664}
665
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000666MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
667 if (!A || !B)
Craig Topperc6207612014-04-09 06:08:46 +0000668 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000669
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000670 APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
671 APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000672 if (AVal.compare(BVal) == APFloat::cmpLessThan)
673 return A;
674 return B;
675}
676
677static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
678 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
679}
680
681static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
682 return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
683}
684
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000685static bool tryMergeRange(SmallVectorImpl<ConstantInt *> &EndPoints,
686 ConstantInt *Low, ConstantInt *High) {
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000687 ConstantRange NewRange(Low->getValue(), High->getValue());
688 unsigned Size = EndPoints.size();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000689 APInt LB = EndPoints[Size - 2]->getValue();
690 APInt LE = EndPoints[Size - 1]->getValue();
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000691 ConstantRange LastRange(LB, LE);
692 if (canBeMerged(NewRange, LastRange)) {
693 ConstantRange Union = LastRange.unionWith(NewRange);
694 Type *Ty = High->getType();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000695 EndPoints[Size - 2] =
696 cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
697 EndPoints[Size - 1] =
698 cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000699 return true;
700 }
701 return false;
702}
703
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000704static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,
705 ConstantInt *Low, ConstantInt *High) {
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000706 if (!EndPoints.empty())
707 if (tryMergeRange(EndPoints, Low, High))
708 return;
709
710 EndPoints.push_back(Low);
711 EndPoints.push_back(High);
712}
713
714MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
715 // Given two ranges, we want to compute the union of the ranges. This
716 // is slightly complitade by having to combine the intervals and merge
717 // the ones that overlap.
718
719 if (!A || !B)
Craig Topperc6207612014-04-09 06:08:46 +0000720 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000721
722 if (A == B)
723 return A;
724
725 // First, walk both lists in older of the lower boundary of each interval.
726 // 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 +0000727 SmallVector<ConstantInt *, 4> EndPoints;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000728 int AI = 0;
729 int BI = 0;
730 int AN = A->getNumOperands() / 2;
731 int BN = B->getNumOperands() / 2;
732 while (AI < AN && BI < BN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000733 ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
734 ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000735
736 if (ALow->getValue().slt(BLow->getValue())) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000737 addRange(EndPoints, ALow,
738 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000739 ++AI;
740 } else {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000741 addRange(EndPoints, BLow,
742 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000743 ++BI;
744 }
745 }
746 while (AI < AN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000747 addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
748 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000749 ++AI;
750 }
751 while (BI < BN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000752 addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
753 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000754 ++BI;
755 }
756
757 // If we have more than 2 ranges (4 endpoints) we have to try to merge
758 // the last and first ones.
759 unsigned Size = EndPoints.size();
760 if (Size > 4) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000761 ConstantInt *FB = EndPoints[0];
762 ConstantInt *FE = EndPoints[1];
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000763 if (tryMergeRange(EndPoints, FB, FE)) {
764 for (unsigned i = 0; i < Size - 2; ++i) {
765 EndPoints[i] = EndPoints[i + 2];
766 }
767 EndPoints.resize(Size - 2);
768 }
769 }
770
771 // If in the end we have a single range, it is possible that it is now the
772 // full range. Just drop the metadata in that case.
773 if (EndPoints.size() == 2) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000774 ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000775 if (Range.isFullSet())
Craig Topperc6207612014-04-09 06:08:46 +0000776 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000777 }
778
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000779 SmallVector<Metadata *, 4> MDs;
780 MDs.reserve(EndPoints.size());
781 for (auto *I : EndPoints)
782 MDs.push_back(ConstantAsMetadata::get(I));
783 return MDNode::get(A->getContext(), MDs);
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000784}
785
Devang Patel05a26fb2009-07-29 00:33:07 +0000786//===----------------------------------------------------------------------===//
Chris Lattnerb0c23e82009-10-19 07:10:59 +0000787// NamedMDNode implementation.
Devang Patel05a26fb2009-07-29 00:33:07 +0000788//
Devang Patel943ddf62010-01-12 18:34:06 +0000789
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000790static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
791 return *(SmallVector<TrackingMDRef, 4> *)Operands;
Chris Lattner1bc810b2009-12-28 08:07:14 +0000792}
793
Dan Gohman2637cc12010-07-21 23:38:33 +0000794NamedMDNode::NamedMDNode(const Twine &N)
Duncan P. N. Exon Smithc5754a62014-11-05 18:16:03 +0000795 : Name(N.str()), Parent(nullptr),
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000796 Operands(new SmallVector<TrackingMDRef, 4>()) {}
Devang Patel5c310be2009-08-11 18:01:24 +0000797
Chris Lattner1bc810b2009-12-28 08:07:14 +0000798NamedMDNode::~NamedMDNode() {
799 dropAllReferences();
800 delete &getNMDOps(Operands);
801}
802
Chris Lattner9b493022009-12-31 01:22:29 +0000803unsigned NamedMDNode::getNumOperands() const {
Chris Lattner1bc810b2009-12-28 08:07:14 +0000804 return (unsigned)getNMDOps(Operands).size();
805}
806
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000807MDNode *NamedMDNode::getOperand(unsigned i) const {
Chris Lattner9b493022009-12-31 01:22:29 +0000808 assert(i < getNumOperands() && "Invalid Operand number!");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000809 auto *N = getNMDOps(Operands)[i].get();
810 if (N && i > 10000)
811 N->dump();
812 return cast_or_null<MDNode>(N);
Chris Lattner1bc810b2009-12-28 08:07:14 +0000813}
814
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000815void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
Chris Lattner1bc810b2009-12-28 08:07:14 +0000816
Devang Patel79238d72009-08-03 06:19:01 +0000817void NamedMDNode::eraseFromParent() {
Dan Gohman2637cc12010-07-21 23:38:33 +0000818 getParent()->eraseNamedMetadata(this);
Devang Patel79238d72009-08-03 06:19:01 +0000819}
820
Devang Patel79238d72009-08-03 06:19:01 +0000821void NamedMDNode::dropAllReferences() {
Chris Lattner1bc810b2009-12-28 08:07:14 +0000822 getNMDOps(Operands).clear();
Devang Patel79238d72009-08-03 06:19:01 +0000823}
824
Devang Patelfcfee0f2010-01-07 19:39:36 +0000825StringRef NamedMDNode::getName() const {
826 return StringRef(Name);
827}
Devang Pateld5497a4b2009-09-16 18:09:00 +0000828
829//===----------------------------------------------------------------------===//
Chris Lattner2f2aa2b2009-12-28 23:41:32 +0000830// Instruction Metadata method implementations.
831//
832
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000833void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
834 if (!Node && !hasMetadata())
835 return;
836 setMetadata(getContext().getMDKindID(Kind), Node);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +0000837}
838
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000839MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
Chris Lattnera0566972009-12-29 09:01:33 +0000840 return getMetadataImpl(getContext().getMDKindID(Kind));
Chris Lattner2f2aa2b2009-12-28 23:41:32 +0000841}
842
Rafael Espindolaab73c492014-01-28 16:56:46 +0000843void Instruction::dropUnknownMetadata(ArrayRef<unsigned> KnownIDs) {
844 SmallSet<unsigned, 5> KnownSet;
845 KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
846
847 // Drop debug if needed
848 if (KnownSet.erase(LLVMContext::MD_dbg))
849 DbgLoc = DebugLoc();
850
851 if (!hasMetadataHashEntry())
852 return; // Nothing to remove!
853
854 DenseMap<const Instruction *, LLVMContextImpl::MDMapTy> &MetadataStore =
855 getContext().pImpl->MetadataStore;
856
857 if (KnownSet.empty()) {
858 // Just drop our entry at the store.
859 MetadataStore.erase(this);
860 setHasMetadataHashEntry(false);
861 return;
862 }
863
864 LLVMContextImpl::MDMapTy &Info = MetadataStore[this];
865 unsigned I;
866 unsigned E;
867 // Walk the array and drop any metadata we don't know.
868 for (I = 0, E = Info.size(); I != E;) {
869 if (KnownSet.count(Info[I].first)) {
870 ++I;
871 continue;
872 }
873
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000874 Info[I] = std::move(Info.back());
Rafael Espindolaab73c492014-01-28 16:56:46 +0000875 Info.pop_back();
876 --E;
877 }
878 assert(E == Info.size());
879
880 if (E == 0) {
881 // Drop our entry at the store.
882 MetadataStore.erase(this);
883 setHasMetadataHashEntry(false);
884 }
885}
886
Chris Lattner2f2aa2b2009-12-28 23:41:32 +0000887/// setMetadata - Set the metadata of of the specified kind to the specified
888/// node. This updates/replaces metadata if already present, or removes it if
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000889/// Node is null.
890void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
891 if (!Node && !hasMetadata())
892 return;
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +0000893
Chris Lattnerc263b422010-03-30 23:03:27 +0000894 // Handle 'dbg' as a special case since it is not stored in the hash table.
895 if (KindID == LLVMContext::MD_dbg) {
Chris Lattner593916d2010-04-02 20:21:22 +0000896 DbgLoc = DebugLoc::getFromDILocation(Node);
Chris Lattnerc263b422010-03-30 23:03:27 +0000897 return;
898 }
899
Chris Lattnera0566972009-12-29 09:01:33 +0000900 // Handle the case when we're adding/updating metadata on an instruction.
901 if (Node) {
902 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
Chris Lattnerc263b422010-03-30 23:03:27 +0000903 assert(!Info.empty() == hasMetadataHashEntry() &&
904 "HasMetadata bit is wonked");
Chris Lattnera0566972009-12-29 09:01:33 +0000905 if (Info.empty()) {
Chris Lattnerc263b422010-03-30 23:03:27 +0000906 setHasMetadataHashEntry(true);
Chris Lattnera0566972009-12-29 09:01:33 +0000907 } else {
908 // Handle replacement of an existing value.
Benjamin Kramer3ad5c962014-03-10 15:03:06 +0000909 for (auto &P : Info)
910 if (P.first == KindID) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000911 P.second.reset(Node);
Chris Lattnera0566972009-12-29 09:01:33 +0000912 return;
913 }
914 }
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +0000915
Chris Lattnera0566972009-12-29 09:01:33 +0000916 // No replacement, just add it to the list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000917 Info.emplace_back(std::piecewise_construct, std::make_tuple(KindID),
918 std::make_tuple(Node));
Chris Lattnera0566972009-12-29 09:01:33 +0000919 return;
920 }
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +0000921
Chris Lattnera0566972009-12-29 09:01:33 +0000922 // Otherwise, we're removing metadata from an instruction.
Nick Lewycky4c131382011-12-27 01:17:40 +0000923 assert((hasMetadataHashEntry() ==
Yaron Keren6d3194f2014-06-20 10:26:56 +0000924 (getContext().pImpl->MetadataStore.count(this) > 0)) &&
Chris Lattnera0566972009-12-29 09:01:33 +0000925 "HasMetadata bit out of date!");
Nick Lewycky4c131382011-12-27 01:17:40 +0000926 if (!hasMetadataHashEntry())
927 return; // Nothing to remove!
Chris Lattnera0566972009-12-29 09:01:33 +0000928 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +0000929
Chris Lattnera0566972009-12-29 09:01:33 +0000930 // Common case is removing the only entry.
931 if (Info.size() == 1 && Info[0].first == KindID) {
932 getContext().pImpl->MetadataStore.erase(this);
Chris Lattnerc263b422010-03-30 23:03:27 +0000933 setHasMetadataHashEntry(false);
Chris Lattnera0566972009-12-29 09:01:33 +0000934 return;
935 }
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +0000936
Chris Lattnerc263b422010-03-30 23:03:27 +0000937 // Handle removal of an existing value.
Chris Lattnera0566972009-12-29 09:01:33 +0000938 for (unsigned i = 0, e = Info.size(); i != e; ++i)
939 if (Info[i].first == KindID) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000940 Info[i] = std::move(Info.back());
Chris Lattnera0566972009-12-29 09:01:33 +0000941 Info.pop_back();
942 assert(!Info.empty() && "Removing last entry should be handled above");
943 return;
944 }
945 // Otherwise, removing an entry that doesn't exist on the instruction.
Chris Lattner2f2aa2b2009-12-28 23:41:32 +0000946}
947
Hal Finkelcc39b672014-07-24 12:16:19 +0000948void Instruction::setAAMetadata(const AAMDNodes &N) {
949 setMetadata(LLVMContext::MD_tbaa, N.TBAA);
Hal Finkel94146652014-07-24 14:25:39 +0000950 setMetadata(LLVMContext::MD_alias_scope, N.Scope);
951 setMetadata(LLVMContext::MD_noalias, N.NoAlias);
Hal Finkelcc39b672014-07-24 12:16:19 +0000952}
953
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000954MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
Chris Lattnerc263b422010-03-30 23:03:27 +0000955 // Handle 'dbg' as a special case since it is not stored in the hash table.
956 if (KindID == LLVMContext::MD_dbg)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000957 return DbgLoc.getAsMDNode();
958
Craig Topperc6207612014-04-09 06:08:46 +0000959 if (!hasMetadataHashEntry()) return nullptr;
Chris Lattnerc263b422010-03-30 23:03:27 +0000960
Chris Lattnera0566972009-12-29 09:01:33 +0000961 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
Chris Lattnerc263b422010-03-30 23:03:27 +0000962 assert(!Info.empty() && "bit out of sync with hash table");
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +0000963
Benjamin Kramer3ad5c962014-03-10 15:03:06 +0000964 for (const auto &I : Info)
965 if (I.first == KindID)
966 return I.second;
Craig Topperc6207612014-04-09 06:08:46 +0000967 return nullptr;
Chris Lattner2f2aa2b2009-12-28 23:41:32 +0000968}
969
Duncan P. N. Exon Smith4abd1a02014-11-01 00:26:42 +0000970void Instruction::getAllMetadataImpl(
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000971 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
Chris Lattnerc263b422010-03-30 23:03:27 +0000972 Result.clear();
973
974 // Handle 'dbg' as a special case since it is not stored in the hash table.
Chris Lattnerc0f5ce32010-04-01 05:23:13 +0000975 if (!DbgLoc.isUnknown()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000976 Result.push_back(
977 std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
Chris Lattnerc263b422010-03-30 23:03:27 +0000978 if (!hasMetadataHashEntry()) return;
979 }
980
981 assert(hasMetadataHashEntry() &&
982 getContext().pImpl->MetadataStore.count(this) &&
Chris Lattnera0566972009-12-29 09:01:33 +0000983 "Shouldn't have called this");
984 const LLVMContextImpl::MDMapTy &Info =
985 getContext().pImpl->MetadataStore.find(this)->second;
986 assert(!Info.empty() && "Shouldn't have called this");
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +0000987
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000988 Result.reserve(Result.size() + Info.size());
989 for (auto &I : Info)
990 Result.push_back(std::make_pair(I.first, cast<MDNode>(I.second.get())));
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +0000991
Chris Lattnera0566972009-12-29 09:01:33 +0000992 // Sort the resulting array so it is stable.
993 if (Result.size() > 1)
994 array_pod_sort(Result.begin(), Result.end());
Chris Lattner2f2aa2b2009-12-28 23:41:32 +0000995}
996
Duncan P. N. Exon Smith3d5a02f2014-11-03 18:13:57 +0000997void Instruction::getAllMetadataOtherThanDebugLocImpl(
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000998 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
Chris Lattnerc0f5ce32010-04-01 05:23:13 +0000999 Result.clear();
1000 assert(hasMetadataHashEntry() &&
1001 getContext().pImpl->MetadataStore.count(this) &&
1002 "Shouldn't have called this");
1003 const LLVMContextImpl::MDMapTy &Info =
Bill Wendlingdd91e732012-04-03 10:50:09 +00001004 getContext().pImpl->MetadataStore.find(this)->second;
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001005 assert(!Info.empty() && "Shouldn't have called this");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001006 Result.reserve(Result.size() + Info.size());
1007 for (auto &I : Info)
1008 Result.push_back(std::make_pair(I.first, cast<MDNode>(I.second.get())));
Bill Wendlingdd91e732012-04-03 10:50:09 +00001009
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001010 // Sort the resulting array so it is stable.
1011 if (Result.size() > 1)
1012 array_pod_sort(Result.begin(), Result.end());
1013}
1014
Dan Gohman48a995f2010-07-20 22:25:04 +00001015/// clearMetadataHashEntries - Clear all hashtable-based metadata from
1016/// this instruction.
1017void Instruction::clearMetadataHashEntries() {
1018 assert(hasMetadataHashEntry() && "Caller should check");
1019 getContext().pImpl->MetadataStore.erase(this);
1020 setHasMetadataHashEntry(false);
Chris Lattner68017802009-12-29 07:44:16 +00001021}
1022